From d77e4d11929adc1f2afd7e6ed012f36928dac7c9 Mon Sep 17 00:00:00 2001 From: c4ch3c4d3 <23181631+c4ch3c4d3@users.noreply.github.com> Date: Tue, 17 Mar 2026 11:10:09 -0600 Subject: [PATCH] Local Options Enabled --- app.css | 2 + background.js | 116 + debug.html | 13 + debug.js | 259996 +++++++++++++++++++ icon-128.png | Bin 0 -> 22603 bytes icon-16.png | Bin 0 -> 757 bytes icon-48.png | Bin 0 -> 4275 bytes icons.html | 14 + icons.js | 26038 ++ manifest.json | 54 + pdfjs-dist/build/pdf.worker.min.mjs | 28 + sandbox.html | 15 + sandbox.js | 57 + sidepanel.html | 13 + sidepanel.js | 335629 +++++++++++++++++++++++++ test.html | 24 + theme-loader.js | 8 + 17 files changed, 622007 insertions(+) create mode 100644 app.css create mode 100644 background.js create mode 100644 debug.html create mode 100644 debug.js create mode 100644 icon-128.png create mode 100644 icon-16.png create mode 100644 icon-48.png create mode 100644 icons.html create mode 100644 icons.js create mode 100644 manifest.json create mode 100644 pdfjs-dist/build/pdf.worker.min.mjs create mode 100644 sandbox.html create mode 100644 sandbox.js create mode 100644 sidepanel.html create mode 100644 sidepanel.js create mode 100644 test.html create mode 100644 theme-loader.js diff --git a/app.css b/app.css new file mode 100644 index 0000000..ef9f6bf --- /dev/null +++ b/app.css @@ -0,0 +1,2 @@ +/*! tailwindcss v4.2.1 | MIT License | https://tailwindcss.com */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-font-weight:initial;--tw-leading:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-x-reverse:0;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-tracking:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}:root{--syntax-keyword:oklch(57.7% .245 27.325);--syntax-entity:oklch(51.1% .136 307.715);--syntax-constant:oklch(43.5% .141 237.016);--syntax-string:oklch(29.6% .103 244.038);--syntax-variable:oklch(60.8% .178 54.291);--syntax-comment:oklch(54% .019 247.858);--syntax-tag:oklch(40.3% .111 145.348);--syntax-heading:oklch(43.5% .141 237.016);--syntax-list:oklch(53.7% .108 88.766);--syntax-addition-bg:oklch(98.4% .029 166.113);--syntax-addition-fg:oklch(40.3% .111 145.348);--syntax-deletion-bg:oklch(98.1% .025 17.672);--syntax-deletion-fg:oklch(43.1% .183 27.522)}.dark{--syntax-keyword:oklch(69.8% .159 21.174);--syntax-entity:oklch(79.2% .124 307.715);--syntax-constant:oklch(73.2% .137 237.016);--syntax-string:oklch(78.6% .08 237.016);--syntax-variable:oklch(74% .141 54.291);--syntax-comment:oklch(62.6% .025 247.858);--syntax-tag:oklch(81.2% .159 145.348);--syntax-heading:oklch(52.3% .181 237.016);--syntax-list:oklch(86.6% .141 88.766);--syntax-addition-bg:oklch(18.8% .06 166.113);--syntax-addition-fg:oklch(87% .147 145.348);--syntax-deletion-bg:oklch(23.3% .129 17.672);--syntax-deletion-fg:oklch(92% .067 17.672)}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:var(--syntax-keyword)}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:var(--syntax-entity)}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-variable,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id{color:var(--syntax-constant)}.hljs-regexp,.hljs-string,.hljs-meta .hljs-string{color:var(--syntax-string)}.hljs-built_in,.hljs-symbol{color:var(--syntax-variable)}.hljs-comment,.hljs-code,.hljs-formula{color:var(--syntax-comment)}.hljs-name,.hljs-quote,.hljs-selector-tag,.hljs-selector-pseudo{color:var(--syntax-tag)}.hljs-subst{color:var(--color-text-primary)}.hljs-section{color:var(--syntax-heading);font-weight:700}.hljs-bullet{color:var(--syntax-list)}.hljs-emphasis{color:var(--color-text-primary);font-style:italic}.hljs-strong{color:var(--color-text-primary);font-weight:700}.hljs-addition{color:var(--syntax-addition-fg);background-color:var(--syntax-addition-bg)}.hljs-deletion{color:var(--syntax-deletion-fg);background-color:var(--syntax-deletion-bg)}@font-face{font-family:KaTeX_AMS;font-style:normal;font-weight:400;src:url(fonts/KaTeX_AMS-Regular.woff2)format("woff2"),url(fonts/KaTeX_AMS-Regular.woff)format("woff"),url(fonts/KaTeX_AMS-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Caligraphic-Bold.woff2)format("woff2"),url(fonts/KaTeX_Caligraphic-Bold.woff)format("woff"),url(fonts/KaTeX_Caligraphic-Bold.ttf)format("truetype")}@font-face{font-family:KaTeX_Caligraphic;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Caligraphic-Regular.woff2)format("woff2"),url(fonts/KaTeX_Caligraphic-Regular.woff)format("woff"),url(fonts/KaTeX_Caligraphic-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Fraktur-Bold.woff2)format("woff2"),url(fonts/KaTeX_Fraktur-Bold.woff)format("woff"),url(fonts/KaTeX_Fraktur-Bold.ttf)format("truetype")}@font-face{font-family:KaTeX_Fraktur;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Fraktur-Regular.woff2)format("woff2"),url(fonts/KaTeX_Fraktur-Regular.woff)format("woff"),url(fonts/KaTeX_Fraktur-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:700;src:url(fonts/KaTeX_Main-Bold.woff2)format("woff2"),url(fonts/KaTeX_Main-Bold.woff)format("woff"),url(fonts/KaTeX_Main-Bold.ttf)format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Main-BoldItalic.woff2)format("woff2"),url(fonts/KaTeX_Main-BoldItalic.woff)format("woff"),url(fonts/KaTeX_Main-BoldItalic.ttf)format("truetype")}@font-face{font-family:KaTeX_Main;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Main-Italic.woff2)format("woff2"),url(fonts/KaTeX_Main-Italic.woff)format("woff"),url(fonts/KaTeX_Main-Italic.ttf)format("truetype")}@font-face{font-family:KaTeX_Main;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Main-Regular.woff2)format("woff2"),url(fonts/KaTeX_Main-Regular.woff)format("woff"),url(fonts/KaTeX_Main-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:700;src:url(fonts/KaTeX_Math-BoldItalic.woff2)format("woff2"),url(fonts/KaTeX_Math-BoldItalic.woff)format("woff"),url(fonts/KaTeX_Math-BoldItalic.ttf)format("truetype")}@font-face{font-family:KaTeX_Math;font-style:italic;font-weight:400;src:url(fonts/KaTeX_Math-Italic.woff2)format("woff2"),url(fonts/KaTeX_Math-Italic.woff)format("woff"),url(fonts/KaTeX_Math-Italic.ttf)format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:700;src:url(fonts/KaTeX_SansSerif-Bold.woff2)format("woff2"),url(fonts/KaTeX_SansSerif-Bold.woff)format("woff"),url(fonts/KaTeX_SansSerif-Bold.ttf)format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:italic;font-weight:400;src:url(fonts/KaTeX_SansSerif-Italic.woff2)format("woff2"),url(fonts/KaTeX_SansSerif-Italic.woff)format("woff"),url(fonts/KaTeX_SansSerif-Italic.ttf)format("truetype")}@font-face{font-family:KaTeX_SansSerif;font-style:normal;font-weight:400;src:url(fonts/KaTeX_SansSerif-Regular.woff2)format("woff2"),url(fonts/KaTeX_SansSerif-Regular.woff)format("woff"),url(fonts/KaTeX_SansSerif-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Script;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Script-Regular.woff2)format("woff2"),url(fonts/KaTeX_Script-Regular.woff)format("woff"),url(fonts/KaTeX_Script-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Size1;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size1-Regular.woff2)format("woff2"),url(fonts/KaTeX_Size1-Regular.woff)format("woff"),url(fonts/KaTeX_Size1-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Size2;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size2-Regular.woff2)format("woff2"),url(fonts/KaTeX_Size2-Regular.woff)format("woff"),url(fonts/KaTeX_Size2-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Size3;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size3-Regular.woff2)format("woff2"),url(fonts/KaTeX_Size3-Regular.woff)format("woff"),url(fonts/KaTeX_Size3-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Size4;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Size4-Regular.woff2)format("woff2"),url(fonts/KaTeX_Size4-Regular.woff)format("woff"),url(fonts/KaTeX_Size4-Regular.ttf)format("truetype")}@font-face{font-family:KaTeX_Typewriter;font-style:normal;font-weight:400;src:url(fonts/KaTeX_Typewriter-Regular.woff2)format("woff2"),url(fonts/KaTeX_Typewriter-Regular.woff)format("woff"),url(fonts/KaTeX_Typewriter-Regular.ttf)format("truetype")}.katex{text-indent:0;text-rendering:auto;font:1.21em/1.2 KaTeX_Main,Times New Roman,serif}.katex *{border-color:currentColor;-ms-high-contrast-adjust:none!important}.katex .katex-version:after{content:"0.16.22"}.katex .katex-mathml{clip:rect(1px,1px,1px,1px);border:0;width:1px;height:1px;padding:0;position:absolute;overflow:hidden}.katex .katex-html>.newline{display:block}.katex .base{white-space:nowrap;width:min-content;position:relative}.katex .base,.katex .strut{display:inline-block}.katex .textbf{font-weight:700}.katex .textit{font-style:italic}.katex .textrm{font-family:KaTeX_Main}.katex .textsf{font-family:KaTeX_SansSerif}.katex .texttt{font-family:KaTeX_Typewriter}.katex .mathnormal{font-family:KaTeX_Math;font-style:italic}.katex .mathit{font-family:KaTeX_Main;font-style:italic}.katex .mathrm{font-style:normal}.katex .mathbf{font-family:KaTeX_Main;font-weight:700}.katex .boldsymbol{font-family:KaTeX_Math;font-style:italic;font-weight:700}.katex .amsrm,.katex .mathbb,.katex .textbb{font-family:KaTeX_AMS}.katex .mathcal{font-family:KaTeX_Caligraphic}.katex .mathfrak,.katex .textfrak{font-family:KaTeX_Fraktur}.katex .mathboldfrak,.katex .textboldfrak{font-family:KaTeX_Fraktur;font-weight:700}.katex .mathtt{font-family:KaTeX_Typewriter}.katex .mathscr,.katex .textscr{font-family:KaTeX_Script}.katex .mathsf,.katex .textsf{font-family:KaTeX_SansSerif}.katex .mathboldsf,.katex .textboldsf{font-family:KaTeX_SansSerif;font-weight:700}.katex .mathitsf,.katex .mathsfit,.katex .textitsf{font-family:KaTeX_SansSerif;font-style:italic}.katex .mainrm{font-family:KaTeX_Main;font-style:normal}.katex .vlist-t{border-collapse:collapse;table-layout:fixed;display:inline-table}.katex .vlist-r{display:table-row}.katex .vlist{vertical-align:bottom;display:table-cell;position:relative}.katex .vlist>span{height:0;display:block;position:relative}.katex .vlist>span>span{display:inline-block}.katex .vlist>span>.pstrut{width:0;overflow:hidden}.katex .vlist-t2{margin-right:-2px}.katex .vlist-s{vertical-align:bottom;width:2px;min-width:2px;font-size:1px;display:table-cell}.katex .vbox{flex-direction:column;align-items:baseline;display:inline-flex}.katex .hbox{width:100%}.katex .hbox,.katex .thinbox{flex-direction:row;display:inline-flex}.katex .thinbox{width:0;max-width:0}.katex .msupsub{text-align:left}.katex .mfrac>span>span{text-align:center}.katex .mfrac .frac-line{border-bottom-style:solid;width:100%;display:inline-block}.katex .hdashline,.katex .hline,.katex .mfrac .frac-line,.katex .overline .overline-line,.katex .rule,.katex .underline .underline-line{min-height:1px}.katex .mspace{display:inline-block}.katex .clap,.katex .llap,.katex .rlap{width:0;position:relative}.katex .clap>.inner,.katex .llap>.inner,.katex .rlap>.inner{position:absolute}.katex .clap>.fix,.katex .llap>.fix,.katex .rlap>.fix{display:inline-block}.katex .llap>.inner{right:0}.katex .clap>.inner,.katex .rlap>.inner{left:0}.katex .clap>.inner>span{margin-left:-50%;margin-right:50%}.katex .rule{border:0 solid;display:inline-block;position:relative}.katex .hline,.katex .overline .overline-line,.katex .underline .underline-line{border-bottom-style:solid;width:100%;display:inline-block}.katex .hdashline{border-bottom-style:dashed;width:100%;display:inline-block}.katex .sqrt>.root{margin-left:.277778em;margin-right:-.555556em}.katex .fontsize-ensurer.reset-size1.size1,.katex .sizing.reset-size1.size1{font-size:1em}.katex .fontsize-ensurer.reset-size1.size2,.katex .sizing.reset-size1.size2{font-size:1.2em}.katex .fontsize-ensurer.reset-size1.size3,.katex .sizing.reset-size1.size3{font-size:1.4em}.katex .fontsize-ensurer.reset-size1.size4,.katex .sizing.reset-size1.size4{font-size:1.6em}.katex .fontsize-ensurer.reset-size1.size5,.katex .sizing.reset-size1.size5{font-size:1.8em}.katex .fontsize-ensurer.reset-size1.size6,.katex .sizing.reset-size1.size6{font-size:2em}.katex .fontsize-ensurer.reset-size1.size7,.katex .sizing.reset-size1.size7{font-size:2.4em}.katex .fontsize-ensurer.reset-size1.size8,.katex .sizing.reset-size1.size8{font-size:2.88em}.katex .fontsize-ensurer.reset-size1.size9,.katex .sizing.reset-size1.size9{font-size:3.456em}.katex .fontsize-ensurer.reset-size1.size10,.katex .sizing.reset-size1.size10{font-size:4.148em}.katex .fontsize-ensurer.reset-size1.size11,.katex .sizing.reset-size1.size11{font-size:4.976em}.katex .fontsize-ensurer.reset-size2.size1,.katex .sizing.reset-size2.size1{font-size:.833333em}.katex .fontsize-ensurer.reset-size2.size2,.katex .sizing.reset-size2.size2{font-size:1em}.katex .fontsize-ensurer.reset-size2.size3,.katex .sizing.reset-size2.size3{font-size:1.16667em}.katex .fontsize-ensurer.reset-size2.size4,.katex .sizing.reset-size2.size4{font-size:1.33333em}.katex .fontsize-ensurer.reset-size2.size5,.katex .sizing.reset-size2.size5{font-size:1.5em}.katex .fontsize-ensurer.reset-size2.size6,.katex .sizing.reset-size2.size6{font-size:1.66667em}.katex .fontsize-ensurer.reset-size2.size7,.katex .sizing.reset-size2.size7{font-size:2em}.katex .fontsize-ensurer.reset-size2.size8,.katex .sizing.reset-size2.size8{font-size:2.4em}.katex .fontsize-ensurer.reset-size2.size9,.katex .sizing.reset-size2.size9{font-size:2.88em}.katex .fontsize-ensurer.reset-size2.size10,.katex .sizing.reset-size2.size10{font-size:3.45667em}.katex .fontsize-ensurer.reset-size2.size11,.katex .sizing.reset-size2.size11{font-size:4.14667em}.katex .fontsize-ensurer.reset-size3.size1,.katex .sizing.reset-size3.size1{font-size:.714286em}.katex .fontsize-ensurer.reset-size3.size2,.katex .sizing.reset-size3.size2{font-size:.857143em}.katex .fontsize-ensurer.reset-size3.size3,.katex .sizing.reset-size3.size3{font-size:1em}.katex .fontsize-ensurer.reset-size3.size4,.katex .sizing.reset-size3.size4{font-size:1.14286em}.katex .fontsize-ensurer.reset-size3.size5,.katex .sizing.reset-size3.size5{font-size:1.28571em}.katex .fontsize-ensurer.reset-size3.size6,.katex .sizing.reset-size3.size6{font-size:1.42857em}.katex .fontsize-ensurer.reset-size3.size7,.katex .sizing.reset-size3.size7{font-size:1.71429em}.katex .fontsize-ensurer.reset-size3.size8,.katex .sizing.reset-size3.size8{font-size:2.05714em}.katex .fontsize-ensurer.reset-size3.size9,.katex .sizing.reset-size3.size9{font-size:2.46857em}.katex .fontsize-ensurer.reset-size3.size10,.katex .sizing.reset-size3.size10{font-size:2.96286em}.katex .fontsize-ensurer.reset-size3.size11,.katex .sizing.reset-size3.size11{font-size:3.55429em}.katex .fontsize-ensurer.reset-size4.size1,.katex .sizing.reset-size4.size1{font-size:.625em}.katex .fontsize-ensurer.reset-size4.size2,.katex .sizing.reset-size4.size2{font-size:.75em}.katex .fontsize-ensurer.reset-size4.size3,.katex .sizing.reset-size4.size3{font-size:.875em}.katex .fontsize-ensurer.reset-size4.size4,.katex .sizing.reset-size4.size4{font-size:1em}.katex .fontsize-ensurer.reset-size4.size5,.katex .sizing.reset-size4.size5{font-size:1.125em}.katex .fontsize-ensurer.reset-size4.size6,.katex .sizing.reset-size4.size6{font-size:1.25em}.katex .fontsize-ensurer.reset-size4.size7,.katex .sizing.reset-size4.size7{font-size:1.5em}.katex .fontsize-ensurer.reset-size4.size8,.katex .sizing.reset-size4.size8{font-size:1.8em}.katex .fontsize-ensurer.reset-size4.size9,.katex .sizing.reset-size4.size9{font-size:2.16em}.katex .fontsize-ensurer.reset-size4.size10,.katex .sizing.reset-size4.size10{font-size:2.5925em}.katex .fontsize-ensurer.reset-size4.size11,.katex .sizing.reset-size4.size11{font-size:3.11em}.katex .fontsize-ensurer.reset-size5.size1,.katex .sizing.reset-size5.size1{font-size:.555556em}.katex .fontsize-ensurer.reset-size5.size2,.katex .sizing.reset-size5.size2{font-size:.666667em}.katex .fontsize-ensurer.reset-size5.size3,.katex .sizing.reset-size5.size3{font-size:.777778em}.katex .fontsize-ensurer.reset-size5.size4,.katex .sizing.reset-size5.size4{font-size:.888889em}.katex .fontsize-ensurer.reset-size5.size5,.katex .sizing.reset-size5.size5{font-size:1em}.katex .fontsize-ensurer.reset-size5.size6,.katex .sizing.reset-size5.size6{font-size:1.11111em}.katex .fontsize-ensurer.reset-size5.size7,.katex .sizing.reset-size5.size7{font-size:1.33333em}.katex .fontsize-ensurer.reset-size5.size8,.katex .sizing.reset-size5.size8{font-size:1.6em}.katex .fontsize-ensurer.reset-size5.size9,.katex .sizing.reset-size5.size9{font-size:1.92em}.katex .fontsize-ensurer.reset-size5.size10,.katex .sizing.reset-size5.size10{font-size:2.30444em}.katex .fontsize-ensurer.reset-size5.size11,.katex .sizing.reset-size5.size11{font-size:2.76444em}.katex .fontsize-ensurer.reset-size6.size1,.katex .sizing.reset-size6.size1{font-size:.5em}.katex .fontsize-ensurer.reset-size6.size2,.katex .sizing.reset-size6.size2{font-size:.6em}.katex .fontsize-ensurer.reset-size6.size3,.katex .sizing.reset-size6.size3{font-size:.7em}.katex .fontsize-ensurer.reset-size6.size4,.katex .sizing.reset-size6.size4{font-size:.8em}.katex .fontsize-ensurer.reset-size6.size5,.katex .sizing.reset-size6.size5{font-size:.9em}.katex .fontsize-ensurer.reset-size6.size6,.katex .sizing.reset-size6.size6{font-size:1em}.katex .fontsize-ensurer.reset-size6.size7,.katex .sizing.reset-size6.size7{font-size:1.2em}.katex .fontsize-ensurer.reset-size6.size8,.katex .sizing.reset-size6.size8{font-size:1.44em}.katex .fontsize-ensurer.reset-size6.size9,.katex .sizing.reset-size6.size9{font-size:1.728em}.katex .fontsize-ensurer.reset-size6.size10,.katex .sizing.reset-size6.size10{font-size:2.074em}.katex .fontsize-ensurer.reset-size6.size11,.katex .sizing.reset-size6.size11{font-size:2.488em}.katex .fontsize-ensurer.reset-size7.size1,.katex .sizing.reset-size7.size1{font-size:.416667em}.katex .fontsize-ensurer.reset-size7.size2,.katex .sizing.reset-size7.size2{font-size:.5em}.katex .fontsize-ensurer.reset-size7.size3,.katex .sizing.reset-size7.size3{font-size:.583333em}.katex .fontsize-ensurer.reset-size7.size4,.katex .sizing.reset-size7.size4{font-size:.666667em}.katex .fontsize-ensurer.reset-size7.size5,.katex .sizing.reset-size7.size5{font-size:.75em}.katex .fontsize-ensurer.reset-size7.size6,.katex .sizing.reset-size7.size6{font-size:.833333em}.katex .fontsize-ensurer.reset-size7.size7,.katex .sizing.reset-size7.size7{font-size:1em}.katex .fontsize-ensurer.reset-size7.size8,.katex .sizing.reset-size7.size8{font-size:1.2em}.katex .fontsize-ensurer.reset-size7.size9,.katex .sizing.reset-size7.size9{font-size:1.44em}.katex .fontsize-ensurer.reset-size7.size10,.katex .sizing.reset-size7.size10{font-size:1.72833em}.katex .fontsize-ensurer.reset-size7.size11,.katex .sizing.reset-size7.size11{font-size:2.07333em}.katex .fontsize-ensurer.reset-size8.size1,.katex .sizing.reset-size8.size1{font-size:.347222em}.katex .fontsize-ensurer.reset-size8.size2,.katex .sizing.reset-size8.size2{font-size:.416667em}.katex .fontsize-ensurer.reset-size8.size3,.katex .sizing.reset-size8.size3{font-size:.486111em}.katex .fontsize-ensurer.reset-size8.size4,.katex .sizing.reset-size8.size4{font-size:.555556em}.katex .fontsize-ensurer.reset-size8.size5,.katex .sizing.reset-size8.size5{font-size:.625em}.katex .fontsize-ensurer.reset-size8.size6,.katex .sizing.reset-size8.size6{font-size:.694444em}.katex .fontsize-ensurer.reset-size8.size7,.katex .sizing.reset-size8.size7{font-size:.833333em}.katex .fontsize-ensurer.reset-size8.size8,.katex .sizing.reset-size8.size8{font-size:1em}.katex .fontsize-ensurer.reset-size8.size9,.katex .sizing.reset-size8.size9{font-size:1.2em}.katex .fontsize-ensurer.reset-size8.size10,.katex .sizing.reset-size8.size10{font-size:1.44028em}.katex .fontsize-ensurer.reset-size8.size11,.katex .sizing.reset-size8.size11{font-size:1.72778em}.katex .fontsize-ensurer.reset-size9.size1,.katex .sizing.reset-size9.size1{font-size:.289352em}.katex .fontsize-ensurer.reset-size9.size2,.katex .sizing.reset-size9.size2{font-size:.347222em}.katex .fontsize-ensurer.reset-size9.size3,.katex .sizing.reset-size9.size3{font-size:.405093em}.katex .fontsize-ensurer.reset-size9.size4,.katex .sizing.reset-size9.size4{font-size:.462963em}.katex .fontsize-ensurer.reset-size9.size5,.katex .sizing.reset-size9.size5{font-size:.520833em}.katex .fontsize-ensurer.reset-size9.size6,.katex .sizing.reset-size9.size6{font-size:.578704em}.katex .fontsize-ensurer.reset-size9.size7,.katex .sizing.reset-size9.size7{font-size:.694444em}.katex .fontsize-ensurer.reset-size9.size8,.katex .sizing.reset-size9.size8{font-size:.833333em}.katex .fontsize-ensurer.reset-size9.size9,.katex .sizing.reset-size9.size9{font-size:1em}.katex .fontsize-ensurer.reset-size9.size10,.katex .sizing.reset-size9.size10{font-size:1.20023em}.katex .fontsize-ensurer.reset-size9.size11,.katex .sizing.reset-size9.size11{font-size:1.43981em}.katex .fontsize-ensurer.reset-size10.size1,.katex .sizing.reset-size10.size1{font-size:.24108em}.katex .fontsize-ensurer.reset-size10.size2,.katex .sizing.reset-size10.size2{font-size:.289296em}.katex .fontsize-ensurer.reset-size10.size3,.katex .sizing.reset-size10.size3{font-size:.337512em}.katex .fontsize-ensurer.reset-size10.size4,.katex .sizing.reset-size10.size4{font-size:.385728em}.katex .fontsize-ensurer.reset-size10.size5,.katex .sizing.reset-size10.size5{font-size:.433944em}.katex .fontsize-ensurer.reset-size10.size6,.katex .sizing.reset-size10.size6{font-size:.48216em}.katex .fontsize-ensurer.reset-size10.size7,.katex .sizing.reset-size10.size7{font-size:.578592em}.katex .fontsize-ensurer.reset-size10.size8,.katex .sizing.reset-size10.size8{font-size:.694311em}.katex .fontsize-ensurer.reset-size10.size9,.katex .sizing.reset-size10.size9{font-size:.833173em}.katex .fontsize-ensurer.reset-size10.size10,.katex .sizing.reset-size10.size10{font-size:1em}.katex .fontsize-ensurer.reset-size10.size11,.katex .sizing.reset-size10.size11{font-size:1.19961em}.katex .fontsize-ensurer.reset-size11.size1,.katex .sizing.reset-size11.size1{font-size:.200965em}.katex .fontsize-ensurer.reset-size11.size2,.katex .sizing.reset-size11.size2{font-size:.241158em}.katex .fontsize-ensurer.reset-size11.size3,.katex .sizing.reset-size11.size3{font-size:.281351em}.katex .fontsize-ensurer.reset-size11.size4,.katex .sizing.reset-size11.size4{font-size:.321543em}.katex .fontsize-ensurer.reset-size11.size5,.katex .sizing.reset-size11.size5{font-size:.361736em}.katex .fontsize-ensurer.reset-size11.size6,.katex .sizing.reset-size11.size6{font-size:.401929em}.katex .fontsize-ensurer.reset-size11.size7,.katex .sizing.reset-size11.size7{font-size:.482315em}.katex .fontsize-ensurer.reset-size11.size8,.katex .sizing.reset-size11.size8{font-size:.578778em}.katex .fontsize-ensurer.reset-size11.size9,.katex .sizing.reset-size11.size9{font-size:.694534em}.katex .fontsize-ensurer.reset-size11.size10,.katex .sizing.reset-size11.size10{font-size:.833601em}.katex .fontsize-ensurer.reset-size11.size11,.katex .sizing.reset-size11.size11{font-size:1em}.katex .delimsizing.size1{font-family:KaTeX_Size1}.katex .delimsizing.size2{font-family:KaTeX_Size2}.katex .delimsizing.size3{font-family:KaTeX_Size3}.katex .delimsizing.size4{font-family:KaTeX_Size4}.katex .delimsizing.mult .delim-size1>span{font-family:KaTeX_Size1}.katex .delimsizing.mult .delim-size4>span{font-family:KaTeX_Size4}.katex .nulldelimiter{width:.12em;display:inline-block}.katex .delimcenter,.katex .op-symbol{position:relative}.katex .op-symbol.small-op{font-family:KaTeX_Size1}.katex .op-symbol.large-op{font-family:KaTeX_Size2}.katex .accent>.vlist-t,.katex .op-limits>.vlist-t{text-align:center}.katex .accent .accent-body{position:relative}.katex .accent .accent-body:not(.accent-full){width:0}.katex .overlay{display:block}.katex .mtable .vertical-separator{min-width:1px;display:inline-block}.katex .mtable .arraycolsep{display:inline-block}.katex .mtable .col-align-c>.vlist-t{text-align:center}.katex .mtable .col-align-l>.vlist-t{text-align:left}.katex .mtable .col-align-r>.vlist-t{text-align:right}.katex .svg-align{text-align:left}.katex svg{fill:currentColor;stroke:currentColor;fill-rule:nonzero;fill-opacity:1;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;height:inherit;width:100%;display:block;position:absolute}.katex svg path{stroke:none}.katex img{border-style:none;min-width:0;max-width:none;min-height:0;max-height:none}.katex .stretchy{width:100%;display:block;position:relative;overflow:hidden}.katex .stretchy:after,.katex .stretchy:before{content:""}.katex .hide-tail{width:100%;position:relative;overflow:hidden}.katex .halfarrow-left{width:50.2%;position:absolute;left:0;overflow:hidden}.katex .halfarrow-right{width:50.2%;position:absolute;right:0;overflow:hidden}.katex .brace-left{width:25.1%;position:absolute;left:0;overflow:hidden}.katex .brace-center{width:50%;position:absolute;left:25%;overflow:hidden}.katex .brace-right{width:25.1%;position:absolute;right:0;overflow:hidden}.katex .x-arrow-pad{padding:0 .5em}.katex .cd-arrow-pad{padding:0 .55556em 0 .27778em}.katex .mover,.katex .munder,.katex .x-arrow{text-align:center}.katex .boxpad{padding:0 .3em}.katex .fbox,.katex .fcolorbox{box-sizing:border-box;border:.04em solid}.katex .cancel-pad{padding:0 .2em}.katex .cancel-lap{margin-left:-.2em;margin-right:-.2em}.katex .sout{border-bottom-style:solid;border-bottom-width:.08em}.katex .angl{box-sizing:border-box;border-top:.049em solid;border-right:.049em solid;margin-right:.03889em}.katex .anglpad{padding:0 .03889em}.katex .eqn-num:before{content:"(" counter(katexEqnNo) ")";counter-increment:katexEqnNo}.katex .mml-eqn-num:before{content:"(" counter(mmlEqnNo) ")";counter-increment:mmlEqnNo}.katex .mtr-glue{width:50%}.katex .cd-vert-arrow{display:inline-block;position:relative}.katex .cd-label-left{text-align:left;display:inline-block;position:absolute;right:calc(50% + .3em)}.katex .cd-label-right{text-align:right;display:inline-block;position:absolute;left:calc(50% + .3em)}.katex-display{text-align:center;margin:1em 0;display:block}.katex-display>.katex{text-align:center;white-space:nowrap;display:block}.katex-display>.katex>.katex-html{display:block;position:relative}.katex-display>.katex>.katex-html>.tag{position:absolute;right:0}.katex-display.leqno>.katex>.katex-html>.tag{left:0;right:auto}.katex-display.fleqn>.katex{text-align:left;padding-left:2em}body{counter-reset:katexEqnNo mmlEqnNo}.katex-display{margin:0}.markdown-content h1{margin-top:calc(var(--spacing) * 5);margin-bottom:calc(var(--spacing) * 2);font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content h2{margin-top:calc(var(--spacing) * 4);margin-bottom:calc(var(--spacing) * 2);font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content h3{margin-top:calc(var(--spacing) * 3);margin-bottom:calc(var(--spacing) * 2);font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content h4{margin-top:calc(var(--spacing) * 3);margin-bottom:calc(var(--spacing) * 2);font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content h5{margin-top:calc(var(--spacing) * 2);margin-bottom:calc(var(--spacing) * 1);font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content h6{margin-top:calc(var(--spacing) * 2);margin-bottom:calc(var(--spacing) * 1);font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height));--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content p{margin-top:calc(var(--spacing) * 4);--tw-leading:var(--leading-relaxed);max-width:100%;line-height:var(--leading-relaxed)}.markdown-content p:first-child{margin-top:calc(var(--spacing) * 0)}.markdown-content a{color:var(--primary);text-decoration-line:underline}@media (hover:hover){.markdown-content a:hover{color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.markdown-content a:hover{color:color-mix(in oklab, var(--primary) 80%, transparent)}}}.markdown-content strong{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.markdown-content em{font-style:italic}.markdown-content ul{margin-block:calc(var(--spacing) * 4);list-style-type:disc}:where(.markdown-content ul>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}.markdown-content ul{padding-left:calc(var(--spacing) * 6)}.markdown-content ol{margin-block:calc(var(--spacing) * 4);list-style-type:decimal}:where(.markdown-content ol>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}.markdown-content ol{padding-left:calc(var(--spacing) * 6)}.markdown-content li{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.markdown-content li>ul,.markdown-content li>ol{margin-top:calc(var(--spacing) * 2);margin-bottom:calc(var(--spacing) * 0)}.markdown-content li>p{margin-bottom:calc(var(--spacing) * 2)}.markdown-content li>p:last-child{margin-bottom:calc(var(--spacing) * 0)}.markdown-content blockquote{margin-block:calc(var(--spacing) * 4);border-left-style:var(--tw-border-style);border-left-width:4px;border-color:var(--border);padding-left:calc(var(--spacing) * 4);color:var(--muted-foreground)}.markdown-content code:not(.hljs){background-color:var(--muted);padding-inline:calc(var(--spacing) * 1.5);padding-block:calc(var(--spacing) * .5);font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height));color:var(--foreground);border-radius:.25rem}.markdown-content table{margin:calc(var(--spacing) * 0);border-collapse:collapse;width:100%}.markdown-content th{border-right-style:var(--tw-border-style);border-right-width:1px;border-bottom-style:var(--tw-border-style);border-bottom-width:1px;border-color:var(--border);background-color:var(--muted);padding:calc(var(--spacing) * 2);text-align:left;--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold);color:var(--foreground)}.markdown-content th:last-child{border-right-style:var(--tw-border-style);border-right-width:0}.markdown-content td{border-right-style:var(--tw-border-style);border-right-width:1px;border-bottom-style:var(--tw-border-style);border-bottom-width:1px;border-color:var(--border);padding:calc(var(--spacing) * 2);color:var(--foreground)}.markdown-content td:last-child{border-right-style:var(--tw-border-style);border-right-width:0}.markdown-content tr:last-child td{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.markdown-content hr{margin-block:calc(var(--spacing) * 8);border-style:var(--tw-border-style);border-width:0;border-top-style:var(--tw-border-style);border-top-width:1px;border-color:var(--border)}:root,:host{--color-foreground:var(--foreground);--color-border:var(--border);--shadow-2xs:var(--shadow-2xs);--shadow-xs:var(--shadow-xs);--shadow-sm:var(--shadow-sm);--shadow:var(--shadow);--shadow-md:var(--shadow-md);--shadow-lg:var(--shadow-lg);--shadow-xl:var(--shadow-xl);--shadow-2xl:var(--shadow-2xl);--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-300:oklch(80.8% .114 19.571);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-orange-400:oklch(75% .183 55.934);--color-orange-500:oklch(70.5% .213 47.604);--color-orange-600:oklch(64.6% .222 41.116);--color-yellow-300:oklch(90.5% .182 98.111);--color-yellow-400:oklch(85.2% .199 91.936);--color-yellow-500:oklch(79.5% .184 86.047);--color-yellow-700:oklch(55.4% .135 66.442);--color-green-300:oklch(87.1% .15 154.449);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-green-700:oklch(52.7% .154 150.069);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-blue-300:oklch(80.9% .105 251.813);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-700:oklch(48.8% .243 264.376);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-600:oklch(44.6% .03 256.802);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-lg:32rem;--container-2xl:42rem;--container-3xl:48rem;--container-4xl:56rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height:calc(1.5 / 1);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--font-weight-light:300;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-tight:-.025em;--leading-tight:1.25;--leading-relaxed:1.625;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--animate-spin:spin 1s linear infinite;--animate-pulse:pulse 2s cubic-bezier(.4, 0, .6, 1) infinite;--blur-sm:8px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}:root{--background:oklch(100% 0 0);--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--popover:oklch(100% 0 0);--popover-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--muted:oklch(97% 0 0);--muted-foreground:oklch(55.6% 0 0);--accent:oklch(97% 0 0);--accent-foreground:oklch(40% .18 240);--destructive:oklch(57.7% .245 27.325);--destructive-foreground:oklch(100% 0 0);--border:oklch(92.2% 0 0);--input:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--chart-1:oklch(81% .1 252);--chart-2:oklch(53.553% .02798 259.829);--chart-3:oklch(55% .22 263);--chart-4:oklch(49% .22 264);--chart-5:oklch(42% .18 266);--sidebar:oklch(98.5% 0 0);--sidebar-foreground:oklch(14.5% 0 0);--sidebar-primary:oklch(20.5% 0 0);--sidebar-primary-foreground:oklch(98.5% 0 0);--sidebar-accent:oklch(97% 0 0);--sidebar-accent-foreground:oklch(20.5% 0 0);--sidebar-border:oklch(92.2% 0 0);--sidebar-ring:oklch(70.8% 0 0);--font-sans:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--radius:.625rem;--shadow-2xs:0 1px 3px 0px #0000000d;--shadow-xs:0 1px 3px 0px #0000000d;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-md:0 1px 3px 0px #0000001a, 0 2px 4px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--shadow-xl:0 1px 3px 0px #0000001a, 0 8px 10px -1px #0000001a;--shadow-2xl:0 1px 3px 0px #00000040;--tracking-normal:0em;--spacing:.25rem}.dark{--background:oklch(14.5% 0 0);--foreground:oklch(98.5% 0 0);--card:oklch(20.5% 0 0);--card-foreground:oklch(98.5% 0 0);--popover:oklch(26.9% 0 0);--popover-foreground:oklch(98.5% 0 0);--primary:oklch(92.2% 0 0);--primary-foreground:oklch(20.5% 0 0);--secondary:oklch(26.9% 0 0);--secondary-foreground:oklch(98.5% 0 0);--muted:oklch(26.9% 0 0);--muted-foreground:oklch(70.8% 0 0);--accent:oklch(37.1% 0 0);--accent-foreground:oklch(75% .18 85);--destructive:oklch(70.4% .191 22.216);--destructive-foreground:oklch(98.5% 0 0);--border:oklch(27.5% 0 0);--input:oklch(32.5% 0 0);--ring:oklch(55.6% 0 0);--chart-1:oklch(81% .1 252);--chart-2:oklch(62% .19 260);--chart-3:oklch(55% .22 263);--chart-4:oklch(49% .22 264);--chart-5:oklch(42% .18 266);--sidebar:oklch(20.5% 0 0);--sidebar-foreground:oklch(98.5% 0 0);--sidebar-primary:oklch(48.8% .243 264.376);--sidebar-primary-foreground:oklch(98.5% 0 0);--sidebar-accent:oklch(26.9% 0 0);--sidebar-accent-foreground:oklch(98.5% 0 0);--sidebar-border:oklch(27.5% 0 0);--sidebar-ring:oklch(43.9% 0 0);--font-sans:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-serif:ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--radius:.625rem;--shadow-2xs:0 1px 3px 0px #0000000d;--shadow-xs:0 1px 3px 0px #0000000d;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-md:0 1px 3px 0px #0000001a, 0 2px 4px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--shadow-xl:0 1px 3px 0px #0000001a, 0 8px 10px -1px #0000001a;--shadow-2xl:0 1px 3px 0px #00000040}@layer theme;@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing) * 0)}.start{inset-inline-start:var(--spacing)}.end{inset-inline-end:var(--spacing)}.-top-1{top:calc(var(--spacing) * -1)}.-top-3{top:calc(var(--spacing) * -3)}.top-0{top:calc(var(--spacing) * 0)}.top-1\/2{top:50%}.top-4{top:calc(var(--spacing) * 4)}.top-5{top:calc(var(--spacing) * 5)}.top-full{top:100%}.-right-1{right:calc(var(--spacing) * -1)}.right-0{right:calc(var(--spacing) * 0)}.right-2{right:calc(var(--spacing) * 2)}.right-4{right:calc(var(--spacing) * 4)}.right-5{right:calc(var(--spacing) * 5)}.-bottom-4{bottom:calc(var(--spacing) * -4)}.bottom-0{bottom:calc(var(--spacing) * 0)}.left-0{left:calc(var(--spacing) * 0)}.left-1\/2{left:50%}.left-4{left:calc(var(--spacing) * 4)}.z-10{z-index:10}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.z-\[9999\]{z-index:9999}.col-start-2{grid-column-start:2}.row-span-2{grid-row:span 2/span 2}.row-start-1{grid-row-start:1}.float-left{float:left}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-0{margin:calc(var(--spacing) * 0)}.mx-1{margin-inline:calc(var(--spacing) * 1)}.mx-4{margin-inline:calc(var(--spacing) * 4)}.mx-auto{margin-inline:auto}.-my-8{margin-block:calc(var(--spacing) * -8)}.my-2{margin-block:calc(var(--spacing) * 2)}.my-4{margin-block:calc(var(--spacing) * 4)}.my-8{margin-block:calc(var(--spacing) * 8)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:calc(var(--spacing) * 1)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-12{margin-top:calc(var(--spacing) * 12)}.mr-2{margin-right:calc(var(--spacing) * 2)}.mb-1{margin-bottom:calc(var(--spacing) * 1)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-8{margin-bottom:calc(var(--spacing) * 8)}.mb-10{margin-bottom:calc(var(--spacing) * 10)}.mb-12{margin-bottom:calc(var(--spacing) * 12)}.mb-16{margin-bottom:calc(var(--spacing) * 16)}.mb-26{margin-bottom:calc(var(--spacing) * 26)}.-ml-6{margin-left:calc(var(--spacing) * -6)}.ml-1{margin-left:calc(var(--spacing) * 1)}.ml-2{margin-left:calc(var(--spacing) * 2)}.ml-4{margin-left:calc(var(--spacing) * 4)}.ml-6{margin-left:calc(var(--spacing) * 6)}.ml-auto{margin-left:auto}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.aspect-square{aspect-ratio:1}.size-8{width:calc(var(--spacing) * 8);height:calc(var(--spacing) * 8)}.h-1{height:calc(var(--spacing) * 1)}.h-2{height:calc(var(--spacing) * 2)}.h-3{height:calc(var(--spacing) * 3)}.h-3\.5{height:calc(var(--spacing) * 3.5)}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-8{height:calc(var(--spacing) * 8)}.h-9{height:calc(var(--spacing) * 9)}.h-10{height:calc(var(--spacing) * 10)}.h-12{height:calc(var(--spacing) * 12)}.h-16{height:calc(var(--spacing) * 16)}.h-20{height:calc(var(--spacing) * 20)}.h-\[1px\]{height:1px}.h-auto{height:auto}.h-full{height:100%}.h-px{height:1px}.max-h-0{max-height:calc(var(--spacing) * 0)}.max-h-16{max-height:calc(var(--spacing) * 16)}.max-h-48{max-height:calc(var(--spacing) * 48)}.max-h-64{max-height:calc(var(--spacing) * 64)}.max-h-96{max-height:calc(var(--spacing) * 96)}.max-h-\[200px\]{max-height:200px}.max-h-\[2000px\]{max-height:2000px}.max-h-full{max-height:100%}.min-h-0{min-height:calc(var(--spacing) * 0)}.min-h-\[80px\]{min-height:80px}.min-h-\[100px\]{min-height:100px}.min-h-\[200px\]{min-height:200px}.min-h-screen{min-height:100vh}.w-1{width:calc(var(--spacing) * 1)}.w-1\/2{width:50%}.w-1\/3{width:33.3333%}.w-2{width:calc(var(--spacing) * 2)}.w-3{width:calc(var(--spacing) * 3)}.w-3\.5{width:calc(var(--spacing) * 3.5)}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-6{width:calc(var(--spacing) * 6)}.w-8{width:calc(var(--spacing) * 8)}.w-11{width:calc(var(--spacing) * 11)}.w-12{width:calc(var(--spacing) * 12)}.w-16{width:calc(var(--spacing) * 16)}.w-48{width:calc(var(--spacing) * 48)}.w-64{width:calc(var(--spacing) * 64)}.w-240{width:calc(var(--spacing) * 240)}.w-\[1px\]{width:1px}.w-fit{width:fit-content}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-3xl{max-width:var(--container-3xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-\[120px\]{max-width:120px}.max-w-\[150px\]{max-width:150px}.max-w-\[200px\]{max-width:200px}.max-w-\[320px\]{max-width:320px}.max-w-\[400px\]{max-width:400px}.max-w-\[1000px\]{max-width:1000px}.max-w-full{max-width:100%}.max-w-lg{max-width:var(--container-lg)}.max-w-md{max-width:var(--container-md)}.max-w-none{max-width:none}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[80px\]{min-width:80px}.min-w-\[120px\]{min-width:120px}.min-w-\[300px\]{min-width:300px}.flex-1{flex:1}.flex-shrink-0,.shrink-0{flex-shrink:0}.grow{flex-grow:1}.border-collapse{border-collapse:collapse}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-x-full{--tw-translate-x:-100%;translate:var(--tw-translate-x) var(--tw-translate-y)}.translate-x-0{--tw-translate-x:calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.-translate-y-1\/2{--tw-translate-y:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.rotate-90{rotate:90deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.animate-pulse{animation:var(--animate-pulse)}.animate-spin{animation:var(--animate-spin)}.cursor-col-resize{cursor:col-resize}.cursor-default{cursor:default}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.cursor-row-resize{cursor:row-resize}.resize{resize:both}.resize-none{resize:none}.resize-x{resize:horizontal}.resize-y{resize:vertical}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.list-disc{list-style-type:disc}.auto-rows-min{grid-auto-rows:min-content}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.grid-rows-\[auto_auto\]{grid-template-rows:auto auto}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.flex-wrap{flex-wrap:wrap}.items-baseline{align-items:baseline}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-6{gap:calc(var(--spacing) * 6)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 1) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 1) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-6>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 6) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 6) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-24>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 24) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 24) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-4{column-gap:calc(var(--spacing) * 4)}:where(.space-x-2>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 2) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-x-reverse)))}:where(.space-x-3>:not(:last-child)){--tw-space-x-reverse:0;margin-inline-start:calc(calc(var(--spacing) * 3) * var(--tw-space-x-reverse));margin-inline-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-x-reverse)))}.gap-y-1{row-gap:calc(var(--spacing) * 1)}.self-start{align-self:flex-start}.justify-self-end{justify-self:flex-end}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.\!rounded-none{border-radius:0!important}.rounded{border-radius:.25rem}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:calc(var(--radius) + 4px)}.rounded-t-md{border-top-left-radius:calc(var(--radius) - 2px);border-top-right-radius:calc(var(--radius) - 2px)}.rounded-b-lg{border-bottom-right-radius:var(--radius);border-bottom-left-radius:var(--radius)}.rounded-b-md{border-bottom-right-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\!border-0{border-style:var(--tw-border-style)!important;border-width:0!important}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-2{border-style:var(--tw-border-style);border-width:2px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-2{border-top-style:var(--tw-border-style);border-top-width:2px}.border-r{border-right-style:var(--tw-border-style);border-right-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-b-2{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.border-l{border-left-style:var(--tw-border-style);border-left-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-border{border-color:var(--border)}.border-destructive,.border-destructive\/20{border-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.border-destructive\/20{border-color:color-mix(in oklab, var(--destructive) 20%, transparent)}}.border-destructive\/50{border-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.border-destructive\/50{border-color:color-mix(in oklab, var(--destructive) 50%, transparent)}}.border-gray-300{border-color:var(--color-gray-300)}.border-input{border-color:var(--input)}.border-orange-500\/20{border-color:#fe6e0033}@supports (color:color-mix(in lab, red, red)){.border-orange-500\/20{border-color:color-mix(in oklab, var(--color-orange-500) 20%, transparent)}}.border-orange-500\/30{border-color:#fe6e004d}@supports (color:color-mix(in lab, red, red)){.border-orange-500\/30{border-color:color-mix(in oklab, var(--color-orange-500) 30%, transparent)}}.border-orange-500\/50{border-color:#fe6e0080}@supports (color:color-mix(in lab, red, red)){.border-orange-500\/50{border-color:color-mix(in oklab, var(--color-orange-500) 50%, transparent)}}.border-primary,.border-primary\/30{border-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.border-primary\/30{border-color:color-mix(in oklab, var(--primary) 30%, transparent)}}.border-transparent{border-color:#0000}.\!bg-background{background-color:var(--background)!important}.\!bg-transparent{background-color:#0000!important}.bg-accent,.bg-accent\/30{background-color:var(--accent)}@supports (color:color-mix(in lab, red, red)){.bg-accent\/30{background-color:color-mix(in oklab, var(--accent) 30%, transparent)}}.bg-accent\/50{background-color:var(--accent)}@supports (color:color-mix(in lab, red, red)){.bg-accent\/50{background-color:color-mix(in oklab, var(--accent) 50%, transparent)}}.bg-background,.bg-background\/90{background-color:var(--background)}@supports (color:color-mix(in lab, red, red)){.bg-background\/90{background-color:color-mix(in oklab, var(--background) 90%, transparent)}}.bg-background\/95{background-color:var(--background)}@supports (color:color-mix(in lab, red, red)){.bg-background\/95{background-color:color-mix(in oklab, var(--background) 95%, transparent)}}.bg-black\/50{background-color:#00000080}@supports (color:color-mix(in lab, red, red)){.bg-black\/50{background-color:color-mix(in oklab, var(--color-black) 50%, transparent)}}.bg-black\/90{background-color:#000000e6}@supports (color:color-mix(in lab, red, red)){.bg-black\/90{background-color:color-mix(in oklab, var(--color-black) 90%, transparent)}}.bg-blue-500\/20{background-color:#3080ff33}@supports (color:color-mix(in lab, red, red)){.bg-blue-500\/20{background-color:color-mix(in oklab, var(--color-blue-500) 20%, transparent)}}.bg-border{background-color:var(--border)}.bg-card{background-color:var(--card)}.bg-destructive,.bg-destructive\/10{background-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/10{background-color:color-mix(in oklab, var(--destructive) 10%, transparent)}}.bg-destructive\/20{background-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.bg-destructive\/20{background-color:color-mix(in oklab, var(--destructive) 20%, transparent)}}.bg-emerald-500\/15{background-color:#00bb7f26}@supports (color:color-mix(in lab, red, red)){.bg-emerald-500\/15{background-color:color-mix(in oklab, var(--color-emerald-500) 15%, transparent)}}.bg-green-500\/20{background-color:#00c75833}@supports (color:color-mix(in lab, red, red)){.bg-green-500\/20{background-color:color-mix(in oklab, var(--color-green-500) 20%, transparent)}}.bg-green-600{background-color:var(--color-green-600)}.bg-muted{background-color:var(--muted)}.bg-muted-foreground,.bg-muted-foreground\/30{background-color:var(--muted-foreground)}@supports (color:color-mix(in lab, red, red)){.bg-muted-foreground\/30{background-color:color-mix(in oklab, var(--muted-foreground) 30%, transparent)}}.bg-muted\/30{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/30{background-color:color-mix(in oklab, var(--muted) 30%, transparent)}}.bg-muted\/50{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/50{background-color:color-mix(in oklab, var(--muted) 50%, transparent)}}.bg-muted\/60{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.bg-muted\/60{background-color:color-mix(in oklab, var(--muted) 60%, transparent)}}.bg-orange-500\/5{background-color:#fe6e000d}@supports (color:color-mix(in lab, red, red)){.bg-orange-500\/5{background-color:color-mix(in oklab, var(--color-orange-500) 5%, transparent)}}.bg-orange-500\/10{background-color:#fe6e001a}@supports (color:color-mix(in lab, red, red)){.bg-orange-500\/10{background-color:color-mix(in oklab, var(--color-orange-500) 10%, transparent)}}.bg-orange-500\/20{background-color:#fe6e0033}@supports (color:color-mix(in lab, red, red)){.bg-orange-500\/20{background-color:color-mix(in oklab, var(--color-orange-500) 20%, transparent)}}.bg-popover{background-color:var(--popover)}.bg-primary{background-color:var(--primary)}.bg-primary-foreground\/20{background-color:var(--primary-foreground)}@supports (color:color-mix(in lab, red, red)){.bg-primary-foreground\/20{background-color:color-mix(in oklab, var(--primary-foreground) 20%, transparent)}}.bg-primary\/5{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.bg-primary\/5{background-color:color-mix(in oklab, var(--primary) 5%, transparent)}}.bg-primary\/10{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.bg-primary\/10{background-color:color-mix(in oklab, var(--primary) 10%, transparent)}}.bg-primary\/20{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.bg-primary\/20{background-color:color-mix(in oklab, var(--primary) 20%, transparent)}}.bg-red-500\/15{background-color:#fb2c3626}@supports (color:color-mix(in lab, red, red)){.bg-red-500\/15{background-color:color-mix(in oklab, var(--color-red-500) 15%, transparent)}}.bg-red-500\/20{background-color:#fb2c3633}@supports (color:color-mix(in lab, red, red)){.bg-red-500\/20{background-color:color-mix(in oklab, var(--color-red-500) 20%, transparent)}}.bg-secondary,.bg-secondary\/5{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.bg-secondary\/5{background-color:color-mix(in oklab, var(--secondary) 5%, transparent)}}.bg-secondary\/20{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.bg-secondary\/20{background-color:color-mix(in oklab, var(--secondary) 20%, transparent)}}.bg-secondary\/30{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.bg-secondary\/30{background-color:color-mix(in oklab, var(--secondary) 30%, transparent)}}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.bg-yellow-500\/20{background-color:#edb20033}@supports (color:color-mix(in lab, red, red)){.bg-yellow-500\/20{background-color:color-mix(in oklab, var(--color-yellow-500) 20%, transparent)}}.bg-gradient-to-r{--tw-gradient-position:to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-muted-foreground{--tw-gradient-from:var(--muted-foreground);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-orange-600{--tw-gradient-from:var(--color-orange-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-foreground{--tw-gradient-via:var(--foreground);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-muted-foreground{--tw-gradient-to:var(--muted-foreground);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-yellow-400{--tw-gradient-to:var(--color-yellow-400);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.bg-\[length\:200\%_100\%\]{background-size:200% 100%}.bg-clip-text{-webkit-background-clip:text;background-clip:text}.bg-center{background-position:50%}.bg-no-repeat{background-repeat:no-repeat}.object-contain{object-fit:contain}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing) * 0)}.p-1{padding:calc(var(--spacing) * 1)}.p-2{padding:calc(var(--spacing) * 2)}.p-2\.5{padding:calc(var(--spacing) * 2.5)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.px-8{padding-inline:calc(var(--spacing) * 8)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:calc(var(--spacing) * 1)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-6{padding-block:calc(var(--spacing) * 6)}.py-8{padding-block:calc(var(--spacing) * 8)}.py-10{padding-block:calc(var(--spacing) * 10)}.py-15{padding-block:calc(var(--spacing) * 15)}.py-16{padding-block:calc(var(--spacing) * 16)}.pt-0{padding-top:calc(var(--spacing) * 0)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pt-4{padding-top:calc(var(--spacing) * 4)}.pt-10{padding-top:calc(var(--spacing) * 10)}.pr-6{padding-right:calc(var(--spacing) * 6)}.pr-8{padding-right:calc(var(--spacing) * 8)}.pb-0{padding-bottom:calc(var(--spacing) * 0)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.pb-6{padding-bottom:calc(var(--spacing) * 6)}.pl-2{padding-left:calc(var(--spacing) * 2)}.pl-4{padding-left:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[9px\]{font-size:9px}.text-\[10px\]{font-size:10px}.leading-none{--tw-leading:1;line-height:1}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-light{--tw-font-weight:var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-accent-foreground{color:var(--accent-foreground)}.text-blue-700{color:var(--color-blue-700)}.text-card-foreground{color:var(--card-foreground)}.text-destructive{color:var(--destructive)}.text-destructive-foreground{color:var(--destructive-foreground)}.text-emerald-600{color:var(--color-emerald-600)}.text-foreground{color:var(--foreground)}.text-gray-600{color:var(--color-gray-600)}.text-green-500{color:var(--color-green-500)}.text-green-600{color:var(--color-green-600)}.text-green-700{color:var(--color-green-700)}.text-muted-foreground,.text-muted-foreground\/50{color:var(--muted-foreground)}@supports (color:color-mix(in lab, red, red)){.text-muted-foreground\/50{color:color-mix(in oklab, var(--muted-foreground) 50%, transparent)}}.text-orange-500{color:var(--color-orange-500)}.text-popover-foreground{color:var(--popover-foreground)}.text-primary{color:var(--primary)}.text-primary-foreground{color:var(--primary-foreground)}.text-red-500{color:var(--color-red-500)}.text-red-600{color:var(--color-red-600)}.text-red-700{color:var(--color-red-700)}.text-secondary-foreground{color:var(--secondary-foreground)}.text-transparent{color:#0000}.text-white{color:var(--color-white)}.text-yellow-500{color:var(--color-yellow-500)}.text-yellow-700{color:var(--color-yellow-700)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,)}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.placeholder-muted-foreground::placeholder{color:var(--muted-foreground)}.opacity-0{opacity:0}.opacity-25{opacity:.25}.opacity-30{opacity:.3}.opacity-50{opacity:.5}.opacity-70{opacity:.7}.opacity-75{opacity:.75}.opacity-90{opacity:.9}.opacity-100{opacity:1}.shadow{--tw-shadow:var(--shadow);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-lg{--tw-shadow:var(--shadow-lg);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-md{--tw-shadow:var(--shadow-md);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:var(--shadow-sm);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:var(--shadow-xl);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xs{--tw-shadow:var(--shadow-xs);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-0{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-offset-background{--tw-ring-offset-color:var(--background)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.filter{filter:var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,)}.backdrop-blur{--tw-backdrop-blur:blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-blur-sm{--tw-backdrop-blur:blur(var(--blur-sm));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-shadow{transition-property:box-shadow;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.outline-none{--tw-outline-style:none;outline-style:none}.select-none{-webkit-user-select:none;user-select:none}@media (hover:hover){.group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}.peer-disabled\:cursor-not-allowed:is(:where(.peer):disabled~*){cursor:not-allowed}.peer-disabled\:opacity-70:is(:where(.peer):disabled~*){opacity:.7}.selection\:bg-primary ::selection{background-color:var(--primary)}.selection\:bg-primary::selection{background-color:var(--primary)}.selection\:text-primary-foreground ::selection{color:var(--primary-foreground)}.selection\:text-primary-foreground::selection{color:var(--primary-foreground)}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:calc(var(--spacing) * 7)}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-transparent::file-selector-button{background-color:#0000}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.placeholder\:text-muted-foreground::placeholder{color:var(--muted-foreground)}.before\:absolute:before{content:var(--tw-content);position:absolute}.before\:inset-x-0:before{content:var(--tw-content);inset-inline:calc(var(--spacing) * 0)}.before\:inset-y-0:before{content:var(--tw-content);inset-block:calc(var(--spacing) * 0)}.before\:-top-2:before{content:var(--tw-content);top:calc(var(--spacing) * -2)}.before\:-right-2:before{content:var(--tw-content);right:calc(var(--spacing) * -2)}.before\:-bottom-2:before{content:var(--tw-content);bottom:calc(var(--spacing) * -2)}.before\:-left-2:before{content:var(--tw-content);left:calc(var(--spacing) * -2)}.before\:h-5:before{content:var(--tw-content);height:calc(var(--spacing) * 5)}.before\:w-5:before{content:var(--tw-content);width:calc(var(--spacing) * 5)}.before\:content-\[\'\'\]:before{--tw-content:"";content:var(--tw-content)}.last\:mb-0:last-child{margin-bottom:calc(var(--spacing) * 0)}@media (hover:hover){.hover\:border-b-2:hover{border-bottom-style:var(--tw-border-style);border-bottom-width:2px}.hover\:border-border:hover{border-color:var(--border)}.hover\:border-orange-500\/50:hover{border-color:#fe6e0080}@supports (color:color-mix(in lab, red, red)){.hover\:border-orange-500\/50:hover{border-color:color-mix(in oklab, var(--color-orange-500) 50%, transparent)}}.hover\:\!bg-accent:hover{background-color:var(--accent)!important}.hover\:bg-accent:hover,.hover\:bg-accent\/50:hover{background-color:var(--accent)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-accent\/50:hover{background-color:color-mix(in oklab, var(--accent) 50%, transparent)}}.hover\:bg-destructive\/10:hover{background-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/10:hover{background-color:color-mix(in oklab, var(--destructive) 10%, transparent)}}.hover\:bg-destructive\/80:hover{background-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/80:hover{background-color:color-mix(in oklab, var(--destructive) 80%, transparent)}}.hover\:bg-destructive\/90:hover{background-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-destructive\/90:hover{background-color:color-mix(in oklab, var(--destructive) 90%, transparent)}}.hover\:bg-muted:hover,.hover\:bg-muted\/30:hover{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/30:hover{background-color:color-mix(in oklab, var(--muted) 30%, transparent)}}.hover\:bg-muted\/50:hover{background-color:var(--muted)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-muted\/50:hover{background-color:color-mix(in oklab, var(--muted) 50%, transparent)}}.hover\:bg-orange-500\/30:hover{background-color:#fe6e004d}@supports (color:color-mix(in lab, red, red)){.hover\:bg-orange-500\/30:hover{background-color:color-mix(in oklab, var(--color-orange-500) 30%, transparent)}}.hover\:bg-primary\/80:hover{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-primary\/80:hover{background-color:color-mix(in oklab, var(--primary) 80%, transparent)}}.hover\:bg-primary\/90:hover{background-color:var(--primary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-primary\/90:hover{background-color:color-mix(in oklab, var(--primary) 90%, transparent)}}.hover\:bg-secondary:hover,.hover\:bg-secondary\/10:hover{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/10:hover{background-color:color-mix(in oklab, var(--secondary) 10%, transparent)}}.hover\:bg-secondary\/50:hover{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/50:hover{background-color:color-mix(in oklab, var(--secondary) 50%, transparent)}}.hover\:bg-secondary\/80:hover{background-color:var(--secondary)}@supports (color:color-mix(in lab, red, red)){.hover\:bg-secondary\/80:hover{background-color:color-mix(in oklab, var(--secondary) 80%, transparent)}}.hover\:bg-white\/20:hover{background-color:#fff3}@supports (color:color-mix(in lab, red, red)){.hover\:bg-white\/20:hover{background-color:color-mix(in oklab, var(--color-white) 20%, transparent)}}.hover\:text-accent-foreground:hover{color:var(--accent-foreground)}.hover\:text-foreground:hover{color:var(--foreground)}.hover\:text-orange-400:hover{color:var(--color-orange-400)}.hover\:text-orange-500:hover{color:var(--color-orange-500)}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-80:hover{opacity:.8}.hover\:opacity-100:hover{opacity:1}.hover\:shadow-lg:hover{--tw-shadow:var(--shadow-lg);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow:var(--shadow-md);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.hover\:shadow-orange-500\/20:hover{--tw-shadow-color:#fe6e0033}@supports (color:color-mix(in lab, red, red)){.hover\:shadow-orange-500\/20:hover{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-orange-500) 20%, transparent) var(--tw-shadow-alpha), transparent)}}}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-primary:focus{--tw-ring-color:var(--primary)}.focus\:ring-ring:focus{--tw-ring-color:var(--ring)}.focus\:ring-offset-2:focus{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus\:ring-offset-background:focus{--tw-ring-offset-color:var(--background)}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.focus-visible\:border-ring:focus-visible{border-color:var(--ring)}.focus-visible\:ring-2:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus-visible\:ring-ring:focus-visible,.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:var(--ring)}@supports (color:color-mix(in lab, red, red)){.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color:color-mix(in oklab, var(--ring) 50%, transparent)}}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width:2px;--tw-ring-offset-shadow:var(--tw-ring-inset,) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color:var(--background)}.focus-visible\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.has-\[ui-card-action\]\:grid-cols-\[1fr_auto\]:has(:is(ui-card-action)){grid-template-columns:1fr auto}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-inline:calc(var(--spacing) * 2.5)}.aria-invalid\:border-destructive[aria-invalid=true]{border-color:var(--destructive)}.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.aria-invalid\:ring-destructive\/20[aria-invalid=true]{--tw-ring-color:color-mix(in oklab, var(--destructive) 20%, transparent)}}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:var(--muted-foreground)}.data-\[state\=checked\]\:translate-x-5[data-state=checked]{--tw-translate-x:calc(var(--spacing) * 5);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:var(--primary)}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:var(--primary-foreground)}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x:calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:var(--input)}@media (min-width:40rem){.sm\:mb-1{margin-bottom:calc(var(--spacing) * 1)}.sm\:mb-2{margin-bottom:calc(var(--spacing) * 2)}.sm\:block{display:block}.sm\:hidden{display:none}.sm\:translate-x-0{--tw-translate-x:calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:px-8{padding-inline:calc(var(--spacing) * 8)}.sm\:py-4{padding-block:calc(var(--spacing) * 4)}.sm\:text-left{text-align:left}}@media (min-width:48rem){.md\:top-0{top:calc(var(--spacing) * 0)}.md\:right-0{right:calc(var(--spacing) * 0)}.md\:left-auto{left:auto}.md\:order-1{order:1}.md\:order-2{order:2}.md\:col-span-2{grid-column:span 2/span 2}.md\:float-none{float:none}.md\:m-0{margin:calc(var(--spacing) * 0)}.md\:mt-0{margin-top:calc(var(--spacing) * 0)}.md\:block{display:block}.md\:hidden{display:none}.md\:inline-block{display:inline-block}.md\:w-full{width:100%}.md\:translate-x-0{--tw-translate-x:calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:border-0{border-style:var(--tw-border-style);border-width:0}.md\:border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.md\:border-solid{--tw-border-style:solid;border-style:solid}.md\:border-gray-400{border-color:var(--color-gray-400)}.md\:p-0{padding:calc(var(--spacing) * 0)}.md\:px-8{padding-inline:calc(var(--spacing) * 8)}.md\:py-8{padding-block:calc(var(--spacing) * 8)}.md\:py-12{padding-block:calc(var(--spacing) * 12)}.md\:pr-0{padding-right:calc(var(--spacing) * 0)}.md\:pb-10{padding-bottom:calc(var(--spacing) * 10)}.md\:pl-6{padding-left:calc(var(--spacing) * 6)}.md\:text-left{text-align:left}.md\:text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.md\:text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.md\:text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.md\:before\:-top-1:before{content:var(--tw-content);top:calc(var(--spacing) * -1)}.md\:before\:-right-1:before{content:var(--tw-content);right:calc(var(--spacing) * -1)}.md\:before\:-bottom-1:before{content:var(--tw-content);bottom:calc(var(--spacing) * -1)}.md\:before\:-left-1:before{content:var(--tw-content);left:calc(var(--spacing) * -1)}.md\:before\:h-3:before{content:var(--tw-content);height:calc(var(--spacing) * 3)}.md\:before\:w-3:before{content:var(--tw-content);width:calc(var(--spacing) * 3)}}@media (min-width:64rem){.lg\:hidden{display:none}.lg\:w-full{width:100%}.lg\:translate-x-0{--tw-translate-x:calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}.lg\:px-8{padding-inline:calc(var(--spacing) * 8)}.lg\:pt-6{padding-top:calc(var(--spacing) * 6)}.lg\:text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}}@media (min-width:80rem){.xl\:hidden{display:none}.xl\:translate-x-0{--tw-translate-x:calc(var(--spacing) * 0);translate:var(--tw-translate-x) var(--tw-translate-y)}}.dark\:border-destructive:where(.dark,.dark *){border-color:var(--destructive)}.dark\:bg-input\/30:where(.dark,.dark *){background-color:var(--input)}@supports (color:color-mix(in lab, red, red)){.dark\:bg-input\/30:where(.dark,.dark *){background-color:color-mix(in oklab, var(--input) 30%, transparent)}}.dark\:text-blue-300:where(.dark,.dark *){color:var(--color-blue-300)}.dark\:text-gray-400:where(.dark,.dark *){color:var(--color-gray-400)}.dark\:text-green-300:where(.dark,.dark *){color:var(--color-green-300)}.dark\:text-green-400:where(.dark,.dark *){color:var(--color-green-400)}.dark\:text-green-500:where(.dark,.dark *){color:var(--color-green-500)}.dark\:text-red-300:where(.dark,.dark *){color:var(--color-red-300)}.dark\:text-yellow-300:where(.dark,.dark *){color:var(--color-yellow-300)}.dark\:aria-invalid\:ring-destructive\/40:where(.dark,.dark *)[aria-invalid=true]{--tw-ring-color:var(--destructive)}@supports (color:color-mix(in lab, red, red)){.dark\:aria-invalid\:ring-destructive\/40:where(.dark,.dark *)[aria-invalid=true]{--tw-ring-color:color-mix(in oklab, var(--destructive) 40%, transparent)}}.\[\&_p\]\:leading-relaxed p{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:calc(var(--spacing) * 4);height:calc(var(--spacing) * 4)}.\[\&\>\*\:last-child\]\:\!mb-0>:last-child{margin-bottom:calc(var(--spacing) * 0)!important}.\[\&\>button\]\:\!bg-transparent>button{background-color:#0000!important}@media (hover:hover){.\[\&\>button\]\:hover\:\!bg-accent>button:hover{background-color:var(--accent)!important}}.\[\&\>svg\]\:pointer-events-none>svg{pointer-events:none}.\[\&\>svg\]\:absolute>svg{position:absolute}.\[\&\>svg\]\:top-4>svg{top:calc(var(--spacing) * 4)}.\[\&\>svg\]\:left-4>svg{left:calc(var(--spacing) * 4)}.\[\&\>svg\]\:size-3>svg{width:calc(var(--spacing) * 3);height:calc(var(--spacing) * 3)}.\[\&\>svg\]\:text-destructive>svg{color:var(--destructive)}.\[\&\>svg\]\:text-foreground>svg{color:var(--foreground)}.\[\&\>svg\+div\]\:translate-y-\[-3px\]>svg+div{--tw-translate-y:-3px;translate:var(--tw-translate-x) var(--tw-translate-y)}.\[\&\>svg\~\*\]\:pl-7>svg~*{padding-left:calc(var(--spacing) * 7)}@media (hover:hover){.\[\@media\(hover\:hover\)\]\:opacity-0{opacity:0}@media (hover:hover){.\[\@media\(hover\:hover\)\]\:group-hover\:opacity-100:is(:where(.group):hover *){opacity:1}}}}body{-webkit-font-smoothing:antialiased;font-size:16px}*,:before,:after{transition:background-color .3s,color .3s,border-color .3s,fill .3s,stroke .3s}*{scrollbar-width:thin;scrollbar-color:var(--color-border) #0000}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:var(--color-border);border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#0000}@keyframes fadeInUp{0%{opacity:0;transform:translateY(30px)}to{opacity:1;transform:translateY(0)}}@keyframes fadeInOut{0%{opacity:0}15%,85%{opacity:1}to{opacity:0}}@keyframes shimmer{0%{background-position:-200%}to{background-position:200%}}.welcome-orb-container{animation:.8s ease-out fadeInUp;position:relative}.orb-container{background-color:var(--background);aspect-ratio:1;width:min(400px,30vh);height:min(400px,30vh);display:block}.orb-container canvas{background-color:var(--background);width:100%;height:100%}.rotating-word{animation:2s ease-in-out infinite fadeInOut}.tutorial-pill{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:linear-gradient(135deg,#d94f0026,#ff6b0026,#d4a50026);border:1px solid #ff6b004d;transition:all .3s cubic-bezier(.4,0,.2,1);position:relative;overflow:hidden}.tutorial-pill:before{content:"";opacity:0;background:linear-gradient(90deg,#0000,#ff6b0066,#0000) 0 0/200% 100%;transition:opacity .3s;animation:3s ease-in-out infinite shimmer;position:absolute;inset:0}.tutorial-pill:hover:before{opacity:1}.tutorial-pill:hover{background:linear-gradient(135deg,#d94f0040,#ff6b0040,#d4a50040);border-color:#ff6b0080;transform:translateY(-2px)scale(1.03);box-shadow:0 8px 20px -4px #ff6b0080}.tutorial-pill:active{transform:translateY(-1px)scale(1.01)}.user-message-container{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:linear-gradient(135deg,#d94f001f,#ff6b001f,#d4a5001f);border:1px solid #ff6b0040;max-width:100%;transition:all .2s cubic-bezier(.4,0,.2,1);position:relative}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-leading{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-x-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}@keyframes spin{to{transform:rotate(360deg)}}@keyframes pulse{50%{opacity:.5}} \ No newline at end of file diff --git a/background.js b/background.js new file mode 100644 index 0000000..7daa475 --- /dev/null +++ b/background.js @@ -0,0 +1,116 @@ +// src/background.ts +chrome.action.onClicked.addListener((tab) => { + const tabId = tab?.id; + if (tabId && chrome.sidePanel.open) { + chrome.sidePanel.open({ tabId }); + } +}); +console.log("[Background] onUserScriptMessage available:", !!chrome.runtime.onUserScriptMessage); +if (chrome.runtime.onUserScriptMessage) { + chrome.runtime.onUserScriptMessage.addListener((message, sender, sendResponse) => { + console.log("[Background] Received userScript message:", message, "from:", sender); + if (message.type === "abort-repl") { + console.log("[Background] Relaying abort-repl to sidepanels"); + chrome.runtime.sendMessage(message); + sendResponse({ success: true }); + return true; + } + }); + console.log("[Background] onUserScriptMessage listener registered"); +} else { + console.error("[Background] onUserScriptMessage NOT available!"); +} +var SIDEPANEL_OPEN_KEY = "sidepanel_open_windows"; +var SESSION_LOCKS_KEY = "session_locks"; +var openSidepanels = /* @__PURE__ */ new Set(); +chrome.storage.session.get(SIDEPANEL_OPEN_KEY, (data) => { + openSidepanels = new Set(data[SIDEPANEL_OPEN_KEY] || []); + console.log("[Background] Initialized openSidepanels cache:", Array.from(openSidepanels)); +}); +chrome.runtime.onConnect.addListener((port) => { + const match = /^sidepanel:(\d+)$/.exec(port.name); + if (!match) return; + const windowId = Number(match[1]); + openSidepanels.add(windowId); + chrome.storage.session.get(SIDEPANEL_OPEN_KEY, (data) => { + const openWindows = new Set(data[SIDEPANEL_OPEN_KEY] || []); + openWindows.add(windowId); + chrome.storage.session.set({ [SIDEPANEL_OPEN_KEY]: Array.from(openWindows) }); + }); + port.onMessage.addListener((msg) => { + if (msg.type === "acquireLock") { + const { sessionId, windowId: reqWindowId } = msg; + chrome.storage.session.get(SESSION_LOCKS_KEY, (data) => { + const sessionLocks = data[SESSION_LOCKS_KEY] || {}; + const ownerWindowId = sessionLocks[sessionId]; + const ownerSidepanelOpen = ownerWindowId !== void 0 && openSidepanels.has(ownerWindowId); + const success = !ownerWindowId || !ownerSidepanelOpen || ownerWindowId === reqWindowId; + const response = success ? { + type: "lockResult", + sessionId, + success: true + } : { + type: "lockResult", + sessionId, + success: false, + ownerWindowId + }; + if (success) { + sessionLocks[sessionId] = reqWindowId; + chrome.storage.session.set({ [SESSION_LOCKS_KEY]: sessionLocks }); + } + port.postMessage(response); + }); + } else if (msg.type === "getLockedSessions") { + chrome.storage.session.get(SESSION_LOCKS_KEY, (data) => { + const locks = data[SESSION_LOCKS_KEY] || {}; + const response = { + type: "lockedSessions", + locks + }; + port.postMessage(response); + }); + } + }); + port.onDisconnect.addListener(() => { + closeSidepanel(windowId, false); + }); +}); +chrome.windows.onRemoved.addListener((windowId) => { + closeSidepanel(windowId, false); +}); +chrome.commands.onCommand.addListener((command, sender) => { + if (command === "toggle-sidepanel") { + if (!sender?.windowId) { + console.log("[Background] Cannot toggle sidepanel: sender windowId not available"); + return; + } + const windowId = sender.windowId; + if (openSidepanels.has(windowId)) { + closeSidepanel(windowId); + } else { + chrome.sidePanel.open({ windowId }); + } + } +}); +function closeSidepanel(windowId, callCloseOnSidePanelAPI = true) { + if (callCloseOnSidePanelAPI) { + chrome.sidePanel.close({ windowId }); + } + openSidepanels.delete(windowId); + chrome.storage.session.get([SESSION_LOCKS_KEY, SIDEPANEL_OPEN_KEY], (data) => { + const sessionLocks = data[SESSION_LOCKS_KEY] || {}; + for (const sessionId in sessionLocks) { + if (sessionLocks[sessionId] === windowId) { + delete sessionLocks[sessionId]; + } + } + const openWindows = new Set(data[SIDEPANEL_OPEN_KEY] || []); + openWindows.delete(windowId); + chrome.storage.session.set({ + [SESSION_LOCKS_KEY]: sessionLocks, + [SIDEPANEL_OPEN_KEY]: Array.from(openWindows) + }); + }); +} +//# sourceMappingURL=background.js.map diff --git a/debug.html b/debug.html new file mode 100644 index 0000000..c90d594 --- /dev/null +++ b/debug.html @@ -0,0 +1,13 @@ + + + + + + Debug + + + + + + + diff --git a/debug.js b/debug.js new file mode 100644 index 0000000..e6bef18 --- /dev/null +++ b/debug.js @@ -0,0 +1,259996 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { + get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] +}) : x2)(function(x2) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x2 + '" is not supported'); +}); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __decorateClass = (decorators, target, key, kind) => { + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + for (var i7 = decorators.length - 1, decorator; i7 >= 0; i7--) + if (decorator = decorators[i7]) + result = (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) __defProp(target, key, result); + return result; +}; + +// scripts/process-shim.js +var processShim, process_shim_default, process; +var init_process_shim = __esm({ + "scripts/process-shim.js"() { + "use strict"; + processShim = { + browser: true, + env: {}, + cwd: () => "/", + platform: "browser", + version: "", + versions: {}, + argv: [], + pid: 0, + title: "browser", + nextTick: (fn, ...args) => Promise.resolve().then(() => fn(...args)), + stderr: {}, + stdout: {}, + stdin: {} + }; + process_shim_default = processShim; + process = processShim; + } +}); + +// ../pi-mono/node_modules/partial-json/dist/options.js +var require_options = __commonJS({ + "../pi-mono/node_modules/partial-json/dist/options.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Allow = exports.ALL = exports.COLLECTION = exports.ATOM = exports.SPECIAL = exports.INF = exports._INFINITY = exports.INFINITY = exports.NAN = exports.BOOL = exports.NULL = exports.OBJ = exports.ARR = exports.NUM = exports.STR = void 0; + exports.STR = 1; + exports.NUM = 2; + exports.ARR = 4; + exports.OBJ = 8; + exports.NULL = 16; + exports.BOOL = 32; + exports.NAN = 64; + exports.INFINITY = 128; + exports._INFINITY = 256; + exports.INF = exports.INFINITY | exports._INFINITY; + exports.SPECIAL = exports.NULL | exports.BOOL | exports.INF | exports.NAN; + exports.ATOM = exports.STR | exports.NUM | exports.SPECIAL; + exports.COLLECTION = exports.ARR | exports.OBJ; + exports.ALL = exports.ATOM | exports.COLLECTION; + exports.Allow = { STR: exports.STR, NUM: exports.NUM, ARR: exports.ARR, OBJ: exports.OBJ, NULL: exports.NULL, BOOL: exports.BOOL, NAN: exports.NAN, INFINITY: exports.INFINITY, _INFINITY: exports._INFINITY, INF: exports.INF, SPECIAL: exports.SPECIAL, ATOM: exports.ATOM, COLLECTION: exports.COLLECTION, ALL: exports.ALL }; + exports.default = exports.Allow; + } +}); + +// ../pi-mono/node_modules/partial-json/dist/index.js +var require_dist = __commonJS({ + "../pi-mono/node_modules/partial-json/dist/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Allow = exports.MalformedJSON = exports.PartialJSON = exports.parseJSON = exports.parse = void 0; + var options_1 = require_options(); + Object.defineProperty(exports, "Allow", { enumerable: true, get: function() { + return options_1.Allow; + } }); + __exportStar(require_options(), exports); + var PartialJSON2 = class extends Error { + }; + exports.PartialJSON = PartialJSON2; + var MalformedJSON2 = class extends Error { + }; + exports.MalformedJSON = MalformedJSON2; + function parseJSON3(jsonString, allowPartial = options_1.Allow.ALL) { + if (typeof jsonString !== "string") { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON2(jsonString.trim(), allowPartial); + } + exports.parseJSON = parseJSON3; + var _parseJSON2 = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON2(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON2(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) + markPartialJSON("Unexpected end of input"); + if (jsonString[index] === '"') + return parseStr(); + if (jsonString[index] === "{") + return parseObj(); + if (jsonString[index] === "[") + return parseArr(); + if (jsonString.substring(index, index + 4) === "null" || options_1.Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === "true" || options_1.Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === "false" || options_1.Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === "NaN" || options_1.Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape4 = false; + index++; + while (index < length && (jsonString[index] !== '"' || escape4 && jsonString[index - 1] === "\\")) { + escape4 = jsonString[index] === "\\" ? !escape4 : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape4))); + } catch (e9) { + throwMalformedError(String(e9)); + } + } else if (options_1.Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape4)) + '"'); + } catch (e9) { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"'); + } + } + markPartialJSON("Unterminated string literal"); + }; + const parseObj = () => { + index++; + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== "}") { + skipBlank(); + if (index >= length && options_1.Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index++; + try { + const value = parseAny(); + obj[key] = value; + } catch (e9) { + if (options_1.Allow.OBJ & allow) + return obj; + else + throw e9; + } + skipBlank(); + if (jsonString[index] === ",") + index++; + } + } catch (e9) { + if (options_1.Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index++; + return obj; + }; + const parseArr = () => { + index++; + const arr = []; + try { + while (jsonString[index] !== "]") { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ",") { + index++; + } + } + } catch (e9) { + if (options_1.Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === "-") + throwMalformedError("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } catch (e9) { + if (options_1.Allow.NUM & allow) + try { + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e"))); + } catch (e10) { + } + throwMalformedError(String(e9)); + } + } + const start = index; + if (jsonString[index] === "-") + index++; + while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1) + index++; + if (index == length && !(options_1.Allow.NUM & allow)) + markPartialJSON("Unterminated number literal"); + try { + return JSON.parse(jsonString.substring(start, index)); + } catch (e9) { + if (jsonString.substring(start, index) === "-") + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e"))); + } catch (e10) { + throwMalformedError(String(e10)); + } + } + }; + const skipBlank = () => { + while (index < length && " \n\r ".includes(jsonString[index])) { + index++; + } + }; + return parseAny(); + }; + var parse = parseJSON3; + exports.parse = parse; + } +}); + +// ../pi-mono/node_modules/retry/lib/retry_operation.js +var require_retry_operation = __commonJS({ + "../pi-mono/node_modules/retry/lib/retry_operation.js"(exports, module) { + init_process_shim(); + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.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); + } + } + module.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = function(fn) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i7 = 0; i7 < this._errors.length; i7++) { + var error = this._errors[i7]; + var message = error.message; + var count = (counts[message] || 0) + 1; + counts[message] = count; + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } + } + return mainError; + }; + } +}); + +// ../pi-mono/node_modules/retry/lib/retry.js +var require_retry = __commonJS({ + "../pi-mono/node_modules/retry/lib/retry.js"(exports) { + init_process_shim(); + var RetryOperation = require_retry_operation(); + exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); + }; + exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i7 = 0; i7 < opts.retries; i7++) { + timeouts.push(this.createTimeout(i7, opts)); + } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i7, opts)); + } + timeouts.sort(function(a3, b4) { + return a3 - b4; + }); + return timeouts; + }; + exports.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports.wrap = function(obj, options, methods2) { + if (options instanceof Array) { + methods2 = options; + options = null; + } + if (!methods2) { + methods2 = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods2.push(key); + } + } + } + for (var i7 = 0; i7 < methods2.length; i7++) { + var method = methods2[i7]; + var original = obj[method]; + obj[method] = function retryWrapper(original2) { + var op2 = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op2.retry(err)) { + return; + } + if (err) { + arguments[0] = op2.mainError(); + } + callback.apply(this, arguments); + }); + op2.attempt(function() { + original2.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } + }; + } +}); + +// ../pi-mono/node_modules/retry/index.js +var require_retry2 = __commonJS({ + "../pi-mono/node_modules/retry/index.js"(exports, module) { + init_process_shim(); + module.exports = require_retry(); + } +}); + +// ../pi-mono/node_modules/p-retry/index.js +var require_p_retry = __commonJS({ + "../pi-mono/node_modules/p-retry/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var retry = require_retry2(); + var networkErrorMsgs = [ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource.", + // Firefox + "The Internet connection appears to be offline.", + // Safari + "Network request failed" + // `cross-fetch` + ]; + var AbortError2 = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } + }; + var decorateErrorWithCounts = (error, attemptNumber, options) => { + const retriesLeft = options.retries - (attemptNumber - 1); + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; + }; + var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); + var pRetry2 = (input, options) => new Promise((resolve, reject) => { + options = { + onFailedAttempt: () => { + }, + retries: 10, + ...options + }; + const operation = retry.operation(options); + operation.attempt(async (attemptNumber) => { + try { + resolve(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + if (error instanceof AbortError2) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + try { + await options.onFailedAttempt(error); + } catch (error2) { + reject(error2); + return; + } + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); + }); + module.exports = pRetry2; + module.exports.default = pRetry2; + module.exports.AbortError = AbortError2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/url.js +var require_url = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/url.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.pathToFunc = pathToFunc; + var hasOwn4 = Object.prototype.hasOwnProperty; + function pathToFunc(pathPattern, options) { + const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; + return function buildURLPath(params = {}) { + return pathPattern.replace(paramRE, function(_3, placeholder) { + if (!hasOwn4.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error(`Parameter '${placeholder}' must be a string or number`); + } + return options?.charEncoding === "percent" ? encodeURIComponent(`${value}`) : `${value}`; + }); + }; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/config.js +var require_config = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/config.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDK_METADATA = exports.ServerList = exports.ServerEu = void 0; + exports.serverURLFromOptions = serverURLFromOptions; + var url_js_1 = require_url(); + exports.ServerEu = "eu"; + exports.ServerList = { + [exports.ServerEu]: "https://api.mistral.ai" + }; + function serverURLFromOptions(options) { + let serverURL = options.serverURL; + const params = {}; + if (!serverURL) { + const server = options.server ?? exports.ServerEu; + serverURL = exports.ServerList[server] || ""; + } + const u5 = (0, url_js_1.pathToFunc)(serverURL)(params); + return new URL(u5); + } + exports.SDK_METADATA = { + language: "typescript", + openapiDocVersion: "1.0.0", + sdkVersion: "1.14.1", + genVersion: "2.797.1", + userAgent: "speakeasy-sdk/typescript 1.14.1 2.797.1 1.0.0 @mistralai/mistralai" + }; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/files.js +var require_files = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/files.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readableStreamToArrayBuffer = readableStreamToArrayBuffer; + exports.getContentTypeFromFileName = getContentTypeFromFileName; + async function readableStreamToArrayBuffer(readable) { + const reader = readable.getReader(); + const chunks = []; + let totalLength = 0; + let done = false; + while (!done) { + const { value, done: doneReading } = await reader.read(); + if (doneReading) { + done = true; + } else { + chunks.push(value); + totalLength += value.length; + } + } + const concatenatedChunks = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of chunks) { + concatenatedChunks.set(chunk, offset); + offset += chunk.length; + } + return concatenatedChunks.buffer; + } + function getContentTypeFromFileName(fileName) { + if (!fileName) + return null; + const ext2 = fileName.toLowerCase().split(".").pop(); + if (!ext2) + return null; + const mimeTypes = { + json: "application/json", + xml: "application/xml", + html: "text/html", + htm: "text/html", + txt: "text/plain", + csv: "text/csv", + pdf: "application/pdf", + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + svg: "image/svg+xml", + js: "application/javascript", + css: "text/css", + zip: "application/zip", + tar: "application/x-tar", + gz: "application/gzip", + mp4: "video/mp4", + mp3: "audio/mpeg", + wav: "audio/wav", + webp: "image/webp", + ico: "image/x-icon", + woff: "font/woff", + woff2: "font/woff2", + ttf: "font/ttf", + otf: "font/otf" + }; + return mimeTypes[ext2] || null; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/http.js +var require_http = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/http.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTPClient = void 0; + exports.matchContentType = matchContentType; + exports.matchStatusCode = matchStatusCode; + exports.matchResponse = matchResponse; + exports.isConnectionError = isConnectionError; + exports.isTimeoutError = isTimeoutError; + exports.isAbortError = isAbortError4; + var DEFAULT_FETCHER = (input, init) => { + if (init == null) { + return fetch(input); + } else { + return fetch(input, init); + } + }; + var HTTPClient = class _HTTPClient { + constructor(options = {}) { + this.options = options; + this.requestHooks = []; + this.requestErrorHooks = []; + this.responseHooks = []; + this.fetcher = options.fetcher || DEFAULT_FETCHER; + } + async request(request) { + let req = request; + for (const hook of this.requestHooks) { + const nextRequest = await hook(req); + if (nextRequest) { + req = nextRequest; + } + } + try { + const res = await this.fetcher(req); + for (const hook of this.responseHooks) { + await hook(res, req); + } + return res; + } catch (err) { + for (const hook of this.requestErrorHooks) { + await hook(err, req); + } + throw err; + } + } + addHook(...args) { + if (args[0] === "beforeRequest") { + this.requestHooks.push(args[1]); + } else if (args[0] === "requestError") { + this.requestErrorHooks.push(args[1]); + } else if (args[0] === "response") { + this.responseHooks.push(args[1]); + } else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + return this; + } + removeHook(...args) { + let target; + if (args[0] === "beforeRequest") { + target = this.requestHooks; + } else if (args[0] === "requestError") { + target = this.requestErrorHooks; + } else if (args[0] === "response") { + target = this.responseHooks; + } else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + const index = target.findIndex((v4) => v4 === args[1]); + if (index >= 0) { + target.splice(index, 1); + } + return this; + } + clone() { + const child = new _HTTPClient(this.options); + child.requestHooks = this.requestHooks.slice(); + child.requestErrorHooks = this.requestErrorHooks.slice(); + child.responseHooks = this.responseHooks.slice(); + return child; + } + }; + exports.HTTPClient = HTTPClient; + var mediaParamSeparator = /\s*;\s*/g; + function matchContentType(response, pattern) { + if (pattern === "*") { + return true; + } + let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream"; + contentType = contentType.toLowerCase(); + const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); + const [wantType = "", ...wantParams] = wantParts; + if (wantType.split("/").length !== 2) { + return false; + } + const gotParts = contentType.split(mediaParamSeparator); + const [gotType = "", ...gotParams] = gotParts; + const [type = "", subtype = ""] = gotType.split("/"); + if (!type || !subtype) { + return false; + } + if (wantType !== "*/*" && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType) { + return false; + } + if (gotParams.length < wantParams.length) { + return false; + } + const params = new Set(gotParams); + for (const wantParam of wantParams) { + if (!params.has(wantParam)) { + return false; + } + } + return true; + } + var codeRangeRE = new RegExp("^[0-9]xx$", "i"); + function matchStatusCode(response, codes) { + const actual = `${response.status}`; + const expectedCodes = Array.isArray(codes) ? codes : [codes]; + if (!expectedCodes.length) { + return false; + } + return expectedCodes.some((ec) => { + const code = `${ec}`; + if (code === "default") { + return true; + } + if (!codeRangeRE.test(`${code}`)) { + return code === actual; + } + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); + } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); + } + return actualFamily === expectFamily; + }); + } + function matchResponse(response, code, contentTypePattern) { + return matchStatusCode(response, code) && matchContentType(response, contentTypePattern); + } + function isConnectionError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + const isBrowserErr = err instanceof TypeError && err.message.toLowerCase().startsWith("failed to fetch"); + const isNodeErr = err instanceof TypeError && err.message.toLowerCase().startsWith("fetch failed"); + const isBunErr = "name" in err && err.name === "ConnectionError"; + const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnreset"; + return isBrowserErr || isNodeErr || isGenericErr || isBunErr; + } + function isTimeoutError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + const isNative = "name" in err && err.name === "TimeoutError"; + const isLegacyNative = "code" in err && err.code === 23; + const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted"; + return isNative || isLegacyNative || isGenericErr; + } + function isAbortError4(err) { + if (typeof err !== "object" || err == null) { + return false; + } + const isNative = "name" in err && err.name === "AbortError"; + const isLegacyNative = "code" in err && err.code === 20; + const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted"; + return isNative || isLegacyNative || isGenericErr; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/custom_user_agent.js +var require_custom_user_agent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/custom_user_agent.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CustomUserAgentHook = void 0; + var config_1 = require_config(); + var CustomUserAgentHook = class { + beforeRequest(_3, request) { + const version5 = config_1.SDK_METADATA.sdkVersion; + const ua = `mistral-client-typescript/${version5}`; + request.headers.set("user-agent", ua); + if (!request.headers.get("user-agent")) { + request.headers.set("x-mistral-user-agent", ua); + } + return request; + } + }; + exports.CustomUserAgentHook = CustomUserAgentHook; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/deprecation_warning.js +var require_deprecation_warning = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/deprecation_warning.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeprecationWarningHook = void 0; + var HEADER_MODEL_DEPRECATION_TIMESTAMP = "x-model-deprecation-timestamp"; + var DeprecationWarningHook = class { + afterSuccess(_3, response) { + if (response.headers.has(HEADER_MODEL_DEPRECATION_TIMESTAMP)) { + response.clone().json().then((body) => { + const model = body.model; + console.warn(`WARNING: The model ${model} is deprecated and will be removed on ${response.headers.get(HEADER_MODEL_DEPRECATION_TIMESTAMP)}. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.`); + }); + } + return response; + } + }; + exports.DeprecationWarningHook = DeprecationWarningHook; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/registration.js +var require_registration = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/registration.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.initHooks = initHooks; + var custom_user_agent_1 = require_custom_user_agent(); + var deprecation_warning_1 = require_deprecation_warning(); + function initHooks(hooks) { + const customUserAgentHook = new custom_user_agent_1.CustomUserAgentHook(); + hooks.registerBeforeRequestHook(customUserAgentHook); + const deprecationWarningHook = new deprecation_warning_1.DeprecationWarningHook(); + hooks.registerAfterSuccessHook(deprecationWarningHook); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/hooks.js +var require_hooks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/hooks.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDKHooks = void 0; + var registration_js_1 = require_registration(); + var SDKHooks = class { + constructor() { + this.sdkInitHooks = []; + this.beforeCreateRequestHooks = []; + this.beforeRequestHooks = []; + this.afterSuccessHooks = []; + this.afterErrorHooks = []; + const presetHooks = []; + for (const hook of presetHooks) { + if ("sdkInit" in hook) { + this.registerSDKInitHook(hook); + } + if ("beforeCreateRequest" in hook) { + this.registerBeforeCreateRequestHook(hook); + } + if ("beforeRequest" in hook) { + this.registerBeforeRequestHook(hook); + } + if ("afterSuccess" in hook) { + this.registerAfterSuccessHook(hook); + } + if ("afterError" in hook) { + this.registerAfterErrorHook(hook); + } + } + (0, registration_js_1.initHooks)(this); + } + registerSDKInitHook(hook) { + this.sdkInitHooks.push(hook); + } + registerBeforeCreateRequestHook(hook) { + this.beforeCreateRequestHooks.push(hook); + } + registerBeforeRequestHook(hook) { + this.beforeRequestHooks.push(hook); + } + registerAfterSuccessHook(hook) { + this.afterSuccessHooks.push(hook); + } + registerAfterErrorHook(hook) { + this.afterErrorHooks.push(hook); + } + sdkInit(opts) { + return this.sdkInitHooks.reduce((opts2, hook) => hook.sdkInit(opts2), opts); + } + beforeCreateRequest(hookCtx, input) { + let inp = input; + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); + } + return inp; + } + async beforeRequest(hookCtx, request) { + let req = request; + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); + } + return req; + } + async afterSuccess(hookCtx, response) { + let res = response; + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); + } + return res; + } + async afterError(hookCtx, response, error) { + let res = response; + let err = error; + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; + } + return { response: res, error: err }; + } + }; + exports.SDKHooks = SDKHooks; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpclienterrors.js +var require_httpclienterrors = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpclienterrors.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConnectionError = exports.RequestTimeoutError = exports.RequestAbortedError = exports.InvalidRequestError = exports.UnexpectedClientError = exports.HTTPClientError = void 0; + var HTTPClientError = class extends Error { + constructor(message, opts) { + let msg = message; + if (opts?.cause) { + msg += `: ${opts.cause}`; + } + super(msg, opts); + this.name = "HTTPClientError"; + if (typeof this.cause === "undefined") { + this.cause = opts?.cause; + } + } + }; + exports.HTTPClientError = HTTPClientError; + var UnexpectedClientError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "UnexpectedClientError"; + } + }; + exports.UnexpectedClientError = UnexpectedClientError; + var InvalidRequestError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "InvalidRequestError"; + } + }; + exports.InvalidRequestError = InvalidRequestError; + var RequestAbortedError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "RequestAbortedError"; + } + }; + exports.RequestAbortedError = RequestAbortedError; + var RequestTimeoutError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "RequestTimeoutError"; + } + }; + exports.RequestTimeoutError = RequestTimeoutError; + var ConnectionError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "ConnectionError"; + } + }; + exports.ConnectionError = ConnectionError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/fp.js +var require_fp = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/fp.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OK = OK3; + exports.ERR = ERR; + exports.unwrap = unwrap; + exports.unwrapAsync = unwrapAsync; + function OK3(value) { + return { ok: true, value }; + } + function ERR(error) { + return { ok: false, error }; + } + function unwrap(r8) { + if (!r8.ok) { + throw r8.error; + } + return r8.value; + } + async function unwrapAsync(pr) { + const r8 = await pr; + if (!r8.ok) { + throw r8.error; + } + return r8.value; + } + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/util.cjs +var require_util = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/util.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; + var util3; + (function(util4) { + util4.assertEqual = (_3) => { + }; + function assertIs(_arg) { + } + util4.assertIs = assertIs; + function assertNever3(_x) { + throw new Error(); + } + util4.assertNever = assertNever3; + util4.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util4.getValidEnumValues = (obj) => { + const validKeys = util4.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); + const filtered = {}; + for (const k2 of validKeys) { + filtered[k2] = obj[k2]; + } + return util4.objectValues(filtered); + }; + util4.objectValues = (obj) => { + return util4.objectKeys(obj).map(function(e9) { + return obj[e9]; + }); + }; + util4.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys2 = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys2.push(key); + } + } + return keys2; + }; + util4.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util4.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2; + function joinValues(array, separator = " | ") { + return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); + } + util4.joinValues = joinValues; + util4.jsonStringifyReplacer = (_3, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util3 || (exports.util = util3 = {})); + var objectUtil3; + (function(objectUtil4) { + objectUtil4.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; + })(objectUtil3 || (exports.objectUtil = objectUtil3 = {})); + exports.ZodParsedType = util3.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); + var getParsedType3 = (data) => { + const t6 = typeof data; + switch (t6) { + case "undefined": + return exports.ZodParsedType.undefined; + case "string": + return exports.ZodParsedType.string; + case "number": + return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; + case "boolean": + return exports.ZodParsedType.boolean; + case "function": + return exports.ZodParsedType.function; + case "bigint": + return exports.ZodParsedType.bigint; + case "symbol": + return exports.ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return exports.ZodParsedType.array; + } + if (data === null) { + return exports.ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return exports.ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return exports.ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return exports.ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return exports.ZodParsedType.date; + } + return exports.ZodParsedType.object; + default: + return exports.ZodParsedType.unknown; + } + }; + exports.getParsedType = getParsedType3; + } +}); + +// ../pi-mono/node_modules/zod/v3/ZodError.cjs +var require_ZodError = __commonJS({ + "../pi-mono/node_modules/zod/v3/ZodError.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; + var util_js_1 = require_util(); + exports.ZodIssueCode = util_js_1.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + var quotelessJson2 = (obj) => { + const json2 = JSON.stringify(obj, null, 2); + return json2.replace(/"([^"]+)":/g, "$1:"); + }; + exports.quotelessJson = quotelessJson2; + var ZodError3 = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub2) => { + this.issues = [...this.issues, sub2]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i7 = 0; + while (i7 < issue.path.length) { + const el = issue.path[i7]; + const terminal = i7 === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i7++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util_js_1.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = /* @__PURE__ */ Object.create(null); + const formErrors = []; + for (const sub2 of this.issues) { + if (sub2.path.length > 0) { + const firstEl = sub2.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub2)); + } else { + formErrors.push(mapper(sub2)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + }; + exports.ZodError = ZodError3; + ZodError3.create = (issues) => { + const error = new ZodError3(issues); + return error; + }; + } +}); + +// ../pi-mono/node_modules/zod/v3/locales/en.cjs +var require_en = __commonJS({ + "../pi-mono/node_modules/zod/v3/locales/en.cjs"(exports, module) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var ZodError_js_1 = require_ZodError(); + var util_js_1 = require_util(); + var errorMap3 = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodError_js_1.ZodIssueCode.invalid_type: + if (issue.received === util_js_1.ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodError_js_1.ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`; + break; + case ZodError_js_1.ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_js_1.ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodError_js_1.ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodError_js_1.ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodError_js_1.ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util_js_1.util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodError_js_1.ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodError_js_1.ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_js_1.ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_js_1.util.assertNever(issue); + } + return { message }; + }; + exports.default = errorMap3; + module.exports = exports.default; + } +}); + +// ../pi-mono/node_modules/zod/v3/errors.cjs +var require_errors = __commonJS({ + "../pi-mono/node_modules/zod/v3/errors.cjs"(exports) { + "use strict"; + init_process_shim(); + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultErrorMap = void 0; + exports.setErrorMap = setErrorMap2; + exports.getErrorMap = getErrorMap3; + var en_js_1 = __importDefault(require_en()); + exports.defaultErrorMap = en_js_1.default; + var overrideErrorMap3 = en_js_1.default; + function setErrorMap2(map) { + overrideErrorMap3 = map; + } + function getErrorMap3() { + return overrideErrorMap3; + } + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/parseUtil.cjs +var require_parseUtil = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/parseUtil.cjs"(exports) { + "use strict"; + init_process_shim(); + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0; + exports.addIssueToContext = addIssueToContext3; + var errors_js_1 = require_errors(); + var en_js_1 = __importDefault(require_en()); + var makeIssue3 = (params) => { + const { data, path: path6, errorMaps, issueData } = params; + const fullPath = [...path6, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m4) => !!m4).slice().reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; + }; + exports.makeIssue = makeIssue3; + exports.EMPTY_PATH = []; + function addIssueToContext3(ctx, issueData) { + const overrideMap = (0, errors_js_1.getErrorMap)(); + const issue = (0, exports.makeIssue)({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_js_1.default ? void 0 : en_js_1.default + // then global default map + ].filter((x2) => !!x2) + }); + ctx.common.issues.push(issue); + } + var ParseStatus3 = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s6 of results) { + if (s6.status === "aborted") + return exports.INVALID; + if (s6.status === "dirty") + status.dirty(); + arrayValue.push(s6.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return exports.INVALID; + if (value.status === "aborted") + return exports.INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + }; + exports.ParseStatus = ParseStatus3; + exports.INVALID = Object.freeze({ + status: "aborted" + }); + var DIRTY3 = (value) => ({ status: "dirty", value }); + exports.DIRTY = DIRTY3; + var OK3 = (value) => ({ status: "valid", value }); + exports.OK = OK3; + var isAborted3 = (x2) => x2.status === "aborted"; + exports.isAborted = isAborted3; + var isDirty3 = (x2) => x2.status === "dirty"; + exports.isDirty = isDirty3; + var isValid3 = (x2) => x2.status === "valid"; + exports.isValid = isValid3; + var isAsync3 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; + exports.isAsync = isAsync3; + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/typeAliases.cjs +var require_typeAliases = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/typeAliases.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/errorUtil.cjs +var require_errorUtil = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/errorUtil.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.errorUtil = void 0; + var errorUtil3; + (function(errorUtil4) { + errorUtil4.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil4.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil3 || (exports.errorUtil = errorUtil3 = {})); + } +}); + +// ../pi-mono/node_modules/zod/v3/types.cjs +var require_types = __commonJS({ + "../pi-mono/node_modules/zod/v3/types.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; + exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0; + exports.datetimeRegex = datetimeRegex3; + exports.custom = custom2; + var ZodError_js_1 = require_ZodError(); + var errors_js_1 = require_errors(); + var errorUtil_js_1 = require_errorUtil(); + var parseUtil_js_1 = require_parseUtil(); + var util_js_1 = require_util(); + var ParseInputLazyPath3 = class { + constructor(parent, value, path6, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path6; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + }; + var handleResult3 = (ctx, result) => { + if ((0, parseUtil_js_1.isValid)(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError_js_1.ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } + }; + function processCreateParams3(params) { + if (!params) + return {}; + const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; + if (errorMap3 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap3) + return { errorMap: errorMap3, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; + } + var ZodType3 = class { + get description() { + return this._def.description; + } + _getType(input) { + return (0, util_js_1.getParsedType)(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new parseUtil_js_1.ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if ((0, parseUtil_js_1.isAsync)(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult3(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return (0, parseUtil_js_1.isValid)(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_js_1.isValid)(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult3(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val2) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val2); + } else { + return message; + } + }; + return this._refinement((val2, ctx) => { + const result = check(val2); + const setError = () => ctx.addIssue({ + code: ZodError_js_1.ZodIssueCode.custom, + ...getIssueProperties(val2) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val2, ctx) => { + if (!check(val2)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects3({ + schema: this, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional3.create(this, this._def); + } + nullable() { + return ZodNullable3.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray3.create(this); + } + promise() { + return ZodPromise3.create(this, this._def); + } + or(option) { + return ZodUnion3.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection3.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects3({ + ...processCreateParams3(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault3({ + ...processCreateParams3(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind3.ZodDefault + }); + } + brand() { + return new ZodBranded3({ + typeName: ZodFirstPartyTypeKind3.ZodBranded, + type: this, + ...processCreateParams3(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch3({ + ...processCreateParams3(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind3.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline3.create(this, target); + } + readonly() { + return ZodReadonly3.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } + }; + exports.ZodType = ZodType3; + exports.Schema = ZodType3; + exports.ZodSchema = ZodType3; + var cuidRegex3 = /^c[^\s-]{8,}$/i; + var cuid2Regex3 = /^[0-9a-z]+$/; + var ulidRegex3 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + var uuidRegex3 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + var nanoidRegex3 = /^[a-z0-9_-]{21}$/i; + var jwtRegex3 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + var durationRegex3 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + var emailRegex3 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + var _emojiRegex3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + var emojiRegex5; + var ipv4Regex3 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + var ipv4CidrRegex3 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + var ipv6Regex3 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + var ipv6CidrRegex3 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + var base64Regex3 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + var base64urlRegex3 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + var dateRegexSource3 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; + var dateRegex3 = new RegExp(`^${dateRegexSource3}$`); + function timeRegexSource3(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; + } + function timeRegex3(args) { + return new RegExp(`^${timeRegexSource3(args)}$`); + } + function datetimeRegex3(args) { + let regex = `${dateRegexSource3}T${timeRegexSource3(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); + } + function isValidIP3(ip, version5) { + if ((version5 === "v4" || !version5) && ipv4Regex3.test(ip)) { + return true; + } + if ((version5 === "v6" || !version5) && ipv6Regex3.test(ip)) { + return true; + } + return false; + } + function isValidJWT3(jwt, alg) { + if (!jwtRegex3.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } + } + function isValidCidr3(ip, version5) { + if ((version5 === "v4" || !version5) && ipv4CidrRegex3.test(ip)) { + return true; + } + if ((version5 === "v6" || !version5) && ipv6CidrRegex3.test(ip)) { + return true; + } + return false; + } + var ZodString3 = class _ZodString extends ZodType3 { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.string, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + const status = new parseUtil_js_1.ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "email", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex5) { + emojiRegex5 = new RegExp(_emojiRegex3, "u"); + } + if (!emojiRegex5.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "emoji", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "uuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "nanoid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid2", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ulid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "regex", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex3(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex3; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex3(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "duration", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP3(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ip", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT3(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "jwt", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr3(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cidr", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodError_js_1.ZodIssueCode.invalid_string, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil_js_1.errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil_js_1.errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil_js_1.errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil_js_1.errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + exports.ZodString = ZodString3; + ZodString3.create = (params) => { + return new ZodString3({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams3(params) + }); + }; + function floatSafeRemainder3(val2, step) { + const valDecCount = (val2.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; + } + var ZodNumber3 = class _ZodNumber extends ZodType3 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.number, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + let ctx = void 0; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_js_1.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder3(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util_js_1.util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + }; + exports.ZodNumber = ZodNumber3; + ZodNumber3.create = (params) => { + return new ZodNumber3({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams3(params) + }); + }; + var ZodBigInt3 = class _ZodBigInt extends ZodType3 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.bigint, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + exports.ZodBigInt = ZodBigInt3; + ZodBigInt3.create = (params) => { + return new ZodBigInt3({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams3(params) + }); + }; + var ZodBoolean3 = class extends ZodType3 { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.boolean, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodBoolean = ZodBoolean3; + ZodBoolean3.create = (params) => { + return new ZodBoolean3({ + typeName: ZodFirstPartyTypeKind3.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams3(params) + }); + }; + var ZodDate3 = class _ZodDate extends ZodType3 { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.date, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_date + }); + return parseUtil_js_1.INVALID; + } + const status = new parseUtil_js_1.ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + }; + exports.ZodDate = ZodDate3; + ZodDate3.create = (params) => { + return new ZodDate3({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind3.ZodDate, + ...processCreateParams3(params) + }); + }; + var ZodSymbol3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.symbol, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodSymbol = ZodSymbol3; + ZodSymbol3.create = (params) => { + return new ZodSymbol3({ + typeName: ZodFirstPartyTypeKind3.ZodSymbol, + ...processCreateParams3(params) + }); + }; + var ZodUndefined3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.undefined, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodUndefined = ZodUndefined3; + ZodUndefined3.create = (params) => { + return new ZodUndefined3({ + typeName: ZodFirstPartyTypeKind3.ZodUndefined, + ...processCreateParams3(params) + }); + }; + var ZodNull3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.null, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodNull = ZodNull3; + ZodNull3.create = (params) => { + return new ZodNull3({ + typeName: ZodFirstPartyTypeKind3.ZodNull, + ...processCreateParams3(params) + }); + }; + var ZodAny3 = class extends ZodType3 { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodAny = ZodAny3; + ZodAny3.create = (params) => { + return new ZodAny3({ + typeName: ZodFirstPartyTypeKind3.ZodAny, + ...processCreateParams3(params) + }); + }; + var ZodUnknown3 = class extends ZodType3 { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodUnknown = ZodUnknown3; + ZodUnknown3.create = (params) => { + return new ZodUnknown3({ + typeName: ZodFirstPartyTypeKind3.ZodUnknown, + ...processCreateParams3(params) + }); + }; + var ZodNever3 = class extends ZodType3 { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.never, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + }; + exports.ZodNever = ZodNever3; + ZodNever3.create = (params) => { + return new ZodNever3({ + typeName: ZodFirstPartyTypeKind3.ZodNever, + ...processCreateParams3(params) + }); + }; + var ZodVoid3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.void, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodVoid = ZodVoid3; + ZodVoid3.create = (params) => { + return new ZodVoid3({ + typeName: ZodFirstPartyTypeKind3.ZodVoid, + ...processCreateParams3(params) + }); + }; + var ZodArray3 = class _ZodArray extends ZodType3 { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i7) => { + return def.type._parseAsync(new ParseInputLazyPath3(ctx, item, ctx.path, i7)); + })).then((result2) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i7) => { + return def.type._parseSync(new ParseInputLazyPath3(ctx, item, ctx.path, i7)); + }); + return parseUtil_js_1.ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } + }; + exports.ZodArray = ZodArray3; + ZodArray3.create = (schema, params) => { + return new ZodArray3({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind3.ZodArray, + ...processCreateParams3(params) + }); + }; + function deepPartialify3(schema) { + if (schema instanceof ZodObject3) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional3.create(deepPartialify3(fieldSchema)); + } + return new ZodObject3({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray3) { + return new ZodArray3({ + ...schema._def, + type: deepPartialify3(schema.element) + }); + } else if (schema instanceof ZodOptional3) { + return ZodOptional3.create(deepPartialify3(schema.unwrap())); + } else if (schema instanceof ZodNullable3) { + return ZodNullable3.create(deepPartialify3(schema.unwrap())); + } else if (schema instanceof ZodTuple3) { + return ZodTuple3.create(schema.items.map((item) => deepPartialify3(item))); + } else { + return schema; + } + } + var ZodObject3 = class _ZodObject extends ZodType3 { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys2 = util_js_1.util.objectKeys(shape); + this._cached = { shape, keys: keys2 }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever3 && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever3) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath3(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil_js_1.errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind3.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new _ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify3(this); + } + partial(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional3) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum3(util_js_1.util.objectKeys(this.shape)); + } + }; + exports.ZodObject = ZodObject3; + ZodObject3.create = (shape, params) => { + return new ZodObject3({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever3.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams3(params) + }); + }; + ZodObject3.strictCreate = (shape, params) => { + return new ZodObject3({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever3.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams3(params) + }); + }; + ZodObject3.lazycreate = (shape, params) => { + return new ZodObject3({ + shape, + unknownKeys: "strip", + catchall: ZodNever3.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams3(params) + }); + }; + var ZodUnion3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError_js_1.ZodError(result.ctx.common.issues)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors + }); + return parseUtil_js_1.INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError_js_1.ZodError(issues2)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors + }); + return parseUtil_js_1.INVALID; + } + } + get options() { + return this._def.options; + } + }; + exports.ZodUnion = ZodUnion3; + ZodUnion3.create = (types2, params) => { + return new ZodUnion3({ + options: types2, + typeName: ZodFirstPartyTypeKind3.ZodUnion, + ...processCreateParams3(params) + }); + }; + var getDiscriminator3 = (type) => { + if (type instanceof ZodLazy3) { + return getDiscriminator3(type.schema); + } else if (type instanceof ZodEffects3) { + return getDiscriminator3(type.innerType()); + } else if (type instanceof ZodLiteral3) { + return [type.value]; + } else if (type instanceof ZodEnum3) { + return type.options; + } else if (type instanceof ZodNativeEnum3) { + return util_js_1.util.objectValues(type.enum); + } else if (type instanceof ZodDefault3) { + return getDiscriminator3(type._def.innerType); + } else if (type instanceof ZodUndefined3) { + return [void 0]; + } else if (type instanceof ZodNull3) { + return [null]; + } else if (type instanceof ZodOptional3) { + return [void 0, ...getDiscriminator3(type.unwrap())]; + } else if (type instanceof ZodNullable3) { + return [null, ...getDiscriminator3(type.unwrap())]; + } else if (type instanceof ZodBranded3) { + return getDiscriminator3(type.unwrap()); + } else if (type instanceof ZodReadonly3) { + return getDiscriminator3(type.unwrap()); + } else if (type instanceof ZodCatch3) { + return getDiscriminator3(type._def.innerType); + } else { + return []; + } + }; + var ZodDiscriminatedUnion3 = class _ZodDiscriminatedUnion extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return parseUtil_js_1.INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator3(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams3(params) + }); + } + }; + exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion3; + function mergeValues3(a3, b4) { + const aType = (0, util_js_1.getParsedType)(a3); + const bType = (0, util_js_1.getParsedType)(b4); + if (a3 === b4) { + return { valid: true, data: a3 }; + } else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) { + const bKeys = util_js_1.util.objectKeys(b4); + const sharedKeys = util_js_1.util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a3, ...b4 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues3(a3[key], b4[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) { + if (a3.length !== b4.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a3.length; index++) { + const itemA = a3[index]; + const itemB = b4[index]; + const sharedValue = mergeValues3(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a3 === +b4) { + return { valid: true, data: a3 }; + } else { + return { valid: false }; + } + } + var ZodIntersection3 = class extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) { + return parseUtil_js_1.INVALID; + } + const merged = mergeValues3(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_intersection_types + }); + return parseUtil_js_1.INVALID; + } + if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.isDirty)(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } + }; + exports.ZodIntersection = ZodIntersection3; + ZodIntersection3.create = (left, right, params) => { + return new ZodIntersection3({ + left, + right, + typeName: ZodFirstPartyTypeKind3.ZodIntersection, + ...processCreateParams3(params) + }); + }; + var ZodTuple3 = class _ZodTuple extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + if (ctx.data.length < this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return parseUtil_js_1.INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath3(ctx, item, ctx.path, itemIndex)); + }).filter((x2) => !!x2); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, results); + }); + } else { + return parseUtil_js_1.ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } + }; + exports.ZodTuple = ZodTuple3; + ZodTuple3.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple3({ + items: schemas, + typeName: ZodFirstPartyTypeKind3.ZodTuple, + rest: null, + ...processCreateParams3(params) + }); + }; + var ZodRecord3 = class _ZodRecord extends ZodType3 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath3(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs); + } else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType3) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind3.ZodRecord, + ...processCreateParams3(third) + }); + } + return new _ZodRecord({ + keyType: ZodString3.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind3.ZodRecord, + ...processCreateParams3(second) + }); + } + }; + exports.ZodRecord = ZodRecord3; + var ZodMap3 = class extends ZodType3 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.map) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.map, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath3(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + }; + exports.ZodMap = ZodMap3; + ZodMap3.create = (keyType, valueType, params) => { + return new ZodMap3({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind3.ZodMap, + ...processCreateParams3(params) + }); + }; + var ZodSet3 = class _ZodSet extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.set) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.set, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return parseUtil_js_1.INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath3(ctx, item, ctx.path, i7))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + }; + exports.ZodSet = ZodSet3; + ZodSet3.create = (valueType, params) => { + return new ZodSet3({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind3.ZodSet, + ...processCreateParams3(params) + }); + }; + var ZodFunction3 = class _ZodFunction extends ZodType3 { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.function) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.function, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + function makeArgsIssue(args, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x2) => !!x2), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x2) => !!x2), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise3) { + const me = this; + return (0, parseUtil_js_1.OK)(async function(...args) { + const error = new ZodError_js_1.ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e9) => { + error.addIssue(makeArgsIssue(args, e9)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => { + error.addIssue(makeReturnsIssue(result, e9)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return (0, parseUtil_js_1.OK)(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError_js_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError_js_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple3.create(items).rest(ZodUnknown3.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple3.create([]).rest(ZodUnknown3.create()), + returns: returns || ZodUnknown3.create(), + typeName: ZodFirstPartyTypeKind3.ZodFunction, + ...processCreateParams3(params) + }); + } + }; + exports.ZodFunction = ZodFunction3; + var ZodLazy3 = class extends ZodType3 { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + exports.ZodLazy = ZodLazy3; + ZodLazy3.create = (getter, params) => { + return new ZodLazy3({ + getter, + typeName: ZodFirstPartyTypeKind3.ZodLazy, + ...processCreateParams3(params) + }); + }; + var ZodLiteral3 = class extends ZodType3 { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return parseUtil_js_1.INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + }; + exports.ZodLiteral = ZodLiteral3; + ZodLiteral3.create = (value, params) => { + return new ZodLiteral3({ + value, + typeName: ZodFirstPartyTypeKind3.ZodLiteral, + ...processCreateParams3(params) + }); + }; + function createZodEnum3(values2, params) { + return new ZodEnum3({ + values: values2, + typeName: ZodFirstPartyTypeKind3.ZodEnum, + ...processCreateParams3(params) + }); + } + var ZodEnum3 = class _ZodEnum extends ZodType3 { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + extract(values2, newDef = this._def) { + return _ZodEnum.create(values2, { + ...this._def, + ...newDef + }); + } + exclude(values2, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), { + ...this._def, + ...newDef + }); + } + }; + exports.ZodEnum = ZodEnum3; + ZodEnum3.create = createZodEnum3; + var ZodNativeEnum3 = class extends ZodType3 { + _parse(input) { + const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + get enum() { + return this._def.values; + } + }; + exports.ZodNativeEnum = ZodNativeEnum3; + ZodNativeEnum3.create = (values2, params) => { + return new ZodNativeEnum3({ + values: values2, + typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, + ...processCreateParams3(params) + }); + }; + var ZodPromise3 = class extends ZodType3 { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.promise, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return (0, parseUtil_js_1.OK)(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } + }; + exports.ZodPromise = ZodPromise3; + ZodPromise3.create = (schema, params) => { + return new ZodPromise3({ + type: schema, + typeName: ZodFirstPartyTypeKind3.ZodPromise, + ...processCreateParams3(params) + }); + }; + var ZodEffects3 = class extends ZodType3 { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + (0, parseUtil_js_1.addIssueToContext)(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner2 = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner2.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner2.status === "dirty") + status.dirty(); + executeRefinement(inner2.value); + return { status: status.value, value: inner2.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => { + if (inner2.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner2.status === "dirty") + status.dirty(); + return executeRefinement(inner2.value).then(() => { + return { status: status.value, value: inner2.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util_js_1.util.assertNever(effect); + } + }; + exports.ZodEffects = ZodEffects3; + exports.ZodTransformer = ZodEffects3; + ZodEffects3.create = (schema, effect, params) => { + return new ZodEffects3({ + schema, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect, + ...processCreateParams3(params) + }); + }; + ZodEffects3.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects3({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + ...processCreateParams3(params) + }); + }; + var ZodOptional3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.undefined) { + return (0, parseUtil_js_1.OK)(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + exports.ZodOptional = ZodOptional3; + ZodOptional3.create = (type, params) => { + return new ZodOptional3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodOptional, + ...processCreateParams3(params) + }); + }; + var ZodNullable3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.null) { + return (0, parseUtil_js_1.OK)(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + exports.ZodNullable = ZodNullable3; + ZodNullable3.create = (type, params) => { + return new ZodNullable3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodNullable, + ...processCreateParams3(params) + }); + }; + var ZodDefault3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === util_js_1.ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } + }; + exports.ZodDefault = ZodDefault3; + ZodDefault3.create = (type, params) => { + return new ZodDefault3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams3(params) + }); + }; + var ZodCatch3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if ((0, parseUtil_js_1.isAsync)(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } + }; + exports.ZodCatch = ZodCatch3; + ZodCatch3.create = (type, params) => { + return new ZodCatch3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams3(params) + }); + }; + var ZodNaN3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.nan, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return { status: "valid", value: input.data }; + } + }; + exports.ZodNaN = ZodNaN3; + ZodNaN3.create = (params) => { + return new ZodNaN3({ + typeName: ZodFirstPartyTypeKind3.ZodNaN, + ...processCreateParams3(params) + }); + }; + exports.BRAND = Symbol("zod_brand"); + var ZodBranded3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } + }; + exports.ZodBranded = ZodBranded3; + var ZodPipeline3 = class _ZodPipeline extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return (0, parseUtil_js_1.DIRTY)(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a3, b4) { + return new _ZodPipeline({ + in: a3, + out: b4, + typeName: ZodFirstPartyTypeKind3.ZodPipeline + }); + } + }; + exports.ZodPipeline = ZodPipeline3; + var ZodReadonly3 = class extends ZodType3 { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze2 = (data) => { + if ((0, parseUtil_js_1.isValid)(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze2(data)) : freeze2(result); + } + unwrap() { + return this._def.innerType; + } + }; + exports.ZodReadonly = ZodReadonly3; + ZodReadonly3.create = (type, params) => { + return new ZodReadonly3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodReadonly, + ...processCreateParams3(params) + }); + }; + function cleanParams2(params, data) { + const p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p22 = typeof p4 === "string" ? { message: p4 } : p4; + return p22; + } + function custom2(check, _params = {}, fatal) { + if (check) + return ZodAny3.create().superRefine((data, ctx) => { + const r8 = check(data); + if (r8 instanceof Promise) { + return r8.then((r9) => { + if (!r9) { + const params = cleanParams2(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r8) { + const params = cleanParams2(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny3.create(); + } + exports.late = { + object: ZodObject3.lazycreate + }; + var ZodFirstPartyTypeKind3; + (function(ZodFirstPartyTypeKind4) { + ZodFirstPartyTypeKind4["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind4["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind4["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind4["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind4["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind4["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind4["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind4["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind4["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind4["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind4["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind4["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind4["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind4["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind4["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind4["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind4["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind4["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind4["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind4["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind4["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind4["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind4["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind4["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind4["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind4["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind4["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind4["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind4["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind4["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind4["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind4["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind4["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind4["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind4["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind4["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind3 || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind3 = {})); + var instanceOfType2 = (cls, params = { + message: `Input not instance of ${cls.name}` + }) => custom2((data) => data instanceof cls, params); + exports.instanceof = instanceOfType2; + var stringType3 = ZodString3.create; + exports.string = stringType3; + var numberType3 = ZodNumber3.create; + exports.number = numberType3; + var nanType3 = ZodNaN3.create; + exports.nan = nanType3; + var bigIntType3 = ZodBigInt3.create; + exports.bigint = bigIntType3; + var booleanType3 = ZodBoolean3.create; + exports.boolean = booleanType3; + var dateType3 = ZodDate3.create; + exports.date = dateType3; + var symbolType3 = ZodSymbol3.create; + exports.symbol = symbolType3; + var undefinedType3 = ZodUndefined3.create; + exports.undefined = undefinedType3; + var nullType3 = ZodNull3.create; + exports.null = nullType3; + var anyType3 = ZodAny3.create; + exports.any = anyType3; + var unknownType3 = ZodUnknown3.create; + exports.unknown = unknownType3; + var neverType3 = ZodNever3.create; + exports.never = neverType3; + var voidType3 = ZodVoid3.create; + exports.void = voidType3; + var arrayType3 = ZodArray3.create; + exports.array = arrayType3; + var objectType3 = ZodObject3.create; + exports.object = objectType3; + var strictObjectType3 = ZodObject3.strictCreate; + exports.strictObject = strictObjectType3; + var unionType3 = ZodUnion3.create; + exports.union = unionType3; + var discriminatedUnionType3 = ZodDiscriminatedUnion3.create; + exports.discriminatedUnion = discriminatedUnionType3; + var intersectionType3 = ZodIntersection3.create; + exports.intersection = intersectionType3; + var tupleType3 = ZodTuple3.create; + exports.tuple = tupleType3; + var recordType3 = ZodRecord3.create; + exports.record = recordType3; + var mapType3 = ZodMap3.create; + exports.map = mapType3; + var setType3 = ZodSet3.create; + exports.set = setType3; + var functionType3 = ZodFunction3.create; + exports.function = functionType3; + var lazyType3 = ZodLazy3.create; + exports.lazy = lazyType3; + var literalType3 = ZodLiteral3.create; + exports.literal = literalType3; + var enumType3 = ZodEnum3.create; + exports.enum = enumType3; + var nativeEnumType3 = ZodNativeEnum3.create; + exports.nativeEnum = nativeEnumType3; + var promiseType3 = ZodPromise3.create; + exports.promise = promiseType3; + var effectsType3 = ZodEffects3.create; + exports.effect = effectsType3; + exports.transformer = effectsType3; + var optionalType3 = ZodOptional3.create; + exports.optional = optionalType3; + var nullableType3 = ZodNullable3.create; + exports.nullable = nullableType3; + var preprocessType3 = ZodEffects3.createWithPreprocess; + exports.preprocess = preprocessType3; + var pipelineType3 = ZodPipeline3.create; + exports.pipeline = pipelineType3; + var ostring2 = () => stringType3().optional(); + exports.ostring = ostring2; + var onumber2 = () => numberType3().optional(); + exports.onumber = onumber2; + var oboolean2 = () => booleanType3().optional(); + exports.oboolean = oboolean2; + exports.coerce = { + string: ((arg) => ZodString3.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber3.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean3.create({ + ...arg, + coerce: true + })), + bigint: ((arg) => ZodBigInt3.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate3.create({ ...arg, coerce: true })) + }; + exports.NEVER = parseUtil_js_1.INVALID; + } +}); + +// ../pi-mono/node_modules/zod/v3/external.cjs +var require_external = __commonJS({ + "../pi-mono/node_modules/zod/v3/external.cjs"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_errors(), exports); + __exportStar(require_parseUtil(), exports); + __exportStar(require_typeAliases(), exports); + __exportStar(require_util(), exports); + __exportStar(require_types(), exports); + __exportStar(require_ZodError(), exports); + } +}); + +// ../pi-mono/node_modules/zod/v3/index.cjs +var require_v3 = __commonJS({ + "../pi-mono/node_modules/zod/v3/index.cjs"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 in mod) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) __createBinding(result, mod, k2); + } + __setModuleDefault(result, mod); + return result; + }; + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.z = void 0; + var z3 = __importStar(require_external()); + exports.z = z3; + __exportStar(require_external(), exports); + exports.default = z3; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/base64.js +var require_base64 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/base64.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.zodInbound = exports.zodOutbound = void 0; + exports.bytesToBase64 = bytesToBase64; + exports.bytesFromBase64 = bytesFromBase64; + exports.stringToBytes = stringToBytes2; + exports.stringFromBytes = stringFromBytes; + exports.stringToBase64 = stringToBase64; + exports.stringFromBase64 = stringFromBase64; + var z3 = __importStar(require_v3()); + function bytesToBase64(u8arr) { + return btoa(String.fromCodePoint(...u8arr)); + } + function bytesFromBase64(encoded) { + return Uint8Array.from(atob(encoded), (c6) => c6.charCodeAt(0)); + } + function stringToBytes2(str2) { + return new TextEncoder().encode(str2); + } + function stringFromBytes(u8arr) { + return new TextDecoder().decode(u8arr); + } + function stringToBase64(str2) { + return bytesToBase64(stringToBytes2(str2)); + } + function stringFromBase64(b64str) { + return stringFromBytes(bytesFromBase64(b64str)); + } + exports.zodOutbound = z3.instanceof(Uint8Array).or(z3.string().transform(stringToBytes2)); + exports.zodInbound = z3.instanceof(Uint8Array).or(z3.string().transform(bytesFromBase64)); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/is-plain-object.js +var require_is_plain_object = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/is-plain-object.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPlainObject = isPlainObject2; + function isPlainObject2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/encodings.js +var require_encodings = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/encodings.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.encodeDeepObjectQuery = exports.encodePipeDelimitedQuery = exports.encodeSpaceDelimitedQuery = exports.encodeFormQuery = exports.encodeJSONQuery = exports.encodeSimple = exports.encodePipeDelimited = exports.encodeSpaceDelimited = exports.encodeForm = exports.EncodingError = void 0; + exports.encodeMatrix = encodeMatrix; + exports.encodeLabel = encodeLabel; + exports.encodeBodyForm = encodeBodyForm; + exports.encodeDeepObject = encodeDeepObject; + exports.encodeDeepObjectObject = encodeDeepObjectObject; + exports.encodeJSON = encodeJSON; + exports.queryJoin = queryJoin; + exports.queryEncoder = queryEncoder; + exports.appendForm = appendForm; + var base64_js_1 = require_base64(); + var is_plain_object_js_1 = require_is_plain_object(); + var EncodingError = class extends Error { + constructor(message) { + super(message); + this.name = "EncodingError"; + } + }; + exports.EncodingError = EncodingError; + function encodeMatrix(key, value, options) { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue = null; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(","); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `,${encodeString(k2)},${encodeValue(v4)}`; + }); + encValue = mapped?.join("").slice(1); + } else { + encValue = `${encodeValue(pv)}`; + } + if (encValue == null) { + return; + } + const keyPrefix = encodeString(pk); + tmp = `${keyPrefix}=${encValue}`; + if (tmp === `${keyPrefix}=`) { + tmp = tmp.slice(0, -1); + } + if (!tmp) { + return; + } + out += `;${tmp}`; + }); + return out; + } + function encodeLabel(key, value, options) { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let encValue = ""; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join("."); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `.${encodeString(k2)}.${encodeValue(v4)}`; + }); + encValue = mapped?.join("").slice(1); + } else { + const k2 = options?.explode && (0, is_plain_object_js_1.isPlainObject)(value) ? `${encodeString(pk)}=` : ""; + encValue = `${k2}${encodeValue(pv)}`; + } + out += encValue == null ? "" : `.${encValue}`; + }); + return out; + } + function formEncoder(sep2) { + return (key, value, options) => { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + const encodedSep = encodeString(sep2); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue = null; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(encodedSep); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + encValue = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `${encodeString(k2)}${encodedSep}${encodeValue(v4)}`; + })?.join(encodedSep); + } else { + encValue = `${encodeValue(pv)}`; + } + if (encValue == null) { + return; + } + tmp = `${encodeString(pk)}=${encValue}`; + if (!tmp || tmp === "=") { + return; + } + out += `&${tmp}`; + }); + return out.slice(1); + }; + } + exports.encodeForm = formEncoder(","); + exports.encodeSpaceDelimited = formEncoder(" "); + exports.encodePipeDelimited = formEncoder("|"); + function encodeBodyForm(key, value, options) { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue = ""; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = JSON.stringify(pv, jsonReplacer); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + encValue = JSON.stringify(pv, jsonReplacer); + } else { + encValue = `${encodeValue(pv)}`; + } + tmp = `${encodeString(pk)}=${encValue}`; + if (!tmp || tmp === "=") { + return; + } + out += `&${tmp}`; + }); + return out.slice(1); + } + function encodeDeepObject(key, value, options) { + if (value == null) { + return; + } + if (!(0, is_plain_object_js_1.isPlainObject)(value)) { + throw new EncodingError(`Value of parameter '${key}' which uses deepObject encoding must be an object or null`); + } + return encodeDeepObjectObject(key, value, options); + } + function encodeDeepObjectObject(key, value, options) { + if (value == null) { + return; + } + let out = ""; + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + if (!(0, is_plain_object_js_1.isPlainObject)(value)) { + throw new EncodingError(`Expected parameter '${key}' to be an object.`); + } + Object.entries(value).forEach(([ck, cv]) => { + if (cv == null) { + return; + } + const pk = `${key}[${ck}]`; + if ((0, is_plain_object_js_1.isPlainObject)(cv)) { + const objOut = encodeDeepObjectObject(pk, cv, options); + out += objOut == null ? "" : `&${objOut}`; + return; + } + const pairs = Array.isArray(cv) ? cv : [cv]; + const encoded = mapDefined(pairs, (v4) => { + return `${encodeString(pk)}=${encodeString(serializeValue(v4))}`; + })?.join("&"); + out += encoded == null ? "" : `&${encoded}`; + }); + return out.slice(1); + } + function encodeJSON(key, value, options) { + if (typeof value === "undefined") { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encVal = encodeString(JSON.stringify(value, jsonReplacer)); + return options?.explode ? encVal : `${encodeString(key)}=${encVal}`; + } + var encodeSimple = (key, value, options) => { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + tmp = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(","); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `,${encodeString(k2)},${encodeValue(v4)}`; + }); + tmp = mapped?.join("").slice(1); + } else { + const k2 = options?.explode && (0, is_plain_object_js_1.isPlainObject)(value) ? `${pk}=` : ""; + tmp = `${k2}${encodeValue(pv)}`; + } + out += tmp ? `,${tmp}` : ""; + }); + return out.slice(1); + }; + exports.encodeSimple = encodeSimple; + function explode(key, value) { + if (Array.isArray(value)) { + return value.map((v4) => [key, v4]); + } else if ((0, is_plain_object_js_1.isPlainObject)(value)) { + const o9 = value ?? {}; + return Object.entries(o9).map(([k2, v4]) => [k2, v4]); + } else { + return [[key, value]]; + } + } + function serializeValue(value) { + if (value == null) { + return ""; + } else if (value instanceof Date) { + return value.toISOString(); + } else if (value instanceof Uint8Array) { + return (0, base64_js_1.bytesToBase64)(value); + } else if (typeof value === "object") { + return JSON.stringify(value, jsonReplacer); + } + return `${value}`; + } + function jsonReplacer(_3, value) { + if (value instanceof Uint8Array) { + return (0, base64_js_1.bytesToBase64)(value); + } else { + return value; + } + } + function mapDefined(inp, mapper) { + const res = inp.reduce((acc, v4) => { + if (v4 == null) { + return acc; + } + const m4 = mapper(v4); + if (m4 == null) { + return acc; + } + acc.push(m4); + return acc; + }, []); + return res.length ? res : null; + } + function mapDefinedEntries(inp, mapper) { + const acc = []; + for (const [k2, v4] of inp) { + if (v4 == null) { + continue; + } + const m4 = mapper([k2, v4]); + if (m4 == null) { + continue; + } + acc.push(m4); + } + return acc.length ? acc : null; + } + function queryJoin(...args) { + return args.filter(Boolean).join("&"); + } + function queryEncoder(f4) { + const bulkEncode = function(values2, options) { + const opts = { + ...options, + explode: options?.explode ?? true, + charEncoding: options?.charEncoding ?? "percent" + }; + const allowEmptySet = new Set(options?.allowEmptyValue ?? []); + const encoded = Object.entries(values2).map(([key, value]) => { + if (allowEmptySet.has(key)) { + if (value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0) { + return `${encodeURIComponent(key)}=`; + } + } + return f4(key, value, opts); + }); + return queryJoin(...encoded); + }; + return bulkEncode; + } + exports.encodeJSONQuery = queryEncoder(encodeJSON); + exports.encodeFormQuery = queryEncoder(exports.encodeForm); + exports.encodeSpaceDelimitedQuery = queryEncoder(exports.encodeSpaceDelimited); + exports.encodePipeDelimitedQuery = queryEncoder(exports.encodePipeDelimited); + exports.encodeDeepObjectQuery = queryEncoder(encodeDeepObject); + function appendForm(fd, key, value, fileName) { + if (value == null) { + return; + } else if (value instanceof Blob && fileName) { + fd.append(key, value, fileName); + } else if (value instanceof Blob) { + fd.append(key, value); + } else { + fd.append(key, String(value)); + } + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/dlv.js +var require_dlv = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/dlv.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dlv = dlv; + function dlv(obj, key, def, p4, undef) { + key = Array.isArray(key) ? key : key.split("."); + for (p4 = 0; p4 < key.length; p4++) { + const k2 = key[p4]; + obj = k2 != null && obj ? obj[k2] : undef; + } + return obj === undef ? def : obj; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/env.js +var require_env = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/env.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.envSchema = void 0; + exports.env = env; + exports.resetEnv = resetEnv; + var z3 = __importStar(require_v3()); + var dlv_js_1 = require_dlv(); + exports.envSchema = z3.object({ + MISTRAL_API_KEY: z3.string().optional(), + MISTRAL_DEBUG: z3.coerce.boolean().optional() + }); + function isDeno() { + if ("Deno" in globalThis) { + return true; + } + return false; + } + var envMemo = void 0; + function env() { + if (envMemo) { + return envMemo; + } + let envObject = {}; + if (isDeno()) { + envObject = globalThis.Deno?.env?.toObject?.() ?? {}; + } else { + envObject = (0, dlv_js_1.dlv)(globalThis, "process.env") ?? {}; + } + envMemo = exports.envSchema.parse(envObject); + return envMemo; + } + function resetEnv() { + envMemo = void 0; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/retries.js +var require_retries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/retries.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TemporaryError = exports.PermanentError = void 0; + exports.retry = retry; + var http_js_1 = require_http(); + var defaultBackoff = { + initialInterval: 500, + maxInterval: 6e4, + exponent: 1.5, + maxElapsedTime: 36e5 + }; + var PermanentError = class _PermanentError extends Error { + constructor(message, options) { + let msg = message; + if (options?.cause) { + msg += `: ${options.cause}`; + } + super(msg, options); + this.name = "PermanentError"; + if (typeof this.cause === "undefined") { + this.cause = options?.cause; + } + Object.setPrototypeOf(this, _PermanentError.prototype); + } + }; + exports.PermanentError = PermanentError; + var TemporaryError = class _TemporaryError extends Error { + constructor(message, response) { + super(message); + this.response = response; + this.name = "TemporaryError"; + Object.setPrototypeOf(this, _TemporaryError.prototype); + } + }; + exports.TemporaryError = TemporaryError; + async function retry(fetchFn, options) { + switch (options.config.strategy) { + case "backoff": + return retryBackoff(wrapFetcher(fetchFn, { + statusCodes: options.statusCodes, + retryConnectionErrors: !!options.config.retryConnectionErrors + }), options.config.backoff ?? defaultBackoff); + default: + return await fetchFn(); + } + } + function wrapFetcher(fn, options) { + return async () => { + try { + const res = await fn(); + if (isRetryableResponse(res, options.statusCodes)) { + throw new TemporaryError("Response failed with retryable status code", res); + } + return res; + } catch (err) { + if (err instanceof TemporaryError) { + throw err; + } + if (options.retryConnectionErrors && ((0, http_js_1.isTimeoutError)(err) || (0, http_js_1.isConnectionError)(err))) { + throw err; + } + throw new PermanentError("Permanent error", { cause: err }); + } + }; + } + var codeRangeRE = new RegExp("^[0-9]xx$", "i"); + function isRetryableResponse(res, statusCodes) { + const actual = `${res.status}`; + return statusCodes.some((code) => { + if (!codeRangeRE.test(code)) { + return code === actual; + } + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); + } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); + } + return actualFamily === expectFamily; + }); + } + async function retryBackoff(fn, strategy) { + const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy; + const start = Date.now(); + let x2 = 0; + while (true) { + try { + const res = await fn(); + return res; + } catch (err) { + if (err instanceof PermanentError) { + throw err.cause; + } + const elapsed = Date.now() - start; + if (elapsed > maxElapsedTime) { + if (err instanceof TemporaryError) { + return err.response; + } + throw err; + } + let retryInterval = 0; + if (err instanceof TemporaryError) { + retryInterval = retryIntervalFromResponse(err.response); + } + if (retryInterval <= 0) { + retryInterval = initialInterval * Math.pow(x2, exponent) + Math.random() * 1e3; + } + const d4 = Math.min(retryInterval, maxInterval); + await delay(d4); + x2++; + } + } + } + function retryIntervalFromResponse(res) { + const retryVal = res.headers.get("retry-after") || ""; + if (!retryVal) { + return 0; + } + const parsedNumber = Number(retryVal); + if (Number.isInteger(parsedNumber)) { + return parsedNumber * 1e3; + } + const parsedDate = Date.parse(retryVal); + if (Number.isInteger(parsedDate)) { + const deltaMS = parsedDate - Date.now(); + return deltaMS > 0 ? Math.ceil(deltaMS) : 0; + } + return 0; + } + async function delay(delay2) { + return new Promise((resolve) => setTimeout(resolve, delay2)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/sdks.js +var require_sdks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/sdks.js"(exports) { + "use strict"; + init_process_shim(); + var __classPrivateFieldSet3 = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f4) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; + }; + var __classPrivateFieldGet3 = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f4) { + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); + }; + var _ClientSDK_httpClient; + var _ClientSDK_hooks; + var _ClientSDK_logger; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClientSDK = void 0; + var hooks_js_1 = require_hooks(); + var httpclienterrors_js_1 = require_httpclienterrors(); + var fp_js_1 = require_fp(); + var base64_js_1 = require_base64(); + var config_js_1 = require_config(); + var encodings_js_1 = require_encodings(); + var env_js_1 = require_env(); + var http_js_1 = require_http(); + var retries_js_1 = require_retries(); + var gt = typeof globalThis === "undefined" ? null : globalThis; + var webWorkerLike = typeof gt === "object" && gt != null && "importScripts" in gt && typeof gt["importScripts"] === "function"; + var isBrowserLike = webWorkerLike || typeof navigator !== "undefined" && "serviceWorker" in navigator || typeof window === "object" && typeof window.document !== "undefined"; + var ClientSDK = class { + constructor(options = {}) { + _ClientSDK_httpClient.set(this, void 0); + _ClientSDK_hooks.set(this, void 0); + _ClientSDK_logger.set(this, void 0); + const opt = options; + if (typeof opt === "object" && opt != null && "hooks" in opt && opt.hooks instanceof hooks_js_1.SDKHooks) { + __classPrivateFieldSet3(this, _ClientSDK_hooks, opt.hooks, "f"); + } else { + __classPrivateFieldSet3(this, _ClientSDK_hooks, new hooks_js_1.SDKHooks(), "f"); + } + const url = (0, config_js_1.serverURLFromOptions)(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + } + const { baseURL, client } = __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").sdkInit({ + baseURL: url, + client: options.httpClient || new http_js_1.HTTPClient() + }); + this._baseURL = baseURL; + __classPrivateFieldSet3(this, _ClientSDK_httpClient, client, "f"); + this._options = { ...options, hooks: __classPrivateFieldGet3(this, _ClientSDK_hooks, "f") }; + __classPrivateFieldSet3(this, _ClientSDK_logger, this._options.debugLogger, "f"); + if (!__classPrivateFieldGet3(this, _ClientSDK_logger, "f") && (0, env_js_1.env)().MISTRAL_DEBUG) { + __classPrivateFieldSet3(this, _ClientSDK_logger, console, "f"); + } + } + _createRequest(context, conf, options) { + const { method, path: path6, query, headers: opHeaders, security } = conf; + const base = conf.baseURL ?? this._baseURL; + if (!base) { + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.InvalidRequestError("No base URL provided for operation")); + } + const reqURL = new URL(base); + const inputURL = new URL(path6, reqURL); + if (path6) { + reqURL.pathname += reqURL.pathname.endsWith("/") ? "" : "/"; + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + } + let finalQuery = query || ""; + const secQuery = []; + for (const [k2, v4] of Object.entries(security?.queryParams || {})) { + const q2 = (0, encodings_js_1.encodeForm)(k2, v4, { charEncoding: "percent" }); + if (typeof q2 !== "undefined") { + secQuery.push(q2); + } + } + if (secQuery.length) { + finalQuery += `&${secQuery.join("&")}`; + } + if (finalQuery) { + const q2 = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + reqURL.search = `?${q2}`; + } + const headers = new Headers(opHeaders); + const username = security?.basic.username; + const password = security?.basic.password; + if (username != null || password != null) { + const encoded = (0, base64_js_1.stringToBase64)([username || "", password || ""].join(":")); + headers.set("Authorization", `Basic ${encoded}`); + } + const securityHeaders = new Headers(security?.headers || {}); + for (const [k2, v4] of securityHeaders) { + headers.set(k2, v4); + } + let cookie = headers.get("cookie") || ""; + for (const [k2, v4] of Object.entries(security?.cookies || {})) { + cookie += `; ${k2}=${v4}`; + } + cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; + headers.set("cookie", cookie); + const userHeaders = new Headers(options?.headers ?? options?.fetchOptions?.headers); + for (const [k2, v4] of userHeaders) { + headers.set(k2, v4); + } + if (!isBrowserLike) { + headers.set(conf.uaHeader ?? "user-agent", conf.userAgent ?? config_js_1.SDK_METADATA.userAgent); + } + const fetchOptions = { + ...options?.fetchOptions, + ...options + }; + if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { + const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); + fetchOptions.signal = timeoutSignal; + } + if (conf.body instanceof ReadableStream) { + Object.assign(fetchOptions, { duplex: "half" }); + } + let input; + try { + input = __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").beforeCreateRequest(context, { + url: reqURL, + options: { + ...fetchOptions, + body: conf.body ?? null, + headers, + method + } + }); + } catch (err) { + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.UnexpectedClientError("Create request hook failed to execute", { + cause: err + })); + } + return (0, fp_js_1.OK)(new Request(input.url, input.options)); + } + async _do(request, options) { + const { context, errorCodes } = options; + return (0, retries_js_1.retry)(async () => { + const req = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").beforeRequest(context, request.clone()); + await logRequest(__classPrivateFieldGet3(this, _ClientSDK_logger, "f"), req).catch((e9) => __classPrivateFieldGet3(this, _ClientSDK_logger, "f")?.log("Failed to log request:", e9)); + let response = await __classPrivateFieldGet3(this, _ClientSDK_httpClient, "f").request(req); + try { + if ((0, http_js_1.matchStatusCode)(response, errorCodes)) { + const result = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").afterError(context, response, null); + if (result.error) { + throw result.error; + } + response = result.response || response; + } else { + response = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").afterSuccess(context, response); + } + } finally { + await logResponse(__classPrivateFieldGet3(this, _ClientSDK_logger, "f"), response, req).catch((e9) => __classPrivateFieldGet3(this, _ClientSDK_logger, "f")?.log("Failed to log response:", e9)); + } + return response; + }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r8) => (0, fp_js_1.OK)(r8), (err) => { + switch (true) { + case (0, http_js_1.isAbortError)(err): + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.RequestAbortedError("Request aborted by client", { + cause: err + })); + case (0, http_js_1.isTimeoutError)(err): + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.RequestTimeoutError("Request timed out", { cause: err })); + case (0, http_js_1.isConnectionError)(err): + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.ConnectionError("Unable to make request", { cause: err })); + default: + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.UnexpectedClientError("Unexpected HTTP client error", { + cause: err + })); + } + }); + } + }; + exports.ClientSDK = ClientSDK; + _ClientSDK_httpClient = /* @__PURE__ */ new WeakMap(), _ClientSDK_hooks = /* @__PURE__ */ new WeakMap(), _ClientSDK_logger = /* @__PURE__ */ new WeakMap(); + var jsonLikeContentTypeRE = /^(application|text)\/([^+]+\+)*json.*/; + var jsonlLikeContentTypeRE = /^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/; + async function logRequest(logger2, req) { + if (!logger2) { + return; + } + const contentType = req.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + logger2.group(`> Request: ${req.method} ${req.url}`); + logger2.group("Headers:"); + for (const [k2, v4] of req.headers.entries()) { + logger2.log(`${k2}: ${v4}`); + } + logger2.groupEnd(); + logger2.group("Body:"); + switch (true) { + case jsonLikeContentTypeRE.test(ct): + logger2.log(await req.clone().json()); + break; + case ct.startsWith("text/"): + logger2.log(await req.clone().text()); + break; + case ct === "multipart/form-data": { + const body = await req.clone().formData(); + for (const [k2, v4] of body) { + const vlabel = v4 instanceof Blob ? "" : v4; + logger2.log(`${k2}: ${vlabel}`); + } + break; + } + default: + logger2.log(`<${contentType}>`); + break; + } + logger2.groupEnd(); + logger2.groupEnd(); + } + async function logResponse(logger2, res, req) { + if (!logger2) { + return; + } + const contentType = res.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + logger2.group(`< Response: ${req.method} ${req.url}`); + logger2.log("Status Code:", res.status, res.statusText); + logger2.group("Headers:"); + for (const [k2, v4] of res.headers.entries()) { + logger2.log(`${k2}: ${v4}`); + } + logger2.groupEnd(); + logger2.group("Body:"); + switch (true) { + case ((0, http_js_1.matchContentType)(res, "application/json") || jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct)): + logger2.log(await res.clone().json()); + break; + case ((0, http_js_1.matchContentType)(res, "application/jsonl") || jsonlLikeContentTypeRE.test(ct)): + logger2.log(await res.clone().text()); + break; + case (0, http_js_1.matchContentType)(res, "text/event-stream"): + logger2.log(`<${contentType}>`); + break; + case (0, http_js_1.matchContentType)(res, "text/*"): + logger2.log(await res.clone().text()); + break; + case (0, http_js_1.matchContentType)(res, "multipart/form-data"): { + const body = await res.clone().formData(); + for (const [k2, v4] of body) { + const vlabel = v4 instanceof Blob ? "" : v4; + logger2.log(`${k2}: ${vlabel}`); + } + break; + } + default: + logger2.log(`<${contentType}>`); + break; + } + logger2.groupEnd(); + logger2.groupEnd(); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/mistralerror.js +var require_mistralerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/mistralerror.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralError = void 0; + var MistralError = class extends Error { + constructor(message, httpMeta) { + super(message); + this.statusCode = httpMeta.response.status; + this.body = httpMeta.body; + this.headers = httpMeta.response.headers; + this.contentType = httpMeta.response.headers.get("content-type") || ""; + this.rawResponse = httpMeta.response; + this.name = "MistralError"; + } + }; + exports.MistralError = MistralError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkvalidationerror.js +var require_sdkvalidationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkvalidationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDKValidationError = void 0; + exports.formatZodError = formatZodError; + var z3 = __importStar(require_v3()); + var SDKValidationError = class extends Error { + // Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError` + static [Symbol.hasInstance](instance) { + if (!(instance instanceof Error)) + return false; + if (!("rawValue" in instance)) + return false; + if (!("rawMessage" in instance)) + return false; + if (!("pretty" in instance)) + return false; + if (typeof instance.pretty !== "function") + return false; + return true; + } + constructor(message, cause, rawValue) { + super(`${message}: ${cause}`); + this.name = "SDKValidationError"; + this.cause = cause; + this.rawValue = rawValue; + this.rawMessage = message; + } + /** + * Return a pretty-formatted error message if the underlying validation error + * is a ZodError or some other recognized error type, otherwise return the + * default error message. + */ + pretty() { + if (this.cause instanceof z3.ZodError) { + return `${this.rawMessage} +${formatZodError(this.cause)}`; + } else { + return this.toString(); + } + } + }; + exports.SDKValidationError = SDKValidationError; + function formatZodError(err, level = 0) { + let pre = " ".repeat(level); + pre = level > 0 ? `\u2502${pre}` : pre; + pre += " ".repeat(level); + let message = ""; + const append = (str2) => message += ` +${pre}${str2}`; + const len = err.issues.length; + const headline = len === 1 ? `${len} issue found` : `${len} issues found`; + if (len) { + append(`\u250C ${headline}:`); + } + for (const issue of err.issues) { + let path6 = issue.path.join("."); + path6 = path6 ? `.${path6}` : ""; + append(`\u2502 \u2022 [${path6}]: ${issue.message} (${issue.code})`); + switch (issue.code) { + case "invalid_literal": + case "invalid_type": { + append(`\u2502 Want: ${issue.expected}`); + append(`\u2502 Got: ${issue.received}`); + break; + } + case "unrecognized_keys": { + append(`\u2502 Keys: ${issue.keys.join(", ")}`); + break; + } + case "invalid_enum_value": { + append(`\u2502 Allowed: ${issue.options.join(", ")}`); + append(`\u2502 Got: ${issue.received}`); + break; + } + case "invalid_union_discriminator": { + append(`\u2502 Allowed: ${issue.options.join(", ")}`); + break; + } + case "invalid_union": { + const len2 = issue.unionErrors.length; + append(`\u2502 \u2716\uFE0E Attemped to deserialize into one of ${len2} union members:`); + issue.unionErrors.forEach((err2, i7) => { + append(`\u2502 \u2716\uFE0E Member ${i7 + 1} of ${len2}`); + append(`${formatZodError(err2, level + 1)}`); + }); + } + } + } + if (err.issues.length) { + append(`\u2514\u2500*`); + } + return message.slice(1); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/responsevalidationerror.js +var require_responsevalidationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/responsevalidationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseValidationError = void 0; + var z3 = __importStar(require_v3()); + var mistralerror_js_1 = require_mistralerror(); + var sdkvalidationerror_js_1 = require_sdkvalidationerror(); + var ResponseValidationError = class extends mistralerror_js_1.MistralError { + constructor(message, extra) { + super(message, extra); + this.name = "ResponseValidationError"; + this.cause = extra.cause; + this.rawValue = extra.rawValue; + this.rawMessage = extra.rawMessage; + } + /** + * Return a pretty-formatted error message if the underlying validation error + * is a ZodError or some other recognized error type, otherwise return the + * default error message. + */ + pretty() { + if (this.cause instanceof z3.ZodError) { + return `${this.rawMessage} +${(0, sdkvalidationerror_js_1.formatZodError)(this.cause)}`; + } else { + return this.toString(); + } + } + }; + exports.ResponseValidationError = ResponseValidationError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkerror.js +var require_sdkerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkerror.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDKError = void 0; + var mistralerror_js_1 = require_mistralerror(); + var SDKError = class extends mistralerror_js_1.MistralError { + constructor(message, httpMeta) { + if (message) { + message += `: `; + } + message += `Status ${httpMeta.response.status}`; + const contentType = httpMeta.response.headers.get("content-type") || `""`; + if (contentType !== "application/json") { + message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`; + } + const body = httpMeta.body || `""`; + message += body.length > 100 ? "\n" : ". "; + let bodyDisplay = body; + if (body.length > 1e4) { + const truncated = body.substring(0, 1e4); + const remaining = body.length - 1e4; + bodyDisplay = `${truncated}...and ${remaining} more chars`; + } + message += `Body: ${bodyDisplay}`; + message = message.trim(); + super(message, httpMeta); + this.name = "SDKError"; + } + }; + exports.SDKError = SDKError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/matchers.js +var require_matchers = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/matchers.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.jsonErr = jsonErr; + exports.json = json2; + exports.jsonl = jsonl; + exports.jsonlErr = jsonlErr; + exports.textErr = textErr; + exports.text = text3; + exports.bytesErr = bytesErr; + exports.bytes = bytes; + exports.streamErr = streamErr; + exports.stream = stream2; + exports.sseErr = sseErr; + exports.sse = sse; + exports.nilErr = nilErr; + exports.nil = nil; + exports.fail = fail; + exports.match = match2; + exports.unpackHeaders = unpackHeaders; + var responsevalidationerror_js_1 = require_responsevalidationerror(); + var sdkerror_js_1 = require_sdkerror(); + var fp_js_1 = require_fp(); + var http_js_1 = require_http(); + var is_plain_object_js_1 = require_is_plain_object(); + var DEFAULT_CONTENT_TYPES = { + jsonl: "application/jsonl", + json: "application/json", + text: "text/plain", + bytes: "application/octet-stream", + stream: "application/octet-stream", + sse: "text/event-stream", + nil: "*", + fail: "*" + }; + function jsonErr(codes, schema, options) { + return { ...options, err: true, enc: "json", codes, schema }; + } + function json2(codes, schema, options) { + return { ...options, enc: "json", codes, schema }; + } + function jsonl(codes, schema, options) { + return { ...options, enc: "jsonl", codes, schema }; + } + function jsonlErr(codes, schema, options) { + return { ...options, err: true, enc: "jsonl", codes, schema }; + } + function textErr(codes, schema, options) { + return { ...options, err: true, enc: "text", codes, schema }; + } + function text3(codes, schema, options) { + return { ...options, enc: "text", codes, schema }; + } + function bytesErr(codes, schema, options) { + return { ...options, err: true, enc: "bytes", codes, schema }; + } + function bytes(codes, schema, options) { + return { ...options, enc: "bytes", codes, schema }; + } + function streamErr(codes, schema, options) { + return { ...options, err: true, enc: "stream", codes, schema }; + } + function stream2(codes, schema, options) { + return { ...options, enc: "stream", codes, schema }; + } + function sseErr(codes, schema, options) { + return { ...options, err: true, enc: "sse", codes, schema }; + } + function sse(codes, schema, options) { + return { ...options, enc: "sse", codes, schema }; + } + function nilErr(codes, schema, options) { + return { ...options, err: true, enc: "nil", codes, schema }; + } + function nil(codes, schema, options) { + return { ...options, enc: "nil", codes, schema }; + } + function fail(codes) { + return { enc: "fail", codes }; + } + function match2(...matchers) { + return async function matchFunc(response, request, options) { + let raw; + let matcher; + for (const match3 of matchers) { + const { codes } = match3; + const ctpattern = "ctype" in match3 ? match3.ctype : DEFAULT_CONTENT_TYPES[match3.enc]; + if (ctpattern && (0, http_js_1.matchResponse)(response, codes, ctpattern)) { + matcher = match3; + break; + } else if (!ctpattern && (0, http_js_1.matchStatusCode)(response, codes)) { + matcher = match3; + break; + } + } + if (!matcher) { + return [{ + ok: false, + error: new sdkerror_js_1.SDKError("Unexpected Status or Content-Type", { + response, + request, + body: await response.text().catch(() => "") + }) + }, raw]; + } + const encoding = matcher.enc; + let body = ""; + switch (encoding) { + case "json": + body = await response.text(); + raw = JSON.parse(body); + break; + case "jsonl": + raw = response.body; + break; + case "bytes": + raw = new Uint8Array(await response.arrayBuffer()); + break; + case "stream": + raw = response.body; + break; + case "text": + body = await response.text(); + raw = body; + break; + case "sse": + raw = response.body; + break; + case "nil": + body = await response.text(); + raw = void 0; + break; + case "fail": + body = await response.text(); + raw = body; + break; + default: + encoding; + throw new Error(`Unsupported response type: ${encoding}`); + } + if (matcher.enc === "fail") { + return [{ + ok: false, + error: new sdkerror_js_1.SDKError("API error occurred", { request, response, body }) + }, raw]; + } + const resultKey = matcher.key || options?.resultKey; + let data; + if ("err" in matcher) { + data = { + ...options?.extraFields, + ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, + ...(0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null, + request$: request, + response$: response, + body$: body + }; + } else if (resultKey) { + data = { + ...options?.extraFields, + ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, + [resultKey]: raw + }; + } else if (matcher.hdrs) { + data = { + ...options?.extraFields, + ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, + ...(0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null + }; + } else { + data = raw; + } + if ("err" in matcher) { + const result = safeParseResponse(data, (v4) => matcher.schema.parse(v4), "Response validation failed", { request, response, body }); + return [result.ok ? { ok: false, error: result.value } : result, raw]; + } else { + return [ + safeParseResponse(data, (v4) => matcher.schema.parse(v4), "Response validation failed", { request, response, body }), + raw + ]; + } + }; + } + var headerValRE = /, */; + function unpackHeaders(headers) { + const out = {}; + for (const [k2, v4] of headers.entries()) { + out[k2] = v4.split(headerValRE); + } + return out; + } + function safeParseResponse(rawValue, fn, errorMessage, httpMeta) { + try { + return (0, fp_js_1.OK)(fn(rawValue)); + } catch (err) { + return (0, fp_js_1.ERR)(new responsevalidationerror_js_1.ResponseValidationError(errorMessage, { + cause: err, + rawValue, + rawMessage: errorMessage, + ...httpMeta + })); + } + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/primitives.js +var require_primitives = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/primitives.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.invariant = invariant; + exports.remap = remap; + exports.combineSignals = combineSignals; + exports.abortSignalAny = abortSignalAny; + exports.compactMap = compactMap; + exports.allRequired = allRequired; + var InvariantError = class extends Error { + constructor(message) { + super(message); + this.name = "InvariantError"; + } + }; + function invariant(condition, message) { + if (!condition) { + throw new InvariantError(message); + } + } + function remap(inp, mappings) { + let out = {}; + if (!Object.keys(mappings).length) { + out = inp; + return out; + } + for (const [k2, v4] of Object.entries(inp)) { + const j3 = mappings[k2]; + if (j3 === null) { + continue; + } + out[j3 ?? k2] = v4; + } + return out; + } + function combineSignals(...signals) { + const filtered = []; + for (const signal of signals) { + if (signal) { + filtered.push(signal); + } + } + switch (filtered.length) { + case 0: + case 1: + return filtered[0] || null; + default: + if ("any" in AbortSignal && typeof AbortSignal.any === "function") { + return AbortSignal.any(filtered); + } + return abortSignalAny(filtered); + } + } + function abortSignalAny(signals) { + const controller = new AbortController(); + const result = controller.signal; + if (!signals.length) { + return controller.signal; + } + if (signals.length === 1) { + return signals[0] || controller.signal; + } + for (const signal of signals) { + if (signal.aborted) { + return signal; + } + } + function abort() { + controller.abort(this.reason); + clean(); + } + const signalRefs = []; + function clean() { + for (const signalRef of signalRefs) { + const signal = signalRef.deref(); + if (signal) { + signal.removeEventListener("abort", abort); + } + } + } + for (const signal of signals) { + signalRefs.push(new WeakRef(signal)); + signal.addEventListener("abort", abort); + } + return result; + } + function compactMap(values2) { + const out = {}; + for (const [k2, v4] of Object.entries(values2)) { + if (typeof v4 !== "undefined") { + out[k2] = v4; + } + } + return out; + } + function allRequired(v4) { + if (Object.values(v4).every((x2) => x2 == null)) { + return void 0; + } + return v4; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/schemas.js +var require_schemas = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/schemas.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parse = parse; + exports.safeParse = safeParse; + exports.collectExtraKeys = collectExtraKeys; + var v3_1 = require_v3(); + var sdkvalidationerror_js_1 = require_sdkvalidationerror(); + var fp_js_1 = require_fp(); + function parse(rawValue, fn, errorMessage) { + try { + return fn(rawValue); + } catch (err) { + if (err instanceof v3_1.ZodError) { + throw new sdkvalidationerror_js_1.SDKValidationError(errorMessage, err, rawValue); + } + throw err; + } + } + function safeParse(rawValue, fn, errorMessage) { + try { + return (0, fp_js_1.OK)(fn(rawValue)); + } catch (err) { + return (0, fp_js_1.ERR)(new sdkvalidationerror_js_1.SDKValidationError(errorMessage, err, rawValue)); + } + } + function collectExtraKeys(obj, extrasKey, optional) { + return obj.transform((val2) => { + const extras = {}; + const { shape } = obj; + for (const [key] of Object.entries(val2)) { + if (key in shape) { + continue; + } + const v4 = val2[key]; + if (typeof v4 === "undefined") { + continue; + } + extras[key] = v4; + delete val2[key]; + } + if (optional && Object.keys(extras).length === 0) { + return val2; + } + return { ...val2, [extrasKey]: extras }; + }); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/security.js +var require_security = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/security.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SecurityError = exports.SecurityErrorCode = void 0; + exports.resolveSecurity = resolveSecurity; + exports.resolveGlobalSecurity = resolveGlobalSecurity; + exports.extractSecurity = extractSecurity; + var env_js_1 = require_env(); + var SecurityErrorCode; + (function(SecurityErrorCode2) { + SecurityErrorCode2["Incomplete"] = "incomplete"; + SecurityErrorCode2["UnrecognisedSecurityType"] = "unrecognized_security_type"; + })(SecurityErrorCode || (exports.SecurityErrorCode = SecurityErrorCode = {})); + var SecurityError = class _SecurityError extends Error { + constructor(code, message) { + super(message); + this.code = code; + this.name = "SecurityError"; + } + static incomplete() { + return new _SecurityError(SecurityErrorCode.Incomplete, "Security requirements not met in order to perform the operation"); + } + static unrecognizedType(type) { + return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType, `Unrecognised security type: ${type}`); + } + }; + exports.SecurityError = SecurityError; + function resolveSecurity(...options) { + const state = { + basic: {}, + headers: {}, + queryParams: {}, + cookies: {}, + oauth2: { type: "none" } + }; + const option = options.find((opts) => { + return opts.every((o9) => { + if (o9.value == null) { + return false; + } else if (o9.type === "http:basic") { + return o9.value.username != null || o9.value.password != null; + } else if (o9.type === "http:custom") { + return null; + } else if (o9.type === "oauth2:password") { + return typeof o9.value === "string" && !!o9.value; + } else if (o9.type === "oauth2:client_credentials") { + if (typeof o9.value == "string") { + return !!o9.value; + } + return o9.value.clientID != null || o9.value.clientSecret != null; + } else if (typeof o9.value === "string") { + return !!o9.value; + } else { + throw new Error(`Unrecognized security type: ${o9.type} (value type: ${typeof o9.value})`); + } + }); + }); + if (option == null) { + return null; + } + option.forEach((spec) => { + if (spec.value == null) { + return; + } + const { type } = spec; + switch (type) { + case "apiKey:header": + state.headers[spec.fieldName] = spec.value; + break; + case "apiKey:query": + state.queryParams[spec.fieldName] = spec.value; + break; + case "apiKey:cookie": + state.cookies[spec.fieldName] = spec.value; + break; + case "http:basic": + applyBasic(state, spec); + break; + case "http:custom": + break; + case "http:bearer": + applyBearer(state, spec); + break; + case "oauth2": + applyBearer(state, spec); + break; + case "oauth2:password": + applyBearer(state, spec); + break; + case "oauth2:client_credentials": + break; + case "openIdConnect": + applyBearer(state, spec); + break; + default: + spec; + throw SecurityError.unrecognizedType(type); + } + }); + return state; + } + function applyBasic(state, spec) { + if (spec.value == null) { + return; + } + state.basic = spec.value; + } + function applyBearer(state, spec) { + if (typeof spec.value !== "string" || !spec.value) { + return; + } + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } + if (spec.fieldName !== void 0) { + state.headers[spec.fieldName] = value; + } + } + function resolveGlobalSecurity(security) { + return resolveSecurity([ + { + fieldName: "Authorization", + type: "http:bearer", + value: security?.apiKey ?? (0, env_js_1.env)().MISTRAL_API_KEY + } + ]); + } + async function extractSecurity(sec) { + if (sec == null) { + return; + } + return typeof sec === "function" ? sec() : sec; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolconfiguration.js +var require_toolconfiguration = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolconfiguration.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolConfiguration$outboundSchema = exports.ToolConfiguration$inboundSchema = void 0; + exports.toolConfigurationToJSON = toolConfigurationToJSON; + exports.toolConfigurationFromJSON = toolConfigurationFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ToolConfiguration$inboundSchema = z3.object({ + exclude: z3.nullable(z3.array(z3.string())).optional(), + include: z3.nullable(z3.array(z3.string())).optional(), + requires_confirmation: z3.nullable(z3.array(z3.string())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "requires_confirmation": "requiresConfirmation" + }); + }); + exports.ToolConfiguration$outboundSchema = z3.object({ + exclude: z3.nullable(z3.array(z3.string())).optional(), + include: z3.nullable(z3.array(z3.string())).optional(), + requiresConfirmation: z3.nullable(z3.array(z3.string())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + requiresConfirmation: "requires_confirmation" + }); + }); + function toolConfigurationToJSON(toolConfiguration) { + return JSON.stringify(exports.ToolConfiguration$outboundSchema.parse(toolConfiguration)); + } + function toolConfigurationFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolConfiguration$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolConfiguration' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/codeinterpretertool.js +var require_codeinterpretertool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/codeinterpretertool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeInterpreterTool$outboundSchema = exports.CodeInterpreterTool$inboundSchema = exports.CodeInterpreterToolType$outboundSchema = exports.CodeInterpreterToolType$inboundSchema = exports.CodeInterpreterToolType = void 0; + exports.codeInterpreterToolToJSON = codeInterpreterToolToJSON; + exports.codeInterpreterToolFromJSON = codeInterpreterToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.CodeInterpreterToolType = { + CodeInterpreter: "code_interpreter" + }; + exports.CodeInterpreterToolType$inboundSchema = z3.nativeEnum(exports.CodeInterpreterToolType); + exports.CodeInterpreterToolType$outboundSchema = exports.CodeInterpreterToolType$inboundSchema; + exports.CodeInterpreterTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.CodeInterpreterToolType$inboundSchema.default("code_interpreter") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.CodeInterpreterTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.CodeInterpreterToolType$outboundSchema.default("code_interpreter") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function codeInterpreterToolToJSON(codeInterpreterTool) { + return JSON.stringify(exports.CodeInterpreterTool$outboundSchema.parse(codeInterpreterTool)); + } + function codeInterpreterToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CodeInterpreterTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CodeInterpreterTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargsstop.js +var require_completionargsstop = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargsstop.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionArgsStop$outboundSchema = exports.CompletionArgsStop$inboundSchema = void 0; + exports.completionArgsStopToJSON = completionArgsStopToJSON; + exports.completionArgsStopFromJSON = completionArgsStopFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.CompletionArgsStop$inboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + exports.CompletionArgsStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function completionArgsStopToJSON(completionArgsStop) { + return JSON.stringify(exports.CompletionArgsStop$outboundSchema.parse(completionArgsStop)); + } + function completionArgsStopFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionArgsStop$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionArgsStop' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/prediction.js +var require_prediction = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/prediction.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Prediction$outboundSchema = exports.Prediction$inboundSchema = void 0; + exports.predictionToJSON = predictionToJSON; + exports.predictionFromJSON = predictionFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Prediction$inboundSchema = z3.object({ + type: z3.literal("content").default("content"), + content: z3.string().default("") + }); + exports.Prediction$outboundSchema = z3.object({ + type: z3.literal("content").default("content"), + content: z3.string().default("") + }); + function predictionToJSON(prediction) { + return JSON.stringify(exports.Prediction$outboundSchema.parse(prediction)); + } + function predictionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Prediction$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Prediction' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jsonschema.js +var require_jsonschema = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jsonschema.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonSchema$outboundSchema = exports.JsonSchema$inboundSchema = void 0; + exports.jsonSchemaToJSON = jsonSchemaToJSON; + exports.jsonSchemaFromJSON = jsonSchemaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.JsonSchema$inboundSchema = z3.object({ + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + schema: z3.record(z3.any()), + strict: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "schema": "schemaDefinition" + }); + }); + exports.JsonSchema$outboundSchema = z3.object({ + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + schemaDefinition: z3.record(z3.any()), + strict: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + schemaDefinition: "schema" + }); + }); + function jsonSchemaToJSON(jsonSchema) { + return JSON.stringify(exports.JsonSchema$outboundSchema.parse(jsonSchema)); + } + function jsonSchemaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JsonSchema$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JsonSchema' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformats.js +var require_responseformats = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformats.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema = exports.ResponseFormats = void 0; + var z3 = __importStar(require_v3()); + exports.ResponseFormats = { + Text: "text", + JsonObject: "json_object", + JsonSchema: "json_schema" + }; + exports.ResponseFormats$inboundSchema = z3.nativeEnum(exports.ResponseFormats); + exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformat.js +var require_responseformat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseFormat$outboundSchema = exports.ResponseFormat$inboundSchema = void 0; + exports.responseFormatToJSON = responseFormatToJSON; + exports.responseFormatFromJSON = responseFormatFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var jsonschema_js_1 = require_jsonschema(); + var responseformats_js_1 = require_responseformats(); + exports.ResponseFormat$inboundSchema = z3.object({ + type: responseformats_js_1.ResponseFormats$inboundSchema.optional(), + json_schema: z3.nullable(jsonschema_js_1.JsonSchema$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "json_schema": "jsonSchema" + }); + }); + exports.ResponseFormat$outboundSchema = z3.object({ + type: responseformats_js_1.ResponseFormats$outboundSchema.optional(), + jsonSchema: z3.nullable(jsonschema_js_1.JsonSchema$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jsonSchema: "json_schema" + }); + }); + function responseFormatToJSON(responseFormat) { + return JSON.stringify(exports.ResponseFormat$outboundSchema.parse(responseFormat)); + } + function responseFormatFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseFormat$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseFormat' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoiceenum.js +var require_toolchoiceenum = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoiceenum.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema = exports.ToolChoiceEnum = void 0; + var z3 = __importStar(require_v3()); + exports.ToolChoiceEnum = { + Auto: "auto", + None: "none", + Any: "any", + Required: "required" + }; + exports.ToolChoiceEnum$inboundSchema = z3.nativeEnum(exports.ToolChoiceEnum); + exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargs.js +var require_completionargs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionArgs$outboundSchema = exports.CompletionArgs$inboundSchema = void 0; + exports.completionArgsToJSON = completionArgsToJSON; + exports.completionArgsFromJSON = completionArgsFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var completionargsstop_js_1 = require_completionargsstop(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + exports.CompletionArgs$inboundSchema = z3.object({ + stop: z3.nullable(completionargsstop_js_1.CompletionArgsStop$inboundSchema).optional(), + presence_penalty: z3.nullable(z3.number()).optional(), + frequency_penalty: z3.nullable(z3.number()).optional(), + temperature: z3.nullable(z3.number()).optional(), + top_p: z3.nullable(z3.number()).optional(), + max_tokens: z3.nullable(z3.number().int()).optional(), + random_seed: z3.nullable(z3.number().int()).optional(), + prediction: z3.nullable(prediction_js_1.Prediction$inboundSchema).optional(), + response_format: z3.nullable(responseformat_js_1.ResponseFormat$inboundSchema).optional(), + tool_choice: toolchoiceenum_js_1.ToolChoiceEnum$inboundSchema.optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "presence_penalty": "presencePenalty", + "frequency_penalty": "frequencyPenalty", + "top_p": "topP", + "max_tokens": "maxTokens", + "random_seed": "randomSeed", + "response_format": "responseFormat", + "tool_choice": "toolChoice" + }); + }); + exports.CompletionArgs$outboundSchema = z3.object({ + stop: z3.nullable(completionargsstop_js_1.CompletionArgsStop$outboundSchema).optional(), + presencePenalty: z3.nullable(z3.number()).optional(), + frequencyPenalty: z3.nullable(z3.number()).optional(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.nullable(z3.number()).optional(), + maxTokens: z3.nullable(z3.number().int()).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + prediction: z3.nullable(prediction_js_1.Prediction$outboundSchema).optional(), + responseFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(), + toolChoice: toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema.optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice" + }); + }); + function completionArgsToJSON(completionArgs) { + return JSON.stringify(exports.CompletionArgs$outboundSchema.parse(completionArgs)); + } + function completionArgsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionArgs$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionArgs' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentlibrarytool.js +var require_documentlibrarytool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentlibrarytool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentLibraryTool$outboundSchema = exports.DocumentLibraryTool$inboundSchema = exports.DocumentLibraryToolType$outboundSchema = exports.DocumentLibraryToolType$inboundSchema = exports.DocumentLibraryToolType = void 0; + exports.documentLibraryToolToJSON = documentLibraryToolToJSON; + exports.documentLibraryToolFromJSON = documentLibraryToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.DocumentLibraryToolType = { + DocumentLibrary: "document_library" + }; + exports.DocumentLibraryToolType$inboundSchema = z3.nativeEnum(exports.DocumentLibraryToolType); + exports.DocumentLibraryToolType$outboundSchema = exports.DocumentLibraryToolType$inboundSchema; + exports.DocumentLibraryTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.DocumentLibraryToolType$inboundSchema.default("document_library"), + library_ids: z3.array(z3.string()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration", + "library_ids": "libraryIds" + }); + }); + exports.DocumentLibraryTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.DocumentLibraryToolType$outboundSchema.default("document_library"), + libraryIds: z3.array(z3.string()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration", + libraryIds: "library_ids" + }); + }); + function documentLibraryToolToJSON(documentLibraryTool) { + return JSON.stringify(exports.DocumentLibraryTool$outboundSchema.parse(documentLibraryTool)); + } + function documentLibraryToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentLibraryTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentLibraryTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/function.js +var require_function = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/function.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionT$outboundSchema = exports.FunctionT$inboundSchema = void 0; + exports.functionToJSON = functionToJSON; + exports.functionFromJSON = functionFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.FunctionT$inboundSchema = z3.object({ + name: z3.string(), + description: z3.string().optional(), + strict: z3.boolean().optional(), + parameters: z3.record(z3.any()) + }); + exports.FunctionT$outboundSchema = z3.object({ + name: z3.string(), + description: z3.string().optional(), + strict: z3.boolean().optional(), + parameters: z3.record(z3.any()) + }); + function functionToJSON(functionT) { + return JSON.stringify(exports.FunctionT$outboundSchema.parse(functionT)); + } + function functionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionT$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionT' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functiontool.js +var require_functiontool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functiontool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionTool$outboundSchema = exports.FunctionTool$inboundSchema = exports.Type$outboundSchema = exports.Type$inboundSchema = exports.Type = void 0; + exports.functionToolToJSON = functionToolToJSON; + exports.functionToolFromJSON = functionToolFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var function_js_1 = require_function(); + exports.Type = { + Function: "function" + }; + exports.Type$inboundSchema = z3.nativeEnum(exports.Type); + exports.Type$outboundSchema = exports.Type$inboundSchema; + exports.FunctionTool$inboundSchema = z3.object({ + type: exports.Type$inboundSchema.default("function"), + function: function_js_1.FunctionT$inboundSchema + }); + exports.FunctionTool$outboundSchema = z3.object({ + type: exports.Type$outboundSchema.default("function"), + function: function_js_1.FunctionT$outboundSchema + }); + function functionToolToJSON(functionTool) { + return JSON.stringify(exports.FunctionTool$outboundSchema.parse(functionTool)); + } + function functionToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imagegenerationtool.js +var require_imagegenerationtool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imagegenerationtool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageGenerationTool$outboundSchema = exports.ImageGenerationTool$inboundSchema = exports.ImageGenerationToolType$outboundSchema = exports.ImageGenerationToolType$inboundSchema = exports.ImageGenerationToolType = void 0; + exports.imageGenerationToolToJSON = imageGenerationToolToJSON; + exports.imageGenerationToolFromJSON = imageGenerationToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.ImageGenerationToolType = { + ImageGeneration: "image_generation" + }; + exports.ImageGenerationToolType$inboundSchema = z3.nativeEnum(exports.ImageGenerationToolType); + exports.ImageGenerationToolType$outboundSchema = exports.ImageGenerationToolType$inboundSchema; + exports.ImageGenerationTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.ImageGenerationToolType$inboundSchema.default("image_generation") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.ImageGenerationTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.ImageGenerationToolType$outboundSchema.default("image_generation") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function imageGenerationToolToJSON(imageGenerationTool) { + return JSON.stringify(exports.ImageGenerationTool$outboundSchema.parse(imageGenerationTool)); + } + function imageGenerationToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageGenerationTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageGenerationTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchpremiumtool.js +var require_websearchpremiumtool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchpremiumtool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSearchPremiumTool$outboundSchema = exports.WebSearchPremiumTool$inboundSchema = exports.WebSearchPremiumToolType$outboundSchema = exports.WebSearchPremiumToolType$inboundSchema = exports.WebSearchPremiumToolType = void 0; + exports.webSearchPremiumToolToJSON = webSearchPremiumToolToJSON; + exports.webSearchPremiumToolFromJSON = webSearchPremiumToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.WebSearchPremiumToolType = { + WebSearchPremium: "web_search_premium" + }; + exports.WebSearchPremiumToolType$inboundSchema = z3.nativeEnum(exports.WebSearchPremiumToolType); + exports.WebSearchPremiumToolType$outboundSchema = exports.WebSearchPremiumToolType$inboundSchema; + exports.WebSearchPremiumTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.WebSearchPremiumToolType$inboundSchema.default("web_search_premium") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.WebSearchPremiumTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.WebSearchPremiumToolType$outboundSchema.default("web_search_premium") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function webSearchPremiumToolToJSON(webSearchPremiumTool) { + return JSON.stringify(exports.WebSearchPremiumTool$outboundSchema.parse(webSearchPremiumTool)); + } + function webSearchPremiumToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WebSearchPremiumTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WebSearchPremiumTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchtool.js +var require_websearchtool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchtool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSearchTool$outboundSchema = exports.WebSearchTool$inboundSchema = exports.WebSearchToolType$outboundSchema = exports.WebSearchToolType$inboundSchema = exports.WebSearchToolType = void 0; + exports.webSearchToolToJSON = webSearchToolToJSON; + exports.webSearchToolFromJSON = webSearchToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.WebSearchToolType = { + WebSearch: "web_search" + }; + exports.WebSearchToolType$inboundSchema = z3.nativeEnum(exports.WebSearchToolType); + exports.WebSearchToolType$outboundSchema = exports.WebSearchToolType$inboundSchema; + exports.WebSearchTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.WebSearchToolType$inboundSchema.default("web_search") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.WebSearchTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.WebSearchToolType$outboundSchema.default("web_search") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function webSearchToolToJSON(webSearchTool) { + return JSON.stringify(exports.WebSearchTool$outboundSchema.parse(webSearchTool)); + } + function webSearchToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WebSearchTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WebSearchTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agent.js +var require_agent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Agent$inboundSchema = exports.AgentTools$inboundSchema = void 0; + exports.agentToolsFromJSON = agentToolsFromJSON; + exports.agentFromJSON = agentFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.AgentTools$inboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function agentToolsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentTools$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentTools' from JSON`); + } + exports.Agent$inboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completion_args: completionargs_js_1.CompletionArgs$inboundSchema.optional(), + model: z3.string(), + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + handoffs: z3.nullable(z3.array(z3.string())).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + object: z3.literal("agent").default("agent"), + id: z3.string(), + version: z3.number().int(), + versions: z3.array(z3.number().int()), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + deployment_chat: z3.boolean(), + source: z3.string(), + version_message: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_args": "completionArgs", + "created_at": "createdAt", + "updated_at": "updatedAt", + "deployment_chat": "deploymentChat", + "version_message": "versionMessage" + }); + }); + function agentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Agent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Agent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentaliasresponse.js +var require_agentaliasresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentaliasresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentAliasResponse$inboundSchema = void 0; + exports.agentAliasResponseFromJSON = agentAliasResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentAliasResponse$inboundSchema = z3.object({ + alias: z3.string(), + version: z3.number().int(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "updated_at": "updatedAt" + }); + }); + function agentAliasResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentAliasResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentAliasResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentconversation.js +var require_agentconversation = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentconversation.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentConversation$inboundSchema = exports.AgentConversationAgentVersion$inboundSchema = void 0; + exports.agentConversationAgentVersionFromJSON = agentConversationAgentVersionFromJSON; + exports.agentConversationFromJSON = agentConversationFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentConversationAgentVersion$inboundSchema = z3.union([z3.string(), z3.number().int()]); + function agentConversationAgentVersionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentConversationAgentVersion$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentConversationAgentVersion' from JSON`); + } + exports.AgentConversation$inboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + object: z3.literal("conversation").default("conversation"), + id: z3.string(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + agent_id: z3.string(), + agent_version: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "updated_at": "updatedAt", + "agent_id": "agentId", + "agent_version": "agentVersion" + }); + }); + function agentConversationFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentConversation$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentConversation' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentcreationrequest.js +var require_agentcreationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentcreationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentCreationRequest$outboundSchema = exports.AgentCreationRequestTools$outboundSchema = void 0; + exports.agentCreationRequestToolsToJSON = agentCreationRequestToolsToJSON; + exports.agentCreationRequestToJSON = agentCreationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.AgentCreationRequestTools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function agentCreationRequestToolsToJSON(agentCreationRequestTools) { + return JSON.stringify(exports.AgentCreationRequestTools$outboundSchema.parse(agentCreationRequestTools)); + } + exports.AgentCreationRequest$outboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + model: z3.string(), + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + handoffs: z3.nullable(z3.array(z3.string())).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + versionMessage: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + completionArgs: "completion_args", + versionMessage: "version_message" + }); + }); + function agentCreationRequestToJSON(agentCreationRequest) { + return JSON.stringify(exports.AgentCreationRequest$outboundSchema.parse(agentCreationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffdoneevent.js +var require_agenthandoffdoneevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffdoneevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentHandoffDoneEvent$inboundSchema = void 0; + exports.agentHandoffDoneEventFromJSON = agentHandoffDoneEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentHandoffDoneEvent$inboundSchema = z3.object({ + type: z3.literal("agent.handoff.done").default("agent.handoff.done"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + next_agent_id: z3.string(), + next_agent_name: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "next_agent_id": "nextAgentId", + "next_agent_name": "nextAgentName" + }); + }); + function agentHandoffDoneEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffDoneEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffentry.js +var require_agenthandoffentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentHandoffEntry$outboundSchema = exports.AgentHandoffEntry$inboundSchema = void 0; + exports.agentHandoffEntryToJSON = agentHandoffEntryToJSON; + exports.agentHandoffEntryFromJSON = agentHandoffEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentHandoffEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("agent.handoff").default("agent.handoff"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + previous_agent_id: z3.string(), + previous_agent_name: z3.string(), + next_agent_id: z3.string(), + next_agent_name: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "previous_agent_id": "previousAgentId", + "previous_agent_name": "previousAgentName", + "next_agent_id": "nextAgentId", + "next_agent_name": "nextAgentName" + }); + }); + exports.AgentHandoffEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("agent.handoff").default("agent.handoff"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + previousAgentId: z3.string(), + previousAgentName: z3.string(), + nextAgentId: z3.string(), + nextAgentName: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + previousAgentId: "previous_agent_id", + previousAgentName: "previous_agent_name", + nextAgentId: "next_agent_id", + nextAgentName: "next_agent_name" + }); + }); + function agentHandoffEntryToJSON(agentHandoffEntry) { + return JSON.stringify(exports.AgentHandoffEntry$outboundSchema.parse(agentHandoffEntry)); + } + function agentHandoffEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffstartedevent.js +var require_agenthandoffstartedevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffstartedevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentHandoffStartedEvent$inboundSchema = void 0; + exports.agentHandoffStartedEventFromJSON = agentHandoffStartedEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentHandoffStartedEvent$inboundSchema = z3.object({ + type: z3.literal("agent.handoff.started").default("agent.handoff.started"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + previous_agent_id: z3.string(), + previous_agent_name: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "previous_agent_id": "previousAgentId", + "previous_agent_name": "previousAgentName" + }); + }); + function agentHandoffStartedEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffStartedEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiochunk.js +var require_audiochunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiochunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioChunk$outboundSchema = exports.AudioChunk$inboundSchema = void 0; + exports.audioChunkToJSON = audioChunkToJSON; + exports.audioChunkFromJSON = audioChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AudioChunk$inboundSchema = z3.object({ + type: z3.literal("input_audio").default("input_audio"), + input_audio: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "input_audio": "inputAudio" + }); + }); + exports.AudioChunk$outboundSchema = z3.object({ + type: z3.literal("input_audio").default("input_audio"), + inputAudio: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputAudio: "input_audio" + }); + }); + function audioChunkToJSON(audioChunk) { + return JSON.stringify(exports.AudioChunk$outboundSchema.parse(audioChunk)); + } + function audioChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AudioChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AudioChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documenturlchunk.js +var require_documenturlchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documenturlchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentURLChunk$outboundSchema = exports.DocumentURLChunk$inboundSchema = void 0; + exports.documentURLChunkToJSON = documentURLChunkToJSON; + exports.documentURLChunkFromJSON = documentURLChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.DocumentURLChunk$inboundSchema = z3.object({ + type: z3.literal("document_url").default("document_url"), + document_url: z3.string(), + document_name: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "document_url": "documentUrl", + "document_name": "documentName" + }); + }); + exports.DocumentURLChunk$outboundSchema = z3.object({ + type: z3.literal("document_url").default("document_url"), + documentUrl: z3.string(), + documentName: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + documentUrl: "document_url", + documentName: "document_name" + }); + }); + function documentURLChunkToJSON(documentURLChunk) { + return JSON.stringify(exports.DocumentURLChunk$outboundSchema.parse(documentURLChunk)); + } + function documentURLChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentURLChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentURLChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filechunk.js +var require_filechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/filechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileChunk$outboundSchema = exports.FileChunk$inboundSchema = void 0; + exports.fileChunkToJSON = fileChunkToJSON; + exports.fileChunkFromJSON = fileChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FileChunk$inboundSchema = z3.object({ + type: z3.literal("file").default("file"), + file_id: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "file_id": "fileId" + }); + }); + exports.FileChunk$outboundSchema = z3.object({ + type: z3.literal("file").default("file"), + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function fileChunkToJSON(fileChunk) { + return JSON.stringify(exports.FileChunk$outboundSchema.parse(fileChunk)); + } + function fileChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imagedetail.js +var require_imagedetail = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imagedetail.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageDetail$outboundSchema = exports.ImageDetail$inboundSchema = exports.ImageDetail = void 0; + var z3 = __importStar(require_v3()); + exports.ImageDetail = { + Low: "low", + Auto: "auto", + High: "high" + }; + exports.ImageDetail$inboundSchema = z3.nativeEnum(exports.ImageDetail); + exports.ImageDetail$outboundSchema = exports.ImageDetail$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurl.js +var require_imageurl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageURL$outboundSchema = exports.ImageURL$inboundSchema = void 0; + exports.imageURLToJSON = imageURLToJSON; + exports.imageURLFromJSON = imageURLFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var imagedetail_js_1 = require_imagedetail(); + exports.ImageURL$inboundSchema = z3.object({ + url: z3.string(), + detail: z3.nullable(imagedetail_js_1.ImageDetail$inboundSchema).optional() + }); + exports.ImageURL$outboundSchema = z3.object({ + url: z3.string(), + detail: z3.nullable(imagedetail_js_1.ImageDetail$outboundSchema).optional() + }); + function imageURLToJSON(imageURL) { + return JSON.stringify(exports.ImageURL$outboundSchema.parse(imageURL)); + } + function imageURLFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURL' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurlchunk.js +var require_imageurlchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurlchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageURLChunk$outboundSchema = exports.ImageURLChunk$inboundSchema = exports.ImageURLChunkImageURL$outboundSchema = exports.ImageURLChunkImageURL$inboundSchema = void 0; + exports.imageURLChunkImageURLToJSON = imageURLChunkImageURLToJSON; + exports.imageURLChunkImageURLFromJSON = imageURLChunkImageURLFromJSON; + exports.imageURLChunkToJSON = imageURLChunkToJSON; + exports.imageURLChunkFromJSON = imageURLChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var imageurl_js_1 = require_imageurl(); + exports.ImageURLChunkImageURL$inboundSchema = z3.union([imageurl_js_1.ImageURL$inboundSchema, z3.string()]); + exports.ImageURLChunkImageURL$outboundSchema = z3.union([imageurl_js_1.ImageURL$outboundSchema, z3.string()]); + function imageURLChunkImageURLToJSON(imageURLChunkImageURL) { + return JSON.stringify(exports.ImageURLChunkImageURL$outboundSchema.parse(imageURLChunkImageURL)); + } + function imageURLChunkImageURLFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURLChunkImageURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURLChunkImageURL' from JSON`); + } + exports.ImageURLChunk$inboundSchema = z3.object({ + type: z3.literal("image_url").default("image_url"), + image_url: z3.union([imageurl_js_1.ImageURL$inboundSchema, z3.string()]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "image_url": "imageUrl" + }); + }); + exports.ImageURLChunk$outboundSchema = z3.object({ + type: z3.literal("image_url").default("image_url"), + imageUrl: z3.union([imageurl_js_1.ImageURL$outboundSchema, z3.string()]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + imageUrl: "image_url" + }); + }); + function imageURLChunkToJSON(imageURLChunk) { + return JSON.stringify(exports.ImageURLChunk$outboundSchema.parse(imageURLChunk)); + } + function imageURLChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURLChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURLChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/referencechunk.js +var require_referencechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/referencechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ReferenceChunk$outboundSchema = exports.ReferenceChunk$inboundSchema = void 0; + exports.referenceChunkToJSON = referenceChunkToJSON; + exports.referenceChunkFromJSON = referenceChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ReferenceChunk$inboundSchema = z3.object({ + type: z3.literal("reference").default("reference"), + reference_ids: z3.array(z3.number().int()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "reference_ids": "referenceIds" + }); + }); + exports.ReferenceChunk$outboundSchema = z3.object({ + type: z3.literal("reference").default("reference"), + referenceIds: z3.array(z3.number().int()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + referenceIds: "reference_ids" + }); + }); + function referenceChunkToJSON(referenceChunk) { + return JSON.stringify(exports.ReferenceChunk$outboundSchema.parse(referenceChunk)); + } + function referenceChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ReferenceChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ReferenceChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/textchunk.js +var require_textchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/textchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TextChunk$outboundSchema = exports.TextChunk$inboundSchema = void 0; + exports.textChunkToJSON = textChunkToJSON; + exports.textChunkFromJSON = textChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.TextChunk$inboundSchema = z3.object({ + type: z3.literal("text").default("text"), + text: z3.string() + }); + exports.TextChunk$outboundSchema = z3.object({ + type: z3.literal("text").default("text"), + text: z3.string() + }); + function textChunkToJSON(textChunk) { + return JSON.stringify(exports.TextChunk$outboundSchema.parse(textChunk)); + } + function textChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TextChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TextChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/builtinconnectors.js +var require_builtinconnectors = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/builtinconnectors.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BuiltInConnectors$outboundSchema = exports.BuiltInConnectors$inboundSchema = exports.BuiltInConnectors = void 0; + var z3 = __importStar(require_v3()); + exports.BuiltInConnectors = { + WebSearch: "web_search", + WebSearchPremium: "web_search_premium", + CodeInterpreter: "code_interpreter", + ImageGeneration: "image_generation", + DocumentLibrary: "document_library" + }; + exports.BuiltInConnectors$inboundSchema = z3.nativeEnum(exports.BuiltInConnectors); + exports.BuiltInConnectors$outboundSchema = exports.BuiltInConnectors$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolreferencechunk.js +var require_toolreferencechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolreferencechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolReferenceChunk$outboundSchema = exports.ToolReferenceChunk$inboundSchema = exports.ToolReferenceChunkTool$outboundSchema = exports.ToolReferenceChunkTool$inboundSchema = void 0; + exports.toolReferenceChunkToolToJSON = toolReferenceChunkToolToJSON; + exports.toolReferenceChunkToolFromJSON = toolReferenceChunkToolFromJSON; + exports.toolReferenceChunkToJSON = toolReferenceChunkToJSON; + exports.toolReferenceChunkFromJSON = toolReferenceChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolReferenceChunkTool$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + exports.ToolReferenceChunkTool$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]); + function toolReferenceChunkToolToJSON(toolReferenceChunkTool) { + return JSON.stringify(exports.ToolReferenceChunkTool$outboundSchema.parse(toolReferenceChunkTool)); + } + function toolReferenceChunkToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolReferenceChunkTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolReferenceChunkTool' from JSON`); + } + exports.ToolReferenceChunk$inboundSchema = z3.object({ + type: z3.literal("tool_reference").default("tool_reference"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + title: z3.string(), + url: z3.nullable(z3.string()).optional(), + favicon: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + exports.ToolReferenceChunk$outboundSchema = z3.object({ + type: z3.literal("tool_reference").default("tool_reference"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]), + title: z3.string(), + url: z3.nullable(z3.string()).optional(), + favicon: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + function toolReferenceChunkToJSON(toolReferenceChunk) { + return JSON.stringify(exports.ToolReferenceChunk$outboundSchema.parse(toolReferenceChunk)); + } + function toolReferenceChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolReferenceChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolReferenceChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/thinkchunk.js +var require_thinkchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/thinkchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ThinkChunk$outboundSchema = exports.ThinkChunk$inboundSchema = exports.Thinking$outboundSchema = exports.Thinking$inboundSchema = void 0; + exports.thinkingToJSON = thinkingToJSON; + exports.thinkingFromJSON = thinkingFromJSON; + exports.thinkChunkToJSON = thinkChunkToJSON; + exports.thinkChunkFromJSON = thinkChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var textchunk_js_1 = require_textchunk(); + var toolreferencechunk_js_1 = require_toolreferencechunk(); + exports.Thinking$inboundSchema = z3.union([toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, textchunk_js_1.TextChunk$inboundSchema]); + exports.Thinking$outboundSchema = z3.union([toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, textchunk_js_1.TextChunk$outboundSchema]); + function thinkingToJSON(thinking) { + return JSON.stringify(exports.Thinking$outboundSchema.parse(thinking)); + } + function thinkingFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Thinking$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Thinking' from JSON`); + } + exports.ThinkChunk$inboundSchema = z3.object({ + type: z3.literal("thinking").default("thinking"), + thinking: z3.array(z3.union([toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, textchunk_js_1.TextChunk$inboundSchema])), + closed: z3.boolean().default(true) + }); + exports.ThinkChunk$outboundSchema = z3.object({ + type: z3.literal("thinking").default("thinking"), + thinking: z3.array(z3.union([toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, textchunk_js_1.TextChunk$outboundSchema])), + closed: z3.boolean().default(true) + }); + function thinkChunkToJSON(thinkChunk) { + return JSON.stringify(exports.ThinkChunk$outboundSchema.parse(thinkChunk)); + } + function thinkChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ThinkChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ThinkChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/contentchunk.js +var require_contentchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/contentchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ContentChunk$outboundSchema = exports.ContentChunk$inboundSchema = void 0; + exports.contentChunkToJSON = contentChunkToJSON; + exports.contentChunkFromJSON = contentChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var audiochunk_js_1 = require_audiochunk(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var filechunk_js_1 = require_filechunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var referencechunk_js_1 = require_referencechunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + exports.ContentChunk$inboundSchema = z3.union([ + imageurlchunk_js_1.ImageURLChunk$inboundSchema.and(z3.object({ type: z3.literal("image_url") })), + documenturlchunk_js_1.DocumentURLChunk$inboundSchema.and(z3.object({ type: z3.literal("document_url") })), + textchunk_js_1.TextChunk$inboundSchema.and(z3.object({ type: z3.literal("text") })), + referencechunk_js_1.ReferenceChunk$inboundSchema.and(z3.object({ type: z3.literal("reference") })), + filechunk_js_1.FileChunk$inboundSchema.and(z3.object({ type: z3.literal("file") })), + thinkchunk_js_1.ThinkChunk$inboundSchema.and(z3.object({ type: z3.literal("thinking") })), + audiochunk_js_1.AudioChunk$inboundSchema.and(z3.object({ type: z3.literal("input_audio") })) + ]); + exports.ContentChunk$outboundSchema = z3.union([ + imageurlchunk_js_1.ImageURLChunk$outboundSchema.and(z3.object({ type: z3.literal("image_url") })), + documenturlchunk_js_1.DocumentURLChunk$outboundSchema.and(z3.object({ type: z3.literal("document_url") })), + textchunk_js_1.TextChunk$outboundSchema.and(z3.object({ type: z3.literal("text") })), + referencechunk_js_1.ReferenceChunk$outboundSchema.and(z3.object({ type: z3.literal("reference") })), + filechunk_js_1.FileChunk$outboundSchema.and(z3.object({ type: z3.literal("file") })), + thinkchunk_js_1.ThinkChunk$outboundSchema.and(z3.object({ type: z3.literal("thinking") })), + audiochunk_js_1.AudioChunk$outboundSchema.and(z3.object({ type: z3.literal("input_audio") })) + ]); + function contentChunkToJSON(contentChunk) { + return JSON.stringify(exports.ContentChunk$outboundSchema.parse(contentChunk)); + } + function contentChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ContentChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ContentChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncall.js +var require_functioncall = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncall.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCall$outboundSchema = exports.FunctionCall$inboundSchema = exports.Arguments$outboundSchema = exports.Arguments$inboundSchema = void 0; + exports.argumentsToJSON = argumentsToJSON; + exports.argumentsFromJSON = argumentsFromJSON; + exports.functionCallToJSON = functionCallToJSON; + exports.functionCallFromJSON = functionCallFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Arguments$inboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + exports.Arguments$outboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + function argumentsToJSON(value) { + return JSON.stringify(exports.Arguments$outboundSchema.parse(value)); + } + function argumentsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Arguments$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Arguments' from JSON`); + } + exports.FunctionCall$inboundSchema = z3.object({ + name: z3.string(), + arguments: z3.union([z3.record(z3.any()), z3.string()]) + }); + exports.FunctionCall$outboundSchema = z3.object({ + name: z3.string(), + arguments: z3.union([z3.record(z3.any()), z3.string()]) + }); + function functionCallToJSON(functionCall) { + return JSON.stringify(exports.FunctionCall$outboundSchema.parse(functionCall)); + } + function functionCallFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCall$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCall' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/unrecognized.js +var require_unrecognized = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/unrecognized.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.startCountingUnrecognized = startCountingUnrecognized; + exports.unrecognized = unrecognized; + function unrecognized(value) { + globalCount++; + return value; + } + var globalCount = 0; + var refCount = 0; + function startCountingUnrecognized() { + refCount++; + const start = globalCount; + return { + /** + * Ends counting and returns the delta. + * @param delta - If provided, only this amount is added to the parent counter + * (used for nested unions where we only want to record the winning option's count). + * If not provided, records all counts since start(). + */ + end: (delta) => { + const count = globalCount - start; + globalCount = start + (delta ?? count); + if (--refCount === 0) + globalCount = 0; + return count; + } + }; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/enums.js +var require_enums = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/enums.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.inboundSchema = inboundSchema; + exports.inboundSchemaInt = inboundSchemaInt; + exports.outboundSchema = outboundSchema; + exports.outboundSchemaInt = outboundSchemaInt; + var z3 = __importStar(require_v3()); + var unrecognized_js_1 = require_unrecognized(); + function inboundSchema(enumObj) { + const options = Object.values(enumObj); + return z3.union([ + ...options.map((x2) => z3.literal(x2)), + z3.string().transform((x2) => (0, unrecognized_js_1.unrecognized)(x2)) + ]); + } + function inboundSchemaInt(enumObj) { + const options = Object.values(enumObj).filter((v4) => typeof v4 === "number"); + return z3.union([ + ...options.map((x2) => z3.literal(x2)), + z3.number().int().transform((x2) => (0, unrecognized_js_1.unrecognized)(x2)) + ]); + } + function outboundSchema(_3) { + return z3.string(); + } + function outboundSchemaInt(_3) { + return z3.number().int(); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/tooltypes.js +var require_tooltypes = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/tooltypes.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolTypes$outboundSchema = exports.ToolTypes$inboundSchema = exports.ToolTypes = void 0; + var openEnums = __importStar(require_enums()); + exports.ToolTypes = { + Function: "function" + }; + exports.ToolTypes$inboundSchema = openEnums.inboundSchema(exports.ToolTypes); + exports.ToolTypes$outboundSchema = openEnums.outboundSchema(exports.ToolTypes); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcall.js +var require_toolcall = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcall.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolCall$outboundSchema = exports.ToolCall$inboundSchema = void 0; + exports.toolCallToJSON = toolCallToJSON; + exports.toolCallFromJSON = toolCallFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var functioncall_js_1 = require_functioncall(); + var tooltypes_js_1 = require_tooltypes(); + exports.ToolCall$inboundSchema = z3.object({ + id: z3.string().default("null"), + type: tooltypes_js_1.ToolTypes$inboundSchema.optional(), + function: functioncall_js_1.FunctionCall$inboundSchema, + index: z3.number().int().default(0) + }); + exports.ToolCall$outboundSchema = z3.object({ + id: z3.string().default("null"), + type: tooltypes_js_1.ToolTypes$outboundSchema.optional(), + function: functioncall_js_1.FunctionCall$outboundSchema, + index: z3.number().int().default(0) + }); + function toolCallToJSON(toolCall) { + return JSON.stringify(exports.ToolCall$outboundSchema.parse(toolCall)); + } + function toolCallFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolCall$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolCall' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/assistantmessage.js +var require_assistantmessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/assistantmessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AssistantMessage$outboundSchema = exports.AssistantMessage$inboundSchema = exports.AssistantMessageContent$outboundSchema = exports.AssistantMessageContent$inboundSchema = void 0; + exports.assistantMessageContentToJSON = assistantMessageContentToJSON; + exports.assistantMessageContentFromJSON = assistantMessageContentFromJSON; + exports.assistantMessageToJSON = assistantMessageToJSON; + exports.assistantMessageFromJSON = assistantMessageFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var contentchunk_js_1 = require_contentchunk(); + var toolcall_js_1 = require_toolcall(); + exports.AssistantMessageContent$inboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)]); + exports.AssistantMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]); + function assistantMessageContentToJSON(assistantMessageContent) { + return JSON.stringify(exports.AssistantMessageContent$outboundSchema.parse(assistantMessageContent)); + } + function assistantMessageContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AssistantMessageContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AssistantMessageContent' from JSON`); + } + exports.AssistantMessage$inboundSchema = z3.object({ + role: z3.literal("assistant").default("assistant"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)])).optional(), + tool_calls: z3.nullable(z3.array(toolcall_js_1.ToolCall$inboundSchema)).optional(), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_calls": "toolCalls" + }); + }); + exports.AssistantMessage$outboundSchema = z3.object({ + role: z3.literal("assistant").default("assistant"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])).optional(), + toolCalls: z3.nullable(z3.array(toolcall_js_1.ToolCall$outboundSchema)).optional(), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolCalls: "tool_calls" + }); + }); + function assistantMessageToJSON(assistantMessage) { + return JSON.stringify(exports.AssistantMessage$outboundSchema.parse(assistantMessage)); + } + function assistantMessageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AssistantMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AssistantMessage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/mistralpromptmode.js +var require_mistralpromptmode = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/mistralpromptmode.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralPromptMode$outboundSchema = exports.MistralPromptMode = void 0; + var openEnums = __importStar(require_enums()); + exports.MistralPromptMode = { + Reasoning: "reasoning" + }; + exports.MistralPromptMode$outboundSchema = openEnums.outboundSchema(exports.MistralPromptMode); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessagecontentchunks.js +var require_systemmessagecontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessagecontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SystemMessageContentChunks$outboundSchema = void 0; + exports.systemMessageContentChunksToJSON = systemMessageContentChunksToJSON; + var z3 = __importStar(require_v3()); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + exports.SystemMessageContentChunks$outboundSchema = z3.union([ + textchunk_js_1.TextChunk$outboundSchema.and(z3.object({ type: z3.literal("text") })), + thinkchunk_js_1.ThinkChunk$outboundSchema.and(z3.object({ type: z3.literal("thinking") })) + ]); + function systemMessageContentChunksToJSON(systemMessageContentChunks) { + return JSON.stringify(exports.SystemMessageContentChunks$outboundSchema.parse(systemMessageContentChunks)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessage.js +var require_systemmessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SystemMessage$outboundSchema = exports.SystemMessageContent$outboundSchema = void 0; + exports.systemMessageContentToJSON = systemMessageContentToJSON; + exports.systemMessageToJSON = systemMessageToJSON; + var z3 = __importStar(require_v3()); + var systemmessagecontentchunks_js_1 = require_systemmessagecontentchunks(); + exports.SystemMessageContent$outboundSchema = z3.union([z3.string(), z3.array(systemmessagecontentchunks_js_1.SystemMessageContentChunks$outboundSchema)]); + function systemMessageContentToJSON(systemMessageContent) { + return JSON.stringify(exports.SystemMessageContent$outboundSchema.parse(systemMessageContent)); + } + exports.SystemMessage$outboundSchema = z3.object({ + role: z3.literal("system").default("system"), + content: z3.union([ + z3.string(), + z3.array(systemmessagecontentchunks_js_1.SystemMessageContentChunks$outboundSchema) + ]) + }); + function systemMessageToJSON(systemMessage) { + return JSON.stringify(exports.SystemMessage$outboundSchema.parse(systemMessage)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/tool.js +var require_tool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/tool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Tool$outboundSchema = void 0; + exports.toolToJSON = toolToJSON; + var z3 = __importStar(require_v3()); + var function_js_1 = require_function(); + var tooltypes_js_1 = require_tooltypes(); + exports.Tool$outboundSchema = z3.object({ + type: tooltypes_js_1.ToolTypes$outboundSchema.optional(), + function: function_js_1.FunctionT$outboundSchema + }); + function toolToJSON(tool) { + return JSON.stringify(exports.Tool$outboundSchema.parse(tool)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functionname.js +var require_functionname = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functionname.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionName$outboundSchema = void 0; + exports.functionNameToJSON = functionNameToJSON; + var z3 = __importStar(require_v3()); + exports.FunctionName$outboundSchema = z3.object({ + name: z3.string() + }); + function functionNameToJSON(functionName) { + return JSON.stringify(exports.FunctionName$outboundSchema.parse(functionName)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoice.js +var require_toolchoice = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoice.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolChoice$outboundSchema = void 0; + exports.toolChoiceToJSON = toolChoiceToJSON; + var z3 = __importStar(require_v3()); + var functionname_js_1 = require_functionname(); + var tooltypes_js_1 = require_tooltypes(); + exports.ToolChoice$outboundSchema = z3.object({ + type: tooltypes_js_1.ToolTypes$outboundSchema.optional(), + function: functionname_js_1.FunctionName$outboundSchema + }); + function toolChoiceToJSON(toolChoice) { + return JSON.stringify(exports.ToolChoice$outboundSchema.parse(toolChoice)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolmessage.js +var require_toolmessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolmessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolMessage$outboundSchema = exports.ToolMessageContent$outboundSchema = void 0; + exports.toolMessageContentToJSON = toolMessageContentToJSON; + exports.toolMessageToJSON = toolMessageToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var contentchunk_js_1 = require_contentchunk(); + exports.ToolMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]); + function toolMessageContentToJSON(toolMessageContent) { + return JSON.stringify(exports.ToolMessageContent$outboundSchema.parse(toolMessageContent)); + } + exports.ToolMessage$outboundSchema = z3.object({ + role: z3.literal("tool").default("tool"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])), + toolCallId: z3.nullable(z3.string()).optional(), + name: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolCallId: "tool_call_id" + }); + }); + function toolMessageToJSON(toolMessage) { + return JSON.stringify(exports.ToolMessage$outboundSchema.parse(toolMessage)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/usermessage.js +var require_usermessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/usermessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UserMessage$outboundSchema = exports.UserMessageContent$outboundSchema = void 0; + exports.userMessageContentToJSON = userMessageContentToJSON; + exports.userMessageToJSON = userMessageToJSON; + var z3 = __importStar(require_v3()); + var contentchunk_js_1 = require_contentchunk(); + exports.UserMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]); + function userMessageContentToJSON(userMessageContent) { + return JSON.stringify(exports.UserMessageContent$outboundSchema.parse(userMessageContent)); + } + exports.UserMessage$outboundSchema = z3.object({ + role: z3.literal("user").default("user"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])) + }); + function userMessageToJSON(userMessage) { + return JSON.stringify(exports.UserMessage$outboundSchema.parse(userMessage)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionrequest.js +var require_agentscompletionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsCompletionRequest$outboundSchema = exports.AgentsCompletionRequestToolChoice$outboundSchema = exports.AgentsCompletionRequestMessages$outboundSchema = exports.AgentsCompletionRequestStop$outboundSchema = void 0; + exports.agentsCompletionRequestStopToJSON = agentsCompletionRequestStopToJSON; + exports.agentsCompletionRequestMessagesToJSON = agentsCompletionRequestMessagesToJSON; + exports.agentsCompletionRequestToolChoiceToJSON = agentsCompletionRequestToolChoiceToJSON; + exports.agentsCompletionRequestToJSON = agentsCompletionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.AgentsCompletionRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function agentsCompletionRequestStopToJSON(agentsCompletionRequestStop) { + return JSON.stringify(exports.AgentsCompletionRequestStop$outboundSchema.parse(agentsCompletionRequestStop)); + } + exports.AgentsCompletionRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function agentsCompletionRequestMessagesToJSON(agentsCompletionRequestMessages) { + return JSON.stringify(exports.AgentsCompletionRequestMessages$outboundSchema.parse(agentsCompletionRequestMessages)); + } + exports.AgentsCompletionRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function agentsCompletionRequestToolChoiceToJSON(agentsCompletionRequestToolChoice) { + return JSON.stringify(exports.AgentsCompletionRequestToolChoice$outboundSchema.parse(agentsCompletionRequestToolChoice)); + } + exports.AgentsCompletionRequest$outboundSchema = z3.object({ + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(false), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + agentId: "agent_id" + }); + }); + function agentsCompletionRequestToJSON(agentsCompletionRequest) { + return JSON.stringify(exports.AgentsCompletionRequest$outboundSchema.parse(agentsCompletionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionstreamrequest.js +var require_agentscompletionstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsCompletionStreamRequest$outboundSchema = exports.AgentsCompletionStreamRequestToolChoice$outboundSchema = exports.AgentsCompletionStreamRequestMessages$outboundSchema = exports.AgentsCompletionStreamRequestStop$outboundSchema = void 0; + exports.agentsCompletionStreamRequestStopToJSON = agentsCompletionStreamRequestStopToJSON; + exports.agentsCompletionStreamRequestMessagesToJSON = agentsCompletionStreamRequestMessagesToJSON; + exports.agentsCompletionStreamRequestToolChoiceToJSON = agentsCompletionStreamRequestToolChoiceToJSON; + exports.agentsCompletionStreamRequestToJSON = agentsCompletionStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.AgentsCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function agentsCompletionStreamRequestStopToJSON(agentsCompletionStreamRequestStop) { + return JSON.stringify(exports.AgentsCompletionStreamRequestStop$outboundSchema.parse(agentsCompletionStreamRequestStop)); + } + exports.AgentsCompletionStreamRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function agentsCompletionStreamRequestMessagesToJSON(agentsCompletionStreamRequestMessages) { + return JSON.stringify(exports.AgentsCompletionStreamRequestMessages$outboundSchema.parse(agentsCompletionStreamRequestMessages)); + } + exports.AgentsCompletionStreamRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function agentsCompletionStreamRequestToolChoiceToJSON(agentsCompletionStreamRequestToolChoice) { + return JSON.stringify(exports.AgentsCompletionStreamRequestToolChoice$outboundSchema.parse(agentsCompletionStreamRequestToolChoice)); + } + exports.AgentsCompletionStreamRequest$outboundSchema = z3.object({ + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(true), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + agentId: "agent_id" + }); + }); + function agentsCompletionStreamRequestToJSON(agentsCompletionStreamRequest) { + return JSON.stringify(exports.AgentsCompletionStreamRequest$outboundSchema.parse(agentsCompletionStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentupdaterequest.js +var require_agentupdaterequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentupdaterequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentUpdateRequest$outboundSchema = exports.AgentUpdateRequestTools$outboundSchema = void 0; + exports.agentUpdateRequestToolsToJSON = agentUpdateRequestToolsToJSON; + exports.agentUpdateRequestToJSON = agentUpdateRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.AgentUpdateRequestTools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function agentUpdateRequestToolsToJSON(agentUpdateRequestTools) { + return JSON.stringify(exports.AgentUpdateRequestTools$outboundSchema.parse(agentUpdateRequestTools)); + } + exports.AgentUpdateRequest$outboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + model: z3.nullable(z3.string()).optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + handoffs: z3.nullable(z3.array(z3.string())).optional(), + deploymentChat: z3.nullable(z3.boolean()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + versionMessage: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + completionArgs: "completion_args", + deploymentChat: "deployment_chat", + versionMessage: "version_message" + }); + }); + function agentUpdateRequestToJSON(agentUpdateRequest) { + return JSON.stringify(exports.AgentUpdateRequest$outboundSchema.parse(agentUpdateRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/apiendpoint.js +var require_apiendpoint = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/apiendpoint.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ApiEndpoint$outboundSchema = exports.ApiEndpoint = void 0; + var openEnums = __importStar(require_enums()); + exports.ApiEndpoint = { + RootV1ChatCompletions: "/v1/chat/completions", + RootV1Embeddings: "/v1/embeddings", + RootV1FimCompletions: "/v1/fim/completions", + RootV1Moderations: "/v1/moderations", + RootV1ChatModerations: "/v1/chat/moderations", + RootV1Ocr: "/v1/ocr", + RootV1Classifications: "/v1/classifications", + RootV1ChatClassifications: "/v1/chat/classifications", + RootV1Conversations: "/v1/conversations", + RootV1AudioTranscriptions: "/v1/audio/transcriptions" + }; + exports.ApiEndpoint$outboundSchema = openEnums.outboundSchema(exports.ApiEndpoint); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/archiveftmodelout.js +var require_archiveftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/archiveftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ArchiveFTModelOut$inboundSchema = void 0; + exports.archiveFTModelOutFromJSON = archiveFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.ArchiveFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + archived: z3.boolean().default(true) + }); + function archiveFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ArchiveFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ArchiveFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audioencoding.js +var require_audioencoding = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audioencoding.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioEncoding$outboundSchema = exports.AudioEncoding$inboundSchema = exports.AudioEncoding = void 0; + var openEnums = __importStar(require_enums()); + exports.AudioEncoding = { + PcmS16le: "pcm_s16le", + PcmS32le: "pcm_s32le", + PcmF16le: "pcm_f16le", + PcmF32le: "pcm_f32le", + PcmMulaw: "pcm_mulaw", + PcmAlaw: "pcm_alaw" + }; + exports.AudioEncoding$inboundSchema = openEnums.inboundSchema(exports.AudioEncoding); + exports.AudioEncoding$outboundSchema = openEnums.outboundSchema(exports.AudioEncoding); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audioformat.js +var require_audioformat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audioformat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioFormat$outboundSchema = exports.AudioFormat$inboundSchema = void 0; + exports.audioFormatToJSON = audioFormatToJSON; + exports.audioFormatFromJSON = audioFormatFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var audioencoding_js_1 = require_audioencoding(); + exports.AudioFormat$inboundSchema = z3.object({ + encoding: audioencoding_js_1.AudioEncoding$inboundSchema, + sample_rate: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "sample_rate": "sampleRate" + }); + }); + exports.AudioFormat$outboundSchema = z3.object({ + encoding: audioencoding_js_1.AudioEncoding$outboundSchema, + sampleRate: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + sampleRate: "sample_rate" + }); + }); + function audioFormatToJSON(audioFormat) { + return JSON.stringify(exports.AudioFormat$outboundSchema.parse(audioFormat)); + } + function audioFormatFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AudioFormat$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AudioFormat' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/blobs.js +var require_blobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/blobs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.blobLikeSchema = void 0; + exports.isBlobLike = isBlobLike4; + var z3 = __importStar(require_v3()); + exports.blobLikeSchema = z3.custom(isBlobLike4, { + message: "expected a Blob, File or Blob-like object", + fatal: true + }); + function isBlobLike4(val2) { + if (val2 instanceof Blob) { + return true; + } + if (typeof val2 !== "object" || val2 == null || !(Symbol.toStringTag in val2)) { + return false; + } + const name = val2[Symbol.toStringTag]; + if (typeof name !== "string") { + return false; + } + if (name !== "Blob" && name !== "File") { + return false; + } + return "stream" in val2 && typeof val2.stream === "function"; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/file.js +var require_file = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/file.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileT$outboundSchema = void 0; + exports.fileToJSON = fileToJSON; + var z3 = __importStar(require_v3()); + exports.FileT$outboundSchema = z3.object({ + fileName: z3.string(), + content: z3.union([ + z3.instanceof(ReadableStream), + z3.instanceof(Blob), + z3.instanceof(ArrayBuffer), + z3.instanceof(Uint8Array) + ]) + }); + function fileToJSON(fileT) { + return JSON.stringify(exports.FileT$outboundSchema.parse(fileT)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/timestampgranularity.js +var require_timestampgranularity = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/timestampgranularity.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TimestampGranularity$outboundSchema = exports.TimestampGranularity = void 0; + var z3 = __importStar(require_v3()); + exports.TimestampGranularity = { + Segment: "segment", + Word: "word" + }; + exports.TimestampGranularity$outboundSchema = z3.nativeEnum(exports.TimestampGranularity); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequest.js +var require_audiotranscriptionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioTranscriptionRequest$outboundSchema = void 0; + exports.audioTranscriptionRequestToJSON = audioTranscriptionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var blobs_js_1 = require_blobs(); + var file_js_1 = require_file(); + var timestampgranularity_js_1 = require_timestampgranularity(); + exports.AudioTranscriptionRequest$outboundSchema = z3.object({ + model: z3.string(), + file: file_js_1.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema).optional(), + fileUrl: z3.nullable(z3.string()).optional(), + fileId: z3.nullable(z3.string()).optional(), + language: z3.nullable(z3.string()).optional(), + temperature: z3.nullable(z3.number()).optional(), + stream: z3.literal(false).default(false), + diarize: z3.boolean().default(false), + contextBias: z3.array(z3.string()).optional(), + timestampGranularities: z3.array(timestampgranularity_js_1.TimestampGranularity$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileUrl: "file_url", + fileId: "file_id", + contextBias: "context_bias", + timestampGranularities: "timestamp_granularities" + }); + }); + function audioTranscriptionRequestToJSON(audioTranscriptionRequest) { + return JSON.stringify(exports.AudioTranscriptionRequest$outboundSchema.parse(audioTranscriptionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequeststream.js +var require_audiotranscriptionrequeststream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequeststream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioTranscriptionRequestStream$outboundSchema = void 0; + exports.audioTranscriptionRequestStreamToJSON = audioTranscriptionRequestStreamToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var blobs_js_1 = require_blobs(); + var file_js_1 = require_file(); + var timestampgranularity_js_1 = require_timestampgranularity(); + exports.AudioTranscriptionRequestStream$outboundSchema = z3.object({ + model: z3.string(), + file: file_js_1.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema).optional(), + fileUrl: z3.nullable(z3.string()).optional(), + fileId: z3.nullable(z3.string()).optional(), + language: z3.nullable(z3.string()).optional(), + temperature: z3.nullable(z3.number()).optional(), + stream: z3.literal(true).default(true), + diarize: z3.boolean().default(false), + contextBias: z3.array(z3.string()).optional(), + timestampGranularities: z3.array(timestampgranularity_js_1.TimestampGranularity$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileUrl: "file_url", + fileId: "file_id", + contextBias: "context_bias", + timestampGranularities: "timestamp_granularities" + }); + }); + function audioTranscriptionRequestStreamToJSON(audioTranscriptionRequestStream) { + return JSON.stringify(exports.AudioTranscriptionRequestStream$outboundSchema.parse(audioTranscriptionRequestStream)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modelcapabilities.js +var require_modelcapabilities = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/modelcapabilities.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModelCapabilities$inboundSchema = void 0; + exports.modelCapabilitiesFromJSON = modelCapabilitiesFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ModelCapabilities$inboundSchema = z3.object({ + completion_chat: z3.boolean().default(false), + function_calling: z3.boolean().default(false), + completion_fim: z3.boolean().default(false), + fine_tuning: z3.boolean().default(false), + vision: z3.boolean().default(false), + ocr: z3.boolean().default(false), + classification: z3.boolean().default(false), + moderation: z3.boolean().default(false), + audio: z3.boolean().default(false), + audio_transcription: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_chat": "completionChat", + "function_calling": "functionCalling", + "completion_fim": "completionFim", + "fine_tuning": "fineTuning", + "audio_transcription": "audioTranscription" + }); + }); + function modelCapabilitiesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelCapabilities$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelCapabilities' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/basemodelcard.js +var require_basemodelcard = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/basemodelcard.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaseModelCard$inboundSchema = void 0; + exports.baseModelCardFromJSON = baseModelCardFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var modelcapabilities_js_1 = require_modelcapabilities(); + exports.BaseModelCard$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().default("model"), + created: z3.number().int().optional(), + owned_by: z3.string().default("mistralai"), + capabilities: modelcapabilities_js_1.ModelCapabilities$inboundSchema, + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + deprecation: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + deprecation_replacement_model: z3.nullable(z3.string()).optional(), + default_model_temperature: z3.nullable(z3.number()).optional(), + type: z3.literal("base").default("base") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "max_context_length": "maxContextLength", + "deprecation_replacement_model": "deprecationReplacementModel", + "default_model_temperature": "defaultModelTemperature" + }); + }); + function baseModelCardFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BaseModelCard$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BaseModelCard' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batcherror.js +var require_batcherror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batcherror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchError$inboundSchema = void 0; + exports.batchErrorFromJSON = batchErrorFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.BatchError$inboundSchema = z3.object({ + message: z3.string(), + count: z3.number().int().default(1) + }); + function batchErrorFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchError' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchrequest.js +var require_batchrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchRequest$outboundSchema = void 0; + exports.batchRequestToJSON = batchRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.BatchRequest$outboundSchema = z3.object({ + customId: z3.nullable(z3.string()).optional(), + body: z3.record(z3.any()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + customId: "custom_id" + }); + }); + function batchRequestToJSON(batchRequest) { + return JSON.stringify(exports.BatchRequest$outboundSchema.parse(batchRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobin.js +var require_batchjobin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobIn$outboundSchema = void 0; + exports.batchJobInToJSON = batchJobInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var apiendpoint_js_1 = require_apiendpoint(); + var batchrequest_js_1 = require_batchrequest(); + exports.BatchJobIn$outboundSchema = z3.object({ + inputFiles: z3.nullable(z3.array(z3.string())).optional(), + requests: z3.nullable(z3.array(batchrequest_js_1.BatchRequest$outboundSchema)).optional(), + endpoint: apiendpoint_js_1.ApiEndpoint$outboundSchema, + model: z3.nullable(z3.string()).optional(), + agentId: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.string())).optional(), + timeoutHours: z3.number().int().default(24) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputFiles: "input_files", + agentId: "agent_id", + timeoutHours: "timeout_hours" + }); + }); + function batchJobInToJSON(batchJobIn) { + return JSON.stringify(exports.BatchJobIn$outboundSchema.parse(batchJobIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobstatus.js +var require_batchjobstatus = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobstatus.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema = exports.BatchJobStatus = void 0; + var z3 = __importStar(require_v3()); + exports.BatchJobStatus = { + Queued: "QUEUED", + Running: "RUNNING", + Success: "SUCCESS", + Failed: "FAILED", + TimeoutExceeded: "TIMEOUT_EXCEEDED", + CancellationRequested: "CANCELLATION_REQUESTED", + Cancelled: "CANCELLED" + }; + exports.BatchJobStatus$inboundSchema = z3.nativeEnum(exports.BatchJobStatus); + exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobout.js +var require_batchjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobOut$inboundSchema = void 0; + exports.batchJobOutFromJSON = batchJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var batcherror_js_1 = require_batcherror(); + var batchjobstatus_js_1 = require_batchjobstatus(); + exports.BatchJobOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("batch").default("batch"), + input_files: z3.array(z3.string()), + metadata: z3.nullable(z3.record(z3.any())).optional(), + endpoint: z3.string(), + model: z3.nullable(z3.string()).optional(), + agent_id: z3.nullable(z3.string()).optional(), + output_file: z3.nullable(z3.string()).optional(), + error_file: z3.nullable(z3.string()).optional(), + errors: z3.array(batcherror_js_1.BatchError$inboundSchema), + outputs: z3.nullable(z3.array(z3.record(z3.any()))).optional(), + status: batchjobstatus_js_1.BatchJobStatus$inboundSchema, + created_at: z3.number().int(), + total_requests: z3.number().int(), + completed_requests: z3.number().int(), + succeeded_requests: z3.number().int(), + failed_requests: z3.number().int(), + started_at: z3.nullable(z3.number().int()).optional(), + completed_at: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "input_files": "inputFiles", + "agent_id": "agentId", + "output_file": "outputFile", + "error_file": "errorFile", + "created_at": "createdAt", + "total_requests": "totalRequests", + "completed_requests": "completedRequests", + "succeeded_requests": "succeededRequests", + "failed_requests": "failedRequests", + "started_at": "startedAt", + "completed_at": "completedAt" + }); + }); + function batchJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobsout.js +var require_batchjobsout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobsout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobsOut$inboundSchema = void 0; + exports.batchJobsOutFromJSON = batchJobsOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var batchjobout_js_1 = require_batchjobout(); + exports.BatchJobsOut$inboundSchema = z3.object({ + data: z3.array(batchjobout_js_1.BatchJobOut$inboundSchema).optional(), + object: z3.literal("list").default("list"), + total: z3.number().int() + }); + function batchJobsOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchJobsOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchJobsOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/instructrequest.js +var require_instructrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/instructrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstructRequest$outboundSchema = exports.InstructRequestMessages$outboundSchema = void 0; + exports.instructRequestMessagesToJSON = instructRequestMessagesToJSON; + exports.instructRequestToJSON = instructRequestToJSON; + var z3 = __importStar(require_v3()); + var assistantmessage_js_1 = require_assistantmessage(); + var systemmessage_js_1 = require_systemmessage(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.InstructRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function instructRequestMessagesToJSON(instructRequestMessages) { + return JSON.stringify(exports.InstructRequestMessages$outboundSchema.parse(instructRequestMessages)); + } + exports.InstructRequest$outboundSchema = z3.object({ + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])) + }); + function instructRequestToJSON(instructRequest) { + return JSON.stringify(exports.InstructRequest$outboundSchema.parse(instructRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/inputs.js +var require_inputs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/inputs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Inputs$outboundSchema = void 0; + exports.inputsToJSON = inputsToJSON; + var z3 = __importStar(require_v3()); + var instructrequest_js_1 = require_instructrequest(); + exports.Inputs$outboundSchema = z3.union([ + instructrequest_js_1.InstructRequest$outboundSchema, + z3.array(instructrequest_js_1.InstructRequest$outboundSchema) + ]); + function inputsToJSON(inputs) { + return JSON.stringify(exports.Inputs$outboundSchema.parse(inputs)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatclassificationrequest.js +var require_chatclassificationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatclassificationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatClassificationRequest$outboundSchema = void 0; + exports.chatClassificationRequestToJSON = chatClassificationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var inputs_js_1 = require_inputs(); + exports.ChatClassificationRequest$outboundSchema = z3.object({ + model: z3.string(), + inputs: inputs_js_1.Inputs$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input" + }); + }); + function chatClassificationRequestToJSON(chatClassificationRequest) { + return JSON.stringify(exports.ChatClassificationRequest$outboundSchema.parse(chatClassificationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionchoice.js +var require_chatcompletionchoice = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionchoice.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionChoice$inboundSchema = exports.FinishReason$inboundSchema = exports.FinishReason = void 0; + exports.chatCompletionChoiceFromJSON = chatCompletionChoiceFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var openEnums = __importStar(require_enums()); + var assistantmessage_js_1 = require_assistantmessage(); + exports.FinishReason = { + Stop: "stop", + Length: "length", + ModelLength: "model_length", + Error: "error", + ToolCalls: "tool_calls" + }; + exports.FinishReason$inboundSchema = openEnums.inboundSchema(exports.FinishReason); + exports.ChatCompletionChoice$inboundSchema = z3.object({ + index: z3.number().int(), + message: assistantmessage_js_1.AssistantMessage$inboundSchema, + finish_reason: exports.FinishReason$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "finish_reason": "finishReason" + }); + }); + function chatCompletionChoiceFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ChatCompletionChoice$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ChatCompletionChoice' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionrequest.js +var require_chatcompletionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionRequest$outboundSchema = exports.ChatCompletionRequestToolChoice$outboundSchema = exports.Messages$outboundSchema = exports.Stop$outboundSchema = void 0; + exports.stopToJSON = stopToJSON; + exports.messagesToJSON = messagesToJSON; + exports.chatCompletionRequestToolChoiceToJSON = chatCompletionRequestToolChoiceToJSON; + exports.chatCompletionRequestToJSON = chatCompletionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.Stop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function stopToJSON(stop) { + return JSON.stringify(exports.Stop$outboundSchema.parse(stop)); + } + exports.Messages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function messagesToJSON(messages) { + return JSON.stringify(exports.Messages$outboundSchema.parse(messages)); + } + exports.ChatCompletionRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function chatCompletionRequestToolChoiceToJSON(chatCompletionRequestToolChoice) { + return JSON.stringify(exports.ChatCompletionRequestToolChoice$outboundSchema.parse(chatCompletionRequestToolChoice)); + } + exports.ChatCompletionRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().optional(), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(false), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + safePrompt: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + safePrompt: "safe_prompt" + }); + }); + function chatCompletionRequestToJSON(chatCompletionRequest) { + return JSON.stringify(exports.ChatCompletionRequest$outboundSchema.parse(chatCompletionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/usageinfo.js +var require_usageinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/usageinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UsageInfo$outboundSchema = exports.UsageInfo$inboundSchema = void 0; + exports.usageInfoToJSON = usageInfoToJSON; + exports.usageInfoFromJSON = usageInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.UsageInfo$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + prompt_tokens: z3.number().int().default(0), + completion_tokens: z3.number().int().default(0), + total_tokens: z3.number().int().default(0), + prompt_audio_seconds: z3.nullable(z3.number().int()).optional() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "prompt_tokens": "promptTokens", + "completion_tokens": "completionTokens", + "total_tokens": "totalTokens", + "prompt_audio_seconds": "promptAudioSeconds" + }); + }); + exports.UsageInfo$outboundSchema = z3.object({ + promptTokens: z3.number().int().default(0), + completionTokens: z3.number().int().default(0), + totalTokens: z3.number().int().default(0), + promptAudioSeconds: z3.nullable(z3.number().int()).optional(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + promptTokens: "prompt_tokens", + completionTokens: "completion_tokens", + totalTokens: "total_tokens", + promptAudioSeconds: "prompt_audio_seconds", + additionalProperties: null + }) + }; + }); + function usageInfoToJSON(usageInfo) { + return JSON.stringify(exports.UsageInfo$outboundSchema.parse(usageInfo)); + } + function usageInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UsageInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionresponse.js +var require_chatcompletionresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionResponse$inboundSchema = void 0; + exports.chatCompletionResponseFromJSON = chatCompletionResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var chatcompletionchoice_js_1 = require_chatcompletionchoice(); + var usageinfo_js_1 = require_usageinfo(); + exports.ChatCompletionResponse$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + created: z3.number().int(), + choices: z3.array(chatcompletionchoice_js_1.ChatCompletionChoice$inboundSchema) + }); + function chatCompletionResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ChatCompletionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ChatCompletionResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionstreamrequest.js +var require_chatcompletionstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionStreamRequest$outboundSchema = exports.ChatCompletionStreamRequestToolChoice$outboundSchema = exports.ChatCompletionStreamRequestMessages$outboundSchema = exports.ChatCompletionStreamRequestStop$outboundSchema = void 0; + exports.chatCompletionStreamRequestStopToJSON = chatCompletionStreamRequestStopToJSON; + exports.chatCompletionStreamRequestMessagesToJSON = chatCompletionStreamRequestMessagesToJSON; + exports.chatCompletionStreamRequestToolChoiceToJSON = chatCompletionStreamRequestToolChoiceToJSON; + exports.chatCompletionStreamRequestToJSON = chatCompletionStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.ChatCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function chatCompletionStreamRequestStopToJSON(chatCompletionStreamRequestStop) { + return JSON.stringify(exports.ChatCompletionStreamRequestStop$outboundSchema.parse(chatCompletionStreamRequestStop)); + } + exports.ChatCompletionStreamRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function chatCompletionStreamRequestMessagesToJSON(chatCompletionStreamRequestMessages) { + return JSON.stringify(exports.ChatCompletionStreamRequestMessages$outboundSchema.parse(chatCompletionStreamRequestMessages)); + } + exports.ChatCompletionStreamRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function chatCompletionStreamRequestToolChoiceToJSON(chatCompletionStreamRequestToolChoice) { + return JSON.stringify(exports.ChatCompletionStreamRequestToolChoice$outboundSchema.parse(chatCompletionStreamRequestToolChoice)); + } + exports.ChatCompletionStreamRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().optional(), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(true), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + safePrompt: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + safePrompt: "safe_prompt" + }); + }); + function chatCompletionStreamRequestToJSON(chatCompletionStreamRequest) { + return JSON.stringify(exports.ChatCompletionStreamRequest$outboundSchema.parse(chatCompletionStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatmoderationrequest.js +var require_chatmoderationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatmoderationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatModerationRequest$outboundSchema = exports.ChatModerationRequestInputs$outboundSchema = exports.One$outboundSchema = exports.Two$outboundSchema = void 0; + exports.twoToJSON = twoToJSON; + exports.oneToJSON = oneToJSON; + exports.chatModerationRequestInputsToJSON = chatModerationRequestInputsToJSON; + exports.chatModerationRequestToJSON = chatModerationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var systemmessage_js_1 = require_systemmessage(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.Two$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function twoToJSON(two) { + return JSON.stringify(exports.Two$outboundSchema.parse(two)); + } + exports.One$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function oneToJSON(one) { + return JSON.stringify(exports.One$outboundSchema.parse(one)); + } + exports.ChatModerationRequestInputs$outboundSchema = z3.union([ + z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + z3.array(z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]))) + ]); + function chatModerationRequestInputsToJSON(chatModerationRequestInputs) { + return JSON.stringify(exports.ChatModerationRequestInputs$outboundSchema.parse(chatModerationRequestInputs)); + } + exports.ChatModerationRequest$outboundSchema = z3.object({ + inputs: z3.union([ + z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + z3.array(z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]))) + ]), + model: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input" + }); + }); + function chatModerationRequestToJSON(chatModerationRequest) { + return JSON.stringify(exports.ChatModerationRequest$outboundSchema.parse(chatModerationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/metricout.js +var require_metricout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/metricout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricOut$inboundSchema = void 0; + exports.metricOutFromJSON = metricOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.MetricOut$inboundSchema = z3.object({ + train_loss: z3.nullable(z3.number()).optional(), + valid_loss: z3.nullable(z3.number()).optional(), + valid_mean_token_accuracy: z3.nullable(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "train_loss": "trainLoss", + "valid_loss": "validLoss", + "valid_mean_token_accuracy": "validMeanTokenAccuracy" + }); + }); + function metricOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MetricOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MetricOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/checkpointout.js +var require_checkpointout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/checkpointout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CheckpointOut$inboundSchema = void 0; + exports.checkpointOutFromJSON = checkpointOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var metricout_js_1 = require_metricout(); + exports.CheckpointOut$inboundSchema = z3.object({ + metrics: metricout_js_1.MetricOut$inboundSchema, + step_number: z3.number().int(), + created_at: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "step_number": "stepNumber", + "created_at": "createdAt" + }); + }); + function checkpointOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CheckpointOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CheckpointOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationrequest.js +var require_classificationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassificationRequest$outboundSchema = exports.ClassificationRequestInputs$outboundSchema = void 0; + exports.classificationRequestInputsToJSON = classificationRequestInputsToJSON; + exports.classificationRequestToJSON = classificationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.ClassificationRequestInputs$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function classificationRequestInputsToJSON(classificationRequestInputs) { + return JSON.stringify(exports.ClassificationRequestInputs$outboundSchema.parse(classificationRequestInputs)); + } + exports.ClassificationRequest$outboundSchema = z3.object({ + model: z3.string(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + inputs: z3.union([z3.string(), z3.array(z3.string())]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input" + }); + }); + function classificationRequestToJSON(classificationRequest) { + return JSON.stringify(exports.ClassificationRequest$outboundSchema.parse(classificationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationtargetresult.js +var require_classificationtargetresult = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationtargetresult.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassificationTargetResult$inboundSchema = void 0; + exports.classificationTargetResultFromJSON = classificationTargetResultFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.ClassificationTargetResult$inboundSchema = z3.object({ + scores: z3.record(z3.number()) + }); + function classificationTargetResultFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassificationTargetResult$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassificationTargetResult' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationresponse.js +var require_classificationresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassificationResponse$inboundSchema = void 0; + exports.classificationResponseFromJSON = classificationResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var classificationtargetresult_js_1 = require_classificationtargetresult(); + exports.ClassificationResponse$inboundSchema = z3.object({ + id: z3.string(), + model: z3.string(), + results: z3.array(z3.record(classificationtargetresult_js_1.ClassificationTargetResult$inboundSchema)) + }); + function classificationResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassificationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassificationResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftclassifierlossfunction.js +var require_ftclassifierlossfunction = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftclassifierlossfunction.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FTClassifierLossFunction$outboundSchema = exports.FTClassifierLossFunction$inboundSchema = exports.FTClassifierLossFunction = void 0; + var z3 = __importStar(require_v3()); + exports.FTClassifierLossFunction = { + SingleClass: "single_class", + MultiClass: "multi_class" + }; + exports.FTClassifierLossFunction$inboundSchema = z3.nativeEnum(exports.FTClassifierLossFunction); + exports.FTClassifierLossFunction$outboundSchema = exports.FTClassifierLossFunction$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetout.js +var require_classifiertargetout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTargetOut$inboundSchema = void 0; + exports.classifierTargetOutFromJSON = classifierTargetOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var ftclassifierlossfunction_js_1 = require_ftclassifierlossfunction(); + exports.ClassifierTargetOut$inboundSchema = z3.object({ + name: z3.string(), + labels: z3.array(z3.string()), + weight: z3.number(), + loss_function: ftclassifierlossfunction_js_1.FTClassifierLossFunction$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "loss_function": "lossFunction" + }); + }); + function classifierTargetOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierTargetOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierTargetOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparameters.js +var require_classifiertrainingparameters = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparameters.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTrainingParameters$inboundSchema = void 0; + exports.classifierTrainingParametersFromJSON = classifierTrainingParametersFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ClassifierTrainingParameters$inboundSchema = z3.object({ + training_steps: z3.nullable(z3.number().int()).optional(), + learning_rate: z3.number().default(1e-4), + weight_decay: z3.nullable(z3.number()).optional(), + warmup_fraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seq_len: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "training_steps": "trainingSteps", + "learning_rate": "learningRate", + "weight_decay": "weightDecay", + "warmup_fraction": "warmupFraction", + "seq_len": "seqLen" + }); + }); + function classifierTrainingParametersFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierTrainingParameters$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierTrainingParameters' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/eventout.js +var require_eventout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/eventout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EventOut$inboundSchema = void 0; + exports.eventOutFromJSON = eventOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.EventOut$inboundSchema = z3.object({ + name: z3.string(), + data: z3.nullable(z3.record(z3.any())).optional(), + created_at: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt" + }); + }); + function eventOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EventOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EventOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobmetadataout.js +var require_jobmetadataout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobmetadataout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobMetadataOut$inboundSchema = void 0; + exports.jobMetadataOutFromJSON = jobMetadataOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.JobMetadataOut$inboundSchema = z3.object({ + expected_duration_seconds: z3.nullable(z3.number().int()).optional(), + cost: z3.nullable(z3.number()).optional(), + cost_currency: z3.nullable(z3.string()).optional(), + train_tokens_per_step: z3.nullable(z3.number().int()).optional(), + train_tokens: z3.nullable(z3.number().int()).optional(), + data_tokens: z3.nullable(z3.number().int()).optional(), + estimated_start_time: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "expected_duration_seconds": "expectedDurationSeconds", + "cost_currency": "costCurrency", + "train_tokens_per_step": "trainTokensPerStep", + "train_tokens": "trainTokens", + "data_tokens": "dataTokens", + "estimated_start_time": "estimatedStartTime" + }); + }); + function jobMetadataOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobMetadataOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobMetadataOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegrationout.js +var require_wandbintegrationout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegrationout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WandbIntegrationOut$inboundSchema = void 0; + exports.wandbIntegrationOutFromJSON = wandbIntegrationOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.WandbIntegrationOut$inboundSchema = z3.object({ + type: z3.literal("wandb").default("wandb"), + project: z3.string(), + name: z3.nullable(z3.string()).optional(), + run_name: z3.nullable(z3.string()).optional(), + url: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "run_name": "runName" + }); + }); + function wandbIntegrationOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WandbIntegrationOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WandbIntegrationOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierdetailedjobout.js +var require_classifierdetailedjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierdetailedjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierDetailedJobOut$inboundSchema = exports.ClassifierDetailedJobOutIntegrations$inboundSchema = exports.ClassifierDetailedJobOutStatus$inboundSchema = exports.ClassifierDetailedJobOutStatus = void 0; + exports.classifierDetailedJobOutIntegrationsFromJSON = classifierDetailedJobOutIntegrationsFromJSON; + exports.classifierDetailedJobOutFromJSON = classifierDetailedJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var checkpointout_js_1 = require_checkpointout(); + var classifiertargetout_js_1 = require_classifiertargetout(); + var classifiertrainingparameters_js_1 = require_classifiertrainingparameters(); + var eventout_js_1 = require_eventout(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.ClassifierDetailedJobOutStatus = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.ClassifierDetailedJobOutStatus$inboundSchema = z3.nativeEnum(exports.ClassifierDetailedJobOutStatus); + exports.ClassifierDetailedJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function classifierDetailedJobOutIntegrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierDetailedJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierDetailedJobOutIntegrations' from JSON`); + } + exports.ClassifierDetailedJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.ClassifierDetailedJobOutStatus$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("classifier").default("classifier"), + hyperparameters: classifiertrainingparameters_js_1.ClassifierTrainingParameters$inboundSchema, + events: z3.array(eventout_js_1.EventOut$inboundSchema).optional(), + checkpoints: z3.array(checkpointout_js_1.CheckpointOut$inboundSchema).optional(), + classifier_targets: z3.array(classifiertargetout_js_1.ClassifierTargetOut$inboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType", + "classifier_targets": "classifierTargets" + }); + }); + function classifierDetailedJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierDetailedJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierDetailedJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcapabilitiesout.js +var require_ftmodelcapabilitiesout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcapabilitiesout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FTModelCapabilitiesOut$inboundSchema = void 0; + exports.ftModelCapabilitiesOutFromJSON = ftModelCapabilitiesOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FTModelCapabilitiesOut$inboundSchema = z3.object({ + completion_chat: z3.boolean().default(true), + completion_fim: z3.boolean().default(false), + function_calling: z3.boolean().default(false), + fine_tuning: z3.boolean().default(false), + classification: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_chat": "completionChat", + "completion_fim": "completionFim", + "function_calling": "functionCalling", + "fine_tuning": "fineTuning" + }); + }); + function ftModelCapabilitiesOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FTModelCapabilitiesOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FTModelCapabilitiesOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierftmodelout.js +var require_classifierftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierFTModelOut$inboundSchema = void 0; + exports.classifierFTModelOutFromJSON = classifierFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var classifiertargetout_js_1 = require_classifiertargetout(); + var ftmodelcapabilitiesout_js_1 = require_ftmodelcapabilitiesout(); + exports.ClassifierFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + created: z3.number().int(), + owned_by: z3.string(), + workspace_id: z3.string(), + root: z3.string(), + root_version: z3.string(), + archived: z3.boolean(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + capabilities: ftmodelcapabilitiesout_js_1.FTModelCapabilitiesOut$inboundSchema, + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + job: z3.string(), + classifier_targets: z3.array(classifiertargetout_js_1.ClassifierTargetOut$inboundSchema), + model_type: z3.literal("classifier").default("classifier") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "workspace_id": "workspaceId", + "root_version": "rootVersion", + "max_context_length": "maxContextLength", + "classifier_targets": "classifierTargets", + "model_type": "modelType" + }); + }); + function classifierFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierjobout.js +var require_classifierjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierJobOut$inboundSchema = exports.ClassifierJobOutIntegrations$inboundSchema = exports.ClassifierJobOutStatus$inboundSchema = exports.ClassifierJobOutStatus = void 0; + exports.classifierJobOutIntegrationsFromJSON = classifierJobOutIntegrationsFromJSON; + exports.classifierJobOutFromJSON = classifierJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var classifiertrainingparameters_js_1 = require_classifiertrainingparameters(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.ClassifierJobOutStatus = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.ClassifierJobOutStatus$inboundSchema = z3.nativeEnum(exports.ClassifierJobOutStatus); + exports.ClassifierJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function classifierJobOutIntegrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierJobOutIntegrations' from JSON`); + } + exports.ClassifierJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.ClassifierJobOutStatus$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("classifier").default("classifier"), + hyperparameters: classifiertrainingparameters_js_1.ClassifierTrainingParameters$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType" + }); + }); + function classifierJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetin.js +var require_classifiertargetin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTargetIn$outboundSchema = void 0; + exports.classifierTargetInToJSON = classifierTargetInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var ftclassifierlossfunction_js_1 = require_ftclassifierlossfunction(); + exports.ClassifierTargetIn$outboundSchema = z3.object({ + name: z3.string(), + labels: z3.array(z3.string()), + weight: z3.number().default(1), + lossFunction: z3.nullable(ftclassifierlossfunction_js_1.FTClassifierLossFunction$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + lossFunction: "loss_function" + }); + }); + function classifierTargetInToJSON(classifierTargetIn) { + return JSON.stringify(exports.ClassifierTargetIn$outboundSchema.parse(classifierTargetIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparametersin.js +var require_classifiertrainingparametersin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparametersin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTrainingParametersIn$outboundSchema = void 0; + exports.classifierTrainingParametersInToJSON = classifierTrainingParametersInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.ClassifierTrainingParametersIn$outboundSchema = z3.object({ + trainingSteps: z3.nullable(z3.number().int()).optional(), + learningRate: z3.number().default(1e-4), + weightDecay: z3.nullable(z3.number()).optional(), + warmupFraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seqLen: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + trainingSteps: "training_steps", + learningRate: "learning_rate", + weightDecay: "weight_decay", + warmupFraction: "warmup_fraction", + seqLen: "seq_len" + }); + }); + function classifierTrainingParametersInToJSON(classifierTrainingParametersIn) { + return JSON.stringify(exports.ClassifierTrainingParametersIn$outboundSchema.parse(classifierTrainingParametersIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deltamessage.js +var require_deltamessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/deltamessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeltaMessage$inboundSchema = exports.Content$inboundSchema = void 0; + exports.contentFromJSON = contentFromJSON; + exports.deltaMessageFromJSON = deltaMessageFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var contentchunk_js_1 = require_contentchunk(); + var toolcall_js_1 = require_toolcall(); + exports.Content$inboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)]); + function contentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Content$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Content' from JSON`); + } + exports.DeltaMessage$inboundSchema = z3.object({ + role: z3.nullable(z3.string()).optional(), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)])).optional(), + tool_calls: z3.nullable(z3.array(toolcall_js_1.ToolCall$inboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_calls": "toolCalls" + }); + }); + function deltaMessageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeltaMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeltaMessage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionresponsestreamchoice.js +var require_completionresponsestreamchoice = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionresponsestreamchoice.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionResponseStreamChoice$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason = void 0; + exports.completionResponseStreamChoiceFromJSON = completionResponseStreamChoiceFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var openEnums = __importStar(require_enums()); + var deltamessage_js_1 = require_deltamessage(); + exports.CompletionResponseStreamChoiceFinishReason = { + Stop: "stop", + Length: "length", + Error: "error", + ToolCalls: "tool_calls" + }; + exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = openEnums.inboundSchema(exports.CompletionResponseStreamChoiceFinishReason); + exports.CompletionResponseStreamChoice$inboundSchema = z3.object({ + index: z3.number().int(), + delta: deltamessage_js_1.DeltaMessage$inboundSchema, + finish_reason: z3.nullable(exports.CompletionResponseStreamChoiceFinishReason$inboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "finish_reason": "finishReason" + }); + }); + function completionResponseStreamChoiceFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionResponseStreamChoice$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionResponseStreamChoice' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionchunk.js +var require_completionchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionChunk$inboundSchema = void 0; + exports.completionChunkFromJSON = completionChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var completionresponsestreamchoice_js_1 = require_completionresponsestreamchoice(); + var usageinfo_js_1 = require_usageinfo(); + exports.CompletionChunk$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().optional(), + created: z3.number().int().optional(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema.optional(), + choices: z3.array(completionresponsestreamchoice_js_1.CompletionResponseStreamChoice$inboundSchema) + }); + function completionChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparameters.js +var require_completiontrainingparameters = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparameters.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionTrainingParameters$inboundSchema = void 0; + exports.completionTrainingParametersFromJSON = completionTrainingParametersFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.CompletionTrainingParameters$inboundSchema = z3.object({ + training_steps: z3.nullable(z3.number().int()).optional(), + learning_rate: z3.number().default(1e-4), + weight_decay: z3.nullable(z3.number()).optional(), + warmup_fraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seq_len: z3.nullable(z3.number().int()).optional(), + fim_ratio: z3.nullable(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "training_steps": "trainingSteps", + "learning_rate": "learningRate", + "weight_decay": "weightDecay", + "warmup_fraction": "warmupFraction", + "seq_len": "seqLen", + "fim_ratio": "fimRatio" + }); + }); + function completionTrainingParametersFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionTrainingParameters$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionTrainingParameters' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryout.js +var require_githubrepositoryout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GithubRepositoryOut$inboundSchema = void 0; + exports.githubRepositoryOutFromJSON = githubRepositoryOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.GithubRepositoryOut$inboundSchema = z3.object({ + type: z3.literal("github").default("github"), + name: z3.string(), + owner: z3.string(), + ref: z3.nullable(z3.string()).optional(), + weight: z3.number().default(1), + commit_id: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "commit_id": "commitId" + }); + }); + function githubRepositoryOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.GithubRepositoryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'GithubRepositoryOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiondetailedjobout.js +var require_completiondetailedjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiondetailedjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionDetailedJobOut$inboundSchema = exports.CompletionDetailedJobOutRepositories$inboundSchema = exports.CompletionDetailedJobOutIntegrations$inboundSchema = exports.CompletionDetailedJobOutStatus$inboundSchema = exports.CompletionDetailedJobOutStatus = void 0; + exports.completionDetailedJobOutIntegrationsFromJSON = completionDetailedJobOutIntegrationsFromJSON; + exports.completionDetailedJobOutRepositoriesFromJSON = completionDetailedJobOutRepositoriesFromJSON; + exports.completionDetailedJobOutFromJSON = completionDetailedJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var checkpointout_js_1 = require_checkpointout(); + var completiontrainingparameters_js_1 = require_completiontrainingparameters(); + var eventout_js_1 = require_eventout(); + var githubrepositoryout_js_1 = require_githubrepositoryout(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.CompletionDetailedJobOutStatus = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.CompletionDetailedJobOutStatus$inboundSchema = z3.nativeEnum(exports.CompletionDetailedJobOutStatus); + exports.CompletionDetailedJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function completionDetailedJobOutIntegrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOutIntegrations' from JSON`); + } + exports.CompletionDetailedJobOutRepositories$inboundSchema = githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema; + function completionDetailedJobOutRepositoriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOutRepositories$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOutRepositories' from JSON`); + } + exports.CompletionDetailedJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.CompletionDetailedJobOutStatus$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("completion").default("completion"), + hyperparameters: completiontrainingparameters_js_1.CompletionTrainingParameters$inboundSchema, + repositories: z3.array(githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema).optional(), + events: z3.array(eventout_js_1.EventOut$inboundSchema).optional(), + checkpoints: z3.array(checkpointout_js_1.CheckpointOut$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType" + }); + }); + function completionDetailedJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionevent.js +var require_completionevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionEvent$inboundSchema = void 0; + exports.completionEventFromJSON = completionEventFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var completionchunk_js_1 = require_completionchunk(); + exports.CompletionEvent$inboundSchema = z3.object({ + data: z3.string().transform((v4, ctx) => { + try { + return JSON.parse(v4); + } catch (err) { + ctx.addIssue({ code: "custom", message: `malformed json: ${err}` }); + return z3.NEVER; + } + }).pipe(completionchunk_js_1.CompletionChunk$inboundSchema) + }); + function completionEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionftmodelout.js +var require_completionftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionFTModelOut$inboundSchema = void 0; + exports.completionFTModelOutFromJSON = completionFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var ftmodelcapabilitiesout_js_1 = require_ftmodelcapabilitiesout(); + exports.CompletionFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + created: z3.number().int(), + owned_by: z3.string(), + workspace_id: z3.string(), + root: z3.string(), + root_version: z3.string(), + archived: z3.boolean(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + capabilities: ftmodelcapabilitiesout_js_1.FTModelCapabilitiesOut$inboundSchema, + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + job: z3.string(), + model_type: z3.literal("completion").default("completion") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "workspace_id": "workspaceId", + "root_version": "rootVersion", + "max_context_length": "maxContextLength", + "model_type": "modelType" + }); + }); + function completionFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionjobout.js +var require_completionjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionJobOut$inboundSchema = exports.Repositories$inboundSchema = exports.Integrations$inboundSchema = exports.Status$inboundSchema = exports.Status = void 0; + exports.integrationsFromJSON = integrationsFromJSON; + exports.repositoriesFromJSON = repositoriesFromJSON; + exports.completionJobOutFromJSON = completionJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var completiontrainingparameters_js_1 = require_completiontrainingparameters(); + var githubrepositoryout_js_1 = require_githubrepositoryout(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.Status = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.Status$inboundSchema = z3.nativeEnum(exports.Status); + exports.Integrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function integrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Integrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Integrations' from JSON`); + } + exports.Repositories$inboundSchema = githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema; + function repositoriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Repositories$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Repositories' from JSON`); + } + exports.CompletionJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.Status$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("completion").default("completion"), + hyperparameters: completiontrainingparameters_js_1.CompletionTrainingParameters$inboundSchema, + repositories: z3.array(githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType" + }); + }); + function completionJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparametersin.js +var require_completiontrainingparametersin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparametersin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionTrainingParametersIn$outboundSchema = void 0; + exports.completionTrainingParametersInToJSON = completionTrainingParametersInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.CompletionTrainingParametersIn$outboundSchema = z3.object({ + trainingSteps: z3.nullable(z3.number().int()).optional(), + learningRate: z3.number().default(1e-4), + weightDecay: z3.nullable(z3.number()).optional(), + warmupFraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seqLen: z3.nullable(z3.number().int()).optional(), + fimRatio: z3.nullable(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + trainingSteps: "training_steps", + learningRate: "learning_rate", + weightDecay: "weight_decay", + warmupFraction: "warmup_fraction", + seqLen: "seq_len", + fimRatio: "fim_ratio" + }); + }); + function completionTrainingParametersInToJSON(completionTrainingParametersIn) { + return JSON.stringify(exports.CompletionTrainingParametersIn$outboundSchema.parse(completionTrainingParametersIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentryarguments.js +var require_functioncallentryarguments = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentryarguments.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCallEntryArguments$outboundSchema = exports.FunctionCallEntryArguments$inboundSchema = void 0; + exports.functionCallEntryArgumentsToJSON = functionCallEntryArgumentsToJSON; + exports.functionCallEntryArgumentsFromJSON = functionCallEntryArgumentsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.FunctionCallEntryArguments$inboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + exports.FunctionCallEntryArguments$outboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + function functionCallEntryArgumentsToJSON(functionCallEntryArguments) { + return JSON.stringify(exports.FunctionCallEntryArguments$outboundSchema.parse(functionCallEntryArguments)); + } + function functionCallEntryArgumentsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEntryArguments$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEntryArguments' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentry.js +var require_functioncallentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCallEntry$outboundSchema = exports.FunctionCallEntry$inboundSchema = exports.ConfirmationStatus$outboundSchema = exports.ConfirmationStatus$inboundSchema = exports.ConfirmationStatus = void 0; + exports.functionCallEntryToJSON = functionCallEntryToJSON; + exports.functionCallEntryFromJSON = functionCallEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var functioncallentryarguments_js_1 = require_functioncallentryarguments(); + exports.ConfirmationStatus = { + Pending: "pending", + Allowed: "allowed", + Denied: "denied" + }; + exports.ConfirmationStatus$inboundSchema = z3.nativeEnum(exports.ConfirmationStatus); + exports.ConfirmationStatus$outboundSchema = exports.ConfirmationStatus$inboundSchema; + exports.FunctionCallEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.call").default("function.call"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + tool_call_id: z3.string(), + name: z3.string(), + arguments: functioncallentryarguments_js_1.FunctionCallEntryArguments$inboundSchema, + confirmation_status: z3.nullable(exports.ConfirmationStatus$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "tool_call_id": "toolCallId", + "confirmation_status": "confirmationStatus" + }); + }); + exports.FunctionCallEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.call").default("function.call"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + toolCallId: z3.string(), + name: z3.string(), + arguments: functioncallentryarguments_js_1.FunctionCallEntryArguments$outboundSchema, + confirmationStatus: z3.nullable(exports.ConfirmationStatus$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + toolCallId: "tool_call_id", + confirmationStatus: "confirmation_status" + }); + }); + function functionCallEntryToJSON(functionCallEntry) { + return JSON.stringify(exports.FunctionCallEntry$outboundSchema.parse(functionCallEntry)); + } + function functionCallEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functionresultentry.js +var require_functionresultentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functionresultentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionResultEntry$outboundSchema = exports.FunctionResultEntry$inboundSchema = void 0; + exports.functionResultEntryToJSON = functionResultEntryToJSON; + exports.functionResultEntryFromJSON = functionResultEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FunctionResultEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.result").default("function.result"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + tool_call_id: z3.string(), + result: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "tool_call_id": "toolCallId" + }); + }); + exports.FunctionResultEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.result").default("function.result"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + toolCallId: z3.string(), + result: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + toolCallId: "tool_call_id" + }); + }); + function functionResultEntryToJSON(functionResultEntry) { + return JSON.stringify(exports.FunctionResultEntry$outboundSchema.parse(functionResultEntry)); + } + function functionResultEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionResultEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionResultEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolfilechunk.js +var require_toolfilechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolfilechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolFileChunk$outboundSchema = exports.ToolFileChunk$inboundSchema = exports.ToolFileChunkTool$outboundSchema = exports.ToolFileChunkTool$inboundSchema = void 0; + exports.toolFileChunkToolToJSON = toolFileChunkToolToJSON; + exports.toolFileChunkToolFromJSON = toolFileChunkToolFromJSON; + exports.toolFileChunkToJSON = toolFileChunkToJSON; + exports.toolFileChunkFromJSON = toolFileChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolFileChunkTool$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + exports.ToolFileChunkTool$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]); + function toolFileChunkToolToJSON(toolFileChunkTool) { + return JSON.stringify(exports.ToolFileChunkTool$outboundSchema.parse(toolFileChunkTool)); + } + function toolFileChunkToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolFileChunkTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolFileChunkTool' from JSON`); + } + exports.ToolFileChunk$inboundSchema = z3.object({ + type: z3.literal("tool_file").default("tool_file"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + file_id: z3.string(), + file_name: z3.nullable(z3.string()).optional(), + file_type: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "file_id": "fileId", + "file_name": "fileName", + "file_type": "fileType" + }); + }); + exports.ToolFileChunk$outboundSchema = z3.object({ + type: z3.literal("tool_file").default("tool_file"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]), + fileId: z3.string(), + fileName: z3.nullable(z3.string()).optional(), + fileType: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id", + fileName: "file_name", + fileType: "file_type" + }); + }); + function toolFileChunkToJSON(toolFileChunk) { + return JSON.stringify(exports.ToolFileChunk$outboundSchema.parse(toolFileChunk)); + } + function toolFileChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolFileChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolFileChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputcontentchunks.js +var require_messageinputcontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputcontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageInputContentChunks$outboundSchema = exports.MessageInputContentChunks$inboundSchema = void 0; + exports.messageInputContentChunksToJSON = messageInputContentChunksToJSON; + exports.messageInputContentChunksFromJSON = messageInputContentChunksFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + var toolfilechunk_js_1 = require_toolfilechunk(); + exports.MessageInputContentChunks$inboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$inboundSchema, + textchunk_js_1.TextChunk$inboundSchema, + imageurlchunk_js_1.ImageURLChunk$inboundSchema, + documenturlchunk_js_1.DocumentURLChunk$inboundSchema, + thinkchunk_js_1.ThinkChunk$inboundSchema + ]); + exports.MessageInputContentChunks$outboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$outboundSchema, + textchunk_js_1.TextChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + thinkchunk_js_1.ThinkChunk$outboundSchema + ]); + function messageInputContentChunksToJSON(messageInputContentChunks) { + return JSON.stringify(exports.MessageInputContentChunks$outboundSchema.parse(messageInputContentChunks)); + } + function messageInputContentChunksFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputContentChunks' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputentry.js +var require_messageinputentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageInputEntry$outboundSchema = exports.MessageInputEntry$inboundSchema = exports.MessageInputEntryContent$outboundSchema = exports.MessageInputEntryContent$inboundSchema = exports.Role$outboundSchema = exports.Role$inboundSchema = exports.Role = void 0; + exports.messageInputEntryContentToJSON = messageInputEntryContentToJSON; + exports.messageInputEntryContentFromJSON = messageInputEntryContentFromJSON; + exports.messageInputEntryToJSON = messageInputEntryToJSON; + exports.messageInputEntryFromJSON = messageInputEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var messageinputcontentchunks_js_1 = require_messageinputcontentchunks(); + exports.Role = { + Assistant: "assistant", + User: "user" + }; + exports.Role$inboundSchema = z3.nativeEnum(exports.Role); + exports.Role$outboundSchema = exports.Role$inboundSchema; + exports.MessageInputEntryContent$inboundSchema = z3.union([z3.string(), z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$inboundSchema)]); + exports.MessageInputEntryContent$outboundSchema = z3.union([z3.string(), z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$outboundSchema)]); + function messageInputEntryContentToJSON(messageInputEntryContent) { + return JSON.stringify(exports.MessageInputEntryContent$outboundSchema.parse(messageInputEntryContent)); + } + function messageInputEntryContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputEntryContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputEntryContent' from JSON`); + } + exports.MessageInputEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.input").default("message.input"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + role: exports.Role$inboundSchema, + content: z3.union([ + z3.string(), + z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$inboundSchema) + ]), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt" + }); + }); + exports.MessageInputEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.input").default("message.input"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + role: exports.Role$outboundSchema, + content: z3.union([ + z3.string(), + z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$outboundSchema) + ]), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at" + }); + }); + function messageInputEntryToJSON(messageInputEntry) { + return JSON.stringify(exports.MessageInputEntry$outboundSchema.parse(messageInputEntry)); + } + function messageInputEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputcontentchunks.js +var require_messageoutputcontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputcontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageOutputContentChunks$outboundSchema = exports.MessageOutputContentChunks$inboundSchema = void 0; + exports.messageOutputContentChunksToJSON = messageOutputContentChunksToJSON; + exports.messageOutputContentChunksFromJSON = messageOutputContentChunksFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + var toolfilechunk_js_1 = require_toolfilechunk(); + var toolreferencechunk_js_1 = require_toolreferencechunk(); + exports.MessageOutputContentChunks$inboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$inboundSchema, + toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, + textchunk_js_1.TextChunk$inboundSchema, + imageurlchunk_js_1.ImageURLChunk$inboundSchema, + documenturlchunk_js_1.DocumentURLChunk$inboundSchema, + thinkchunk_js_1.ThinkChunk$inboundSchema + ]); + exports.MessageOutputContentChunks$outboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$outboundSchema, + toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, + textchunk_js_1.TextChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + thinkchunk_js_1.ThinkChunk$outboundSchema + ]); + function messageOutputContentChunksToJSON(messageOutputContentChunks) { + return JSON.stringify(exports.MessageOutputContentChunks$outboundSchema.parse(messageOutputContentChunks)); + } + function messageOutputContentChunksFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputContentChunks' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputentry.js +var require_messageoutputentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageOutputEntry$outboundSchema = exports.MessageOutputEntry$inboundSchema = exports.MessageOutputEntryContent$outboundSchema = exports.MessageOutputEntryContent$inboundSchema = void 0; + exports.messageOutputEntryContentToJSON = messageOutputEntryContentToJSON; + exports.messageOutputEntryContentFromJSON = messageOutputEntryContentFromJSON; + exports.messageOutputEntryToJSON = messageOutputEntryToJSON; + exports.messageOutputEntryFromJSON = messageOutputEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var messageoutputcontentchunks_js_1 = require_messageoutputcontentchunks(); + exports.MessageOutputEntryContent$inboundSchema = z3.union([z3.string(), z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$inboundSchema)]); + exports.MessageOutputEntryContent$outboundSchema = z3.union([z3.string(), z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$outboundSchema)]); + function messageOutputEntryContentToJSON(messageOutputEntryContent) { + return JSON.stringify(exports.MessageOutputEntryContent$outboundSchema.parse(messageOutputEntryContent)); + } + function messageOutputEntryContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEntryContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEntryContent' from JSON`); + } + exports.MessageOutputEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.output").default("message.output"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + agent_id: z3.nullable(z3.string()).optional(), + model: z3.nullable(z3.string()).optional(), + role: z3.literal("assistant").default("assistant"), + content: z3.union([ + z3.string(), + z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$inboundSchema) + ]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "agent_id": "agentId" + }); + }); + exports.MessageOutputEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.output").default("message.output"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + agentId: z3.nullable(z3.string()).optional(), + model: z3.nullable(z3.string()).optional(), + role: z3.literal("assistant").default("assistant"), + content: z3.union([ + z3.string(), + z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$outboundSchema) + ]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + agentId: "agent_id" + }); + }); + function messageOutputEntryToJSON(messageOutputEntry) { + return JSON.stringify(exports.MessageOutputEntry$outboundSchema.parse(messageOutputEntry)); + } + function messageOutputEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionentry.js +var require_toolexecutionentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionEntry$outboundSchema = exports.ToolExecutionEntry$inboundSchema = exports.Name$outboundSchema = exports.Name$inboundSchema = void 0; + exports.nameToJSON = nameToJSON; + exports.nameFromJSON = nameFromJSON; + exports.toolExecutionEntryToJSON = toolExecutionEntryToJSON; + exports.toolExecutionEntryFromJSON = toolExecutionEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.Name$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + exports.Name$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]); + function nameToJSON(name) { + return JSON.stringify(exports.Name$outboundSchema.parse(name)); + } + function nameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Name$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Name' from JSON`); + } + exports.ToolExecutionEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("tool.execution").default("tool.execution"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + arguments: z3.string(), + info: z3.record(z3.any()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt" + }); + }); + exports.ToolExecutionEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("tool.execution").default("tool.execution"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]), + arguments: z3.string(), + info: z3.record(z3.any()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at" + }); + }); + function toolExecutionEntryToJSON(toolExecutionEntry) { + return JSON.stringify(exports.ToolExecutionEntry$outboundSchema.parse(toolExecutionEntry)); + } + function toolExecutionEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/inputentries.js +var require_inputentries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/inputentries.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InputEntries$outboundSchema = void 0; + exports.inputEntriesToJSON = inputEntriesToJSON; + var z3 = __importStar(require_v3()); + var agenthandoffentry_js_1 = require_agenthandoffentry(); + var functioncallentry_js_1 = require_functioncallentry(); + var functionresultentry_js_1 = require_functionresultentry(); + var messageinputentry_js_1 = require_messageinputentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + var toolexecutionentry_js_1 = require_toolexecutionentry(); + exports.InputEntries$outboundSchema = z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$outboundSchema, + functioncallentry_js_1.FunctionCallEntry$outboundSchema, + messageinputentry_js_1.MessageInputEntry$outboundSchema, + functionresultentry_js_1.FunctionResultEntry$outboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$outboundSchema, + messageoutputentry_js_1.MessageOutputEntry$outboundSchema + ]); + function inputEntriesToJSON(inputEntries) { + return JSON.stringify(exports.InputEntries$outboundSchema.parse(inputEntries)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationinputs.js +var require_conversationinputs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationinputs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationInputs$outboundSchema = void 0; + exports.conversationInputsToJSON = conversationInputsToJSON; + var z3 = __importStar(require_v3()); + var inputentries_js_1 = require_inputentries(); + exports.ConversationInputs$outboundSchema = z3.union([z3.string(), z3.array(inputentries_js_1.InputEntries$outboundSchema)]); + function conversationInputsToJSON(conversationInputs) { + return JSON.stringify(exports.ConversationInputs$outboundSchema.parse(conversationInputs)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcallconfirmation.js +var require_toolcallconfirmation = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcallconfirmation.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolCallConfirmation$outboundSchema = exports.Confirmation$outboundSchema = exports.Confirmation = void 0; + exports.toolCallConfirmationToJSON = toolCallConfirmationToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.Confirmation = { + Allow: "allow", + Deny: "deny" + }; + exports.Confirmation$outboundSchema = z3.nativeEnum(exports.Confirmation); + exports.ToolCallConfirmation$outboundSchema = z3.object({ + toolCallId: z3.string(), + confirmation: exports.Confirmation$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolCallId: "tool_call_id" + }); + }); + function toolCallConfirmationToJSON(toolCallConfirmation) { + return JSON.stringify(exports.ToolCallConfirmation$outboundSchema.parse(toolCallConfirmation)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendrequest.js +var require_conversationappendrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationAppendRequest$outboundSchema = exports.ConversationAppendRequestHandoffExecution$outboundSchema = exports.ConversationAppendRequestHandoffExecution = void 0; + exports.conversationAppendRequestToJSON = conversationAppendRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var toolcallconfirmation_js_1 = require_toolcallconfirmation(); + exports.ConversationAppendRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationAppendRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationAppendRequestHandoffExecution); + exports.ConversationAppendRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(false), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationAppendRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + toolConfirmations: z3.nullable(z3.array(toolcallconfirmation_js_1.ToolCallConfirmation$outboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + toolConfirmations: "tool_confirmations" + }); + }); + function conversationAppendRequestToJSON(conversationAppendRequest) { + return JSON.stringify(exports.ConversationAppendRequest$outboundSchema.parse(conversationAppendRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendstreamrequest.js +var require_conversationappendstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationAppendStreamRequest$outboundSchema = exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema = exports.ConversationAppendStreamRequestHandoffExecution = void 0; + exports.conversationAppendStreamRequestToJSON = conversationAppendStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var toolcallconfirmation_js_1 = require_toolcallconfirmation(); + exports.ConversationAppendStreamRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationAppendStreamRequestHandoffExecution); + exports.ConversationAppendStreamRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(true), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + toolConfirmations: z3.nullable(z3.array(toolcallconfirmation_js_1.ToolCallConfirmation$outboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + toolConfirmations: "tool_confirmations" + }); + }); + function conversationAppendStreamRequestToJSON(conversationAppendStreamRequest) { + return JSON.stringify(exports.ConversationAppendStreamRequest$outboundSchema.parse(conversationAppendStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallevent.js +var require_functioncallevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCallEvent$inboundSchema = exports.FunctionCallEventConfirmationStatus$inboundSchema = exports.FunctionCallEventConfirmationStatus = void 0; + exports.functionCallEventFromJSON = functionCallEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FunctionCallEventConfirmationStatus = { + Pending: "pending", + Allowed: "allowed", + Denied: "denied" + }; + exports.FunctionCallEventConfirmationStatus$inboundSchema = z3.nativeEnum(exports.FunctionCallEventConfirmationStatus); + exports.FunctionCallEvent$inboundSchema = z3.object({ + type: z3.literal("function.call.delta").default("function.call.delta"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.string(), + tool_call_id: z3.string(), + arguments: z3.string(), + confirmation_status: z3.nullable(exports.FunctionCallEventConfirmationStatus$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "tool_call_id": "toolCallId", + "confirmation_status": "confirmationStatus" + }); + }); + function functionCallEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/outputcontentchunks.js +var require_outputcontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/outputcontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OutputContentChunks$inboundSchema = void 0; + exports.outputContentChunksFromJSON = outputContentChunksFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + var toolfilechunk_js_1 = require_toolfilechunk(); + var toolreferencechunk_js_1 = require_toolreferencechunk(); + exports.OutputContentChunks$inboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$inboundSchema, + toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, + textchunk_js_1.TextChunk$inboundSchema, + imageurlchunk_js_1.ImageURLChunk$inboundSchema, + documenturlchunk_js_1.DocumentURLChunk$inboundSchema, + thinkchunk_js_1.ThinkChunk$inboundSchema + ]); + function outputContentChunksFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OutputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OutputContentChunks' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputevent.js +var require_messageoutputevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageOutputEvent$inboundSchema = exports.MessageOutputEventContent$inboundSchema = void 0; + exports.messageOutputEventContentFromJSON = messageOutputEventContentFromJSON; + exports.messageOutputEventFromJSON = messageOutputEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var outputcontentchunks_js_1 = require_outputcontentchunks(); + exports.MessageOutputEventContent$inboundSchema = z3.union([z3.string(), outputcontentchunks_js_1.OutputContentChunks$inboundSchema]); + function messageOutputEventContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEventContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEventContent' from JSON`); + } + exports.MessageOutputEvent$inboundSchema = z3.object({ + type: z3.literal("message.output.delta").default("message.output.delta"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + content_index: z3.number().int().default(0), + model: z3.nullable(z3.string()).optional(), + agent_id: z3.nullable(z3.string()).optional(), + role: z3.literal("assistant").default("assistant"), + content: z3.union([z3.string(), outputcontentchunks_js_1.OutputContentChunks$inboundSchema]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "content_index": "contentIndex", + "agent_id": "agentId" + }); + }); + function messageOutputEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationusageinfo.js +var require_conversationusageinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationusageinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationUsageInfo$inboundSchema = void 0; + exports.conversationUsageInfoFromJSON = conversationUsageInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ConversationUsageInfo$inboundSchema = z3.object({ + prompt_tokens: z3.number().int().default(0), + completion_tokens: z3.number().int().default(0), + total_tokens: z3.number().int().default(0), + connector_tokens: z3.nullable(z3.number().int()).optional(), + connectors: z3.nullable(z3.record(z3.number().int())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "prompt_tokens": "promptTokens", + "completion_tokens": "completionTokens", + "total_tokens": "totalTokens", + "connector_tokens": "connectorTokens" + }); + }); + function conversationUsageInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationUsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationUsageInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responsedoneevent.js +var require_responsedoneevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responsedoneevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseDoneEvent$inboundSchema = void 0; + exports.responseDoneEventFromJSON = responseDoneEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var conversationusageinfo_js_1 = require_conversationusageinfo(); + exports.ResponseDoneEvent$inboundSchema = z3.object({ + type: z3.literal("conversation.response.done").default("conversation.response.done"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + usage: conversationusageinfo_js_1.ConversationUsageInfo$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt" + }); + }); + function responseDoneEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseDoneEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseerrorevent.js +var require_responseerrorevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseerrorevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseErrorEvent$inboundSchema = void 0; + exports.responseErrorEventFromJSON = responseErrorEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ResponseErrorEvent$inboundSchema = z3.object({ + type: z3.literal("conversation.response.error").default("conversation.response.error"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + message: z3.string(), + code: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt" + }); + }); + function responseErrorEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseErrorEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseErrorEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responsestartedevent.js +var require_responsestartedevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responsestartedevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseStartedEvent$inboundSchema = void 0; + exports.responseStartedEventFromJSON = responseStartedEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ResponseStartedEvent$inboundSchema = z3.object({ + type: z3.literal("conversation.response.started").default("conversation.response.started"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + conversation_id: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "conversation_id": "conversationId" + }); + }); + function responseStartedEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseStartedEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ssetypes.js +var require_ssetypes = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ssetypes.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SSETypes$inboundSchema = exports.SSETypes = void 0; + var z3 = __importStar(require_v3()); + exports.SSETypes = { + ConversationResponseStarted: "conversation.response.started", + ConversationResponseDone: "conversation.response.done", + ConversationResponseError: "conversation.response.error", + MessageOutputDelta: "message.output.delta", + ToolExecutionStarted: "tool.execution.started", + ToolExecutionDelta: "tool.execution.delta", + ToolExecutionDone: "tool.execution.done", + AgentHandoffStarted: "agent.handoff.started", + AgentHandoffDone: "agent.handoff.done", + FunctionCallDelta: "function.call.delta" + }; + exports.SSETypes$inboundSchema = z3.nativeEnum(exports.SSETypes); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondeltaevent.js +var require_toolexecutiondeltaevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondeltaevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionDeltaEvent$inboundSchema = exports.ToolExecutionDeltaEventName$inboundSchema = void 0; + exports.toolExecutionDeltaEventNameFromJSON = toolExecutionDeltaEventNameFromJSON; + exports.toolExecutionDeltaEventFromJSON = toolExecutionDeltaEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolExecutionDeltaEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + function toolExecutionDeltaEventNameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDeltaEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDeltaEventName' from JSON`); + } + exports.ToolExecutionDeltaEvent$inboundSchema = z3.object({ + type: z3.literal("tool.execution.delta").default("tool.execution.delta"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + arguments: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex" + }); + }); + function toolExecutionDeltaEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDeltaEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDeltaEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondoneevent.js +var require_toolexecutiondoneevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondoneevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionDoneEvent$inboundSchema = exports.ToolExecutionDoneEventName$inboundSchema = void 0; + exports.toolExecutionDoneEventNameFromJSON = toolExecutionDoneEventNameFromJSON; + exports.toolExecutionDoneEventFromJSON = toolExecutionDoneEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolExecutionDoneEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + function toolExecutionDoneEventNameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDoneEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDoneEventName' from JSON`); + } + exports.ToolExecutionDoneEvent$inboundSchema = z3.object({ + type: z3.literal("tool.execution.done").default("tool.execution.done"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + info: z3.record(z3.any()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex" + }); + }); + function toolExecutionDoneEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDoneEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionstartedevent.js +var require_toolexecutionstartedevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionstartedevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionStartedEvent$inboundSchema = exports.ToolExecutionStartedEventName$inboundSchema = void 0; + exports.toolExecutionStartedEventNameFromJSON = toolExecutionStartedEventNameFromJSON; + exports.toolExecutionStartedEventFromJSON = toolExecutionStartedEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolExecutionStartedEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + function toolExecutionStartedEventNameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionStartedEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionStartedEventName' from JSON`); + } + exports.ToolExecutionStartedEvent$inboundSchema = z3.object({ + type: z3.literal("tool.execution.started").default("tool.execution.started"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + arguments: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex" + }); + }); + function toolExecutionStartedEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionStartedEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationevents.js +var require_conversationevents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationevents.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationEvents$inboundSchema = exports.ConversationEventsData$inboundSchema = void 0; + exports.conversationEventsDataFromJSON = conversationEventsDataFromJSON; + exports.conversationEventsFromJSON = conversationEventsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var agenthandoffdoneevent_js_1 = require_agenthandoffdoneevent(); + var agenthandoffstartedevent_js_1 = require_agenthandoffstartedevent(); + var functioncallevent_js_1 = require_functioncallevent(); + var messageoutputevent_js_1 = require_messageoutputevent(); + var responsedoneevent_js_1 = require_responsedoneevent(); + var responseerrorevent_js_1 = require_responseerrorevent(); + var responsestartedevent_js_1 = require_responsestartedevent(); + var ssetypes_js_1 = require_ssetypes(); + var toolexecutiondeltaevent_js_1 = require_toolexecutiondeltaevent(); + var toolexecutiondoneevent_js_1 = require_toolexecutiondoneevent(); + var toolexecutionstartedevent_js_1 = require_toolexecutionstartedevent(); + exports.ConversationEventsData$inboundSchema = z3.union([ + agenthandoffdoneevent_js_1.AgentHandoffDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.done") })), + agenthandoffstartedevent_js_1.AgentHandoffStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.started") })), + responsedoneevent_js_1.ResponseDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.done") })), + responseerrorevent_js_1.ResponseErrorEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.error") })), + responsestartedevent_js_1.ResponseStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.started") })), + functioncallevent_js_1.FunctionCallEvent$inboundSchema.and(z3.object({ type: z3.literal("function.call.delta") })), + messageoutputevent_js_1.MessageOutputEvent$inboundSchema.and(z3.object({ type: z3.literal("message.output.delta") })), + toolexecutiondeltaevent_js_1.ToolExecutionDeltaEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.delta") })), + toolexecutiondoneevent_js_1.ToolExecutionDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.done") })), + toolexecutionstartedevent_js_1.ToolExecutionStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.started") })) + ]); + function conversationEventsDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationEventsData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationEventsData' from JSON`); + } + exports.ConversationEvents$inboundSchema = z3.object({ + event: ssetypes_js_1.SSETypes$inboundSchema, + data: z3.string().transform((v4, ctx) => { + try { + return JSON.parse(v4); + } catch (err) { + ctx.addIssue({ code: "custom", message: `malformed json: ${err}` }); + return z3.NEVER; + } + }).pipe(z3.union([ + agenthandoffdoneevent_js_1.AgentHandoffDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.done") })), + agenthandoffstartedevent_js_1.AgentHandoffStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.started") })), + responsedoneevent_js_1.ResponseDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.done") })), + responseerrorevent_js_1.ResponseErrorEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.error") })), + responsestartedevent_js_1.ResponseStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.started") })), + functioncallevent_js_1.FunctionCallEvent$inboundSchema.and(z3.object({ type: z3.literal("function.call.delta") })), + messageoutputevent_js_1.MessageOutputEvent$inboundSchema.and(z3.object({ type: z3.literal("message.output.delta") })), + toolexecutiondeltaevent_js_1.ToolExecutionDeltaEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.delta") })), + toolexecutiondoneevent_js_1.ToolExecutionDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.done") })), + toolexecutionstartedevent_js_1.ToolExecutionStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.started") })) + ])) + }); + function conversationEventsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationEvents$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationEvents' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationhistory.js +var require_conversationhistory = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationhistory.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationHistory$inboundSchema = exports.Entries$inboundSchema = void 0; + exports.entriesFromJSON = entriesFromJSON; + exports.conversationHistoryFromJSON = conversationHistoryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var agenthandoffentry_js_1 = require_agenthandoffentry(); + var functioncallentry_js_1 = require_functioncallentry(); + var functionresultentry_js_1 = require_functionresultentry(); + var messageinputentry_js_1 = require_messageinputentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + var toolexecutionentry_js_1 = require_toolexecutionentry(); + exports.Entries$inboundSchema = z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + messageinputentry_js_1.MessageInputEntry$inboundSchema, + functionresultentry_js_1.FunctionResultEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ]); + function entriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Entries$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Entries' from JSON`); + } + exports.ConversationHistory$inboundSchema = z3.object({ + object: z3.literal("conversation.history").default("conversation.history"), + conversation_id: z3.string(), + entries: z3.array(z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + messageinputentry_js_1.MessageInputEntry$inboundSchema, + functionresultentry_js_1.FunctionResultEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ])) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "conversation_id": "conversationId" + }); + }); + function conversationHistoryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationHistory$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationHistory' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageentries.js +var require_messageentries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageentries.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageEntries$inboundSchema = void 0; + exports.messageEntriesFromJSON = messageEntriesFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var messageinputentry_js_1 = require_messageinputentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + exports.MessageEntries$inboundSchema = z3.union([ + messageinputentry_js_1.MessageInputEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ]); + function messageEntriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageEntries$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageEntries' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationmessages.js +var require_conversationmessages = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationmessages.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationMessages$inboundSchema = void 0; + exports.conversationMessagesFromJSON = conversationMessagesFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var messageentries_js_1 = require_messageentries(); + exports.ConversationMessages$inboundSchema = z3.object({ + object: z3.literal("conversation.messages").default("conversation.messages"), + conversation_id: z3.string(), + messages: z3.array(messageentries_js_1.MessageEntries$inboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "conversation_id": "conversationId" + }); + }); + function conversationMessagesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationMessages$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationMessages' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrequest.js +var require_conversationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationRequest$outboundSchema = exports.AgentVersion$outboundSchema = exports.Tools$outboundSchema = exports.HandoffExecution$outboundSchema = exports.HandoffExecution = void 0; + exports.toolsToJSON = toolsToJSON; + exports.agentVersionToJSON = agentVersionToJSON; + exports.conversationRequestToJSON = conversationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.HandoffExecution = { + Client: "client", + Server: "server" + }; + exports.HandoffExecution$outboundSchema = z3.nativeEnum(exports.HandoffExecution); + exports.Tools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function toolsToJSON(tools) { + return JSON.stringify(exports.Tools$outboundSchema.parse(tools)); + } + exports.AgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function agentVersionToJSON(agentVersion) { + return JSON.stringify(exports.AgentVersion$outboundSchema.parse(agentVersion)); + } + exports.ConversationRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema, + stream: z3.boolean().default(false), + store: z3.nullable(z3.boolean()).optional(), + handoffExecution: z3.nullable(exports.HandoffExecution$outboundSchema).optional(), + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: z3.nullable(completionargs_js_1.CompletionArgs$outboundSchema).optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + agentId: z3.nullable(z3.string()).optional(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional(), + model: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + agentId: "agent_id", + agentVersion: "agent_version" + }); + }); + function conversationRequestToJSON(conversationRequest) { + return JSON.stringify(exports.ConversationRequest$outboundSchema.parse(conversationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationresponse.js +var require_conversationresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationResponse$inboundSchema = exports.Outputs$inboundSchema = void 0; + exports.outputsFromJSON = outputsFromJSON; + exports.conversationResponseFromJSON = conversationResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var agenthandoffentry_js_1 = require_agenthandoffentry(); + var conversationusageinfo_js_1 = require_conversationusageinfo(); + var functioncallentry_js_1 = require_functioncallentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + var toolexecutionentry_js_1 = require_toolexecutionentry(); + exports.Outputs$inboundSchema = z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ]); + function outputsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Outputs$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Outputs' from JSON`); + } + exports.ConversationResponse$inboundSchema = z3.object({ + object: z3.literal("conversation.response").default("conversation.response"), + conversation_id: z3.string(), + outputs: z3.array(z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ])), + usage: conversationusageinfo_js_1.ConversationUsageInfo$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "conversation_id": "conversationId" + }); + }); + function conversationResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartrequest.js +var require_conversationrestartrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationRestartRequest$outboundSchema = exports.ConversationRestartRequestAgentVersion$outboundSchema = exports.ConversationRestartRequestHandoffExecution$outboundSchema = exports.ConversationRestartRequestHandoffExecution = void 0; + exports.conversationRestartRequestAgentVersionToJSON = conversationRestartRequestAgentVersionToJSON; + exports.conversationRestartRequestToJSON = conversationRestartRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + exports.ConversationRestartRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationRestartRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationRestartRequestHandoffExecution); + exports.ConversationRestartRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function conversationRestartRequestAgentVersionToJSON(conversationRestartRequestAgentVersion) { + return JSON.stringify(exports.ConversationRestartRequestAgentVersion$outboundSchema.parse(conversationRestartRequestAgentVersion)); + } + exports.ConversationRestartRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(false), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationRestartRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + fromEntryId: z3.string(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + fromEntryId: "from_entry_id", + agentVersion: "agent_version" + }); + }); + function conversationRestartRequestToJSON(conversationRestartRequest) { + return JSON.stringify(exports.ConversationRestartRequest$outboundSchema.parse(conversationRestartRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartstreamrequest.js +var require_conversationrestartstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationRestartStreamRequest$outboundSchema = exports.ConversationRestartStreamRequestAgentVersion$outboundSchema = exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema = exports.ConversationRestartStreamRequestHandoffExecution = void 0; + exports.conversationRestartStreamRequestAgentVersionToJSON = conversationRestartStreamRequestAgentVersionToJSON; + exports.conversationRestartStreamRequestToJSON = conversationRestartStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + exports.ConversationRestartStreamRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationRestartStreamRequestHandoffExecution); + exports.ConversationRestartStreamRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function conversationRestartStreamRequestAgentVersionToJSON(conversationRestartStreamRequestAgentVersion) { + return JSON.stringify(exports.ConversationRestartStreamRequestAgentVersion$outboundSchema.parse(conversationRestartStreamRequestAgentVersion)); + } + exports.ConversationRestartStreamRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(true), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + fromEntryId: z3.string(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + fromEntryId: "from_entry_id", + agentVersion: "agent_version" + }); + }); + function conversationRestartStreamRequestToJSON(conversationRestartStreamRequest) { + return JSON.stringify(exports.ConversationRestartStreamRequest$outboundSchema.parse(conversationRestartStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationstreamrequest.js +var require_conversationstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationStreamRequest$outboundSchema = exports.ConversationStreamRequestAgentVersion$outboundSchema = exports.ConversationStreamRequestTools$outboundSchema = exports.ConversationStreamRequestHandoffExecution$outboundSchema = exports.ConversationStreamRequestHandoffExecution = void 0; + exports.conversationStreamRequestToolsToJSON = conversationStreamRequestToolsToJSON; + exports.conversationStreamRequestAgentVersionToJSON = conversationStreamRequestAgentVersionToJSON; + exports.conversationStreamRequestToJSON = conversationStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.ConversationStreamRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationStreamRequestHandoffExecution); + exports.ConversationStreamRequestTools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function conversationStreamRequestToolsToJSON(conversationStreamRequestTools) { + return JSON.stringify(exports.ConversationStreamRequestTools$outboundSchema.parse(conversationStreamRequestTools)); + } + exports.ConversationStreamRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function conversationStreamRequestAgentVersionToJSON(conversationStreamRequestAgentVersion) { + return JSON.stringify(exports.ConversationStreamRequestAgentVersion$outboundSchema.parse(conversationStreamRequestAgentVersion)); + } + exports.ConversationStreamRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema, + stream: z3.boolean().default(true), + store: z3.nullable(z3.boolean()).optional(), + handoffExecution: z3.nullable(exports.ConversationStreamRequestHandoffExecution$outboundSchema).optional(), + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: z3.nullable(completionargs_js_1.CompletionArgs$outboundSchema).optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + agentId: z3.nullable(z3.string()).optional(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional(), + model: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + agentId: "agent_id", + agentVersion: "agent_version" + }); + }); + function conversationStreamRequestToJSON(conversationStreamRequest) { + return JSON.stringify(exports.ConversationStreamRequest$outboundSchema.parse(conversationStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deletefileout.js +var require_deletefileout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/deletefileout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteFileOut$inboundSchema = void 0; + exports.deleteFileOutFromJSON = deleteFileOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.DeleteFileOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + deleted: z3.boolean() + }); + function deleteFileOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeleteFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeleteFileOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deletemodelout.js +var require_deletemodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/deletemodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteModelOut$inboundSchema = void 0; + exports.deleteModelOutFromJSON = deleteModelOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.DeleteModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().default("model"), + deleted: z3.boolean().default(true) + }); + function deleteModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeleteModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeleteModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentout.js +var require_documentout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentOut$inboundSchema = void 0; + exports.documentOutFromJSON = documentOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.DocumentOut$inboundSchema = z3.object({ + id: z3.string(), + library_id: z3.string(), + hash: z3.nullable(z3.string()), + mime_type: z3.nullable(z3.string()), + extension: z3.nullable(z3.string()), + size: z3.nullable(z3.number().int()), + name: z3.string(), + summary: z3.nullable(z3.string()).optional(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + last_processed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + number_of_pages: z3.nullable(z3.number().int()).optional(), + uploaded_by_id: z3.nullable(z3.string()), + uploaded_by_type: z3.string(), + tokens_processing_main_content: z3.nullable(z3.number().int()).optional(), + tokens_processing_summary: z3.nullable(z3.number().int()).optional(), + url: z3.nullable(z3.string()).optional(), + attributes: z3.nullable(z3.record(z3.any())).optional(), + processing_status: z3.string(), + tokens_processing_total: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "library_id": "libraryId", + "mime_type": "mimeType", + "created_at": "createdAt", + "last_processed_at": "lastProcessedAt", + "number_of_pages": "numberOfPages", + "uploaded_by_id": "uploadedById", + "uploaded_by_type": "uploadedByType", + "tokens_processing_main_content": "tokensProcessingMainContent", + "tokens_processing_summary": "tokensProcessingSummary", + "processing_status": "processingStatus", + "tokens_processing_total": "tokensProcessingTotal" + }); + }); + function documentOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documenttextcontent.js +var require_documenttextcontent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documenttextcontent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentTextContent$inboundSchema = void 0; + exports.documentTextContentFromJSON = documentTextContentFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.DocumentTextContent$inboundSchema = z3.object({ + text: z3.string() + }); + function documentTextContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentTextContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentTextContent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentupdatein.js +var require_documentupdatein = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentupdatein.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentUpdateIn$outboundSchema = exports.Attributes$outboundSchema = void 0; + exports.attributesToJSON = attributesToJSON; + exports.documentUpdateInToJSON = documentUpdateInToJSON; + var z3 = __importStar(require_v3()); + exports.Attributes$outboundSchema = z3.union([ + z3.boolean(), + z3.string(), + z3.number().int(), + z3.number(), + z3.date().transform((v4) => v4.toISOString()), + z3.array(z3.string()), + z3.array(z3.number().int()), + z3.array(z3.number()), + z3.array(z3.boolean()) + ]); + function attributesToJSON(attributes) { + return JSON.stringify(exports.Attributes$outboundSchema.parse(attributes)); + } + exports.DocumentUpdateIn$outboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + attributes: z3.nullable(z3.record(z3.union([ + z3.boolean(), + z3.string(), + z3.number().int(), + z3.number(), + z3.date().transform((v4) => v4.toISOString()), + z3.array(z3.string()), + z3.array(z3.number().int()), + z3.array(z3.number()), + z3.array(z3.boolean()) + ]))).optional() + }); + function documentUpdateInToJSON(documentUpdateIn) { + return JSON.stringify(exports.DocumentUpdateIn$outboundSchema.parse(documentUpdateIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingdtype.js +var require_embeddingdtype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingdtype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingDtype$outboundSchema = exports.EmbeddingDtype = void 0; + var z3 = __importStar(require_v3()); + exports.EmbeddingDtype = { + Float: "float", + Int8: "int8", + Uint8: "uint8", + Binary: "binary", + Ubinary: "ubinary" + }; + exports.EmbeddingDtype$outboundSchema = z3.nativeEnum(exports.EmbeddingDtype); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/encodingformat.js +var require_encodingformat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/encodingformat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EncodingFormat$outboundSchema = exports.EncodingFormat = void 0; + var z3 = __importStar(require_v3()); + exports.EncodingFormat = { + Float: "float", + Base64: "base64" + }; + exports.EncodingFormat$outboundSchema = z3.nativeEnum(exports.EncodingFormat); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingrequest.js +var require_embeddingrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingRequest$outboundSchema = exports.EmbeddingRequestInputs$outboundSchema = void 0; + exports.embeddingRequestInputsToJSON = embeddingRequestInputsToJSON; + exports.embeddingRequestToJSON = embeddingRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var embeddingdtype_js_1 = require_embeddingdtype(); + var encodingformat_js_1 = require_encodingformat(); + exports.EmbeddingRequestInputs$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function embeddingRequestInputsToJSON(embeddingRequestInputs) { + return JSON.stringify(exports.EmbeddingRequestInputs$outboundSchema.parse(embeddingRequestInputs)); + } + exports.EmbeddingRequest$outboundSchema = z3.object({ + model: z3.string(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + inputs: z3.union([z3.string(), z3.array(z3.string())]), + outputDimension: z3.nullable(z3.number().int()).optional(), + outputDtype: embeddingdtype_js_1.EmbeddingDtype$outboundSchema.optional(), + encodingFormat: encodingformat_js_1.EncodingFormat$outboundSchema.optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input", + outputDimension: "output_dimension", + outputDtype: "output_dtype", + encodingFormat: "encoding_format" + }); + }); + function embeddingRequestToJSON(embeddingRequest) { + return JSON.stringify(exports.EmbeddingRequest$outboundSchema.parse(embeddingRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponsedata.js +var require_embeddingresponsedata = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponsedata.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingResponseData$inboundSchema = void 0; + exports.embeddingResponseDataFromJSON = embeddingResponseDataFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.EmbeddingResponseData$inboundSchema = z3.object({ + object: z3.string().optional(), + embedding: z3.array(z3.number()).optional(), + index: z3.number().int().optional() + }); + function embeddingResponseDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EmbeddingResponseData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EmbeddingResponseData' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponse.js +var require_embeddingresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingResponse$inboundSchema = void 0; + exports.embeddingResponseFromJSON = embeddingResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var embeddingresponsedata_js_1 = require_embeddingresponsedata(); + var usageinfo_js_1 = require_usageinfo(); + exports.EmbeddingResponse$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + data: z3.array(embeddingresponsedata_js_1.EmbeddingResponseData$inboundSchema) + }); + function embeddingResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EmbeddingResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EmbeddingResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/entitytype.js +var require_entitytype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/entitytype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EntityType$outboundSchema = exports.EntityType = void 0; + var openEnums = __importStar(require_enums()); + exports.EntityType = { + User: "User", + Workspace: "Workspace", + Org: "Org" + }; + exports.EntityType$outboundSchema = openEnums.outboundSchema(exports.EntityType); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filepurpose.js +var require_filepurpose = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/filepurpose.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilePurpose$outboundSchema = exports.FilePurpose$inboundSchema = exports.FilePurpose = void 0; + var openEnums = __importStar(require_enums()); + exports.FilePurpose = { + FineTune: "fine-tune", + Batch: "batch", + Ocr: "ocr" + }; + exports.FilePurpose$inboundSchema = openEnums.inboundSchema(exports.FilePurpose); + exports.FilePurpose$outboundSchema = openEnums.outboundSchema(exports.FilePurpose); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sampletype.js +var require_sampletype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sampletype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SampleType$outboundSchema = exports.SampleType$inboundSchema = exports.SampleType = void 0; + var openEnums = __importStar(require_enums()); + exports.SampleType = { + Pretrain: "pretrain", + Instruct: "instruct", + BatchRequest: "batch_request", + BatchResult: "batch_result", + BatchError: "batch_error" + }; + exports.SampleType$inboundSchema = openEnums.inboundSchema(exports.SampleType); + exports.SampleType$outboundSchema = openEnums.outboundSchema(exports.SampleType); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/source.js +var require_source = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/source.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Source$outboundSchema = exports.Source$inboundSchema = exports.Source = void 0; + var openEnums = __importStar(require_enums()); + exports.Source = { + Upload: "upload", + Repository: "repository", + Mistral: "mistral" + }; + exports.Source$inboundSchema = openEnums.inboundSchema(exports.Source); + exports.Source$outboundSchema = openEnums.outboundSchema(exports.Source); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fileschema.js +var require_fileschema = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fileschema.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileSchema$inboundSchema = void 0; + exports.fileSchemaFromJSON = fileSchemaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var filepurpose_js_1 = require_filepurpose(); + var sampletype_js_1 = require_sampletype(); + var source_js_1 = require_source(); + exports.FileSchema$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + bytes: z3.number().int(), + created_at: z3.number().int(), + filename: z3.string(), + purpose: filepurpose_js_1.FilePurpose$inboundSchema, + sample_type: sampletype_js_1.SampleType$inboundSchema, + num_lines: z3.nullable(z3.number().int()).optional(), + mimetype: z3.nullable(z3.string()).optional(), + source: source_js_1.Source$inboundSchema, + signature: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "bytes": "sizeBytes", + "created_at": "createdAt", + "sample_type": "sampleType", + "num_lines": "numLines" + }); + }); + function fileSchemaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileSchema$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileSchema' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filesignedurl.js +var require_filesignedurl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/filesignedurl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileSignedURL$inboundSchema = void 0; + exports.fileSignedURLFromJSON = fileSignedURLFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.FileSignedURL$inboundSchema = z3.object({ + url: z3.string() + }); + function fileSignedURLFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileSignedURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileSignedURL' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionrequest.js +var require_fimcompletionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FIMCompletionRequest$outboundSchema = exports.FIMCompletionRequestStop$outboundSchema = void 0; + exports.fimCompletionRequestStopToJSON = fimCompletionRequestStopToJSON; + exports.fimCompletionRequestToJSON = fimCompletionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FIMCompletionRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function fimCompletionRequestStopToJSON(fimCompletionRequestStop) { + return JSON.stringify(exports.FIMCompletionRequestStop$outboundSchema.parse(fimCompletionRequestStop)); + } + exports.FIMCompletionRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().default(1), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(false), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + prompt: z3.string(), + suffix: z3.nullable(z3.string()).optional(), + minTokens: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + minTokens: "min_tokens" + }); + }); + function fimCompletionRequestToJSON(fimCompletionRequest) { + return JSON.stringify(exports.FIMCompletionRequest$outboundSchema.parse(fimCompletionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionresponse.js +var require_fimcompletionresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FIMCompletionResponse$inboundSchema = void 0; + exports.fimCompletionResponseFromJSON = fimCompletionResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var chatcompletionchoice_js_1 = require_chatcompletionchoice(); + var usageinfo_js_1 = require_usageinfo(); + exports.FIMCompletionResponse$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + created: z3.number().int(), + choices: z3.array(chatcompletionchoice_js_1.ChatCompletionChoice$inboundSchema) + }); + function fimCompletionResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FIMCompletionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FIMCompletionResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionstreamrequest.js +var require_fimcompletionstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FIMCompletionStreamRequest$outboundSchema = exports.FIMCompletionStreamRequestStop$outboundSchema = void 0; + exports.fimCompletionStreamRequestStopToJSON = fimCompletionStreamRequestStopToJSON; + exports.fimCompletionStreamRequestToJSON = fimCompletionStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FIMCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function fimCompletionStreamRequestStopToJSON(fimCompletionStreamRequestStop) { + return JSON.stringify(exports.FIMCompletionStreamRequestStop$outboundSchema.parse(fimCompletionStreamRequestStop)); + } + exports.FIMCompletionStreamRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().default(1), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(true), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + prompt: z3.string(), + suffix: z3.nullable(z3.string()).optional(), + minTokens: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + minTokens: "min_tokens" + }); + }); + function fimCompletionStreamRequestToJSON(fimCompletionStreamRequest) { + return JSON.stringify(exports.FIMCompletionStreamRequest$outboundSchema.parse(fimCompletionStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/finetuneablemodeltype.js +var require_finetuneablemodeltype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/finetuneablemodeltype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FineTuneableModelType$outboundSchema = exports.FineTuneableModelType = void 0; + var z3 = __importStar(require_v3()); + exports.FineTuneableModelType = { + Completion: "completion", + Classifier: "classifier" + }; + exports.FineTuneableModelType$outboundSchema = z3.nativeEnum(exports.FineTuneableModelType); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcard.js +var require_ftmodelcard = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcard.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FTModelCard$inboundSchema = void 0; + exports.ftModelCardFromJSON = ftModelCardFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var modelcapabilities_js_1 = require_modelcapabilities(); + exports.FTModelCard$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().default("model"), + created: z3.number().int().optional(), + owned_by: z3.string().default("mistralai"), + capabilities: modelcapabilities_js_1.ModelCapabilities$inboundSchema, + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + deprecation: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + deprecation_replacement_model: z3.nullable(z3.string()).optional(), + default_model_temperature: z3.nullable(z3.number()).optional(), + type: z3.literal("fine-tuned").default("fine-tuned"), + job: z3.string(), + root: z3.string(), + archived: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "max_context_length": "maxContextLength", + "deprecation_replacement_model": "deprecationReplacementModel", + "default_model_temperature": "defaultModelTemperature" + }); + }); + function ftModelCardFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FTModelCard$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FTModelCard' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryin.js +var require_githubrepositoryin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GithubRepositoryIn$outboundSchema = void 0; + exports.githubRepositoryInToJSON = githubRepositoryInToJSON; + var z3 = __importStar(require_v3()); + exports.GithubRepositoryIn$outboundSchema = z3.object({ + type: z3.literal("github").default("github"), + name: z3.string(), + owner: z3.string(), + ref: z3.nullable(z3.string()).optional(), + weight: z3.number().default(1), + token: z3.string() + }); + function githubRepositoryInToJSON(githubRepositoryIn) { + return JSON.stringify(exports.GithubRepositoryIn$outboundSchema.parse(githubRepositoryIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/trainingfile.js +var require_trainingfile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/trainingfile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TrainingFile$outboundSchema = void 0; + exports.trainingFileToJSON = trainingFileToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.TrainingFile$outboundSchema = z3.object({ + fileId: z3.string(), + weight: z3.number().default(1) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function trainingFileToJSON(trainingFile) { + return JSON.stringify(exports.TrainingFile$outboundSchema.parse(trainingFile)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegration.js +var require_wandbintegration = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegration.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WandbIntegration$outboundSchema = void 0; + exports.wandbIntegrationToJSON = wandbIntegrationToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.WandbIntegration$outboundSchema = z3.object({ + type: z3.literal("wandb").default("wandb"), + project: z3.string(), + name: z3.nullable(z3.string()).optional(), + apiKey: z3.string(), + runName: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + apiKey: "api_key", + runName: "run_name" + }); + }); + function wandbIntegrationToJSON(wandbIntegration) { + return JSON.stringify(exports.WandbIntegration$outboundSchema.parse(wandbIntegration)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobin.js +var require_jobin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobIn$outboundSchema = exports.JobInRepositories$outboundSchema = exports.Hyperparameters$outboundSchema = exports.JobInIntegrations$outboundSchema = void 0; + exports.jobInIntegrationsToJSON = jobInIntegrationsToJSON; + exports.hyperparametersToJSON = hyperparametersToJSON; + exports.jobInRepositoriesToJSON = jobInRepositoriesToJSON; + exports.jobInToJSON = jobInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var classifiertargetin_js_1 = require_classifiertargetin(); + var classifiertrainingparametersin_js_1 = require_classifiertrainingparametersin(); + var completiontrainingparametersin_js_1 = require_completiontrainingparametersin(); + var finetuneablemodeltype_js_1 = require_finetuneablemodeltype(); + var githubrepositoryin_js_1 = require_githubrepositoryin(); + var trainingfile_js_1 = require_trainingfile(); + var wandbintegration_js_1 = require_wandbintegration(); + exports.JobInIntegrations$outboundSchema = wandbintegration_js_1.WandbIntegration$outboundSchema; + function jobInIntegrationsToJSON(jobInIntegrations) { + return JSON.stringify(exports.JobInIntegrations$outboundSchema.parse(jobInIntegrations)); + } + exports.Hyperparameters$outboundSchema = z3.union([ + completiontrainingparametersin_js_1.CompletionTrainingParametersIn$outboundSchema, + classifiertrainingparametersin_js_1.ClassifierTrainingParametersIn$outboundSchema + ]); + function hyperparametersToJSON(hyperparameters) { + return JSON.stringify(exports.Hyperparameters$outboundSchema.parse(hyperparameters)); + } + exports.JobInRepositories$outboundSchema = githubrepositoryin_js_1.GithubRepositoryIn$outboundSchema; + function jobInRepositoriesToJSON(jobInRepositories) { + return JSON.stringify(exports.JobInRepositories$outboundSchema.parse(jobInRepositories)); + } + exports.JobIn$outboundSchema = z3.object({ + model: z3.string(), + trainingFiles: z3.array(trainingfile_js_1.TrainingFile$outboundSchema).optional(), + validationFiles: z3.nullable(z3.array(z3.string())).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegration_js_1.WandbIntegration$outboundSchema)).optional(), + autoStart: z3.boolean().optional(), + invalidSampleSkipPercentage: z3.number().default(0), + jobType: z3.nullable(finetuneablemodeltype_js_1.FineTuneableModelType$outboundSchema).optional(), + hyperparameters: z3.union([ + completiontrainingparametersin_js_1.CompletionTrainingParametersIn$outboundSchema, + classifiertrainingparametersin_js_1.ClassifierTrainingParametersIn$outboundSchema + ]), + repositories: z3.nullable(z3.array(githubrepositoryin_js_1.GithubRepositoryIn$outboundSchema)).optional(), + classifierTargets: z3.nullable(z3.array(classifiertargetin_js_1.ClassifierTargetIn$outboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + trainingFiles: "training_files", + validationFiles: "validation_files", + autoStart: "auto_start", + invalidSampleSkipPercentage: "invalid_sample_skip_percentage", + jobType: "job_type", + classifierTargets: "classifier_targets" + }); + }); + function jobInToJSON(jobIn) { + return JSON.stringify(exports.JobIn$outboundSchema.parse(jobIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobsout.js +var require_jobsout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobsout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsOut$inboundSchema = exports.JobsOutData$inboundSchema = void 0; + exports.jobsOutDataFromJSON = jobsOutDataFromJSON; + exports.jobsOutFromJSON = jobsOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var classifierjobout_js_1 = require_classifierjobout(); + var completionjobout_js_1 = require_completionjobout(); + exports.JobsOutData$inboundSchema = z3.union([ + classifierjobout_js_1.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + completionjobout_js_1.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsOutDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsOutData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsOutData' from JSON`); + } + exports.JobsOut$inboundSchema = z3.object({ + data: z3.array(z3.union([ + classifierjobout_js_1.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + completionjobout_js_1.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ])).optional(), + object: z3.literal("list").default("list"), + total: z3.number().int() + }); + function jobsOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/legacyjobmetadataout.js +var require_legacyjobmetadataout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/legacyjobmetadataout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LegacyJobMetadataOut$inboundSchema = void 0; + exports.legacyJobMetadataOutFromJSON = legacyJobMetadataOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.LegacyJobMetadataOut$inboundSchema = z3.object({ + expected_duration_seconds: z3.nullable(z3.number().int()).optional(), + cost: z3.nullable(z3.number()).optional(), + cost_currency: z3.nullable(z3.string()).optional(), + train_tokens_per_step: z3.nullable(z3.number().int()).optional(), + train_tokens: z3.nullable(z3.number().int()).optional(), + data_tokens: z3.nullable(z3.number().int()).optional(), + estimated_start_time: z3.nullable(z3.number().int()).optional(), + deprecated: z3.boolean().default(true), + details: z3.string(), + epochs: z3.nullable(z3.number()).optional(), + training_steps: z3.nullable(z3.number().int()).optional(), + object: z3.literal("job.metadata").default("job.metadata") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "expected_duration_seconds": "expectedDurationSeconds", + "cost_currency": "costCurrency", + "train_tokens_per_step": "trainTokensPerStep", + "train_tokens": "trainTokens", + "data_tokens": "dataTokens", + "estimated_start_time": "estimatedStartTime", + "training_steps": "trainingSteps" + }); + }); + function legacyJobMetadataOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.LegacyJobMetadataOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'LegacyJobMetadataOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryin.js +var require_libraryin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibraryIn$outboundSchema = void 0; + exports.libraryInToJSON = libraryInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibraryIn$outboundSchema = z3.object({ + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + chunkSize: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + chunkSize: "chunk_size" + }); + }); + function libraryInToJSON(libraryIn) { + return JSON.stringify(exports.LibraryIn$outboundSchema.parse(libraryIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryinupdate.js +var require_libraryinupdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryinupdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibraryInUpdate$outboundSchema = void 0; + exports.libraryInUpdateToJSON = libraryInUpdateToJSON; + var z3 = __importStar(require_v3()); + exports.LibraryInUpdate$outboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + function libraryInUpdateToJSON(libraryInUpdate) { + return JSON.stringify(exports.LibraryInUpdate$outboundSchema.parse(libraryInUpdate)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryout.js +var require_libraryout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibraryOut$inboundSchema = void 0; + exports.libraryOutFromJSON = libraryOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.LibraryOut$inboundSchema = z3.object({ + id: z3.string(), + name: z3.string(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + owner_id: z3.nullable(z3.string()), + owner_type: z3.string(), + total_size: z3.number().int(), + nb_documents: z3.number().int(), + chunk_size: z3.nullable(z3.number().int()), + emoji: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + generated_description: z3.nullable(z3.string()).optional(), + explicit_user_members_count: z3.nullable(z3.number().int()).optional(), + explicit_workspace_members_count: z3.nullable(z3.number().int()).optional(), + org_sharing_role: z3.nullable(z3.string()).optional(), + generated_name: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "updated_at": "updatedAt", + "owner_id": "ownerId", + "owner_type": "ownerType", + "total_size": "totalSize", + "nb_documents": "nbDocuments", + "chunk_size": "chunkSize", + "generated_description": "generatedDescription", + "explicit_user_members_count": "explicitUserMembersCount", + "explicit_workspace_members_count": "explicitWorkspaceMembersCount", + "org_sharing_role": "orgSharingRole", + "generated_name": "generatedName" + }); + }); + function libraryOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.LibraryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'LibraryOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/paginationinfo.js +var require_paginationinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/paginationinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PaginationInfo$inboundSchema = void 0; + exports.paginationInfoFromJSON = paginationInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.PaginationInfo$inboundSchema = z3.object({ + total_items: z3.number().int(), + total_pages: z3.number().int(), + current_page: z3.number().int(), + page_size: z3.number().int(), + has_more: z3.boolean() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "total_items": "totalItems", + "total_pages": "totalPages", + "current_page": "currentPage", + "page_size": "pageSize", + "has_more": "hasMore" + }); + }); + function paginationInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.PaginationInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'PaginationInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listdocumentout.js +var require_listdocumentout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listdocumentout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListDocumentOut$inboundSchema = void 0; + exports.listDocumentOutFromJSON = listDocumentOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documentout_js_1 = require_documentout(); + var paginationinfo_js_1 = require_paginationinfo(); + exports.ListDocumentOut$inboundSchema = z3.object({ + pagination: paginationinfo_js_1.PaginationInfo$inboundSchema, + data: z3.array(documentout_js_1.DocumentOut$inboundSchema) + }); + function listDocumentOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListDocumentOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListDocumentOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listfilesout.js +var require_listfilesout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listfilesout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListFilesOut$inboundSchema = void 0; + exports.listFilesOutFromJSON = listFilesOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var fileschema_js_1 = require_fileschema(); + exports.ListFilesOut$inboundSchema = z3.object({ + data: z3.array(fileschema_js_1.FileSchema$inboundSchema), + object: z3.string(), + total: z3.nullable(z3.number().int()).optional() + }); + function listFilesOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListFilesOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListFilesOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listlibraryout.js +var require_listlibraryout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listlibraryout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListLibraryOut$inboundSchema = void 0; + exports.listLibraryOutFromJSON = listLibraryOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var libraryout_js_1 = require_libraryout(); + exports.ListLibraryOut$inboundSchema = z3.object({ + data: z3.array(libraryout_js_1.LibraryOut$inboundSchema) + }); + function listLibraryOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListLibraryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListLibraryOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingout.js +var require_sharingout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SharingOut$inboundSchema = void 0; + exports.sharingOutFromJSON = sharingOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.SharingOut$inboundSchema = z3.object({ + library_id: z3.string(), + user_id: z3.nullable(z3.string()).optional(), + org_id: z3.string(), + role: z3.string(), + share_with_type: z3.string(), + share_with_uuid: z3.nullable(z3.string()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "library_id": "libraryId", + "user_id": "userId", + "org_id": "orgId", + "share_with_type": "shareWithType", + "share_with_uuid": "shareWithUuid" + }); + }); + function sharingOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.SharingOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'SharingOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listsharingout.js +var require_listsharingout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listsharingout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListSharingOut$inboundSchema = void 0; + exports.listSharingOutFromJSON = listSharingOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var sharingout_js_1 = require_sharingout(); + exports.ListSharingOut$inboundSchema = z3.object({ + data: z3.array(sharingout_js_1.SharingOut$inboundSchema) + }); + function listSharingOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListSharingOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListSharingOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modelconversation.js +var require_modelconversation = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/modelconversation.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModelConversation$inboundSchema = exports.ModelConversationTools$inboundSchema = void 0; + exports.modelConversationToolsFromJSON = modelConversationToolsFromJSON; + exports.modelConversationFromJSON = modelConversationFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.ModelConversationTools$inboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function modelConversationToolsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelConversationTools$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelConversationTools' from JSON`); + } + exports.ModelConversation$inboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completion_args: completionargs_js_1.CompletionArgs$inboundSchema.optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + object: z3.literal("conversation").default("conversation"), + id: z3.string(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + model: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_args": "completionArgs", + "created_at": "createdAt", + "updated_at": "updatedAt" + }); + }); + function modelConversationFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelConversation$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelConversation' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modellist.js +var require_modellist = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/modellist.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModelList$inboundSchema = exports.Data$inboundSchema = void 0; + exports.dataFromJSON = dataFromJSON; + exports.modelListFromJSON = modelListFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var basemodelcard_js_1 = require_basemodelcard(); + var ftmodelcard_js_1 = require_ftmodelcard(); + exports.Data$inboundSchema = z3.union([ + basemodelcard_js_1.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })), + ftmodelcard_js_1.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") })) + ]); + function dataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Data$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Data' from JSON`); + } + exports.ModelList$inboundSchema = z3.object({ + object: z3.string().default("list"), + data: z3.array(z3.union([ + basemodelcard_js_1.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })), + ftmodelcard_js_1.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") })) + ])).optional() + }); + function modelListFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelList$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelList' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationobject.js +var require_moderationobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModerationObject$inboundSchema = void 0; + exports.moderationObjectFromJSON = moderationObjectFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ModerationObject$inboundSchema = z3.object({ + categories: z3.record(z3.boolean()).optional(), + category_scores: z3.record(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "category_scores": "categoryScores" + }); + }); + function moderationObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModerationObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModerationObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationresponse.js +var require_moderationresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModerationResponse$inboundSchema = void 0; + exports.moderationResponseFromJSON = moderationResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var moderationobject_js_1 = require_moderationobject(); + exports.ModerationResponse$inboundSchema = z3.object({ + id: z3.string(), + model: z3.string(), + results: z3.array(moderationobject_js_1.ModerationObject$inboundSchema) + }); + function moderationResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModerationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModerationResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrimageobject.js +var require_ocrimageobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrimageobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRImageObject$inboundSchema = void 0; + exports.ocrImageObjectFromJSON = ocrImageObjectFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.OCRImageObject$inboundSchema = z3.object({ + id: z3.string(), + top_left_x: z3.nullable(z3.number().int()), + top_left_y: z3.nullable(z3.number().int()), + bottom_right_x: z3.nullable(z3.number().int()), + bottom_right_y: z3.nullable(z3.number().int()), + image_base64: z3.nullable(z3.string()).optional(), + image_annotation: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "top_left_x": "topLeftX", + "top_left_y": "topLeftY", + "bottom_right_x": "bottomRightX", + "bottom_right_y": "bottomRightY", + "image_base64": "imageBase64", + "image_annotation": "imageAnnotation" + }); + }); + function ocrImageObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRImageObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRImageObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpagedimensions.js +var require_ocrpagedimensions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpagedimensions.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRPageDimensions$inboundSchema = void 0; + exports.ocrPageDimensionsFromJSON = ocrPageDimensionsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.OCRPageDimensions$inboundSchema = z3.object({ + dpi: z3.number().int(), + height: z3.number().int(), + width: z3.number().int() + }); + function ocrPageDimensionsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRPageDimensions$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRPageDimensions' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrtableobject.js +var require_ocrtableobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrtableobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRTableObject$inboundSchema = exports.Format$inboundSchema = exports.Format = void 0; + exports.ocrTableObjectFromJSON = ocrTableObjectFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Format = { + Markdown: "markdown", + Html: "html" + }; + exports.Format$inboundSchema = z3.nativeEnum(exports.Format); + exports.OCRTableObject$inboundSchema = z3.object({ + id: z3.string(), + content: z3.string(), + format: exports.Format$inboundSchema + }); + function ocrTableObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRTableObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRTableObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpageobject.js +var require_ocrpageobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpageobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRPageObject$inboundSchema = void 0; + exports.ocrPageObjectFromJSON = ocrPageObjectFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var ocrimageobject_js_1 = require_ocrimageobject(); + var ocrpagedimensions_js_1 = require_ocrpagedimensions(); + var ocrtableobject_js_1 = require_ocrtableobject(); + exports.OCRPageObject$inboundSchema = z3.object({ + index: z3.number().int(), + markdown: z3.string(), + images: z3.array(ocrimageobject_js_1.OCRImageObject$inboundSchema), + tables: z3.array(ocrtableobject_js_1.OCRTableObject$inboundSchema).optional(), + hyperlinks: z3.array(z3.string()).optional(), + header: z3.nullable(z3.string()).optional(), + footer: z3.nullable(z3.string()).optional(), + dimensions: z3.nullable(ocrpagedimensions_js_1.OCRPageDimensions$inboundSchema) + }); + function ocrPageObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRPageObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRPageObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrrequest.js +var require_ocrrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRRequest$outboundSchema = exports.TableFormat$outboundSchema = exports.Document$outboundSchema = exports.TableFormat = void 0; + exports.documentToJSON = documentToJSON; + exports.ocrRequestToJSON = ocrRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var filechunk_js_1 = require_filechunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var responseformat_js_1 = require_responseformat(); + exports.TableFormat = { + Markdown: "markdown", + Html: "html" + }; + exports.Document$outboundSchema = z3.union([ + filechunk_js_1.FileChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema + ]); + function documentToJSON(document2) { + return JSON.stringify(exports.Document$outboundSchema.parse(document2)); + } + exports.TableFormat$outboundSchema = z3.nativeEnum(exports.TableFormat); + exports.OCRRequest$outboundSchema = z3.object({ + model: z3.nullable(z3.string()), + id: z3.string().optional(), + document: z3.union([ + filechunk_js_1.FileChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema + ]), + pages: z3.nullable(z3.array(z3.number().int())).optional(), + includeImageBase64: z3.nullable(z3.boolean()).optional(), + imageLimit: z3.nullable(z3.number().int()).optional(), + imageMinSize: z3.nullable(z3.number().int()).optional(), + bboxAnnotationFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(), + documentAnnotationFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(), + documentAnnotationPrompt: z3.nullable(z3.string()).optional(), + tableFormat: z3.nullable(exports.TableFormat$outboundSchema).optional(), + extractHeader: z3.boolean().optional(), + extractFooter: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + includeImageBase64: "include_image_base64", + imageLimit: "image_limit", + imageMinSize: "image_min_size", + bboxAnnotationFormat: "bbox_annotation_format", + documentAnnotationFormat: "document_annotation_format", + documentAnnotationPrompt: "document_annotation_prompt", + tableFormat: "table_format", + extractHeader: "extract_header", + extractFooter: "extract_footer" + }); + }); + function ocrRequestToJSON(ocrRequest) { + return JSON.stringify(exports.OCRRequest$outboundSchema.parse(ocrRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrusageinfo.js +var require_ocrusageinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrusageinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRUsageInfo$inboundSchema = void 0; + exports.ocrUsageInfoFromJSON = ocrUsageInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.OCRUsageInfo$inboundSchema = z3.object({ + pages_processed: z3.number().int(), + doc_size_bytes: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "pages_processed": "pagesProcessed", + "doc_size_bytes": "docSizeBytes" + }); + }); + function ocrUsageInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRUsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRUsageInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrresponse.js +var require_ocrresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRResponse$inboundSchema = void 0; + exports.ocrResponseFromJSON = ocrResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var ocrpageobject_js_1 = require_ocrpageobject(); + var ocrusageinfo_js_1 = require_ocrusageinfo(); + exports.OCRResponse$inboundSchema = z3.object({ + pages: z3.array(ocrpageobject_js_1.OCRPageObject$inboundSchema), + model: z3.string(), + document_annotation: z3.nullable(z3.string()).optional(), + usage_info: ocrusageinfo_js_1.OCRUsageInfo$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "document_annotation": "documentAnnotation", + "usage_info": "usageInfo" + }); + }); + function ocrResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/processingstatusout.js +var require_processingstatusout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/processingstatusout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProcessingStatusOut$inboundSchema = void 0; + exports.processingStatusOutFromJSON = processingStatusOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ProcessingStatusOut$inboundSchema = z3.object({ + document_id: z3.string(), + processing_status: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "document_id": "documentId", + "processing_status": "processingStatus" + }); + }); + function processingStatusOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ProcessingStatusOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ProcessingStatusOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerrordetail.js +var require_realtimetranscriptionerrordetail = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerrordetail.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionErrorDetail$outboundSchema = exports.RealtimeTranscriptionErrorDetail$inboundSchema = exports.Message$outboundSchema = exports.Message$inboundSchema = void 0; + exports.messageToJSON = messageToJSON; + exports.messageFromJSON = messageFromJSON; + exports.realtimeTranscriptionErrorDetailToJSON = realtimeTranscriptionErrorDetailToJSON; + exports.realtimeTranscriptionErrorDetailFromJSON = realtimeTranscriptionErrorDetailFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Message$inboundSchema = z3.union([z3.string(), z3.record(z3.any())]); + exports.Message$outboundSchema = z3.union([z3.string(), z3.record(z3.any())]); + function messageToJSON(message) { + return JSON.stringify(exports.Message$outboundSchema.parse(message)); + } + function messageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Message$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Message' from JSON`); + } + exports.RealtimeTranscriptionErrorDetail$inboundSchema = z3.object({ + message: z3.union([z3.string(), z3.record(z3.any())]), + code: z3.number().int() + }); + exports.RealtimeTranscriptionErrorDetail$outboundSchema = z3.object({ + message: z3.union([z3.string(), z3.record(z3.any())]), + code: z3.number().int() + }); + function realtimeTranscriptionErrorDetailToJSON(realtimeTranscriptionErrorDetail) { + return JSON.stringify(exports.RealtimeTranscriptionErrorDetail$outboundSchema.parse(realtimeTranscriptionErrorDetail)); + } + function realtimeTranscriptionErrorDetailFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionErrorDetail$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionErrorDetail' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerror.js +var require_realtimetranscriptionerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionError$outboundSchema = exports.RealtimeTranscriptionError$inboundSchema = void 0; + exports.realtimeTranscriptionErrorToJSON = realtimeTranscriptionErrorToJSON; + exports.realtimeTranscriptionErrorFromJSON = realtimeTranscriptionErrorFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionerrordetail_js_1 = require_realtimetranscriptionerrordetail(); + exports.RealtimeTranscriptionError$inboundSchema = z3.object({ + type: z3.literal("error").default("error"), + error: realtimetranscriptionerrordetail_js_1.RealtimeTranscriptionErrorDetail$inboundSchema + }); + exports.RealtimeTranscriptionError$outboundSchema = z3.object({ + type: z3.literal("error").default("error"), + error: realtimetranscriptionerrordetail_js_1.RealtimeTranscriptionErrorDetail$outboundSchema + }); + function realtimeTranscriptionErrorToJSON(realtimeTranscriptionError) { + return JSON.stringify(exports.RealtimeTranscriptionError$outboundSchema.parse(realtimeTranscriptionError)); + } + function realtimeTranscriptionErrorFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionError' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioappend.js +var require_realtimetranscriptioninputaudioappend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioappend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionInputAudioAppend$outboundSchema = exports.RealtimeTranscriptionInputAudioAppend$inboundSchema = void 0; + exports.realtimeTranscriptionInputAudioAppendToJSON = realtimeTranscriptionInputAudioAppendToJSON; + exports.realtimeTranscriptionInputAudioAppendFromJSON = realtimeTranscriptionInputAudioAppendFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.RealtimeTranscriptionInputAudioAppend$inboundSchema = z3.object({ + type: z3.literal("input_audio.append").default("input_audio.append"), + audio: z3.string() + }); + exports.RealtimeTranscriptionInputAudioAppend$outboundSchema = z3.object({ + type: z3.literal("input_audio.append").default("input_audio.append"), + audio: z3.string() + }); + function realtimeTranscriptionInputAudioAppendToJSON(realtimeTranscriptionInputAudioAppend) { + return JSON.stringify(exports.RealtimeTranscriptionInputAudioAppend$outboundSchema.parse(realtimeTranscriptionInputAudioAppend)); + } + function realtimeTranscriptionInputAudioAppendFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioAppend$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioAppend' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioend.js +var require_realtimetranscriptioninputaudioend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionInputAudioEnd$outboundSchema = exports.RealtimeTranscriptionInputAudioEnd$inboundSchema = void 0; + exports.realtimeTranscriptionInputAudioEndToJSON = realtimeTranscriptionInputAudioEndToJSON; + exports.realtimeTranscriptionInputAudioEndFromJSON = realtimeTranscriptionInputAudioEndFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.RealtimeTranscriptionInputAudioEnd$inboundSchema = z3.object({ + type: z3.literal("input_audio.end").default("input_audio.end") + }); + exports.RealtimeTranscriptionInputAudioEnd$outboundSchema = z3.object({ + type: z3.literal("input_audio.end").default("input_audio.end") + }); + function realtimeTranscriptionInputAudioEndToJSON(realtimeTranscriptionInputAudioEnd) { + return JSON.stringify(exports.RealtimeTranscriptionInputAudioEnd$outboundSchema.parse(realtimeTranscriptionInputAudioEnd)); + } + function realtimeTranscriptionInputAudioEndFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioEnd$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioEnd' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioflush.js +var require_realtimetranscriptioninputaudioflush = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioflush.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionInputAudioFlush$outboundSchema = exports.RealtimeTranscriptionInputAudioFlush$inboundSchema = void 0; + exports.realtimeTranscriptionInputAudioFlushToJSON = realtimeTranscriptionInputAudioFlushToJSON; + exports.realtimeTranscriptionInputAudioFlushFromJSON = realtimeTranscriptionInputAudioFlushFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.RealtimeTranscriptionInputAudioFlush$inboundSchema = z3.object({ + type: z3.literal("input_audio.flush").default("input_audio.flush") + }); + exports.RealtimeTranscriptionInputAudioFlush$outboundSchema = z3.object({ + type: z3.literal("input_audio.flush").default("input_audio.flush") + }); + function realtimeTranscriptionInputAudioFlushToJSON(realtimeTranscriptionInputAudioFlush) { + return JSON.stringify(exports.RealtimeTranscriptionInputAudioFlush$outboundSchema.parse(realtimeTranscriptionInputAudioFlush)); + } + function realtimeTranscriptionInputAudioFlushFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioFlush$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioFlush' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsession.js +var require_realtimetranscriptionsession = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsession.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSession$outboundSchema = exports.RealtimeTranscriptionSession$inboundSchema = void 0; + exports.realtimeTranscriptionSessionToJSON = realtimeTranscriptionSessionToJSON; + exports.realtimeTranscriptionSessionFromJSON = realtimeTranscriptionSessionFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var audioformat_js_1 = require_audioformat(); + exports.RealtimeTranscriptionSession$inboundSchema = z3.object({ + request_id: z3.string(), + model: z3.string(), + audio_format: audioformat_js_1.AudioFormat$inboundSchema, + target_streaming_delay_ms: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "request_id": "requestId", + "audio_format": "audioFormat", + "target_streaming_delay_ms": "targetStreamingDelayMs" + }); + }); + exports.RealtimeTranscriptionSession$outboundSchema = z3.object({ + requestId: z3.string(), + model: z3.string(), + audioFormat: audioformat_js_1.AudioFormat$outboundSchema, + targetStreamingDelayMs: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + requestId: "request_id", + audioFormat: "audio_format", + targetStreamingDelayMs: "target_streaming_delay_ms" + }); + }); + function realtimeTranscriptionSessionToJSON(realtimeTranscriptionSession) { + return JSON.stringify(exports.RealtimeTranscriptionSession$outboundSchema.parse(realtimeTranscriptionSession)); + } + function realtimeTranscriptionSessionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSession$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSession' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessioncreated.js +var require_realtimetranscriptionsessioncreated = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessioncreated.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionCreated$outboundSchema = exports.RealtimeTranscriptionSessionCreated$inboundSchema = void 0; + exports.realtimeTranscriptionSessionCreatedToJSON = realtimeTranscriptionSessionCreatedToJSON; + exports.realtimeTranscriptionSessionCreatedFromJSON = realtimeTranscriptionSessionCreatedFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionsession_js_1 = require_realtimetranscriptionsession(); + exports.RealtimeTranscriptionSessionCreated$inboundSchema = z3.object({ + type: z3.literal("session.created").default("session.created"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$inboundSchema + }); + exports.RealtimeTranscriptionSessionCreated$outboundSchema = z3.object({ + type: z3.literal("session.created").default("session.created"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$outboundSchema + }); + function realtimeTranscriptionSessionCreatedToJSON(realtimeTranscriptionSessionCreated) { + return JSON.stringify(exports.RealtimeTranscriptionSessionCreated$outboundSchema.parse(realtimeTranscriptionSessionCreated)); + } + function realtimeTranscriptionSessionCreatedFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionCreated$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionCreated' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdated.js +var require_realtimetranscriptionsessionupdated = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdated.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionUpdated$outboundSchema = exports.RealtimeTranscriptionSessionUpdated$inboundSchema = void 0; + exports.realtimeTranscriptionSessionUpdatedToJSON = realtimeTranscriptionSessionUpdatedToJSON; + exports.realtimeTranscriptionSessionUpdatedFromJSON = realtimeTranscriptionSessionUpdatedFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionsession_js_1 = require_realtimetranscriptionsession(); + exports.RealtimeTranscriptionSessionUpdated$inboundSchema = z3.object({ + type: z3.literal("session.updated").default("session.updated"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$inboundSchema + }); + exports.RealtimeTranscriptionSessionUpdated$outboundSchema = z3.object({ + type: z3.literal("session.updated").default("session.updated"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$outboundSchema + }); + function realtimeTranscriptionSessionUpdatedToJSON(realtimeTranscriptionSessionUpdated) { + return JSON.stringify(exports.RealtimeTranscriptionSessionUpdated$outboundSchema.parse(realtimeTranscriptionSessionUpdated)); + } + function realtimeTranscriptionSessionUpdatedFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdated$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdated' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatepayload.js +var require_realtimetranscriptionsessionupdatepayload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatepayload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema = exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema = void 0; + exports.realtimeTranscriptionSessionUpdatePayloadToJSON = realtimeTranscriptionSessionUpdatePayloadToJSON; + exports.realtimeTranscriptionSessionUpdatePayloadFromJSON = realtimeTranscriptionSessionUpdatePayloadFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var audioformat_js_1 = require_audioformat(); + exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema = z3.object({ + audio_format: z3.nullable(audioformat_js_1.AudioFormat$inboundSchema).optional(), + target_streaming_delay_ms: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "audio_format": "audioFormat", + "target_streaming_delay_ms": "targetStreamingDelayMs" + }); + }); + exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema = z3.object({ + audioFormat: z3.nullable(audioformat_js_1.AudioFormat$outboundSchema).optional(), + targetStreamingDelayMs: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + audioFormat: "audio_format", + targetStreamingDelayMs: "target_streaming_delay_ms" + }); + }); + function realtimeTranscriptionSessionUpdatePayloadToJSON(realtimeTranscriptionSessionUpdatePayload) { + return JSON.stringify(exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema.parse(realtimeTranscriptionSessionUpdatePayload)); + } + function realtimeTranscriptionSessionUpdatePayloadFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdatePayload' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatemessage.js +var require_realtimetranscriptionsessionupdatemessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatemessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema = exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema = void 0; + exports.realtimeTranscriptionSessionUpdateMessageToJSON = realtimeTranscriptionSessionUpdateMessageToJSON; + exports.realtimeTranscriptionSessionUpdateMessageFromJSON = realtimeTranscriptionSessionUpdateMessageFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionsessionupdatepayload_js_1 = require_realtimetranscriptionsessionupdatepayload(); + exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema = z3.object({ + type: z3.literal("session.update").default("session.update"), + session: realtimetranscriptionsessionupdatepayload_js_1.RealtimeTranscriptionSessionUpdatePayload$inboundSchema + }); + exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema = z3.object({ + type: z3.literal("session.update").default("session.update"), + session: realtimetranscriptionsessionupdatepayload_js_1.RealtimeTranscriptionSessionUpdatePayload$outboundSchema + }); + function realtimeTranscriptionSessionUpdateMessageToJSON(realtimeTranscriptionSessionUpdateMessage) { + return JSON.stringify(exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema.parse(realtimeTranscriptionSessionUpdateMessage)); + } + function realtimeTranscriptionSessionUpdateMessageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdateMessage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/requestsource.js +var require_requestsource = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/requestsource.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RequestSource$outboundSchema = exports.RequestSource = void 0; + var z3 = __importStar(require_v3()); + exports.RequestSource = { + Api: "api", + Playground: "playground", + AgentBuilderV1: "agent_builder_v1" + }; + exports.RequestSource$outboundSchema = z3.nativeEnum(exports.RequestSource); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/retrievefileout.js +var require_retrievefileout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/retrievefileout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RetrieveFileOut$inboundSchema = void 0; + exports.retrieveFileOutFromJSON = retrieveFileOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var filepurpose_js_1 = require_filepurpose(); + var sampletype_js_1 = require_sampletype(); + var source_js_1 = require_source(); + exports.RetrieveFileOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + bytes: z3.number().int(), + created_at: z3.number().int(), + filename: z3.string(), + purpose: filepurpose_js_1.FilePurpose$inboundSchema, + sample_type: sampletype_js_1.SampleType$inboundSchema, + num_lines: z3.nullable(z3.number().int()).optional(), + mimetype: z3.nullable(z3.string()).optional(), + source: source_js_1.Source$inboundSchema, + signature: z3.nullable(z3.string()).optional(), + deleted: z3.boolean() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "bytes": "sizeBytes", + "created_at": "createdAt", + "sample_type": "sampleType", + "num_lines": "numLines" + }); + }); + function retrieveFileOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RetrieveFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RetrieveFileOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/security.js +var require_security2 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/security.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Security$outboundSchema = void 0; + exports.securityToJSON = securityToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.Security$outboundSchema = z3.object({ + apiKey: z3.string().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + apiKey: "ApiKey" + }); + }); + function securityToJSON(security) { + return JSON.stringify(exports.Security$outboundSchema.parse(security)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/shareenum.js +var require_shareenum = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/shareenum.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ShareEnum$outboundSchema = exports.ShareEnum = void 0; + var openEnums = __importStar(require_enums()); + exports.ShareEnum = { + Viewer: "Viewer", + Editor: "Editor" + }; + exports.ShareEnum$outboundSchema = openEnums.outboundSchema(exports.ShareEnum); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingdelete.js +var require_sharingdelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingdelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SharingDelete$outboundSchema = void 0; + exports.sharingDeleteToJSON = sharingDeleteToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var entitytype_js_1 = require_entitytype(); + exports.SharingDelete$outboundSchema = z3.object({ + orgId: z3.nullable(z3.string()).optional(), + shareWithUuid: z3.string(), + shareWithType: entitytype_js_1.EntityType$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + orgId: "org_id", + shareWithUuid: "share_with_uuid", + shareWithType: "share_with_type" + }); + }); + function sharingDeleteToJSON(sharingDelete) { + return JSON.stringify(exports.SharingDelete$outboundSchema.parse(sharingDelete)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingin.js +var require_sharingin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SharingIn$outboundSchema = void 0; + exports.sharingInToJSON = sharingInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var entitytype_js_1 = require_entitytype(); + var shareenum_js_1 = require_shareenum(); + exports.SharingIn$outboundSchema = z3.object({ + orgId: z3.nullable(z3.string()).optional(), + level: shareenum_js_1.ShareEnum$outboundSchema, + shareWithUuid: z3.string(), + shareWithType: entitytype_js_1.EntityType$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + orgId: "org_id", + shareWithUuid: "share_with_uuid", + shareWithType: "share_with_type" + }); + }); + function sharingInToJSON(sharingIn) { + return JSON.stringify(exports.SharingIn$outboundSchema.parse(sharingIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionsegmentchunk.js +var require_transcriptionsegmentchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionsegmentchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionSegmentChunk$outboundSchema = exports.TranscriptionSegmentChunk$inboundSchema = void 0; + exports.transcriptionSegmentChunkToJSON = transcriptionSegmentChunkToJSON; + exports.transcriptionSegmentChunkFromJSON = transcriptionSegmentChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionSegmentChunk$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription_segment").default("transcription_segment"), + text: z3.string(), + start: z3.number(), + end: z3.number(), + score: z3.nullable(z3.number()).optional(), + speaker_id: z3.nullable(z3.string()).optional() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "speaker_id": "speakerId" + }); + }); + exports.TranscriptionSegmentChunk$outboundSchema = z3.object({ + type: z3.literal("transcription_segment").default("transcription_segment"), + text: z3.string(), + start: z3.number(), + end: z3.number(), + score: z3.nullable(z3.number()).optional(), + speakerId: z3.nullable(z3.string()).optional(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + speakerId: "speaker_id", + additionalProperties: null + }) + }; + }); + function transcriptionSegmentChunkToJSON(transcriptionSegmentChunk) { + return JSON.stringify(exports.TranscriptionSegmentChunk$outboundSchema.parse(transcriptionSegmentChunk)); + } + function transcriptionSegmentChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionSegmentChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionSegmentChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionresponse.js +var require_transcriptionresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionResponse$inboundSchema = void 0; + exports.transcriptionResponseFromJSON = transcriptionResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var transcriptionsegmentchunk_js_1 = require_transcriptionsegmentchunk(); + var usageinfo_js_1 = require_usageinfo(); + exports.TranscriptionResponse$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + model: z3.string(), + text: z3.string(), + segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$inboundSchema).optional(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + language: z3.nullable(z3.string()) + }).catchall(z3.any()), "additionalProperties", true); + function transcriptionResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamdone.js +var require_transcriptionstreamdone = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamdone.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamDone$outboundSchema = exports.TranscriptionStreamDone$inboundSchema = void 0; + exports.transcriptionStreamDoneToJSON = transcriptionStreamDoneToJSON; + exports.transcriptionStreamDoneFromJSON = transcriptionStreamDoneFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var transcriptionsegmentchunk_js_1 = require_transcriptionsegmentchunk(); + var usageinfo_js_1 = require_usageinfo(); + exports.TranscriptionStreamDone$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + model: z3.string(), + text: z3.string(), + segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$inboundSchema).optional(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + type: z3.literal("transcription.done").default("transcription.done"), + language: z3.nullable(z3.string()) + }).catchall(z3.any()), "additionalProperties", true); + exports.TranscriptionStreamDone$outboundSchema = z3.object({ + model: z3.string(), + text: z3.string(), + segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$outboundSchema).optional(), + usage: usageinfo_js_1.UsageInfo$outboundSchema, + type: z3.literal("transcription.done").default("transcription.done"), + language: z3.nullable(z3.string()), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + additionalProperties: null + }) + }; + }); + function transcriptionStreamDoneToJSON(transcriptionStreamDone) { + return JSON.stringify(exports.TranscriptionStreamDone$outboundSchema.parse(transcriptionStreamDone)); + } + function transcriptionStreamDoneFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamDone$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamDone' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreameventtypes.js +var require_transcriptionstreameventtypes = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreameventtypes.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamEventTypes$inboundSchema = exports.TranscriptionStreamEventTypes = void 0; + var z3 = __importStar(require_v3()); + exports.TranscriptionStreamEventTypes = { + TranscriptionLanguage: "transcription.language", + TranscriptionSegment: "transcription.segment", + TranscriptionTextDelta: "transcription.text.delta", + TranscriptionDone: "transcription.done" + }; + exports.TranscriptionStreamEventTypes$inboundSchema = z3.nativeEnum(exports.TranscriptionStreamEventTypes); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamlanguage.js +var require_transcriptionstreamlanguage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamlanguage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamLanguage$outboundSchema = exports.TranscriptionStreamLanguage$inboundSchema = void 0; + exports.transcriptionStreamLanguageToJSON = transcriptionStreamLanguageToJSON; + exports.transcriptionStreamLanguageFromJSON = transcriptionStreamLanguageFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionStreamLanguage$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription.language").default("transcription.language"), + audio_language: z3.string() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "audio_language": "audioLanguage" + }); + }); + exports.TranscriptionStreamLanguage$outboundSchema = z3.object({ + type: z3.literal("transcription.language").default("transcription.language"), + audioLanguage: z3.string(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + audioLanguage: "audio_language", + additionalProperties: null + }) + }; + }); + function transcriptionStreamLanguageToJSON(transcriptionStreamLanguage) { + return JSON.stringify(exports.TranscriptionStreamLanguage$outboundSchema.parse(transcriptionStreamLanguage)); + } + function transcriptionStreamLanguageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamLanguage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamLanguage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamsegmentdelta.js +var require_transcriptionstreamsegmentdelta = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamsegmentdelta.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamSegmentDelta$inboundSchema = void 0; + exports.transcriptionStreamSegmentDeltaFromJSON = transcriptionStreamSegmentDeltaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionStreamSegmentDelta$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription.segment").default("transcription.segment"), + text: z3.string(), + start: z3.number(), + end: z3.number(), + speaker_id: z3.nullable(z3.string()).optional() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "speaker_id": "speakerId" + }); + }); + function transcriptionStreamSegmentDeltaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamSegmentDelta$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamSegmentDelta' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamtextdelta.js +var require_transcriptionstreamtextdelta = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamtextdelta.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamTextDelta$outboundSchema = exports.TranscriptionStreamTextDelta$inboundSchema = void 0; + exports.transcriptionStreamTextDeltaToJSON = transcriptionStreamTextDeltaToJSON; + exports.transcriptionStreamTextDeltaFromJSON = transcriptionStreamTextDeltaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionStreamTextDelta$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription.text.delta").default("transcription.text.delta"), + text: z3.string() + }).catchall(z3.any()), "additionalProperties", true); + exports.TranscriptionStreamTextDelta$outboundSchema = z3.object({ + type: z3.literal("transcription.text.delta").default("transcription.text.delta"), + text: z3.string(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + additionalProperties: null + }) + }; + }); + function transcriptionStreamTextDeltaToJSON(transcriptionStreamTextDelta) { + return JSON.stringify(exports.TranscriptionStreamTextDelta$outboundSchema.parse(transcriptionStreamTextDelta)); + } + function transcriptionStreamTextDeltaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamTextDelta$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamTextDelta' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamevents.js +var require_transcriptionstreamevents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamevents.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamEvents$inboundSchema = exports.TranscriptionStreamEventsData$inboundSchema = void 0; + exports.transcriptionStreamEventsDataFromJSON = transcriptionStreamEventsDataFromJSON; + exports.transcriptionStreamEventsFromJSON = transcriptionStreamEventsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var transcriptionstreamdone_js_1 = require_transcriptionstreamdone(); + var transcriptionstreameventtypes_js_1 = require_transcriptionstreameventtypes(); + var transcriptionstreamlanguage_js_1 = require_transcriptionstreamlanguage(); + var transcriptionstreamsegmentdelta_js_1 = require_transcriptionstreamsegmentdelta(); + var transcriptionstreamtextdelta_js_1 = require_transcriptionstreamtextdelta(); + exports.TranscriptionStreamEventsData$inboundSchema = z3.union([ + transcriptionstreamdone_js_1.TranscriptionStreamDone$inboundSchema.and(z3.object({ type: z3.literal("transcription.done") })), + transcriptionstreamlanguage_js_1.TranscriptionStreamLanguage$inboundSchema.and(z3.object({ type: z3.literal("transcription.language") })), + transcriptionstreamsegmentdelta_js_1.TranscriptionStreamSegmentDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.segment") })), + transcriptionstreamtextdelta_js_1.TranscriptionStreamTextDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.text.delta") })) + ]); + function transcriptionStreamEventsDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamEventsData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamEventsData' from JSON`); + } + exports.TranscriptionStreamEvents$inboundSchema = z3.object({ + event: transcriptionstreameventtypes_js_1.TranscriptionStreamEventTypes$inboundSchema, + data: z3.string().transform((v4, ctx) => { + try { + return JSON.parse(v4); + } catch (err) { + ctx.addIssue({ code: "custom", message: `malformed json: ${err}` }); + return z3.NEVER; + } + }).pipe(z3.union([ + transcriptionstreamdone_js_1.TranscriptionStreamDone$inboundSchema.and(z3.object({ type: z3.literal("transcription.done") })), + transcriptionstreamlanguage_js_1.TranscriptionStreamLanguage$inboundSchema.and(z3.object({ type: z3.literal("transcription.language") })), + transcriptionstreamsegmentdelta_js_1.TranscriptionStreamSegmentDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.segment") })), + transcriptionstreamtextdelta_js_1.TranscriptionStreamTextDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.text.delta") })) + ])) + }); + function transcriptionStreamEventsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamEvents$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamEvents' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/unarchiveftmodelout.js +var require_unarchiveftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/unarchiveftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UnarchiveFTModelOut$inboundSchema = void 0; + exports.unarchiveFTModelOutFromJSON = unarchiveFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.UnarchiveFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + archived: z3.boolean().default(false) + }); + function unarchiveFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UnarchiveFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UnarchiveFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/updateftmodelin.js +var require_updateftmodelin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/updateftmodelin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UpdateFTModelIn$outboundSchema = void 0; + exports.updateFTModelInToJSON = updateFTModelInToJSON; + var z3 = __importStar(require_v3()); + exports.UpdateFTModelIn$outboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + function updateFTModelInToJSON(updateFTModelIn) { + return JSON.stringify(exports.UpdateFTModelIn$outboundSchema.parse(updateFTModelIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/uploadfileout.js +var require_uploadfileout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/uploadfileout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UploadFileOut$inboundSchema = void 0; + exports.uploadFileOutFromJSON = uploadFileOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var filepurpose_js_1 = require_filepurpose(); + var sampletype_js_1 = require_sampletype(); + var source_js_1 = require_source(); + exports.UploadFileOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + bytes: z3.number().int(), + created_at: z3.number().int(), + filename: z3.string(), + purpose: filepurpose_js_1.FilePurpose$inboundSchema, + sample_type: sampletype_js_1.SampleType$inboundSchema, + num_lines: z3.nullable(z3.number().int()).optional(), + mimetype: z3.nullable(z3.string()).optional(), + source: source_js_1.Source$inboundSchema, + signature: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "bytes": "sizeBytes", + "created_at": "createdAt", + "sample_type": "sampleType", + "num_lines": "numLines" + }); + }); + function uploadFileOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UploadFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UploadFileOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/validationerror.js +var require_validationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/validationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValidationError$inboundSchema = exports.Loc$inboundSchema = void 0; + exports.locFromJSON = locFromJSON; + exports.validationErrorFromJSON = validationErrorFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Loc$inboundSchema = z3.union([z3.string(), z3.number().int()]); + function locFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Loc$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Loc' from JSON`); + } + exports.ValidationError$inboundSchema = z3.object({ + loc: z3.array(z3.union([z3.string(), z3.number().int()])), + msg: z3.string(), + type: z3.string() + }); + function validationErrorFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ValidationError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ValidationError' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/index.js +var require_components = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_agent(), exports); + __exportStar(require_agentaliasresponse(), exports); + __exportStar(require_agentconversation(), exports); + __exportStar(require_agentcreationrequest(), exports); + __exportStar(require_agenthandoffdoneevent(), exports); + __exportStar(require_agenthandoffentry(), exports); + __exportStar(require_agenthandoffstartedevent(), exports); + __exportStar(require_agentscompletionrequest(), exports); + __exportStar(require_agentscompletionstreamrequest(), exports); + __exportStar(require_agentupdaterequest(), exports); + __exportStar(require_apiendpoint(), exports); + __exportStar(require_archiveftmodelout(), exports); + __exportStar(require_assistantmessage(), exports); + __exportStar(require_audiochunk(), exports); + __exportStar(require_audioencoding(), exports); + __exportStar(require_audioformat(), exports); + __exportStar(require_audiotranscriptionrequest(), exports); + __exportStar(require_audiotranscriptionrequeststream(), exports); + __exportStar(require_basemodelcard(), exports); + __exportStar(require_batcherror(), exports); + __exportStar(require_batchjobin(), exports); + __exportStar(require_batchjobout(), exports); + __exportStar(require_batchjobsout(), exports); + __exportStar(require_batchjobstatus(), exports); + __exportStar(require_batchrequest(), exports); + __exportStar(require_builtinconnectors(), exports); + __exportStar(require_chatclassificationrequest(), exports); + __exportStar(require_chatcompletionchoice(), exports); + __exportStar(require_chatcompletionrequest(), exports); + __exportStar(require_chatcompletionresponse(), exports); + __exportStar(require_chatcompletionstreamrequest(), exports); + __exportStar(require_chatmoderationrequest(), exports); + __exportStar(require_checkpointout(), exports); + __exportStar(require_classificationrequest(), exports); + __exportStar(require_classificationresponse(), exports); + __exportStar(require_classificationtargetresult(), exports); + __exportStar(require_classifierdetailedjobout(), exports); + __exportStar(require_classifierftmodelout(), exports); + __exportStar(require_classifierjobout(), exports); + __exportStar(require_classifiertargetin(), exports); + __exportStar(require_classifiertargetout(), exports); + __exportStar(require_classifiertrainingparameters(), exports); + __exportStar(require_classifiertrainingparametersin(), exports); + __exportStar(require_codeinterpretertool(), exports); + __exportStar(require_completionargs(), exports); + __exportStar(require_completionargsstop(), exports); + __exportStar(require_completionchunk(), exports); + __exportStar(require_completiondetailedjobout(), exports); + __exportStar(require_completionevent(), exports); + __exportStar(require_completionftmodelout(), exports); + __exportStar(require_completionjobout(), exports); + __exportStar(require_completionresponsestreamchoice(), exports); + __exportStar(require_completiontrainingparameters(), exports); + __exportStar(require_completiontrainingparametersin(), exports); + __exportStar(require_contentchunk(), exports); + __exportStar(require_conversationappendrequest(), exports); + __exportStar(require_conversationappendstreamrequest(), exports); + __exportStar(require_conversationevents(), exports); + __exportStar(require_conversationhistory(), exports); + __exportStar(require_conversationinputs(), exports); + __exportStar(require_conversationmessages(), exports); + __exportStar(require_conversationrequest(), exports); + __exportStar(require_conversationresponse(), exports); + __exportStar(require_conversationrestartrequest(), exports); + __exportStar(require_conversationrestartstreamrequest(), exports); + __exportStar(require_conversationstreamrequest(), exports); + __exportStar(require_conversationusageinfo(), exports); + __exportStar(require_deletefileout(), exports); + __exportStar(require_deletemodelout(), exports); + __exportStar(require_deltamessage(), exports); + __exportStar(require_documentlibrarytool(), exports); + __exportStar(require_documentout(), exports); + __exportStar(require_documenttextcontent(), exports); + __exportStar(require_documentupdatein(), exports); + __exportStar(require_documenturlchunk(), exports); + __exportStar(require_embeddingdtype(), exports); + __exportStar(require_embeddingrequest(), exports); + __exportStar(require_embeddingresponse(), exports); + __exportStar(require_embeddingresponsedata(), exports); + __exportStar(require_encodingformat(), exports); + __exportStar(require_entitytype(), exports); + __exportStar(require_eventout(), exports); + __exportStar(require_file(), exports); + __exportStar(require_filechunk(), exports); + __exportStar(require_filepurpose(), exports); + __exportStar(require_fileschema(), exports); + __exportStar(require_filesignedurl(), exports); + __exportStar(require_fimcompletionrequest(), exports); + __exportStar(require_fimcompletionresponse(), exports); + __exportStar(require_fimcompletionstreamrequest(), exports); + __exportStar(require_finetuneablemodeltype(), exports); + __exportStar(require_ftclassifierlossfunction(), exports); + __exportStar(require_ftmodelcapabilitiesout(), exports); + __exportStar(require_ftmodelcard(), exports); + __exportStar(require_function(), exports); + __exportStar(require_functioncall(), exports); + __exportStar(require_functioncallentry(), exports); + __exportStar(require_functioncallentryarguments(), exports); + __exportStar(require_functioncallevent(), exports); + __exportStar(require_functionname(), exports); + __exportStar(require_functionresultentry(), exports); + __exportStar(require_functiontool(), exports); + __exportStar(require_githubrepositoryin(), exports); + __exportStar(require_githubrepositoryout(), exports); + __exportStar(require_imagedetail(), exports); + __exportStar(require_imagegenerationtool(), exports); + __exportStar(require_imageurl(), exports); + __exportStar(require_imageurlchunk(), exports); + __exportStar(require_inputentries(), exports); + __exportStar(require_inputs(), exports); + __exportStar(require_instructrequest(), exports); + __exportStar(require_jobin(), exports); + __exportStar(require_jobmetadataout(), exports); + __exportStar(require_jobsout(), exports); + __exportStar(require_jsonschema(), exports); + __exportStar(require_legacyjobmetadataout(), exports); + __exportStar(require_libraryin(), exports); + __exportStar(require_libraryinupdate(), exports); + __exportStar(require_libraryout(), exports); + __exportStar(require_listdocumentout(), exports); + __exportStar(require_listfilesout(), exports); + __exportStar(require_listlibraryout(), exports); + __exportStar(require_listsharingout(), exports); + __exportStar(require_messageentries(), exports); + __exportStar(require_messageinputcontentchunks(), exports); + __exportStar(require_messageinputentry(), exports); + __exportStar(require_messageoutputcontentchunks(), exports); + __exportStar(require_messageoutputentry(), exports); + __exportStar(require_messageoutputevent(), exports); + __exportStar(require_metricout(), exports); + __exportStar(require_mistralpromptmode(), exports); + __exportStar(require_modelcapabilities(), exports); + __exportStar(require_modelconversation(), exports); + __exportStar(require_modellist(), exports); + __exportStar(require_moderationobject(), exports); + __exportStar(require_moderationresponse(), exports); + __exportStar(require_ocrimageobject(), exports); + __exportStar(require_ocrpagedimensions(), exports); + __exportStar(require_ocrpageobject(), exports); + __exportStar(require_ocrrequest(), exports); + __exportStar(require_ocrresponse(), exports); + __exportStar(require_ocrtableobject(), exports); + __exportStar(require_ocrusageinfo(), exports); + __exportStar(require_outputcontentchunks(), exports); + __exportStar(require_paginationinfo(), exports); + __exportStar(require_prediction(), exports); + __exportStar(require_processingstatusout(), exports); + __exportStar(require_realtimetranscriptionerror(), exports); + __exportStar(require_realtimetranscriptionerrordetail(), exports); + __exportStar(require_realtimetranscriptioninputaudioappend(), exports); + __exportStar(require_realtimetranscriptioninputaudioend(), exports); + __exportStar(require_realtimetranscriptioninputaudioflush(), exports); + __exportStar(require_realtimetranscriptionsession(), exports); + __exportStar(require_realtimetranscriptionsessioncreated(), exports); + __exportStar(require_realtimetranscriptionsessionupdated(), exports); + __exportStar(require_realtimetranscriptionsessionupdatemessage(), exports); + __exportStar(require_realtimetranscriptionsessionupdatepayload(), exports); + __exportStar(require_referencechunk(), exports); + __exportStar(require_requestsource(), exports); + __exportStar(require_responsedoneevent(), exports); + __exportStar(require_responseerrorevent(), exports); + __exportStar(require_responseformat(), exports); + __exportStar(require_responseformats(), exports); + __exportStar(require_responsestartedevent(), exports); + __exportStar(require_retrievefileout(), exports); + __exportStar(require_sampletype(), exports); + __exportStar(require_security2(), exports); + __exportStar(require_shareenum(), exports); + __exportStar(require_sharingdelete(), exports); + __exportStar(require_sharingin(), exports); + __exportStar(require_sharingout(), exports); + __exportStar(require_source(), exports); + __exportStar(require_ssetypes(), exports); + __exportStar(require_systemmessage(), exports); + __exportStar(require_systemmessagecontentchunks(), exports); + __exportStar(require_textchunk(), exports); + __exportStar(require_thinkchunk(), exports); + __exportStar(require_timestampgranularity(), exports); + __exportStar(require_tool(), exports); + __exportStar(require_toolcall(), exports); + __exportStar(require_toolcallconfirmation(), exports); + __exportStar(require_toolchoice(), exports); + __exportStar(require_toolchoiceenum(), exports); + __exportStar(require_toolconfiguration(), exports); + __exportStar(require_toolexecutiondeltaevent(), exports); + __exportStar(require_toolexecutiondoneevent(), exports); + __exportStar(require_toolexecutionentry(), exports); + __exportStar(require_toolexecutionstartedevent(), exports); + __exportStar(require_toolfilechunk(), exports); + __exportStar(require_toolmessage(), exports); + __exportStar(require_toolreferencechunk(), exports); + __exportStar(require_tooltypes(), exports); + __exportStar(require_trainingfile(), exports); + __exportStar(require_transcriptionresponse(), exports); + __exportStar(require_transcriptionsegmentchunk(), exports); + __exportStar(require_transcriptionstreamdone(), exports); + __exportStar(require_transcriptionstreamevents(), exports); + __exportStar(require_transcriptionstreameventtypes(), exports); + __exportStar(require_transcriptionstreamlanguage(), exports); + __exportStar(require_transcriptionstreamsegmentdelta(), exports); + __exportStar(require_transcriptionstreamtextdelta(), exports); + __exportStar(require_unarchiveftmodelout(), exports); + __exportStar(require_updateftmodelin(), exports); + __exportStar(require_uploadfileout(), exports); + __exportStar(require_usageinfo(), exports); + __exportStar(require_usermessage(), exports); + __exportStar(require_validationerror(), exports); + __exportStar(require_wandbintegration(), exports); + __exportStar(require_wandbintegrationout(), exports); + __exportStar(require_websearchpremiumtool(), exports); + __exportStar(require_websearchtool(), exports); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpvalidationerror.js +var require_httpvalidationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpvalidationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTPValidationError$inboundSchema = exports.HTTPValidationError = void 0; + var z3 = __importStar(require_v3()); + var components = __importStar(require_components()); + var mistralerror_js_1 = require_mistralerror(); + var HTTPValidationError = class extends mistralerror_js_1.MistralError { + constructor(err, httpMeta) { + const message = "message" in err && typeof err.message === "string" ? err.message : `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + if (err.detail != null) + this.detail = err.detail; + this.name = "HTTPValidationError"; + } + }; + exports.HTTPValidationError = HTTPValidationError; + exports.HTTPValidationError$inboundSchema = z3.object({ + detail: z3.array(components.ValidationError$inboundSchema).optional(), + request$: z3.instanceof(Request), + response$: z3.instanceof(Response), + body$: z3.string() + }).transform((v4) => { + return new HTTPValidationError(v4, { + request: v4.request$, + response: v4.response$, + body: v4.body$ + }); + }); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/index.js +var require_errors2 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_httpclienterrors(), exports); + __exportStar(require_httpvalidationerror(), exports); + __exportStar(require_mistralerror(), exports); + __exportStar(require_responsevalidationerror(), exports); + __exportStar(require_sdkerror(), exports); + __exportStar(require_sdkvalidationerror(), exports); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/async.js +var require_async = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/async.js"(exports) { + "use strict"; + init_process_shim(); + var __classPrivateFieldSet3 = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f4) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; + }; + var __classPrivateFieldGet3 = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f4) { + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); + }; + var _APIPromise_promise; + var _APIPromise_unwrapped; + var _a7; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.APIPromise = void 0; + var APIPromise4 = class { + constructor(p4) { + _APIPromise_promise.set(this, void 0); + _APIPromise_unwrapped.set(this, void 0); + this[_a7] = "APIPromise"; + __classPrivateFieldSet3(this, _APIPromise_promise, p4 instanceof Promise ? p4 : Promise.resolve(p4), "f"); + __classPrivateFieldSet3(this, _APIPromise_unwrapped, p4 instanceof Promise ? __classPrivateFieldGet3(this, _APIPromise_promise, "f").then(([value]) => value) : Promise.resolve(p4[0]), "f"); + } + then(onfulfilled, onrejected) { + return __classPrivateFieldGet3(this, _APIPromise_promise, "f").then(onfulfilled ? ([value]) => onfulfilled(value) : void 0, onrejected); + } + catch(onrejected) { + return __classPrivateFieldGet3(this, _APIPromise_unwrapped, "f").catch(onrejected); + } + finally(onfinally) { + return __classPrivateFieldGet3(this, _APIPromise_unwrapped, "f").finally(onfinally); + } + $inspect() { + return __classPrivateFieldGet3(this, _APIPromise_promise, "f"); + } + }; + exports.APIPromise = APIPromise4; + _APIPromise_promise = /* @__PURE__ */ new WeakMap(), _APIPromise_unwrapped = /* @__PURE__ */ new WeakMap(), _a7 = Symbol.toStringTag; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsComplete.js +var require_agentsComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.agentsComplete = agentsComplete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function agentsComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentsCompletionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/completions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_completion_v1_agents_completions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ChatCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/event-streams.js +var require_event_streams = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/event-streams.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EventStream = void 0; + var EventStream3 = class extends ReadableStream { + constructor(responseBody, parse) { + const upstream = responseBody.getReader(); + let buffer = new Uint8Array(); + super({ + async pull(downstream) { + try { + while (true) { + const match2 = findBoundary(buffer); + if (!match2) { + const chunk = await upstream.read(); + if (chunk.done) + return downstream.close(); + buffer = concatBuffer(buffer, chunk.value); + continue; + } + const message = buffer.slice(0, match2.index); + buffer = buffer.slice(match2.index + match2.length); + const item = parseMessage2(message, parse); + if (item && !item.done) + return downstream.enqueue(item.value); + if (item?.done) { + await upstream.cancel("done"); + return downstream.close(); + } + } + } catch (e9) { + downstream.error(e9); + await upstream.cancel(e9); + } + }, + cancel: (reason) => upstream.cancel(reason) + }); + } + // Polyfill for older browsers + [Symbol.asyncIterator]() { + const fn = ReadableStream.prototype[Symbol.asyncIterator]; + if (typeof fn === "function") + return fn.call(this); + const reader = this.getReader(); + return { + next: async () => { + const r8 = await reader.read(); + if (r8.done) { + reader.releaseLock(); + return { done: true, value: void 0 }; + } + return { done: false, value: r8.value }; + }, + throw: async (e9) => { + await reader.cancel(e9); + reader.releaseLock(); + return { done: true, value: void 0 }; + }, + return: async () => { + await reader.cancel("done"); + reader.releaseLock(); + return { done: true, value: void 0 }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; + } + }; + exports.EventStream = EventStream3; + function concatBuffer(a3, b4) { + const c6 = new Uint8Array(a3.length + b4.length); + c6.set(a3, 0); + c6.set(b4, a3.length); + return c6; + } + function findBoundary(buf) { + const len = buf.length; + for (let i7 = 0; i7 < len; i7++) { + if (i7 <= len - 4 && buf[i7] === 13 && buf[i7 + 1] === 10 && buf[i7 + 2] === 13 && buf[i7 + 3] === 10) { + return { index: i7, length: 4 }; + } + if (i7 <= len - 2 && buf[i7] === 13 && buf[i7 + 1] === 13) { + return { index: i7, length: 2 }; + } + if (i7 <= len - 2 && buf[i7] === 10 && buf[i7 + 1] === 10) { + return { index: i7, length: 2 }; + } + } + return null; + } + function parseMessage2(chunk, parse) { + const text3 = new TextDecoder().decode(chunk); + const lines = text3.split(/\r\n|\r|\n/); + const dataLines = []; + const ret = {}; + let ignore = true; + for (const line of lines) { + if (!line || line.startsWith(":")) + continue; + ignore = false; + const i7 = line.indexOf(":"); + const field = line.slice(0, i7); + const value = line[i7 + 1] === " " ? line.slice(i7 + 2) : line.slice(i7 + 1); + if (field === "data") + dataLines.push(value); + else if (field === "event") + ret.event = value; + else if (field === "id") + ret.id = value; + else if (field === "retry") { + const n7 = Number(value); + if (!isNaN(n7)) + ret.retry = n7; + } + } + if (ignore) + return; + if (dataLines.length) + ret.data = dataLines.join("\n"); + return parse(ret); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsStream.js +var require_agentsStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.agentsStream = agentsStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function agentsStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentsCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/completions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "stream_agents", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + if (rawEvent.data === "[DONE]") + return { done: true }; + return { + value: components.CompletionEvent$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/agents.js +var require_agents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/agents.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Agents = void 0; + var agentsComplete_js_1 = require_agentsComplete(); + var agentsStream_js_1 = require_agentsStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Agents = class extends sdks_js_1.ClientSDK { + /** + * Agents Completion + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, agentsComplete_js_1.agentsComplete)(this, request, options)); + } + /** + * Stream Agents completion + * + * @remarks + * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON. + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, agentsStream_js_1.agentsStream)(this, request, options)); + } + }; + exports.Agents = Agents; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/streams.js +var require_streams = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/streams.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isReadableStream = isReadableStream; + function isReadableStream(val2) { + if (typeof val2 !== "object" || val2 === null) { + return false; + } + const stream2 = val2; + return typeof stream2.getReader === "function" && typeof stream2.cancel === "function" && typeof stream2.tee === "function"; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsComplete.js +var require_audioTranscriptionsComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.audioTranscriptionsComplete = audioTranscriptionsComplete; + var encodings_js_1 = require_encodings(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function audioTranscriptionsComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AudioTranscriptionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + (0, encodings_js_1.appendForm)(body, "model", payload.model); + if (payload.context_bias !== void 0) { + (0, encodings_js_1.appendForm)(body, "context_bias", payload.context_bias); + } + if (payload.diarize !== void 0) { + (0, encodings_js_1.appendForm)(body, "diarize", payload.diarize); + } + if (payload.file !== void 0) { + if ((0, blobs_js_1.isBlobLike)(payload.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.file); + } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName); + } + } + if (payload.file_id !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_id", payload.file_id); + } + if (payload.file_url !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_url", payload.file_url); + } + if (payload.language !== void 0) { + (0, encodings_js_1.appendForm)(body, "language", payload.language); + } + if (payload.stream !== void 0) { + (0, encodings_js_1.appendForm)(body, "stream", payload.stream); + } + if (payload.temperature !== void 0) { + (0, encodings_js_1.appendForm)(body, "temperature", payload.temperature); + } + if (payload.timestamp_granularities !== void 0) { + (0, encodings_js_1.appendForm)(body, "timestamp_granularities", payload.timestamp_granularities); + } + const path6 = (0, url_js_1.pathToFunc)("/v1/audio/transcriptions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "audio_api_v1_transcriptions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.TranscriptionResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsStream.js +var require_audioTranscriptionsStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.audioTranscriptionsStream = audioTranscriptionsStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function audioTranscriptionsStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AudioTranscriptionRequestStream$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + (0, encodings_js_1.appendForm)(body, "model", payload.model); + if (payload.context_bias !== void 0) { + (0, encodings_js_1.appendForm)(body, "context_bias", payload.context_bias); + } + if (payload.diarize !== void 0) { + (0, encodings_js_1.appendForm)(body, "diarize", payload.diarize); + } + if (payload.file !== void 0) { + if ((0, blobs_js_1.isBlobLike)(payload.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.file); + } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName); + } + } + if (payload.file_id !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_id", payload.file_id); + } + if (payload.file_url !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_url", payload.file_url); + } + if (payload.language !== void 0) { + (0, encodings_js_1.appendForm)(body, "language", payload.language); + } + if (payload.stream !== void 0) { + (0, encodings_js_1.appendForm)(body, "stream", payload.stream); + } + if (payload.temperature !== void 0) { + (0, encodings_js_1.appendForm)(body, "temperature", payload.temperature); + } + if (payload.timestamp_granularities !== void 0) { + (0, encodings_js_1.appendForm)(body, "timestamp_granularities", payload.timestamp_granularities); + } + const path6 = (0, url_js_1.pathToFunc)("/v1/audio/transcriptions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "audio_api_v1_transcriptions_post_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.TranscriptionStreamEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/transcriptions.js +var require_transcriptions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/transcriptions.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Transcriptions = void 0; + var audioTranscriptionsComplete_js_1 = require_audioTranscriptionsComplete(); + var audioTranscriptionsStream_js_1 = require_audioTranscriptionsStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Transcriptions2 = class extends sdks_js_1.ClientSDK { + /** + * Create Transcription + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, audioTranscriptionsComplete_js_1.audioTranscriptionsComplete)(this, request, options)); + } + /** + * Create Streaming Transcription (SSE) + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, audioTranscriptionsStream_js_1.audioTranscriptionsStream)(this, request, options)); + } + }; + exports.Transcriptions = Transcriptions2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/audio.js +var require_audio = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/audio.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Audio = void 0; + var sdks_js_1 = require_sdks(); + var transcriptions_js_1 = require_transcriptions(); + var Audio2 = class extends sdks_js_1.ClientSDK { + get transcriptions() { + return this._transcriptions ?? (this._transcriptions = new transcriptions_js_1.Transcriptions(this._options)); + } + }; + exports.Audio = Audio2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentscreateorupdatealias.js +var require_agentsapiv1agentscreateorupdatealias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentscreateorupdatealias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON = agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema = z3.object({ + agentId: z3.string(), + alias: z3.string(), + version: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON(agentsApiV1AgentsCreateOrUpdateAliasRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema.parse(agentsApiV1AgentsCreateOrUpdateAliasRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdelete.js +var require_agentsapiv1agentsdelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsDeleteRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsDeleteRequestToJSON = agentsApiV1AgentsDeleteRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsDeleteRequest$outboundSchema = z3.object({ + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsDeleteRequestToJSON(agentsApiV1AgentsDeleteRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsDeleteRequest$outboundSchema.parse(agentsApiV1AgentsDeleteRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdeletealias.js +var require_agentsapiv1agentsdeletealias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdeletealias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsDeleteAliasRequestToJSON = agentsApiV1AgentsDeleteAliasRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema = z3.object({ + agentId: z3.string(), + alias: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsDeleteAliasRequestToJSON(agentsApiV1AgentsDeleteAliasRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema.parse(agentsApiV1AgentsDeleteAliasRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsget.js +var require_agentsapiv1agentsget = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsget.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsGetRequest$outboundSchema = exports.AgentVersion$outboundSchema = void 0; + exports.agentVersionToJSON = agentVersionToJSON; + exports.agentsApiV1AgentsGetRequestToJSON = agentsApiV1AgentsGetRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentVersion$outboundSchema = z3.union([z3.number().int(), z3.string()]); + function agentVersionToJSON(agentVersion) { + return JSON.stringify(exports.AgentVersion$outboundSchema.parse(agentVersion)); + } + exports.AgentsApiV1AgentsGetRequest$outboundSchema = z3.object({ + agentId: z3.string(), + agentVersion: z3.nullable(z3.union([z3.number().int(), z3.string()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id", + agentVersion: "agent_version" + }); + }); + function agentsApiV1AgentsGetRequestToJSON(agentsApiV1AgentsGetRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsGetRequest$outboundSchema.parse(agentsApiV1AgentsGetRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsgetversion.js +var require_agentsapiv1agentsgetversion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsgetversion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsGetVersionRequestToJSON = agentsApiV1AgentsGetVersionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema = z3.object({ + agentId: z3.string(), + version: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsGetVersionRequestToJSON(agentsApiV1AgentsGetVersionRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema.parse(agentsApiV1AgentsGetVersionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslist.js +var require_agentsapiv1agentslist = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslist.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsListRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsListRequestToJSON = agentsApiV1AgentsListRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1AgentsListRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(20), + deploymentChat: z3.nullable(z3.boolean()).optional(), + sources: z3.nullable(z3.array(components.RequestSource$outboundSchema)).optional(), + name: z3.nullable(z3.string()).optional(), + search: z3.nullable(z3.string()).optional(), + id: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + deploymentChat: "deployment_chat" + }); + }); + function agentsApiV1AgentsListRequestToJSON(agentsApiV1AgentsListRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsListRequest$outboundSchema.parse(agentsApiV1AgentsListRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversionaliases.js +var require_agentsapiv1agentslistversionaliases = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversionaliases.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsListVersionAliasesRequestToJSON = agentsApiV1AgentsListVersionAliasesRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema = z3.object({ + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsListVersionAliasesRequestToJSON(agentsApiV1AgentsListVersionAliasesRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema.parse(agentsApiV1AgentsListVersionAliasesRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversions.js +var require_agentsapiv1agentslistversions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversions.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsListVersionsRequestToJSON = agentsApiV1AgentsListVersionsRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema = z3.object({ + agentId: z3.string(), + page: z3.number().int().default(0), + pageSize: z3.number().int().default(20) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id", + pageSize: "page_size" + }); + }); + function agentsApiV1AgentsListVersionsRequestToJSON(agentsApiV1AgentsListVersionsRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema.parse(agentsApiV1AgentsListVersionsRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdate.js +var require_agentsapiv1agentsupdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsUpdateRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsUpdateRequestToJSON = agentsApiV1AgentsUpdateRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1AgentsUpdateRequest$outboundSchema = z3.object({ + agentId: z3.string(), + agentUpdateRequest: components.AgentUpdateRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id", + agentUpdateRequest: "AgentUpdateRequest" + }); + }); + function agentsApiV1AgentsUpdateRequestToJSON(agentsApiV1AgentsUpdateRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsUpdateRequest$outboundSchema.parse(agentsApiV1AgentsUpdateRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdateversion.js +var require_agentsapiv1agentsupdateversion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdateversion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsUpdateVersionRequestToJSON = agentsApiV1AgentsUpdateVersionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema = z3.object({ + agentId: z3.string(), + version: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsUpdateVersionRequestToJSON(agentsApiV1AgentsUpdateVersionRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema.parse(agentsApiV1AgentsUpdateVersionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappend.js +var require_agentsapiv1conversationsappend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsAppendRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsAppendRequestToJSON = agentsApiV1ConversationsAppendRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsAppendRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationAppendRequest: components.ConversationAppendRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationAppendRequest: "ConversationAppendRequest" + }); + }); + function agentsApiV1ConversationsAppendRequestToJSON(agentsApiV1ConversationsAppendRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsAppendRequest$outboundSchema.parse(agentsApiV1ConversationsAppendRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappendstream.js +var require_agentsapiv1conversationsappendstream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappendstream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsAppendStreamRequestToJSON = agentsApiV1ConversationsAppendStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationAppendStreamRequest: components.ConversationAppendStreamRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationAppendStreamRequest: "ConversationAppendStreamRequest" + }); + }); + function agentsApiV1ConversationsAppendStreamRequestToJSON(agentsApiV1ConversationsAppendStreamRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema.parse(agentsApiV1ConversationsAppendStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsdelete.js +var require_agentsapiv1conversationsdelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsdelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsDeleteRequestToJSON = agentsApiV1ConversationsDeleteRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsDeleteRequestToJSON(agentsApiV1ConversationsDeleteRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema.parse(agentsApiV1ConversationsDeleteRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsget.js +var require_agentsapiv1conversationsget = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsget.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema = exports.AgentsApiV1ConversationsGetRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsGetRequestToJSON = agentsApiV1ConversationsGetRequestToJSON; + exports.agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON = agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsGetRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsGetRequestToJSON(agentsApiV1ConversationsGetRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsGetRequest$outboundSchema.parse(agentsApiV1ConversationsGetRequest)); + } + exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema = z3.union([ + components.ModelConversation$inboundSchema, + components.AgentConversation$inboundSchema + ]); + function agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentsApiV1ConversationsGetResponseV1ConversationsGet' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationshistory.js +var require_agentsapiv1conversationshistory = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationshistory.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsHistoryRequestToJSON = agentsApiV1ConversationsHistoryRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsHistoryRequestToJSON(agentsApiV1ConversationsHistoryRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema.parse(agentsApiV1ConversationsHistoryRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationslist.js +var require_agentsapiv1conversationslist = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationslist.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseBody$inboundSchema = exports.AgentsApiV1ConversationsListRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsListRequestToJSON = agentsApiV1ConversationsListRequestToJSON; + exports.responseBodyFromJSON = responseBodyFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsListRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + metadata: z3.nullable(z3.record(z3.any())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size" + }); + }); + function agentsApiV1ConversationsListRequestToJSON(agentsApiV1ConversationsListRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsListRequest$outboundSchema.parse(agentsApiV1ConversationsListRequest)); + } + exports.ResponseBody$inboundSchema = z3.union([ + components.ModelConversation$inboundSchema, + components.AgentConversation$inboundSchema + ]); + function responseBodyFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseBody$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseBody' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsmessages.js +var require_agentsapiv1conversationsmessages = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsmessages.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsMessagesRequestToJSON = agentsApiV1ConversationsMessagesRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsMessagesRequestToJSON(agentsApiV1ConversationsMessagesRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema.parse(agentsApiV1ConversationsMessagesRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestart.js +var require_agentsapiv1conversationsrestart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsRestartRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsRestartRequestToJSON = agentsApiV1ConversationsRestartRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsRestartRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationRestartRequest: components.ConversationRestartRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationRestartRequest: "ConversationRestartRequest" + }); + }); + function agentsApiV1ConversationsRestartRequestToJSON(agentsApiV1ConversationsRestartRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsRestartRequest$outboundSchema.parse(agentsApiV1ConversationsRestartRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestartstream.js +var require_agentsapiv1conversationsrestartstream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestartstream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsRestartStreamRequestToJSON = agentsApiV1ConversationsRestartStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationRestartStreamRequest: components.ConversationRestartStreamRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationRestartStreamRequest: "ConversationRestartStreamRequest" + }); + }); + function agentsApiV1ConversationsRestartStreamRequestToJSON(agentsApiV1ConversationsRestartStreamRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema.parse(agentsApiV1ConversationsRestartStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/deletemodelv1modelsmodeliddelete.js +var require_deletemodelv1modelsmodeliddelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/deletemodelv1modelsmodeliddelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = void 0; + exports.deleteModelV1ModelsModelIdDeleteRequestToJSON = deleteModelV1ModelsModelIdDeleteRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function deleteModelV1ModelsModelIdDeleteRequestToJSON(deleteModelV1ModelsModelIdDeleteRequest) { + return JSON.stringify(exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema.parse(deleteModelV1ModelsModelIdDeleteRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdeletefile.js +var require_filesapiroutesdeletefile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdeletefile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesDeleteFileRequest$outboundSchema = void 0; + exports.filesApiRoutesDeleteFileRequestToJSON = filesApiRoutesDeleteFileRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesDeleteFileRequest$outboundSchema = z3.object({ + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesDeleteFileRequestToJSON(filesApiRoutesDeleteFileRequest) { + return JSON.stringify(exports.FilesApiRoutesDeleteFileRequest$outboundSchema.parse(filesApiRoutesDeleteFileRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdownloadfile.js +var require_filesapiroutesdownloadfile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdownloadfile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesDownloadFileRequest$outboundSchema = void 0; + exports.filesApiRoutesDownloadFileRequestToJSON = filesApiRoutesDownloadFileRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesDownloadFileRequest$outboundSchema = z3.object({ + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesDownloadFileRequestToJSON(filesApiRoutesDownloadFileRequest) { + return JSON.stringify(exports.FilesApiRoutesDownloadFileRequest$outboundSchema.parse(filesApiRoutesDownloadFileRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesgetsignedurl.js +var require_filesapiroutesgetsignedurl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesgetsignedurl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = void 0; + exports.filesApiRoutesGetSignedUrlRequestToJSON = filesApiRoutesGetSignedUrlRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = z3.object({ + fileId: z3.string(), + expiry: z3.number().int().default(24) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesGetSignedUrlRequestToJSON(filesApiRoutesGetSignedUrlRequest) { + return JSON.stringify(exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema.parse(filesApiRoutesGetSignedUrlRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapirouteslistfiles.js +var require_filesapirouteslistfiles = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapirouteslistfiles.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesListFilesRequest$outboundSchema = void 0; + exports.filesApiRoutesListFilesRequestToJSON = filesApiRoutesListFilesRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.FilesApiRoutesListFilesRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + includeTotal: z3.boolean().default(true), + sampleType: z3.nullable(z3.array(components.SampleType$outboundSchema)).optional(), + source: z3.nullable(z3.array(components.Source$outboundSchema)).optional(), + search: z3.nullable(z3.string()).optional(), + purpose: z3.nullable(components.FilePurpose$outboundSchema).optional(), + mimetypes: z3.nullable(z3.array(z3.string())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + includeTotal: "include_total", + sampleType: "sample_type" + }); + }); + function filesApiRoutesListFilesRequestToJSON(filesApiRoutesListFilesRequest) { + return JSON.stringify(exports.FilesApiRoutesListFilesRequest$outboundSchema.parse(filesApiRoutesListFilesRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesretrievefile.js +var require_filesapiroutesretrievefile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesretrievefile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = void 0; + exports.filesApiRoutesRetrieveFileRequestToJSON = filesApiRoutesRetrieveFileRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = z3.object({ + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesRetrieveFileRequestToJSON(filesApiRoutesRetrieveFileRequest) { + return JSON.stringify(exports.FilesApiRoutesRetrieveFileRequest$outboundSchema.parse(filesApiRoutesRetrieveFileRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesuploadfile.js +var require_filesapiroutesuploadfile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesuploadfile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema = void 0; + exports.filesApiRoutesUploadFileMultiPartBodyParamsToJSON = filesApiRoutesUploadFileMultiPartBodyParamsToJSON; + var z3 = __importStar(require_v3()); + var blobs_js_1 = require_blobs(); + var components = __importStar(require_components()); + exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema = z3.object({ + purpose: components.FilePurpose$outboundSchema.optional(), + file: components.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema) + }); + function filesApiRoutesUploadFileMultiPartBodyParamsToJSON(filesApiRoutesUploadFileMultiPartBodyParams) { + return JSON.stringify(exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema.parse(filesApiRoutesUploadFileMultiPartBodyParams)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchcancelbatchjob.js +var require_jobsapiroutesbatchcancelbatchjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchcancelbatchjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesBatchCancelBatchJobRequestToJSON = jobsApiRoutesBatchCancelBatchJobRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesBatchCancelBatchJobRequestToJSON(jobsApiRoutesBatchCancelBatchJobRequest) { + return JSON.stringify(exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema.parse(jobsApiRoutesBatchCancelBatchJobRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjob.js +var require_jobsapiroutesbatchgetbatchjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesBatchGetBatchJobRequestToJSON = jobsApiRoutesBatchGetBatchJobRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = z3.object({ + jobId: z3.string(), + inline: z3.nullable(z3.boolean()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesBatchGetBatchJobRequestToJSON(jobsApiRoutesBatchGetBatchJobRequest) { + return JSON.stringify(exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema.parse(jobsApiRoutesBatchGetBatchJobRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjobs.js +var require_jobsapiroutesbatchgetbatchjobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjobs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = exports.OrderBy$outboundSchema = exports.OrderBy = void 0; + exports.jobsApiRoutesBatchGetBatchJobsRequestToJSON = jobsApiRoutesBatchGetBatchJobsRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.OrderBy = { + Created: "created", + MinusCreated: "-created" + }; + exports.OrderBy$outboundSchema = z3.nativeEnum(exports.OrderBy); + exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + model: z3.nullable(z3.string()).optional(), + agentId: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + createdAfter: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + createdByMe: z3.boolean().default(false), + status: z3.nullable(z3.array(components.BatchJobStatus$outboundSchema)).optional(), + orderBy: exports.OrderBy$outboundSchema.default("-created") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + agentId: "agent_id", + createdAfter: "created_after", + createdByMe: "created_by_me", + orderBy: "order_by" + }); + }); + function jobsApiRoutesBatchGetBatchJobsRequestToJSON(jobsApiRoutesBatchGetBatchJobsRequest) { + return JSON.stringify(exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema.parse(jobsApiRoutesBatchGetBatchJobsRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningarchivefinetunedmodel.js +var require_jobsapiroutesfinetuningarchivefinetunedmodel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningarchivefinetunedmodel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON(jobsApiRoutesFineTuningArchiveFineTunedModelRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningArchiveFineTunedModelRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcancelfinetuningjob.js +var require_jobsapiroutesfinetuningcancelfinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcancelfinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON; + exports.jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON(jobsApiRoutesFineTuningCancelFineTuningJobRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningCancelFineTuningJobRequest)); + } + exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema = z3.union([ + components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningCancelFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcreatefinetuningjob.js +var require_jobsapiroutesfinetuningcreatefinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcreatefinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = exports.One$inboundSchema = void 0; + exports.oneFromJSON = oneFromJSON; + exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.One$inboundSchema = z3.union([ + components.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function oneFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.One$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'One' from JSON`); + } + exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = z3.union([ + components.LegacyJobMetadataOut$inboundSchema, + z3.union([ + components.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]) + ]); + function jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningCreateFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjob.js +var require_jobsapiroutesfinetuninggetfinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON; + exports.jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON(jobsApiRoutesFineTuningGetFineTuningJobRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningGetFineTuningJobRequest)); + } + exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema = z3.union([ + components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningGetFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjobs.js +var require_jobsapiroutesfinetuninggetfinetuningjobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjobs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = exports.Status$outboundSchema = exports.Status = void 0; + exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.Status = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.Status$outboundSchema = z3.nativeEnum(exports.Status); + exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + model: z3.nullable(z3.string()).optional(), + createdAfter: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + createdBefore: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + createdByMe: z3.boolean().default(false), + status: z3.nullable(exports.Status$outboundSchema).optional(), + wandbProject: z3.nullable(z3.string()).optional(), + wandbName: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + createdAfter: "created_after", + createdBefore: "created_before", + createdByMe: "created_by_me", + wandbProject: "wandb_project", + wandbName: "wandb_name" + }); + }); + function jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON(jobsApiRoutesFineTuningGetFineTuningJobsRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema.parse(jobsApiRoutesFineTuningGetFineTuningJobsRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningstartfinetuningjob.js +var require_jobsapiroutesfinetuningstartfinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningstartfinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON; + exports.jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON(jobsApiRoutesFineTuningStartFineTuningJobRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningStartFineTuningJobRequest)); + } + exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema = z3.union([ + components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningStartFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningunarchivefinetunedmodel.js +var require_jobsapiroutesfinetuningunarchivefinetunedmodel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningunarchivefinetunedmodel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON(jobsApiRoutesFineTuningUnarchiveFineTunedModelRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningUnarchiveFineTunedModelRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningupdatefinetunedmodel.js +var require_jobsapiroutesfinetuningupdatefinetunedmodel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningupdatefinetunedmodel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON; + exports.jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON = jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = z3.object({ + modelId: z3.string(), + updateFTModelIn: components.UpdateFTModelIn$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id", + updateFTModelIn: "UpdateFTModelIn" + }); + }); + function jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON(jobsApiRoutesFineTuningUpdateFineTunedModelRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningUpdateFineTunedModelRequest)); + } + exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema = z3.union([ + components.ClassifierFTModelOut$inboundSchema.and(z3.object({ model_type: z3.literal("classifier") }).transform((v4) => ({ + modelType: v4.model_type + }))), + components.CompletionFTModelOut$inboundSchema.and(z3.object({ model_type: z3.literal("completion") }).transform((v4) => ({ + modelType: v4.model_type + }))) + ]); + function jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningUpdateFineTunedModelResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdeletev1.js +var require_librariesdeletev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdeletev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDeleteV1Request$outboundSchema = void 0; + exports.librariesDeleteV1RequestToJSON = librariesDeleteV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDeleteV1Request$outboundSchema = z3.object({ + libraryId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id" + }); + }); + function librariesDeleteV1RequestToJSON(librariesDeleteV1Request) { + return JSON.stringify(exports.LibrariesDeleteV1Request$outboundSchema.parse(librariesDeleteV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsdeletev1.js +var require_librariesdocumentsdeletev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsdeletev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsDeleteV1Request$outboundSchema = void 0; + exports.librariesDocumentsDeleteV1RequestToJSON = librariesDocumentsDeleteV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsDeleteV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsDeleteV1RequestToJSON(librariesDocumentsDeleteV1Request) { + return JSON.stringify(exports.LibrariesDocumentsDeleteV1Request$outboundSchema.parse(librariesDocumentsDeleteV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetextractedtextsignedurlv1.js +var require_librariesdocumentsgetextractedtextsignedurlv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetextractedtextsignedurlv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON = librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON(librariesDocumentsGetExtractedTextSignedUrlV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema.parse(librariesDocumentsGetExtractedTextSignedUrlV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetsignedurlv1.js +var require_librariesdocumentsgetsignedurlv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetsignedurlv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetSignedUrlV1RequestToJSON = librariesDocumentsGetSignedUrlV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetSignedUrlV1RequestToJSON(librariesDocumentsGetSignedUrlV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema.parse(librariesDocumentsGetSignedUrlV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetstatusv1.js +var require_librariesdocumentsgetstatusv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetstatusv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetStatusV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetStatusV1RequestToJSON = librariesDocumentsGetStatusV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetStatusV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetStatusV1RequestToJSON(librariesDocumentsGetStatusV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetStatusV1Request$outboundSchema.parse(librariesDocumentsGetStatusV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgettextcontentv1.js +var require_librariesdocumentsgettextcontentv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgettextcontentv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetTextContentV1RequestToJSON = librariesDocumentsGetTextContentV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetTextContentV1RequestToJSON(librariesDocumentsGetTextContentV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema.parse(librariesDocumentsGetTextContentV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetv1.js +var require_librariesdocumentsgetv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetV1RequestToJSON = librariesDocumentsGetV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetV1RequestToJSON(librariesDocumentsGetV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetV1Request$outboundSchema.parse(librariesDocumentsGetV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentslistv1.js +var require_librariesdocumentslistv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentslistv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsListV1Request$outboundSchema = void 0; + exports.librariesDocumentsListV1RequestToJSON = librariesDocumentsListV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsListV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + search: z3.nullable(z3.string()).optional(), + pageSize: z3.number().int().default(100), + page: z3.number().int().default(0), + filtersAttributes: z3.nullable(z3.string()).optional(), + sortBy: z3.string().default("created_at"), + sortOrder: z3.string().default("desc") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + pageSize: "page_size", + filtersAttributes: "filters_attributes", + sortBy: "sort_by", + sortOrder: "sort_order" + }); + }); + function librariesDocumentsListV1RequestToJSON(librariesDocumentsListV1Request) { + return JSON.stringify(exports.LibrariesDocumentsListV1Request$outboundSchema.parse(librariesDocumentsListV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsreprocessv1.js +var require_librariesdocumentsreprocessv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsreprocessv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsReprocessV1Request$outboundSchema = void 0; + exports.librariesDocumentsReprocessV1RequestToJSON = librariesDocumentsReprocessV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsReprocessV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsReprocessV1RequestToJSON(librariesDocumentsReprocessV1Request) { + return JSON.stringify(exports.LibrariesDocumentsReprocessV1Request$outboundSchema.parse(librariesDocumentsReprocessV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsupdatev1.js +var require_librariesdocumentsupdatev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsupdatev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsUpdateV1Request$outboundSchema = void 0; + exports.librariesDocumentsUpdateV1RequestToJSON = librariesDocumentsUpdateV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesDocumentsUpdateV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string(), + documentUpdateIn: components.DocumentUpdateIn$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id", + documentUpdateIn: "DocumentUpdateIn" + }); + }); + function librariesDocumentsUpdateV1RequestToJSON(librariesDocumentsUpdateV1Request) { + return JSON.stringify(exports.LibrariesDocumentsUpdateV1Request$outboundSchema.parse(librariesDocumentsUpdateV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsuploadv1.js +var require_librariesdocumentsuploadv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsuploadv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsUploadV1Request$outboundSchema = exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema = void 0; + exports.librariesDocumentsUploadV1DocumentUploadToJSON = librariesDocumentsUploadV1DocumentUploadToJSON; + exports.librariesDocumentsUploadV1RequestToJSON = librariesDocumentsUploadV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var blobs_js_1 = require_blobs(); + var components = __importStar(require_components()); + exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema = z3.object({ + file: components.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema) + }); + function librariesDocumentsUploadV1DocumentUploadToJSON(librariesDocumentsUploadV1DocumentUpload) { + return JSON.stringify(exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema.parse(librariesDocumentsUploadV1DocumentUpload)); + } + exports.LibrariesDocumentsUploadV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + requestBody: z3.lazy(() => exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + requestBody: "RequestBody" + }); + }); + function librariesDocumentsUploadV1RequestToJSON(librariesDocumentsUploadV1Request) { + return JSON.stringify(exports.LibrariesDocumentsUploadV1Request$outboundSchema.parse(librariesDocumentsUploadV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesgetv1.js +var require_librariesgetv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesgetv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesGetV1Request$outboundSchema = void 0; + exports.librariesGetV1RequestToJSON = librariesGetV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesGetV1Request$outboundSchema = z3.object({ + libraryId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id" + }); + }); + function librariesGetV1RequestToJSON(librariesGetV1Request) { + return JSON.stringify(exports.LibrariesGetV1Request$outboundSchema.parse(librariesGetV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharecreatev1.js +var require_librariessharecreatev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharecreatev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesShareCreateV1Request$outboundSchema = void 0; + exports.librariesShareCreateV1RequestToJSON = librariesShareCreateV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesShareCreateV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + sharingIn: components.SharingIn$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + sharingIn: "SharingIn" + }); + }); + function librariesShareCreateV1RequestToJSON(librariesShareCreateV1Request) { + return JSON.stringify(exports.LibrariesShareCreateV1Request$outboundSchema.parse(librariesShareCreateV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharedeletev1.js +var require_librariessharedeletev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharedeletev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesShareDeleteV1Request$outboundSchema = void 0; + exports.librariesShareDeleteV1RequestToJSON = librariesShareDeleteV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesShareDeleteV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + sharingDelete: components.SharingDelete$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + sharingDelete: "SharingDelete" + }); + }); + function librariesShareDeleteV1RequestToJSON(librariesShareDeleteV1Request) { + return JSON.stringify(exports.LibrariesShareDeleteV1Request$outboundSchema.parse(librariesShareDeleteV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharelistv1.js +var require_librariessharelistv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharelistv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesShareListV1Request$outboundSchema = void 0; + exports.librariesShareListV1RequestToJSON = librariesShareListV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesShareListV1Request$outboundSchema = z3.object({ + libraryId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id" + }); + }); + function librariesShareListV1RequestToJSON(librariesShareListV1Request) { + return JSON.stringify(exports.LibrariesShareListV1Request$outboundSchema.parse(librariesShareListV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesupdatev1.js +var require_librariesupdatev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesupdatev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesUpdateV1Request$outboundSchema = void 0; + exports.librariesUpdateV1RequestToJSON = librariesUpdateV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesUpdateV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + libraryInUpdate: components.LibraryInUpdate$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + libraryInUpdate: "LibraryInUpdate" + }); + }); + function librariesUpdateV1RequestToJSON(librariesUpdateV1Request) { + return JSON.stringify(exports.LibrariesUpdateV1Request$outboundSchema.parse(librariesUpdateV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/retrievemodelv1modelsmodelidget.js +var require_retrievemodelv1modelsmodelidget = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/retrievemodelv1modelsmodelidget.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema = exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema = void 0; + exports.retrieveModelV1ModelsModelIdGetRequestToJSON = retrieveModelV1ModelsModelIdGetRequestToJSON; + exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function retrieveModelV1ModelsModelIdGetRequestToJSON(retrieveModelV1ModelsModelIdGetRequest) { + return JSON.stringify(exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema.parse(retrieveModelV1ModelsModelIdGetRequest)); + } + exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema = z3.union([ + components.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })), + components.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") })) + ]); + function retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/index.js +var require_operations = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_agentsapiv1agentscreateorupdatealias(), exports); + __exportStar(require_agentsapiv1agentsdelete(), exports); + __exportStar(require_agentsapiv1agentsdeletealias(), exports); + __exportStar(require_agentsapiv1agentsget(), exports); + __exportStar(require_agentsapiv1agentsgetversion(), exports); + __exportStar(require_agentsapiv1agentslist(), exports); + __exportStar(require_agentsapiv1agentslistversionaliases(), exports); + __exportStar(require_agentsapiv1agentslistversions(), exports); + __exportStar(require_agentsapiv1agentsupdate(), exports); + __exportStar(require_agentsapiv1agentsupdateversion(), exports); + __exportStar(require_agentsapiv1conversationsappend(), exports); + __exportStar(require_agentsapiv1conversationsappendstream(), exports); + __exportStar(require_agentsapiv1conversationsdelete(), exports); + __exportStar(require_agentsapiv1conversationsget(), exports); + __exportStar(require_agentsapiv1conversationshistory(), exports); + __exportStar(require_agentsapiv1conversationslist(), exports); + __exportStar(require_agentsapiv1conversationsmessages(), exports); + __exportStar(require_agentsapiv1conversationsrestart(), exports); + __exportStar(require_agentsapiv1conversationsrestartstream(), exports); + __exportStar(require_deletemodelv1modelsmodeliddelete(), exports); + __exportStar(require_filesapiroutesdeletefile(), exports); + __exportStar(require_filesapiroutesdownloadfile(), exports); + __exportStar(require_filesapiroutesgetsignedurl(), exports); + __exportStar(require_filesapirouteslistfiles(), exports); + __exportStar(require_filesapiroutesretrievefile(), exports); + __exportStar(require_filesapiroutesuploadfile(), exports); + __exportStar(require_jobsapiroutesbatchcancelbatchjob(), exports); + __exportStar(require_jobsapiroutesbatchgetbatchjob(), exports); + __exportStar(require_jobsapiroutesbatchgetbatchjobs(), exports); + __exportStar(require_jobsapiroutesfinetuningarchivefinetunedmodel(), exports); + __exportStar(require_jobsapiroutesfinetuningcancelfinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuningcreatefinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuninggetfinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuninggetfinetuningjobs(), exports); + __exportStar(require_jobsapiroutesfinetuningstartfinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuningunarchivefinetunedmodel(), exports); + __exportStar(require_jobsapiroutesfinetuningupdatefinetunedmodel(), exports); + __exportStar(require_librariesdeletev1(), exports); + __exportStar(require_librariesdocumentsdeletev1(), exports); + __exportStar(require_librariesdocumentsgetextractedtextsignedurlv1(), exports); + __exportStar(require_librariesdocumentsgetsignedurlv1(), exports); + __exportStar(require_librariesdocumentsgetstatusv1(), exports); + __exportStar(require_librariesdocumentsgettextcontentv1(), exports); + __exportStar(require_librariesdocumentsgetv1(), exports); + __exportStar(require_librariesdocumentslistv1(), exports); + __exportStar(require_librariesdocumentsreprocessv1(), exports); + __exportStar(require_librariesdocumentsupdatev1(), exports); + __exportStar(require_librariesdocumentsuploadv1(), exports); + __exportStar(require_librariesgetv1(), exports); + __exportStar(require_librariessharecreatev1(), exports); + __exportStar(require_librariessharedeletev1(), exports); + __exportStar(require_librariessharelistv1(), exports); + __exportStar(require_librariesupdatev1(), exports); + __exportStar(require_retrievemodelv1modelsmodelidget(), exports); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCancel.js +var require_batchJobsCancel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCancel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsCancel = batchJobsCancel; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function batchJobsCancel(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs/{job_id}/cancel")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_cancel_batch_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCreate.js +var require_batchJobsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsCreate = batchJobsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + function batchJobsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.BatchJobIn$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_create_batch_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsGet.js +var require_batchJobsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsGet = batchJobsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function batchJobsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs/{job_id}")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "inline": payload.inline + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_get_batch_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsList.js +var require_batchJobsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsList = batchJobsList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function batchJobsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs")(); + const query = (0, encodings_js_1.encodeFormQuery)({ + "agent_id": payload?.agent_id, + "created_after": payload?.created_after, + "created_by_me": payload?.created_by_me, + "metadata": payload?.metadata, + "model": payload?.model, + "order_by": payload?.order_by, + "page": payload?.page, + "page_size": payload?.page_size, + "status": payload?.status + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_get_batch_jobs", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobsOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/mistraljobs.js +var require_mistraljobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/mistraljobs.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralJobs = void 0; + var batchJobsCancel_js_1 = require_batchJobsCancel(); + var batchJobsCreate_js_1 = require_batchJobsCreate(); + var batchJobsGet_js_1 = require_batchJobsGet(); + var batchJobsList_js_1 = require_batchJobsList(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var MistralJobs = class extends sdks_js_1.ClientSDK { + /** + * Get Batch Jobs + * + * @remarks + * Get a list of batch jobs for your organization and user. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsList_js_1.batchJobsList)(this, request, options)); + } + /** + * Create Batch Job + * + * @remarks + * Create a new batch job, it will be queued for processing. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsCreate_js_1.batchJobsCreate)(this, request, options)); + } + /** + * Get Batch Job + * + * @remarks + * Get a batch job details by its UUID. + * + * Args: + * inline: If True, return results inline in the response. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsGet_js_1.batchJobsGet)(this, request, options)); + } + /** + * Cancel Batch Job + * + * @remarks + * Request the cancellation of a batch job. + */ + async cancel(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsCancel_js_1.batchJobsCancel)(this, request, options)); + } + }; + exports.MistralJobs = MistralJobs; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/batch.js +var require_batch = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/batch.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Batch = void 0; + var sdks_js_1 = require_sdks(); + var mistraljobs_js_1 = require_mistraljobs(); + var Batch = class extends sdks_js_1.ClientSDK { + get jobs() { + return this._jobs ?? (this._jobs = new mistraljobs_js_1.MistralJobs(this._options)); + } + }; + exports.Batch = Batch; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppend.js +var require_betaConversationsAppend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsAppend = betaConversationsAppend; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsAppend(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsAppendRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationAppendRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_append", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppendStream.js +var require_betaConversationsAppendStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppendStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsAppendStream = betaConversationsAppendStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsAppendStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationAppendStreamRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}#stream")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_append_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.ConversationEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsDelete.js +var require_betaConversationsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsDelete = betaConversationsDelete; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsDeleteRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_delete", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGet.js +var require_betaConversationsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsGet = betaConversationsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsGetRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, operations.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetHistory.js +var require_betaConversationsGetHistory = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetHistory.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsGetHistory = betaConversationsGetHistory; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsGetHistory(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsHistoryRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/history")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_history", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationHistory$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetMessages.js +var require_betaConversationsGetMessages = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetMessages.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsGetMessages = betaConversationsGetMessages; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsGetMessages(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsMessagesRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/messages")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_messages", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationMessages$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsList.js +var require_betaConversationsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsList = betaConversationsList; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsListRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations")(); + const query = (0, encodings_js_1.queryJoin)((0, encodings_js_1.encodeFormQuery)({ + "page": payload?.page, + "page_size": payload?.page_size + }), (0, encodings_js_1.encodeJSONQuery)({ + "metadata": payload?.metadata + }, { explode: false })); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_list", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(operations.ResponseBody$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestart.js +var require_betaConversationsRestart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsRestart = betaConversationsRestart; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsRestart(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsRestartRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationRestartRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/restart")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_restart", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestartStream.js +var require_betaConversationsRestartStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestartStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsRestartStream = betaConversationsRestartStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsRestartStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationRestartStreamRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/restart#stream")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_restart_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.ConversationEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStart.js +var require_betaConversationsStart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsStart = betaConversationsStart; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaConversationsStart(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ConversationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_start", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStartStream.js +var require_betaConversationsStartStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStartStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsStartStream = betaConversationsStartStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaConversationsStartStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ConversationStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_start_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.ConversationEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/conversations.js +var require_conversations = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/conversations.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Conversations = void 0; + var betaConversationsAppend_js_1 = require_betaConversationsAppend(); + var betaConversationsAppendStream_js_1 = require_betaConversationsAppendStream(); + var betaConversationsDelete_js_1 = require_betaConversationsDelete(); + var betaConversationsGet_js_1 = require_betaConversationsGet(); + var betaConversationsGetHistory_js_1 = require_betaConversationsGetHistory(); + var betaConversationsGetMessages_js_1 = require_betaConversationsGetMessages(); + var betaConversationsList_js_1 = require_betaConversationsList(); + var betaConversationsRestart_js_1 = require_betaConversationsRestart(); + var betaConversationsRestartStream_js_1 = require_betaConversationsRestartStream(); + var betaConversationsStart_js_1 = require_betaConversationsStart(); + var betaConversationsStartStream_js_1 = require_betaConversationsStartStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Conversations2 = class extends sdks_js_1.ClientSDK { + /** + * Create a conversation and append entries to it. + * + * @remarks + * Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation. + */ + async start(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsStart_js_1.betaConversationsStart)(this, request, options)); + } + /** + * List all created conversations. + * + * @remarks + * Retrieve a list of conversation entities sorted by creation time. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsList_js_1.betaConversationsList)(this, request, options)); + } + /** + * Retrieve a conversation information. + * + * @remarks + * Given a conversation_id retrieve a conversation entity with its attributes. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsGet_js_1.betaConversationsGet)(this, request, options)); + } + /** + * Delete a conversation. + * + * @remarks + * Delete a conversation given a conversation_id. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsDelete_js_1.betaConversationsDelete)(this, request, options)); + } + /** + * Append new entries to an existing conversation. + * + * @remarks + * Run completion on the history of the conversation and the user entries. Return the new created entries. + */ + async append(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsAppend_js_1.betaConversationsAppend)(this, request, options)); + } + /** + * Retrieve all entries in a conversation. + * + * @remarks + * Given a conversation_id retrieve all the entries belonging to that conversation. The entries are sorted in the order they were appended, those can be messages, connectors or function_call. + */ + async getHistory(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsGetHistory_js_1.betaConversationsGetHistory)(this, request, options)); + } + /** + * Retrieve all messages in a conversation. + * + * @remarks + * Given a conversation_id retrieve all the messages belonging to that conversation. This is similar to retrieving all entries except we filter the messages only. + */ + async getMessages(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsGetMessages_js_1.betaConversationsGetMessages)(this, request, options)); + } + /** + * Restart a conversation starting from a given entry. + * + * @remarks + * Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned. + */ + async restart(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsRestart_js_1.betaConversationsRestart)(this, request, options)); + } + /** + * Create a conversation and append entries to it. + * + * @remarks + * Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation. + */ + async startStream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsStartStream_js_1.betaConversationsStartStream)(this, request, options)); + } + /** + * Append new entries to an existing conversation. + * + * @remarks + * Run completion on the history of the conversation and the user entries. Return the new created entries. + */ + async appendStream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsAppendStream_js_1.betaConversationsAppendStream)(this, request, options)); + } + /** + * Restart a conversation starting from a given entry. + * + * @remarks + * Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned. + */ + async restartStream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsRestartStream_js_1.betaConversationsRestartStream)(this, request, options)); + } + }; + exports.Conversations = Conversations2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesCreate.js +var require_betaLibrariesCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesCreate = betaLibrariesCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaLibrariesCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.LibraryIn$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_create_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(201, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDelete.js +var require_betaLibrariesDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDelete = betaLibrariesDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDeleteV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_delete_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesGet.js +var require_betaLibrariesGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesGet = betaLibrariesGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesGetV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_get_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesList.js +var require_betaLibrariesList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesList = betaLibrariesList; + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + function betaLibrariesList(client, options) { + return new async_js_1.APIPromise($do(client, options)); + } + async function $do(client, options) { + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_list_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ListLibraryOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesUpdate.js +var require_betaLibrariesUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesUpdate = betaLibrariesUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesUpdateV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.LibraryInUpdate, { explode: true }); + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_update_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesDelete.js +var require_betaLibrariesAccessesDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesAccessesDelete = betaLibrariesAccessesDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesAccessesDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareDeleteV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.SharingDelete, { explode: true }); + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_share_delete_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.SharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesList.js +var require_betaLibrariesAccessesList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesAccessesList = betaLibrariesAccessesList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesAccessesList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareListV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_share_list_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ListSharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesUpdateOrCreate.js +var require_betaLibrariesAccessesUpdateOrCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesUpdateOrCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesAccessesUpdateOrCreate = betaLibrariesAccessesUpdateOrCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesAccessesUpdateOrCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareCreateV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.SharingIn, { explode: true }); + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_share_create_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.SharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/accesses.js +var require_accesses = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/accesses.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Accesses = void 0; + var betaLibrariesAccessesDelete_js_1 = require_betaLibrariesAccessesDelete(); + var betaLibrariesAccessesList_js_1 = require_betaLibrariesAccessesList(); + var betaLibrariesAccessesUpdateOrCreate_js_1 = require_betaLibrariesAccessesUpdateOrCreate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Accesses = class extends sdks_js_1.ClientSDK { + /** + * List all of the access to this library. + * + * @remarks + * Given a library, list all of the Entity that have access and to what level. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesList_js_1.betaLibrariesAccessesList)(this, request, options)); + } + /** + * Create or update an access level. + * + * @remarks + * Given a library id, you can create or update the access level of an entity. You have to be owner of the library to share a library. An owner cannot change their own role. A library cannot be shared outside of the organization. + */ + async updateOrCreate(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesUpdateOrCreate_js_1.betaLibrariesAccessesUpdateOrCreate)(this, request, options)); + } + /** + * Delete an access level. + * + * @remarks + * Given a library id, you can delete the access level of an entity. An owner cannot delete it's own access. You have to be the owner of the library to delete an acces other than yours. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesDelete_js_1.betaLibrariesAccessesDelete)(this, request, options)); + } + }; + exports.Accesses = Accesses; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsDelete.js +var require_betaLibrariesDocumentsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsDelete = betaLibrariesDocumentsDelete; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsDeleteV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_delete_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsExtractedTextSignedUrl.js +var require_betaLibrariesDocumentsExtractedTextSignedUrl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsExtractedTextSignedUrl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsExtractedTextSignedUrl = betaLibrariesDocumentsExtractedTextSignedUrl; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsExtractedTextSignedUrl(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/extracted-text-signed-url")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_extracted_text_signed_url_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.string()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGet.js +var require_betaLibrariesDocumentsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsGet = betaLibrariesDocumentsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGetSignedUrl.js +var require_betaLibrariesDocumentsGetSignedUrl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGetSignedUrl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsGetSignedUrl = betaLibrariesDocumentsGetSignedUrl; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsGetSignedUrl(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/signed-url")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_signed_url_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.string()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsList.js +var require_betaLibrariesDocumentsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsList = betaLibrariesDocumentsList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsListV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "filters_attributes": payload.filters_attributes, + "page": payload.page, + "page_size": payload.page_size, + "search": payload.search, + "sort_by": payload.sort_by, + "sort_order": payload.sort_order + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_list_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ListDocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsReprocess.js +var require_betaLibrariesDocumentsReprocess = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsReprocess.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsReprocess = betaLibrariesDocumentsReprocess; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsReprocess(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsReprocessV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/reprocess")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_reprocess_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsStatus.js +var require_betaLibrariesDocumentsStatus = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsStatus.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsStatus = betaLibrariesDocumentsStatus; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsStatus(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetStatusV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/status")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_status_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ProcessingStatusOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsTextContent.js +var require_betaLibrariesDocumentsTextContent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsTextContent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsTextContent = betaLibrariesDocumentsTextContent; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsTextContent(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetTextContentV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/text_content")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_text_content_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DocumentTextContent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpdate.js +var require_betaLibrariesDocumentsUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsUpdate = betaLibrariesDocumentsUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsUpdateV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.DocumentUpdateIn, { explode: true }); + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_update_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpload.js +var require_betaLibrariesDocumentsUpload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsUpload = betaLibrariesDocumentsUpload; + var encodings_js_1 = require_encodings(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function betaLibrariesDocumentsUpload(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsUploadV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + if ((0, blobs_js_1.isBlobLike)(payload.RequestBody.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.RequestBody.file); + } else if ((0, streams_js_1.isReadableStream)(payload.RequestBody.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.RequestBody.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.RequestBody.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.RequestBody.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.RequestBody.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.RequestBody.file.content], { type: contentType }), payload.RequestBody.file.fileName); + } + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_upload_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json([200, 201], components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/documents.js +var require_documents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/documents.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Documents = void 0; + var betaLibrariesDocumentsDelete_js_1 = require_betaLibrariesDocumentsDelete(); + var betaLibrariesDocumentsExtractedTextSignedUrl_js_1 = require_betaLibrariesDocumentsExtractedTextSignedUrl(); + var betaLibrariesDocumentsGet_js_1 = require_betaLibrariesDocumentsGet(); + var betaLibrariesDocumentsGetSignedUrl_js_1 = require_betaLibrariesDocumentsGetSignedUrl(); + var betaLibrariesDocumentsList_js_1 = require_betaLibrariesDocumentsList(); + var betaLibrariesDocumentsReprocess_js_1 = require_betaLibrariesDocumentsReprocess(); + var betaLibrariesDocumentsStatus_js_1 = require_betaLibrariesDocumentsStatus(); + var betaLibrariesDocumentsTextContent_js_1 = require_betaLibrariesDocumentsTextContent(); + var betaLibrariesDocumentsUpdate_js_1 = require_betaLibrariesDocumentsUpdate(); + var betaLibrariesDocumentsUpload_js_1 = require_betaLibrariesDocumentsUpload(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Documents2 = class extends sdks_js_1.ClientSDK { + /** + * List documents in a given library. + * + * @remarks + * Given a library, lists the document that have been uploaded to that library. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsList_js_1.betaLibrariesDocumentsList)(this, request, options)); + } + /** + * Upload a new document. + * + * @remarks + * Given a library, upload a new document to that library. It is queued for processing, it status will change it has been processed. The processing has to be completed in order be discoverable for the library search + */ + async upload(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsUpload_js_1.betaLibrariesDocumentsUpload)(this, request, options)); + } + /** + * Retrieve the metadata of a specific document. + * + * @remarks + * Given a library and a document in this library, you can retrieve the metadata of that document. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsGet_js_1.betaLibrariesDocumentsGet)(this, request, options)); + } + /** + * Update the metadata of a specific document. + * + * @remarks + * Given a library and a document in that library, update the name of that document. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsUpdate_js_1.betaLibrariesDocumentsUpdate)(this, request, options)); + } + /** + * Delete a document. + * + * @remarks + * Given a library and a document in that library, delete that document. The document will be deleted from the library and the search index. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsDelete_js_1.betaLibrariesDocumentsDelete)(this, request, options)); + } + /** + * Retrieve the text content of a specific document. + * + * @remarks + * Given a library and a document in that library, you can retrieve the text content of that document if it exists. For documents like pdf, docx and pptx the text content results from our processing using Mistral OCR. + */ + async textContent(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsTextContent_js_1.betaLibrariesDocumentsTextContent)(this, request, options)); + } + /** + * Retrieve the processing status of a specific document. + * + * @remarks + * Given a library and a document in that library, retrieve the processing status of that document. + */ + async status(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsStatus_js_1.betaLibrariesDocumentsStatus)(this, request, options)); + } + /** + * Retrieve the signed URL of a specific document. + * + * @remarks + * Given a library and a document in that library, retrieve the signed URL of a specific document.The url will expire after 30 minutes and can be accessed by anyone with the link. + */ + async getSignedUrl(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsGetSignedUrl_js_1.betaLibrariesDocumentsGetSignedUrl)(this, request, options)); + } + /** + * Retrieve the signed URL of text extracted from a given document. + * + * @remarks + * Given a library and a document in that library, retrieve the signed URL of text extracted. For documents that are sent to the OCR this returns the result of the OCR queries. + */ + async extractedTextSignedUrl(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsExtractedTextSignedUrl_js_1.betaLibrariesDocumentsExtractedTextSignedUrl)(this, request, options)); + } + /** + * Reprocess a document. + * + * @remarks + * Given a library and a document in that library, reprocess that document, it will be billed again. + */ + async reprocess(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsReprocess_js_1.betaLibrariesDocumentsReprocess)(this, request, options)); + } + }; + exports.Documents = Documents2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/libraries.js +var require_libraries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/libraries.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Libraries = void 0; + var betaLibrariesCreate_js_1 = require_betaLibrariesCreate(); + var betaLibrariesDelete_js_1 = require_betaLibrariesDelete(); + var betaLibrariesGet_js_1 = require_betaLibrariesGet(); + var betaLibrariesList_js_1 = require_betaLibrariesList(); + var betaLibrariesUpdate_js_1 = require_betaLibrariesUpdate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var accesses_js_1 = require_accesses(); + var documents_js_1 = require_documents(); + var Libraries = class extends sdks_js_1.ClientSDK { + get documents() { + return this._documents ?? (this._documents = new documents_js_1.Documents(this._options)); + } + get accesses() { + return this._accesses ?? (this._accesses = new accesses_js_1.Accesses(this._options)); + } + /** + * List all libraries you have access to. + * + * @remarks + * List all libraries that you have created or have been shared with you. + */ + async list(options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesList_js_1.betaLibrariesList)(this, options)); + } + /** + * Create a new Library. + * + * @remarks + * Create a new Library, you will be marked as the owner and only you will have the possibility to share it with others. When first created this will only be accessible by you. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesCreate_js_1.betaLibrariesCreate)(this, request, options)); + } + /** + * Detailed information about a specific Library. + * + * @remarks + * Given a library id, details information about that Library. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesGet_js_1.betaLibrariesGet)(this, request, options)); + } + /** + * Delete a library and all of it's document. + * + * @remarks + * Given a library id, deletes it together with all documents that have been uploaded to that library. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDelete_js_1.betaLibrariesDelete)(this, request, options)); + } + /** + * Update a library. + * + * @remarks + * Given a library id, you can update the name and description. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesUpdate_js_1.betaLibrariesUpdate)(this, request, options)); + } + }; + exports.Libraries = Libraries; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreate.js +var require_betaAgentsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsCreate = betaAgentsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaAgentsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentCreationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/agents")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_create", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreateVersionAlias.js +var require_betaAgentsCreateVersionAlias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreateVersionAlias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsCreateVersionAlias = betaAgentsCreateVersionAlias; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsCreateVersionAlias(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "alias": payload.alias, + "version": payload.version + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_create_or_update_alias", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.AgentAliasResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDelete.js +var require_betaAgentsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsDelete = betaAgentsDelete; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsDeleteRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_delete", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDeleteVersionAlias.js +var require_betaAgentsDeleteVersionAlias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDeleteVersionAlias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsDeleteVersionAlias = betaAgentsDeleteVersionAlias; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsDeleteVersionAlias(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "alias": payload.alias + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_delete_alias", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGet.js +var require_betaAgentsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsGet = betaAgentsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsGetRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "agent_version": payload.agent_version + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGetVersion.js +var require_betaAgentsGetVersion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGetVersion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsGetVersion = betaAgentsGetVersion; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsGetVersion(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsGetVersionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }), + version: (0, encodings_js_1.encodeSimple)("version", payload.version, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/versions/{version}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_get_version", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsList.js +var require_betaAgentsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsList = betaAgentsList; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents")(); + const query = (0, encodings_js_1.queryJoin)((0, encodings_js_1.encodeFormQuery)({ + "deployment_chat": payload?.deployment_chat, + "id": payload?.id, + "name": payload?.name, + "page": payload?.page, + "page_size": payload?.page_size, + "search": payload?.search, + "sources": payload?.sources + }), (0, encodings_js_1.encodeJSONQuery)({ + "metadata": payload?.metadata + }, { explode: false })); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_list", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(components.Agent$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersionAliases.js +var require_betaAgentsListVersionAliases = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersionAliases.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsListVersionAliases = betaAgentsListVersionAliases; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsListVersionAliases(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_list_version_aliases", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(components.AgentAliasResponse$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersions.js +var require_betaAgentsListVersions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersions.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsListVersions = betaAgentsListVersions; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsListVersions(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListVersionsRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/versions")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "page": payload.page, + "page_size": payload.page_size + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_list_versions", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(components.Agent$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdate.js +var require_betaAgentsUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsUpdate = betaAgentsUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsUpdateRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.AgentUpdateRequest, { + explode: true + }); + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_update", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdateVersion.js +var require_betaAgentsUpdateVersion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdateVersion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsUpdateVersion = betaAgentsUpdateVersion; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsUpdateVersion(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/version")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "version": payload.version + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_update_version", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/mistralagents.js +var require_mistralagents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/mistralagents.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralAgents = void 0; + var betaAgentsCreate_js_1 = require_betaAgentsCreate(); + var betaAgentsCreateVersionAlias_js_1 = require_betaAgentsCreateVersionAlias(); + var betaAgentsDelete_js_1 = require_betaAgentsDelete(); + var betaAgentsDeleteVersionAlias_js_1 = require_betaAgentsDeleteVersionAlias(); + var betaAgentsGet_js_1 = require_betaAgentsGet(); + var betaAgentsGetVersion_js_1 = require_betaAgentsGetVersion(); + var betaAgentsList_js_1 = require_betaAgentsList(); + var betaAgentsListVersionAliases_js_1 = require_betaAgentsListVersionAliases(); + var betaAgentsListVersions_js_1 = require_betaAgentsListVersions(); + var betaAgentsUpdate_js_1 = require_betaAgentsUpdate(); + var betaAgentsUpdateVersion_js_1 = require_betaAgentsUpdateVersion(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var MistralAgents = class extends sdks_js_1.ClientSDK { + /** + * Create a agent that can be used within a conversation. + * + * @remarks + * Create a new agent giving it instructions, tools, description. The agent is then available to be used as a regular assistant in a conversation or as part of an agent pool from which it can be used. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsCreate_js_1.betaAgentsCreate)(this, request, options)); + } + /** + * List agent entities. + * + * @remarks + * Retrieve a list of agent entities sorted by creation time. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsList_js_1.betaAgentsList)(this, request, options)); + } + /** + * Retrieve an agent entity. + * + * @remarks + * Given an agent, retrieve an agent entity with its attributes. The agent_version parameter can be an integer version number or a string alias. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsGet_js_1.betaAgentsGet)(this, request, options)); + } + /** + * Update an agent entity. + * + * @remarks + * Update an agent attributes and create a new version. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsUpdate_js_1.betaAgentsUpdate)(this, request, options)); + } + /** + * Delete an agent entity. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsDelete_js_1.betaAgentsDelete)(this, request, options)); + } + /** + * Update an agent version. + * + * @remarks + * Switch the version of an agent. + */ + async updateVersion(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsUpdateVersion_js_1.betaAgentsUpdateVersion)(this, request, options)); + } + /** + * List all versions of an agent. + * + * @remarks + * Retrieve all versions for a specific agent with full agent context. Supports pagination. + */ + async listVersions(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsListVersions_js_1.betaAgentsListVersions)(this, request, options)); + } + /** + * Retrieve a specific version of an agent. + * + * @remarks + * Get a specific agent version by version number. + */ + async getVersion(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsGetVersion_js_1.betaAgentsGetVersion)(this, request, options)); + } + /** + * Create or update an agent version alias. + * + * @remarks + * Create a new alias or update an existing alias to point to a specific version. Aliases are unique per agent and can be reassigned to different versions. + */ + async createVersionAlias(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsCreateVersionAlias_js_1.betaAgentsCreateVersionAlias)(this, request, options)); + } + /** + * List all aliases for an agent. + * + * @remarks + * Retrieve all version aliases for a specific agent. + */ + async listVersionAliases(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsListVersionAliases_js_1.betaAgentsListVersionAliases)(this, request, options)); + } + /** + * Delete an agent version alias. + * + * @remarks + * Delete an existing alias for an agent. + */ + async deleteVersionAlias(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsDeleteVersionAlias_js_1.betaAgentsDeleteVersionAlias)(this, request, options)); + } + }; + exports.MistralAgents = MistralAgents; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/beta.js +var require_beta = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/beta.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Beta = void 0; + var sdks_js_1 = require_sdks(); + var conversations_js_1 = require_conversations(); + var libraries_js_1 = require_libraries(); + var mistralagents_js_1 = require_mistralagents(); + var Beta3 = class extends sdks_js_1.ClientSDK { + get conversations() { + return this._conversations ?? (this._conversations = new conversations_js_1.Conversations(this._options)); + } + get agents() { + return this._agents ?? (this._agents = new mistralagents_js_1.MistralAgents(this._options)); + } + get libraries() { + return this._libraries ?? (this._libraries = new libraries_js_1.Libraries(this._options)); + } + }; + exports.Beta = Beta3; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/chatComplete.js +var require_chatComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/chatComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.chatComplete = chatComplete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function chatComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatCompletionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/completions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "chat_completion_v1_chat_completions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ChatCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/chatStream.js +var require_chatStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/chatStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.chatStream = chatStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function chatStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/completions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "stream_chat", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + if (rawEvent.data === "[DONE]") + return { done: true }; + return { + value: components.CompletionEvent$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Options.js +var require_Options = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Options.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getDefaultOptions = exports.defaultOptions = exports.jsonDescription = exports.ignoreOverride = void 0; + exports.ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + var jsonDescription = (jsonSchema, def) => { + if (def.description) { + try { + return { + ...jsonSchema, + ...JSON.parse(def.description) + }; + } catch { + } + } + return jsonSchema; + }; + exports.jsonDescription = jsonDescription; + exports.defaultOptions = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" + }; + var getDefaultOptions2 = (options) => typeof options === "string" ? { + ...exports.defaultOptions, + name: options + } : { + ...exports.defaultOptions, + ...options + }; + exports.getDefaultOptions = getDefaultOptions2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Refs.js +var require_Refs = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Refs.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRefs = void 0; + var Options_js_1 = require_Options(); + var getRefs2 = (options) => { + const _options = (0, Options_js_1.getDefaultOptions)(options); + const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: void 0 + } + ])) + }; + }; + exports.getRefs = getRefs2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js +var require_errorMessages = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setResponseValueAndErrors = exports.addErrorMessage = void 0; + function addErrorMessage2(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; + } + } + exports.addErrorMessage = addErrorMessage2; + function setResponseValueAndErrors2(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage2(res, key, errorMessage, refs); + } + exports.setResponseValueAndErrors = setResponseValueAndErrors2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js +var require_getRelativePath = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRelativePath = void 0; + var getRelativePath2 = (pathA, pathB) => { + let i7 = 0; + for (; i7 < pathA.length && i7 < pathB.length; i7++) { + if (pathA[i7] !== pathB[i7]) + break; + } + return [(pathA.length - i7).toString(), ...pathB.slice(i7)].join("/"); + }; + exports.getRelativePath = getRelativePath2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js +var require_any = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseAnyDef = void 0; + var getRelativePath_js_1 = require_getRelativePath(); + function parseAnyDef2(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" ? (0, getRelativePath_js_1.getRelativePath)(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") + }; + } + exports.parseAnyDef = parseAnyDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js +var require_array = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseArrayDef = void 0; + var v3_1 = require_v3(); + var errorMessages_js_1 = require_errorMessages(); + var parseDef_js_1 = require_parseDef(); + function parseArrayDef2(def, refs) { + const res = { + type: "array" + }; + if (def.type?._def && def.type?._def?.typeName !== v3_1.ZodFirstPartyTypeKind.ZodAny) { + res.items = (0, parseDef_js_1.parseDef)(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + } + if (def.minLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; + } + exports.parseArrayDef = parseArrayDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js +var require_bigint = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseBigintDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + function parseBigintDef2(def, refs) { + const res = { + type: "integer", + format: "int64" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; + } + exports.parseBigintDef = parseBigintDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js +var require_boolean = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseBooleanDef = void 0; + function parseBooleanDef2() { + return { + type: "boolean" + }; + } + exports.parseBooleanDef = parseBooleanDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js +var require_branded = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseBrandedDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseBrandedDef2(_def, refs) { + return (0, parseDef_js_1.parseDef)(_def.type._def, refs); + } + exports.parseBrandedDef = parseBrandedDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js +var require_catch = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseCatchDef = void 0; + var parseDef_js_1 = require_parseDef(); + var parseCatchDef2 = (def, refs) => { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + }; + exports.parseCatchDef = parseCatchDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js +var require_date = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseDateDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + function parseDateDef2(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i7) => parseDateDef2(def, refs, item)) + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time" + }; + case "format:date": + return { + type: "string", + format: "date" + }; + case "integer": + return integerDateParser2(def, refs); + } + } + exports.parseDateDef = parseDateDef2; + var integerDateParser2 = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_js_1.setResponseValueAndErrors)( + res, + "minimum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + case "max": + (0, errorMessages_js_1.setResponseValueAndErrors)( + res, + "maximum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + } + } + return res; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js +var require_default = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseDefaultDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseDefaultDef2(_def, refs) { + return { + ...(0, parseDef_js_1.parseDef)(_def.innerType._def, refs), + default: _def.defaultValue() + }; + } + exports.parseDefaultDef = parseDefaultDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js +var require_effects = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseEffectsDef = void 0; + var parseDef_js_1 = require_parseDef(); + var any_js_1 = require_any(); + function parseEffectsDef2(_def, refs) { + return refs.effectStrategy === "input" ? (0, parseDef_js_1.parseDef)(_def.schema._def, refs) : (0, any_js_1.parseAnyDef)(refs); + } + exports.parseEffectsDef = parseEffectsDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js +var require_enum = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseEnumDef = void 0; + function parseEnumDef2(def) { + return { + type: "string", + enum: Array.from(def.values) + }; + } + exports.parseEnumDef = parseEnumDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js +var require_intersection = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseIntersectionDef = void 0; + var parseDef_js_1 = require_parseDef(); + var isJsonSchema7AllOfType2 = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; + }; + function parseIntersectionDef2(def, refs) { + const allOf = [ + (0, parseDef_js_1.parseDef)(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }), + (0, parseDef_js_1.parseDef)(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"] + }) + ].filter((x2) => !!x2); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType2(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) { + unevaluatedProperties = void 0; + } + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else { + unevaluatedProperties = void 0; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; + } + exports.parseIntersectionDef = parseIntersectionDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js +var require_literal = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseLiteralDef = void 0; + function parseLiteralDef2(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object" + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value] + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value + }; + } + exports.parseLiteralDef = parseLiteralDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js +var require_string = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseStringDef = exports.zodPatterns = void 0; + var errorMessages_js_1 = require_errorMessages(); + var emojiRegex5 = void 0; + exports.zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex5 === void 0) { + emojiRegex5 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + } + return emojiRegex5; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ + }; + function parseStringDef2(def, refs) { + const res = { + type: "string" + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case "max": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat2(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat2(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern2(res, exports.zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat2(res, "uri", check.message, refs); + break; + case "uuid": + addFormat2(res, "uuid", check.message, refs); + break; + case "regex": + addPattern2(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern2(res, exports.zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern2(res, exports.zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern2(res, RegExp(`^${escapeLiteralCheckValue2(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern2(res, RegExp(`${escapeLiteralCheckValue2(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat2(res, "date-time", check.message, refs); + break; + case "date": + addFormat2(res, "date", check.message, refs); + break; + case "time": + addFormat2(res, "time", check.message, refs); + break; + case "duration": + addFormat2(res, "duration", check.message, refs); + break; + case "length": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": { + addPattern2(res, RegExp(escapeLiteralCheckValue2(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat2(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat2(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern2(res, exports.zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern2(res, exports.zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern2(res, exports.zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern2(res, exports.zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern2(res, exports.zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern2(res, exports.zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat2(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern2(res, exports.zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern2(res, exports.zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + /* @__PURE__ */ ((_3) => { + })(check); + } + } + } + return res; + } + exports.parseStringDef = parseStringDef2; + function escapeLiteralCheckValue2(literal, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal) : literal; + } + var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + function escapeNonAlphaNumeric2(source) { + let result = ""; + for (let i7 = 0; i7 < source.length; i7++) { + if (!ALPHA_NUMERIC2.has(source[i7])) { + result += "\\"; + } + result += source[i7]; + } + return result; + } + function addFormat2(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x2) => x2.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format } + } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "format", value, message, refs); + } + } + function addPattern2(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern } + } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags2(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "pattern", stringifyRegExpWithFlags2(regex, refs), message, refs); + } + } + function stringifyRegExpWithFlags2(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + // `.` matches newlines + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i7 = 0; i7 < source.length; i7++) { + if (isEscaped) { + pattern += source[i7]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i7].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i7]; + pattern += `${source[i7 - 2]}-${source[i7]}`.toUpperCase(); + inCharRange = false; + } else if (source[i7 + 1] === "-" && source[i7 + 2]?.match(/[a-z]/)) { + pattern += source[i7]; + inCharRange = true; + } else { + pattern += `${source[i7]}${source[i7].toUpperCase()}`; + } + continue; + } + } else if (source[i7].match(/[a-z]/)) { + pattern += `[${source[i7]}${source[i7].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i7] === "^") { + pattern += `(^|(?<=[\r +]))`; + continue; + } else if (source[i7] === "$") { + pattern += `($|(?=[\r +]))`; + continue; + } + } + if (flags.s && source[i7] === ".") { + pattern += inCharGroup ? `${source[i7]}\r +` : `[${source[i7]}\r +]`; + continue; + } + pattern += source[i7]; + if (source[i7] === "\\") { + isEscaped = true; + } else if (inCharGroup && source[i7] === "]") { + inCharGroup = false; + } else if (!inCharGroup && source[i7] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; + } + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js +var require_record = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseRecordDef = void 0; + var v3_1 = require_v3(); + var parseDef_js_1 = require_parseDef(); + var string_js_1 = require_string(); + var branded_js_1 = require_branded(); + var any_js_1 = require_any(); + function parseRecordDef2(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key] + }) ?? (0, any_js_1.parseAnyDef)(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + } + const schema = { + type: "object", + additionalProperties: (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") { + return schema; + } + if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const { type, ...keyType } = (0, string_js_1.parseStringDef)(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values + } + }; + } else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = (0, branded_js_1.parseBrandedDef)(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; + } + exports.parseRecordDef = parseRecordDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js +var require_map = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseMapDef = void 0; + var parseDef_js_1 = require_parseDef(); + var record_js_1 = require_record(); + var any_js_1 = require_any(); + function parseMapDef2(def, refs) { + if (refs.mapStrategy === "record") { + return (0, record_js_1.parseRecordDef)(def, refs); + } + const keys2 = (0, parseDef_js_1.parseDef)(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"] + }) || (0, any_js_1.parseAnyDef)(refs); + const values2 = (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"] + }) || (0, any_js_1.parseAnyDef)(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys2, values2], + minItems: 2, + maxItems: 2 + } + }; + } + exports.parseMapDef = parseMapDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js +var require_nativeEnum = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNativeEnumDef = void 0; + function parseNativeEnumDef2(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values2) => typeof values2))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; + } + exports.parseNativeEnumDef = parseNativeEnumDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js +var require_never = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNeverDef = void 0; + var any_js_1 = require_any(); + function parseNeverDef2(refs) { + return refs.target === "openAi" ? void 0 : { + not: (0, any_js_1.parseAnyDef)({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) + }; + } + exports.parseNeverDef = parseNeverDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js +var require_null = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNullDef = void 0; + function parseNullDef2(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { + type: "null" + }; + } + exports.parseNullDef = parseNullDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js +var require_union = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUnionDef = exports.primitiveMappings = void 0; + var parseDef_js_1 = require_parseDef(); + exports.primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" + }; + function parseUnionDef2(def, refs) { + if (refs.target === "openApi3") + return asAnyOf2(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x2) => x2._def.typeName in exports.primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) { + const types2 = options.reduce((types3, x2) => { + const type = exports.primitiveMappings[x2._def.typeName]; + return type && !types3.includes(type) ? [...types3, type] : types3; + }, []); + return { + type: types2.length > 1 ? types2 : types2[0] + }; + } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) { + const types2 = options.reduce((acc, x2) => { + const type = typeof x2._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x2._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types2.length === options.length) { + const uniqueTypes = types2.filter((x2, i7, a3) => a3.indexOf(x2) === i7); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x2) => { + return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value]; + }, []) + }; + } + } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x2) => [ + ...acc, + ...x2._def.values.filter((x3) => !acc.includes(x3)) + ], []) + }; + } + return asAnyOf2(def, refs); + } + exports.parseUnionDef = parseUnionDef2; + var asAnyOf2 = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i7}`] + })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)); + return anyOf.length ? { anyOf } : void 0; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js +var require_nullable = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNullableDef = void 0; + var parseDef_js_1 = require_parseDef(); + var union_js_1 = require_union(); + function parseNullableDef2(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: union_js_1.primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + } + return { + type: [ + union_js_1.primitiveMappings[def.innerType._def.typeName], + "null" + ] + }; + } + if (refs.target === "openApi3") { + const base2 = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }); + if (base2 && "$ref" in base2) + return { allOf: [base2], nullable: true }; + return base2 && { ...base2, nullable: true }; + } + const base = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"] + }); + return base && { anyOf: [base, { type: "null" }] }; + } + exports.parseNullableDef = parseNullableDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js +var require_number = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNumberDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + function parseNumberDef2(def, refs) { + const res = { + type: "number" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + (0, errorMessages_js_1.addErrorMessage)(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; + } + exports.parseNumberDef = parseNumberDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js +var require_object = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseObjectDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseObjectDef2(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) { + continue; + } + let propOptional = safeIsOptional2(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; + } + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; + } + const parsedDef = (0, parseDef_js_1.parseDef)(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName] + }); + if (parsedDef === void 0) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required.push(propName); + } + } + if (required.length) { + result.required = required; + } + const additionalProperties = decideAdditionalProperties2(def, refs); + if (additionalProperties !== void 0) { + result.additionalProperties = additionalProperties; + } + return result; + } + exports.parseObjectDef = parseObjectDef2; + function decideAdditionalProperties2(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return (0, parseDef_js_1.parseDef)(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } + } + function safeIsOptional2(schema) { + try { + return schema.isOptional(); + } catch { + return true; + } + } + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js +var require_optional = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseOptionalDef = void 0; + var parseDef_js_1 = require_parseDef(); + var any_js_1 = require_any(); + var parseOptionalDef2 = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + } + const innerSchema = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"] + }); + return innerSchema ? { + anyOf: [ + { + not: (0, any_js_1.parseAnyDef)(refs) + }, + innerSchema + ] + } : (0, any_js_1.parseAnyDef)(refs); + }; + exports.parseOptionalDef = parseOptionalDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js +var require_pipeline = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parsePipelineDef = void 0; + var parseDef_js_1 = require_parseDef(); + var parsePipelineDef2 = (def, refs) => { + if (refs.pipeStrategy === "input") { + return (0, parseDef_js_1.parseDef)(def.in._def, refs); + } else if (refs.pipeStrategy === "output") { + return (0, parseDef_js_1.parseDef)(def.out._def, refs); + } + const a3 = (0, parseDef_js_1.parseDef)(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }); + const b4 = (0, parseDef_js_1.parseDef)(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"] + }); + return { + allOf: [a3, b4].filter((x2) => x2 !== void 0) + }; + }; + exports.parsePipelineDef = parsePipelineDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js +var require_promise = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parsePromiseDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parsePromiseDef2(def, refs) { + return (0, parseDef_js_1.parseDef)(def.type._def, refs); + } + exports.parsePromiseDef = parsePromiseDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js +var require_set = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseSetDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + var parseDef_js_1 = require_parseDef(); + function parseSetDef2(def, refs) { + const items = (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + const schema = { + type: "array", + uniqueItems: true, + items + }; + if (def.minSize) { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; + } + exports.parseSetDef = parseSetDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js +var require_tuple = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseTupleDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseTupleDef2(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items.map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i7}`] + })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []), + additionalItems: (0, parseDef_js_1.parseDef)(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + } else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i7}`] + })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []) + }; + } + } + exports.parseTupleDef = parseTupleDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js +var require_undefined = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUndefinedDef = void 0; + var any_js_1 = require_any(); + function parseUndefinedDef2(refs) { + return { + not: (0, any_js_1.parseAnyDef)(refs) + }; + } + exports.parseUndefinedDef = parseUndefinedDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js +var require_unknown = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUnknownDef = void 0; + var any_js_1 = require_any(); + function parseUnknownDef2(refs) { + return (0, any_js_1.parseAnyDef)(refs); + } + exports.parseUnknownDef = parseUnknownDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js +var require_readonly = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseReadonlyDef = void 0; + var parseDef_js_1 = require_parseDef(); + var parseReadonlyDef2 = (def, refs) => { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + }; + exports.parseReadonlyDef = parseReadonlyDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/selectParser.js +var require_selectParser = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/selectParser.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.selectParser = void 0; + var v3_1 = require_v3(); + var any_js_1 = require_any(); + var array_js_1 = require_array(); + var bigint_js_1 = require_bigint(); + var boolean_js_1 = require_boolean(); + var branded_js_1 = require_branded(); + var catch_js_1 = require_catch(); + var date_js_1 = require_date(); + var default_js_1 = require_default(); + var effects_js_1 = require_effects(); + var enum_js_1 = require_enum(); + var intersection_js_1 = require_intersection(); + var literal_js_1 = require_literal(); + var map_js_1 = require_map(); + var nativeEnum_js_1 = require_nativeEnum(); + var never_js_1 = require_never(); + var null_js_1 = require_null(); + var nullable_js_1 = require_nullable(); + var number_js_1 = require_number(); + var object_js_1 = require_object(); + var optional_js_1 = require_optional(); + var pipeline_js_1 = require_pipeline(); + var promise_js_1 = require_promise(); + var record_js_1 = require_record(); + var set_js_1 = require_set(); + var string_js_1 = require_string(); + var tuple_js_1 = require_tuple(); + var undefined_js_1 = require_undefined(); + var union_js_1 = require_union(); + var unknown_js_1 = require_unknown(); + var readonly_js_1 = require_readonly(); + var selectParser2 = (def, typeName, refs) => { + switch (typeName) { + case v3_1.ZodFirstPartyTypeKind.ZodString: + return (0, string_js_1.parseStringDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodNumber: + return (0, number_js_1.parseNumberDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodObject: + return (0, object_js_1.parseObjectDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBigInt: + return (0, bigint_js_1.parseBigintDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBoolean: + return (0, boolean_js_1.parseBooleanDef)(); + case v3_1.ZodFirstPartyTypeKind.ZodDate: + return (0, date_js_1.parseDateDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodUndefined: + return (0, undefined_js_1.parseUndefinedDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodNull: + return (0, null_js_1.parseNullDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodArray: + return (0, array_js_1.parseArrayDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodUnion: + case v3_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return (0, union_js_1.parseUnionDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodIntersection: + return (0, intersection_js_1.parseIntersectionDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodTuple: + return (0, tuple_js_1.parseTupleDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodRecord: + return (0, record_js_1.parseRecordDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodLiteral: + return (0, literal_js_1.parseLiteralDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodEnum: + return (0, enum_js_1.parseEnumDef)(def); + case v3_1.ZodFirstPartyTypeKind.ZodNativeEnum: + return (0, nativeEnum_js_1.parseNativeEnumDef)(def); + case v3_1.ZodFirstPartyTypeKind.ZodNullable: + return (0, nullable_js_1.parseNullableDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodOptional: + return (0, optional_js_1.parseOptionalDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodMap: + return (0, map_js_1.parseMapDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodSet: + return (0, set_js_1.parseSetDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case v3_1.ZodFirstPartyTypeKind.ZodPromise: + return (0, promise_js_1.parsePromiseDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodNaN: + case v3_1.ZodFirstPartyTypeKind.ZodNever: + return (0, never_js_1.parseNeverDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodEffects: + return (0, effects_js_1.parseEffectsDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodAny: + return (0, any_js_1.parseAnyDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodUnknown: + return (0, unknown_js_1.parseUnknownDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodDefault: + return (0, default_js_1.parseDefaultDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBranded: + return (0, branded_js_1.parseBrandedDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodReadonly: + return (0, readonly_js_1.parseReadonlyDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodCatch: + return (0, catch_js_1.parseCatchDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodPipeline: + return (0, pipeline_js_1.parsePipelineDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodFunction: + case v3_1.ZodFirstPartyTypeKind.ZodVoid: + case v3_1.ZodFirstPartyTypeKind.ZodSymbol: + return void 0; + default: + return /* @__PURE__ */ ((_3) => void 0)(typeName); + } + }; + exports.selectParser = selectParser2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseDef.js +var require_parseDef = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseDef.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseDef = void 0; + var Options_js_1 = require_Options(); + var selectParser_js_1 = require_selectParser(); + var getRelativePath_js_1 = require_getRelativePath(); + var any_js_1 = require_any(); + function parseDef2(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== Options_js_1.ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref2(seenItem, refs); + if (seenSchema !== void 0) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = (0, selectParser_js_1.selectParser)(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta2(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; + } + exports.parseDef = parseDef2; + var get$ref2 = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: (0, getRelativePath_js_1.getRelativePath)(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return (0, any_js_1.parseAnyDef)(refs); + } + return refs.$refStrategy === "seen" ? (0, any_js_1.parseAnyDef)(refs) : void 0; + } + } + }; + var addMeta2 = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js +var require_parseTypes = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js +var require_zodToJsonSchema = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.zodToJsonSchema = void 0; + var parseDef_js_1 = require_parseDef(); + var Refs_js_1 = require_Refs(); + var any_js_1 = require_any(); + var zodToJsonSchema2 = (schema, options) => { + const refs = (0, Refs_js_1.getRefs)(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ + ...acc, + [name2]: (0, parseDef_js_1.parseDef)(schema2._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name2] + }, true) ?? (0, any_js_1.parseAnyDef)(refs) + }), {}) : void 0; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main2 = (0, parseDef_js_1.parseDef)(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name] + }, false) ?? (0, any_js_1.parseAnyDef)(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) { + main2.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") + } + }; + } + } + const combined = name === void 0 ? definitions ? { + ...main2, + [refs.definitionPath]: definitions + } : main2 : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main2 + } + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; + }; + exports.zodToJsonSchema = zodToJsonSchema2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/index.js +var require_cjs = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_Options(), exports); + __exportStar(require_Refs(), exports); + __exportStar(require_errorMessages(), exports); + __exportStar(require_getRelativePath(), exports); + __exportStar(require_parseDef(), exports); + __exportStar(require_parseTypes(), exports); + __exportStar(require_any(), exports); + __exportStar(require_array(), exports); + __exportStar(require_bigint(), exports); + __exportStar(require_boolean(), exports); + __exportStar(require_branded(), exports); + __exportStar(require_catch(), exports); + __exportStar(require_date(), exports); + __exportStar(require_default(), exports); + __exportStar(require_effects(), exports); + __exportStar(require_enum(), exports); + __exportStar(require_intersection(), exports); + __exportStar(require_literal(), exports); + __exportStar(require_map(), exports); + __exportStar(require_nativeEnum(), exports); + __exportStar(require_never(), exports); + __exportStar(require_null(), exports); + __exportStar(require_nullable(), exports); + __exportStar(require_number(), exports); + __exportStar(require_object(), exports); + __exportStar(require_optional(), exports); + __exportStar(require_pipeline(), exports); + __exportStar(require_promise(), exports); + __exportStar(require_readonly(), exports); + __exportStar(require_record(), exports); + __exportStar(require_set(), exports); + __exportStar(require_string(), exports); + __exportStar(require_tuple(), exports); + __exportStar(require_undefined(), exports); + __exportStar(require_union(), exports); + __exportStar(require_unknown(), exports); + __exportStar(require_selectParser(), exports); + __exportStar(require_zodToJsonSchema(), exports); + var zodToJsonSchema_js_1 = require_zodToJsonSchema(); + exports.default = zodToJsonSchema_js_1.zodToJsonSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/extra/structChat.js +var require_structChat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/extra/structChat.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.transformToChatCompletionRequest = transformToChatCompletionRequest; + exports.convertToParsedChatCompletionResponse = convertToParsedChatCompletionResponse; + exports.responseFormatFromZodObject = responseFormatFromZodObject; + var zod_to_json_schema_1 = require_cjs(); + function transformToChatCompletionRequest(parsedRequest) { + const { responseFormat, ...rest } = parsedRequest; + const transformedResponseFormat = responseFormatFromZodObject(responseFormat); + return { + ...rest, + responseFormat: transformedResponseFormat + }; + } + function convertToParsedChatCompletionResponse(response, responseFormat) { + if (response.choices === void 0 || response.choices.length === 0) { + return { + ...response, + choices: response.choices === void 0 ? void 0 : [] + }; + } + const parsedChoices = []; + for (const _choice of response.choices) { + if (_choice.message === null || typeof _choice.message === "undefined") { + parsedChoices.push({ ..._choice, message: void 0 }); + } else { + if (_choice.message.content !== null && typeof _choice.message.content !== "undefined" && !Array.isArray(_choice.message.content)) { + parsedChoices.push({ + ..._choice, + message: { + ..._choice.message, + parsed: responseFormat.safeParse(JSON.parse(_choice.message.content)).data + } + }); + } + } + } + return { + ...response, + choices: parsedChoices + }; + } + function responseFormatFromZodObject(responseFormat) { + const responseJsonSchema = (0, zod_to_json_schema_1.zodToJsonSchema)(responseFormat); + const placeholderName = "placeholderName"; + return { + type: "json_schema", + jsonSchema: { + name: placeholderName, + schemaDefinition: responseJsonSchema, + strict: true + } + }; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/chat.js +var require_chat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/chat.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Chat = void 0; + var chatComplete_js_1 = require_chatComplete(); + var chatStream_js_1 = require_chatStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var structChat_js_1 = require_structChat(); + var Chat4 = class extends sdks_js_1.ClientSDK { + // #region sdk-class-body + /** + * Chat Completion with the response parsed in the same format as the input requestFormat. + * + * @remarks + * The response will be parsed back to the initial Zod object passed in the requestFormat field. + */ + async parse(request, options) { + const ccr_request = (0, structChat_js_1.transformToChatCompletionRequest)(request); + const response = await (0, fp_js_1.unwrapAsync)((0, chatComplete_js_1.chatComplete)(this, ccr_request, options)); + const parsed_response = (0, structChat_js_1.convertToParsedChatCompletionResponse)(response, request.responseFormat); + return parsed_response; + } + /** + * Stream chat completion with a parsed request input. + * + * @remarks + * Unlike the .parse method, this method will return a stream of events containing the JSON response. It will not be parsed back to the initial Zod object. + * If you need to parse the stream, see the examples/src/async_structured_outputs.ts file. + */ + async parseStream(request, options) { + const ccr_request = (0, structChat_js_1.transformToChatCompletionRequest)(request); + return (0, fp_js_1.unwrapAsync)((0, chatStream_js_1.chatStream)(this, ccr_request, options)); + } + // #endregion sdk-class-body + /** + * Chat Completion + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, chatComplete_js_1.chatComplete)(this, request, options)); + } + /** + * Stream chat completion + * + * @remarks + * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON. + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, chatStream_js_1.chatStream)(this, request, options)); + } + }; + exports.Chat = Chat4; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassify.js +var require_classifiersClassify = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassify.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersClassify = classifiersClassify; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersClassify(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ClassificationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/classifications")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "classifications_v1_classifications_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ClassificationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassifyChat.js +var require_classifiersClassifyChat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassifyChat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersClassifyChat = classifiersClassifyChat; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersClassifyChat(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatClassificationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/classifications")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "chat_classifications_v1_chat_classifications_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ClassificationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerate.js +var require_classifiersModerate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersModerate = classifiersModerate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersModerate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ClassificationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/moderations")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "moderations_v1_moderations_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ModerationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerateChat.js +var require_classifiersModerateChat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerateChat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersModerateChat = classifiersModerateChat; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersModerateChat(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatModerationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/moderations")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "chat_moderations_v1_chat_moderations_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ModerationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/classifiers.js +var require_classifiers = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/classifiers.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Classifiers = void 0; + var classifiersClassify_js_1 = require_classifiersClassify(); + var classifiersClassifyChat_js_1 = require_classifiersClassifyChat(); + var classifiersModerate_js_1 = require_classifiersModerate(); + var classifiersModerateChat_js_1 = require_classifiersModerateChat(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Classifiers = class extends sdks_js_1.ClientSDK { + /** + * Moderations + */ + async moderate(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersModerate_js_1.classifiersModerate)(this, request, options)); + } + /** + * Chat Moderations + */ + async moderateChat(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersModerateChat_js_1.classifiersModerateChat)(this, request, options)); + } + /** + * Classifications + */ + async classify(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersClassify_js_1.classifiersClassify)(this, request, options)); + } + /** + * Chat Classifications + */ + async classifyChat(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersClassifyChat_js_1.classifiersClassifyChat)(this, request, options)); + } + }; + exports.Classifiers = Classifiers; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/embeddingsCreate.js +var require_embeddingsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/embeddingsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.embeddingsCreate = embeddingsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function embeddingsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.EmbeddingRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/embeddings")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "embeddings_v1_embeddings_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.EmbeddingResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/embeddings.js +var require_embeddings = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/embeddings.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Embeddings = void 0; + var embeddingsCreate_js_1 = require_embeddingsCreate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Embeddings2 = class extends sdks_js_1.ClientSDK { + /** + * Embeddings + * + * @remarks + * Embeddings + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, embeddingsCreate_js_1.embeddingsCreate)(this, request, options)); + } + }; + exports.Embeddings = Embeddings2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDelete.js +var require_filesDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesDelete = filesDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesDeleteFileRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_delete_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.DeleteFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDownload.js +var require_filesDownload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDownload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesDownload = filesDownload; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesDownload(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesDownloadFileRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}/content")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/octet-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_download_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.stream(200, z3.instanceof(ReadableStream)), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesGetSignedUrl.js +var require_filesGetSignedUrl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesGetSignedUrl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesGetSignedUrl = filesGetSignedUrl; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesGetSignedUrl(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesGetSignedUrlRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}/url")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "expiry": payload.expiry + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_get_signed_url", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.FileSignedURL$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesList.js +var require_filesList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesList = filesList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesListFilesRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/files")(); + const query = (0, encodings_js_1.encodeFormQuery)({ + "include_total": payload?.include_total, + "mimetypes": payload?.mimetypes, + "page": payload?.page, + "page_size": payload?.page_size, + "purpose": payload?.purpose, + "sample_type": payload?.sample_type, + "search": payload?.search, + "source": payload?.source + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_list_files", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ListFilesOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesRetrieve.js +var require_filesRetrieve = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesRetrieve.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesRetrieve = filesRetrieve; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesRetrieve(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesRetrieveFileRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_retrieve_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.RetrieveFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesUpload.js +var require_filesUpload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesUpload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesUpload = filesUpload; + var encodings_js_1 = require_encodings(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function filesUpload(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + if ((0, blobs_js_1.isBlobLike)(payload.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.file); + } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName); + } + if (payload.purpose !== void 0) { + (0, encodings_js_1.appendForm)(body, "purpose", payload.purpose); + } + const path6 = (0, url_js_1.pathToFunc)("/v1/files")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_upload_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.UploadFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/files.js +var require_files2 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/files.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Files = void 0; + var filesDelete_js_1 = require_filesDelete(); + var filesDownload_js_1 = require_filesDownload(); + var filesGetSignedUrl_js_1 = require_filesGetSignedUrl(); + var filesList_js_1 = require_filesList(); + var filesRetrieve_js_1 = require_filesRetrieve(); + var filesUpload_js_1 = require_filesUpload(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Files6 = class extends sdks_js_1.ClientSDK { + /** + * Upload File + * + * @remarks + * Upload a file that can be used across various endpoints. + * + * The size of individual files can be a maximum of 512 MB. The Fine-tuning API only supports .jsonl files. + * + * Please contact us if you need to increase these storage limits. + */ + async upload(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesUpload_js_1.filesUpload)(this, request, options)); + } + /** + * List Files + * + * @remarks + * Returns a list of files that belong to the user's organization. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesList_js_1.filesList)(this, request, options)); + } + /** + * Retrieve File + * + * @remarks + * Returns information about a specific file. + */ + async retrieve(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesRetrieve_js_1.filesRetrieve)(this, request, options)); + } + /** + * Delete File + * + * @remarks + * Delete a file. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesDelete_js_1.filesDelete)(this, request, options)); + } + /** + * Download File + * + * @remarks + * Download a file + */ + async download(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesDownload_js_1.filesDownload)(this, request, options)); + } + /** + * Get Signed Url + */ + async getSignedUrl(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesGetSignedUrl_js_1.filesGetSignedUrl)(this, request, options)); + } + }; + exports.Files = Files6; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fimComplete.js +var require_fimComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fimComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fimComplete = fimComplete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function fimComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.FIMCompletionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/fim/completions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "fim_completion_v1_fim_completions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.FIMCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fimStream.js +var require_fimStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fimStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fimStream = fimStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function fimStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.FIMCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/fim/completions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "stream_fim", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + if (rawEvent.data === "[DONE]") + return { done: true }; + return { + value: components.CompletionEvent$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/fim.js +var require_fim = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/fim.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Fim = void 0; + var fimComplete_js_1 = require_fimComplete(); + var fimStream_js_1 = require_fimStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Fim = class extends sdks_js_1.ClientSDK { + /** + * Fim Completion + * + * @remarks + * FIM completion. + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fimComplete_js_1.fimComplete)(this, request, options)); + } + /** + * Stream fim completion + * + * @remarks + * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON. + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fimStream_js_1.fimStream)(this, request, options)); + } + }; + exports.Fim = Fim; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCancel.js +var require_fineTuningJobsCancel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCancel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsCancel = fineTuningJobsCancel; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsCancel(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}/cancel")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_cancel_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCreate.js +var require_fineTuningJobsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsCreate = fineTuningJobsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.JobIn$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_create_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsGet.js +var require_fineTuningJobsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsGet = fineTuningJobsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_get_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsList.js +var require_fineTuningJobsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsList = fineTuningJobsList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs")(); + const query = (0, encodings_js_1.encodeFormQuery)({ + "created_after": payload?.created_after, + "created_before": payload?.created_before, + "created_by_me": payload?.created_by_me, + "model": payload?.model, + "page": payload?.page, + "page_size": payload?.page_size, + "status": payload?.status, + "suffix": payload?.suffix, + "wandb_name": payload?.wandb_name, + "wandb_project": payload?.wandb_project + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_get_fine_tuning_jobs", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.JobsOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsStart.js +var require_fineTuningJobsStart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsStart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsStart = fineTuningJobsStart; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsStart(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}/start")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_start_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/jobs.js +var require_jobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/jobs.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Jobs = void 0; + var fineTuningJobsCancel_js_1 = require_fineTuningJobsCancel(); + var fineTuningJobsCreate_js_1 = require_fineTuningJobsCreate(); + var fineTuningJobsGet_js_1 = require_fineTuningJobsGet(); + var fineTuningJobsList_js_1 = require_fineTuningJobsList(); + var fineTuningJobsStart_js_1 = require_fineTuningJobsStart(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Jobs2 = class extends sdks_js_1.ClientSDK { + /** + * Get Fine Tuning Jobs + * + * @remarks + * Get a list of fine-tuning jobs for your organization and user. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsList_js_1.fineTuningJobsList)(this, request, options)); + } + /** + * Create Fine Tuning Job + * + * @remarks + * Create a new fine-tuning job, it will be queued for processing. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsCreate_js_1.fineTuningJobsCreate)(this, request, options)); + } + /** + * Get Fine Tuning Job + * + * @remarks + * Get a fine-tuned job details by its UUID. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsGet_js_1.fineTuningJobsGet)(this, request, options)); + } + /** + * Cancel Fine Tuning Job + * + * @remarks + * Request the cancellation of a fine tuning job. + */ + async cancel(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsCancel_js_1.fineTuningJobsCancel)(this, request, options)); + } + /** + * Start Fine Tuning Job + * + * @remarks + * Request the start of a validated fine tuning job. + */ + async start(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsStart_js_1.fineTuningJobsStart)(this, request, options)); + } + }; + exports.Jobs = Jobs2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/finetuning.js +var require_finetuning = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/finetuning.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FineTuning = void 0; + var sdks_js_1 = require_sdks(); + var jobs_js_1 = require_jobs(); + var FineTuning2 = class extends sdks_js_1.ClientSDK { + get jobs() { + return this._jobs ?? (this._jobs = new jobs_js_1.Jobs(this._options)); + } + }; + exports.FineTuning = FineTuning2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsArchive.js +var require_modelsArchive = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsArchive.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsArchive = modelsArchive; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsArchive(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}/archive")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_archive_fine_tuned_model", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ArchiveFTModelOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsDelete.js +var require_modelsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsDelete = modelsDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/models/{model_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "delete_model_v1_models__model_id__delete", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DeleteModelOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsList.js +var require_modelsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsList = modelsList; + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + function modelsList(client, options) { + return new async_js_1.APIPromise($do(client, options)); + } + async function $do(client, options) { + const path6 = (0, url_js_1.pathToFunc)("/v1/models")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "list_models_v1_models_get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ModelList$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsRetrieve.js +var require_modelsRetrieve = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsRetrieve.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsRetrieve = modelsRetrieve; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsRetrieve(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/models/{model_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "retrieve_model_v1_models__model_id__get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, operations.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUnarchive.js +var require_modelsUnarchive = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUnarchive.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsUnarchive = modelsUnarchive; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsUnarchive(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}/archive")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_unarchive_fine_tuned_model", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.UnarchiveFTModelOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUpdate.js +var require_modelsUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsUpdate = modelsUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.UpdateFTModelIn, { explode: true }); + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_update_fine_tuned_model", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/models.js +var require_models = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/models.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Models = void 0; + var modelsArchive_js_1 = require_modelsArchive(); + var modelsDelete_js_1 = require_modelsDelete(); + var modelsList_js_1 = require_modelsList(); + var modelsRetrieve_js_1 = require_modelsRetrieve(); + var modelsUnarchive_js_1 = require_modelsUnarchive(); + var modelsUpdate_js_1 = require_modelsUpdate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Models5 = class extends sdks_js_1.ClientSDK { + /** + * List Models + * + * @remarks + * List all models available to the user. + */ + async list(options) { + return (0, fp_js_1.unwrapAsync)((0, modelsList_js_1.modelsList)(this, options)); + } + /** + * Retrieve Model + * + * @remarks + * Retrieve information about a model. + */ + async retrieve(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsRetrieve_js_1.modelsRetrieve)(this, request, options)); + } + /** + * Delete Model + * + * @remarks + * Delete a fine-tuned model. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsDelete_js_1.modelsDelete)(this, request, options)); + } + /** + * Update Fine Tuned Model + * + * @remarks + * Update a model name or description. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsUpdate_js_1.modelsUpdate)(this, request, options)); + } + /** + * Archive Fine Tuned Model + * + * @remarks + * Archive a fine-tuned model. + */ + async archive(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsArchive_js_1.modelsArchive)(this, request, options)); + } + /** + * Unarchive Fine Tuned Model + * + * @remarks + * Un-archive a fine-tuned model. + */ + async unarchive(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsUnarchive_js_1.modelsUnarchive)(this, request, options)); + } + }; + exports.Models = Models5; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/ocrProcess.js +var require_ocrProcess = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/ocrProcess.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ocrProcess = ocrProcess; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function ocrProcess(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.OCRRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/ocr")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "ocr_v1_ocr_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.OCRResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/ocr.js +var require_ocr = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/ocr.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Ocr = void 0; + var ocrProcess_js_1 = require_ocrProcess(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Ocr = class extends sdks_js_1.ClientSDK { + /** + * OCR + */ + async process(request, options) { + return (0, fp_js_1.unwrapAsync)((0, ocrProcess_js_1.ocrProcess)(this, request, options)); + } + }; + exports.Ocr = Ocr; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/sdk.js +var require_sdk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/sdk.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Mistral = void 0; + var sdks_js_1 = require_sdks(); + var agents_js_1 = require_agents(); + var audio_js_1 = require_audio(); + var batch_js_1 = require_batch(); + var beta_js_1 = require_beta(); + var chat_js_1 = require_chat(); + var classifiers_js_1 = require_classifiers(); + var embeddings_js_1 = require_embeddings(); + var files_js_1 = require_files2(); + var fim_js_1 = require_fim(); + var finetuning_js_1 = require_finetuning(); + var models_js_1 = require_models(); + var ocr_js_1 = require_ocr(); + var Mistral2 = class extends sdks_js_1.ClientSDK { + get models() { + return this._models ?? (this._models = new models_js_1.Models(this._options)); + } + get beta() { + return this._beta ?? (this._beta = new beta_js_1.Beta(this._options)); + } + get files() { + return this._files ?? (this._files = new files_js_1.Files(this._options)); + } + get fineTuning() { + return this._fineTuning ?? (this._fineTuning = new finetuning_js_1.FineTuning(this._options)); + } + get batch() { + return this._batch ?? (this._batch = new batch_js_1.Batch(this._options)); + } + get chat() { + return this._chat ?? (this._chat = new chat_js_1.Chat(this._options)); + } + get fim() { + return this._fim ?? (this._fim = new fim_js_1.Fim(this._options)); + } + get agents() { + return this._agents ?? (this._agents = new agents_js_1.Agents(this._options)); + } + get embeddings() { + return this._embeddings ?? (this._embeddings = new embeddings_js_1.Embeddings(this._options)); + } + get classifiers() { + return this._classifiers ?? (this._classifiers = new classifiers_js_1.Classifiers(this._options)); + } + get ocr() { + return this._ocr ?? (this._ocr = new ocr_js_1.Ocr(this._options)); + } + get audio() { + return this._audio ?? (this._audio = new audio_js_1.Audio(this._options)); + } + }; + exports.Mistral = Mistral2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/index.js +var require_mistralai = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTPClient = exports.files = void 0; + __exportStar(require_config(), exports); + exports.files = __importStar(require_files()); + var http_js_1 = require_http(); + Object.defineProperty(exports, "HTTPClient", { enumerable: true, get: function() { + return http_js_1.HTTPClient; + } }); + __exportStar(require_sdk(), exports); + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s6) { + super(); + if (!exports.IDENTIFIER.test(s6)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s6; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a7; + return (_a7 = this._str) !== null && _a7 !== void 0 ? _a7 : this._str = this._items.reduce((s6, c6) => `${s6}${c6}`, ""); + } + get names() { + var _a7; + return (_a7 = this._names) !== null && _a7 !== void 0 ? _a7 : this._names = this._items.reduce((names, c6) => { + if (c6 instanceof Name) + names[c6.str] = (names[c6.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _3(strs2, ...args) { + const code = [strs2[0]]; + let i7 = 0; + while (i7 < args.length) { + addCodeArg(code, args[i7]); + code.push(strs2[++i7]); + } + return new _Code(code); + } + exports._ = _3; + var plus = new _Code("+"); + function str2(strs2, ...args) { + const expr = [safeStringify(strs2[0])]; + let i7 = 0; + while (i7 < args.length) { + expr.push(plus); + addCodeArg(expr, args[i7]); + expr.push(plus, safeStringify(strs2[++i7])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str2; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i7 = 1; + while (i7 < expr.length - 1) { + if (expr[i7] === plus) { + const res = mergeExprItems(expr[i7 - 1], expr[i7 + 1]); + if (res !== void 0) { + expr.splice(i7 - 1, 3, res); + continue; + } + expr[i7++] = "+"; + } + i7++; + } + } + function mergeExprItems(a3, b4) { + if (b4 === '""') + return a3; + if (a3 === '""') + return b4; + if (typeof a3 == "string") { + if (b4 instanceof Name || a3[a3.length - 1] !== '"') + return; + if (typeof b4 != "string") + return `${a3.slice(0, -1)}${b4}"`; + if (b4[0] === '"') + return a3.slice(0, -1) + b4.slice(1); + return; + } + if (typeof b4 == "string" && b4[0] === '"' && !(a3 instanceof Name)) + return `"${a3}${b4.slice(1)}`; + return; + } + function strConcat(c1, c22) { + return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str2`${c1}${c22}`; + } + exports.strConcat = strConcat; + function interpolate(x2) { + return typeof x2 == "number" || typeof x2 == "boolean" || x2 === null ? x2 : safeStringify(Array.isArray(x2) ? x2.join(",") : x2); + } + function stringify2(x2) { + return new _Code(safeStringify(x2)); + } + exports.stringify = stringify2; + function safeStringify(x2) { + return JSON.stringify(x2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _3`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a7, _b; + if (((_b = (_a7 = this._parent) === null || _a7 === void 0 ? void 0 : _a7._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a7; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a7 = value.key) !== null && _a7 !== void 0 ? _a7 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s6 = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s6.length; + s6[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values2 = this._values) { + return this._reduceValues(values2, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values2 = this._values, usedValues, getCode) { + return this._reduceValues(values2, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values2, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values2) { + const vs = values2[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c6 = valueCode(name); + if (c6) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c6};${this.opts._n}`; + } else if (c6 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c6}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node2 = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node2 { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node2 { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op2, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op2; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label2 = class extends Node2 { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node2 { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw3 = class extends Node2 { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node2 { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node2 { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n7) => code + n7.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i7 = nodes.length; + while (i7--) { + const n7 = nodes[i7].optimizeNodes(); + if (Array.isArray(n7)) + nodes.splice(i7, 1, ...n7); + else if (n7) + nodes[i7] = n7; + else + nodes.splice(i7, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i7 = nodes.length; + while (i7--) { + const n7 = nodes[i7]; + if (n7.optimizeNames(names, constants)) + continue; + subtractNames(names, n7.names); + nodes.splice(i7, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n7) => addNames(names, n7.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e9 = this.else; + if (e9) { + const ns2 = e9.optimizeNodes(); + e9 = this.else = Array.isArray(ns2) ? new Else(ns2) : ns2; + } + if (e9) { + if (cond === false) + return e9 instanceof _If ? e9 : e9.nodes; + if (this.nodes.length) + return this; + return new _If(not(cond), e9 instanceof _If ? [e9] : e9.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names, constants) { + var _a7; + this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a7, _b; + super.optimizeNodes(); + (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a7, _b; + super.optimizeNames(names, constants); + (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c6) { + if (typeof c6 == "function") + c6(); + else if (c6 !== code_1.nil) + this._leafNode(new AnyCode(c6)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i7) => { + this.var(name, (0, code_1._)`${arr}[${i7}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label2(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error) { + return this._leafNode(new Throw3(error)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n7 = 1) { + while (n7-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N22) { + const n7 = this._currNode; + if (n7 instanceof N1 || N22 && n7 instanceof N22) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N22 ? `${N1.kind}/${N22.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n7 = this._currNode; + if (!(n7 instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n7.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns2 = this._nodes; + return ns2[ns2.length - 1]; + } + set _currNode(node) { + const ns2 = this._nodes; + ns2[ns2.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n7 in from) + names[n7] = (names[n7] || 0) + (from[n7] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c6) => { + if (c6 instanceof code_1.Name) + c6 = replaceName(c6); + if (c6 instanceof code_1._Code) + items.push(...c6._items); + else + items.push(c6); + return items; + }, [])); + function replaceName(n7) { + const c6 = constants[n7.str]; + if (c6 === void 0 || names[n7.str] !== 1) + return n7; + delete names[n7.str]; + return c6; + } + function canOptimize(e9) { + return e9 instanceof code_1._Code && e9._items.some((c6) => c6 instanceof code_1.Name && names[c6.str] === 1 && constants[c6.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n7 in from) + names[n7] = (names[n7] || 0) - (from[n7] || 0); + } + function not(x2) { + return typeof x2 == "boolean" || typeof x2 == "number" || x2 === null ? !x2 : (0, code_1._)`!${par(x2)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op2) { + return (x2, y4) => x2 === code_1.nil ? y4 : y4 === code_1.nil ? x2 : (0, code_1._)`${par(x2)} ${op2} ${par(y4)}`; + } + function par(x2) { + return x2 instanceof code_1.Name ? x2 : (0, code_1._)`(${x2})`; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/util.js +var require_util2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str2) { + return unescapeJsonPointer(decodeURIComponent(str2)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str2) { + return encodeURIComponent(escapeJsonPointer(str2)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str2) { + if (typeof str2 == "number") + return `${str2}`; + return str2.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str2) { + return str2.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f4) { + if (Array.isArray(xs)) { + for (const x2 of xs) + f4(x2); + } else { + f4(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { ...from, ...to }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p4) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p4)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f4) { + return gen.scopeValue("func", { + ref: f4, + code: snippets[f4.code] || (snippets[f4.code] = new code_1._Code(f4.code)) + }); + } + exports.useFunc = useFunc; + var Type4; + (function(Type5) { + Type5[Type5["Num"] = 0] = "Num"; + Type5[Type5["Str"] = 1] = "Str"; + })(Type4 || (exports.Type = Type4 = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber2 = dataPropType === Type4.Num; + return jsPropertySyntax ? isNumber2 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber2 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/errors.js +var require_errors3 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i7) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i7}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E3 = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E3.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E3.keyword, keyword], [E3.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E3.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E3.schema, schemaValue], [E3.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E3.propertyName, propertyName]); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x2) { + return typeof x2 == "string" && jsonTypes.has(x2); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self: self2 }, type) { + const group = self2.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a7; + return schema[rule.keyword] !== void 0 || ((_a7 = rule.definition.implements) === null || _a7 === void 0 ? void 0 : _a7.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types2 = getJSONTypes(schema.type); + const hasNull = types2.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types2.length && schema.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types2.push("null"); + } + return types2; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types2 = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types2.every(rules_1.isJSONType)) + return types2; + throw new Error("type must be JSONType or JSONType[]: " + types2.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types2) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types2, opts.coerceTypes); + const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types2[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types2, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types2, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types2, coerceTypes) { + return coerceTypes ? types2.filter((t6) => COERCIBLE.has(t6) || coerceTypes === "array" && t6 === "array") : []; + } + function coerceData(it, types2, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types2, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t6 of coerceTo) { + if (COERCIBLE.has(t6) || t6 === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t6); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t6) { + switch (t6) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types2 = (0, util_1.toHash)(dataTypes); + if (types2.array && types2.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types2.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types2.null; + delete types2.array; + delete types2.object; + } else { + cond = codegen_1.nil; + } + if (types2.number) + delete types2.integer; + for (const t6 in types2) + cond = (0, codegen_1.and)(cond, checkDataType(t6, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i7) => assignDefault(it, i7, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var names_1 = require_names(); + var util_2 = require_util2(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p4) => p4 !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p4) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p4])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u5 = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u5); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u5})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i7) => { + cxt.subschema({ + keyword, + dataProp: i7, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i7) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i7, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors3(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a7; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a7 = def.valid) !== null && _a7 !== void 0 ? _a7 : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e9) => gen.assign(valid, false).if((0, codegen_1._)`${e9} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e9}.errors`), () => gen.throw(e9))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a8; + gen.if((0, codegen_1.not)((_a8 = def.valid) !== null && _a8 !== void 0 ? _a8 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// ../pi-mono/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "../pi-mono/node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + init_process_shim(); + module.exports = function equal(a3, b4) { + if (a3 === b4) return true; + if (a3 && b4 && typeof a3 == "object" && typeof b4 == "object") { + if (a3.constructor !== b4.constructor) return false; + var length, i7, keys2; + if (Array.isArray(a3)) { + length = a3.length; + if (length != b4.length) return false; + for (i7 = length; i7-- !== 0; ) + if (!equal(a3[i7], b4[i7])) return false; + return true; + } + if (a3.constructor === RegExp) return a3.source === b4.source && a3.flags === b4.flags; + if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b4.valueOf(); + if (a3.toString !== Object.prototype.toString) return a3.toString() === b4.toString(); + keys2 = Object.keys(a3); + length = keys2.length; + if (length !== Object.keys(b4).length) return false; + for (i7 = length; i7-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b4, keys2[i7])) return false; + for (i7 = length; i7-- !== 0; ) { + var key = keys2[i7]; + if (!equal(a3[key], b4[key])) return false; + } + return true; + } + return a3 !== a3 && b4 !== b4; + }; + } +}); + +// ../pi-mono/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "../pi-mono/node_modules/json-schema-traverse/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var traverse2 = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post2 = cb.post || function() { + }; + _traverse(opts, pre, post2, schema, "", schema); + }; + traverse2.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse2.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse2.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse2.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post2, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse2.arrayKeywords) { + for (var i7 = 0; i7 < sch.length; i7++) + _traverse(opts, pre, post2, sch[i7], jsonPtr + "/" + key + "/" + i7, rootSchema, jsonPtr, key, schema, i7); + } + } else if (key in traverse2.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post2, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse2.keywords || opts.allKeys && !(key in traverse2.skipKeywords)) { + _traverse(opts, pre, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + } + post2(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str2) { + return str2.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util2(); + var equal = require_fast_deep_equal(); + var traverse2 = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit2 = true) { + if (typeof schema == "boolean") + return true; + if (limit2 === true) + return !hasRef(schema); + if (!limit2) + return false; + return countKeys(schema) <= limit2; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + } + if (count === Infinity) + return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p4 = resolver.parse(id); + return _getFullPath(resolver, p4); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p4) { + const serialized = resolver.serialize(p4); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse2(schema, { allKeys: true }, (sch, jsonPtr, _3, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util2(); + var errors_1 = require_errors3(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self: self2 }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types2 = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types2); + schemaKeywords(it, types2, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self: self2 } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types2, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self: self2 } = it; + const { RULES } = self2; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types2); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types2.length === 1 && types2[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types2) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types2); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types2); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types2) { + if (!types2.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types2; + return; + } + types2.forEach((t6) => { + if (!includesType(it.dataTypes, t6)) { + strictTypesError(it, `type "${t6}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types2); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t6) => hasApplicableType(ts, t6))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t6) { + return ts.includes(t6) || t6 === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t6 of it.dataTypes) { + if (includesType(withTypes, t6)) + ts.push(t6); + else if (withTypes.includes("integer") && t6 === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util2(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a7; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a7 = env.baseId) !== null && _a7 !== void 0 ? _a7 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e9) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e9; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a7; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a7 = root.localRefs) === null || _a7 === void 0 ? void 0 : _a7[ref]; + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s22) { + return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p4 = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p4); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p4, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p4, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p4, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a7; + if (((_a7 = parsedRef.fragment) === null || _a7 === void 0 ? void 0 : _a7[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return void 0; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "../pi-mono/node_modules/ajv/dist/refs/data.json"(exports, module) { + module.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// ../pi-mono/node_modules/fast-uri/lib/utils.js +var require_utils = __commonJS({ + "../pi-mono/node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + init_process_shim(); + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i7 = 0; + for (i7 = 0; i7 < input.length; i7++) { + code = input[i7].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i7]; + break; + } + for (i7 += 1; i7 < input.length; i7++) { + code = input[i7].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i7]; + } + return acc; + } + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") { + address.push(hex); + } else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { error: false, address: "", zone: "" }; + const address = []; + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i7 = 0; i7 < input.length; i7++) { + const cursor = input[i7]; + if (cursor === "[" || cursor === "]") { + continue; + } + if (cursor === ":") { + if (endipv6Encountered === true) { + endIpv6 = true; + } + if (!consume(buffer, address, output)) { + break; + } + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i7 > 0 && input[i7 - 1] === ":") { + endipv6Encountered = true; + } + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) { + break; + } + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) { + if (consume === consumeIsZone) { + output.zone = buffer.join(""); + } else if (endIpv6) { + address.push(buffer.join("")); + } else { + address.push(stringArrayToHexStripped(buffer)); + } + } + output.address = address.join(""); + return output; + } + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) { + return { host, isIPV6: false }; + } + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { host: newHost, isIPV6: true, escapedHost }; + } else { + return { host, isIPV6: false }; + } + } + function findToken(str2, token) { + let ind = 0; + for (let i7 = 0; i7 < str2.length; i7++) { + if (str2[i7] === token) ind++; + } + return ind; + } + function removeDotSegments(path6) { + let input = path6; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) { + component.scheme = func(component.scheme); + } + if (component.userinfo !== void 0) { + component.userinfo = func(component.userinfo); + } + if (component.host !== void 0) { + component.host = func(component.host); + } + if (component.path !== void 0) { + component.path = func(component.path); + } + if (component.query !== void 0) { + component.query = func(component.query); + } + if (component.fragment !== void 0) { + component.fragment = func(component.fragment); + } + return component; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = component.host; + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// ../pi-mono/node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "../pi-mono/node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + init_process_shim(); + var { isUUID } = require_utils(); + var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path6, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path6 && path6 !== "/" ? path6 : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// ../pi-mono/node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "../pi-mono/node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + serialize2(parse(uri, options), options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse(serialize2(uri, options), options); + } + return uri; + } + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize2(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse(serialize2(base, options), options); + relative = parse(serialize2(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path[0] === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize2(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true }); + } else if (typeof uriA === "object") { + uriA = serialize2(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); + } + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize2(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true }); + } else if (typeof uriB === "object") { + uriB = serialize2(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); + } + return uriA.toLowerCase() === uriB.toLowerCase(); + } + function serialize2(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) { + component.path = component.path.split("%3A").join(":"); + } + } else { + component.path = unescape(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s6 = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s6 = removeDotSegments(s6); + } + if (authority === void 0 && s6[0] === "/" && s6[1] === "/") { + s6 = "/%2F" + s6.slice(2); + } + uriTokens.push(s6); + } + if (component.query !== void 0) { + uriTokens.push("?", component.query); + } + if (component.fragment !== void 0) { + uriTokens.push("#", component.fragment); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function parse(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e9) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e9; + } + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) { + parsed.scheme = unescape(parsed.scheme); + } + if (parsed.host !== void 0) { + parsed.host = unescape(parsed.host); + } + } + if (parsed.path) { + parsed.path = escape(unescape(parsed.path)); + } + if (parsed.fragment) { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return parsed; + } + var fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize: serialize2, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/uri.js +var require_uri = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// ../pi-mono/node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "../pi-mono/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util2(); + var $dataRefSchema = require_data(); + var uri_1 = require_uri(); + var defaultRegExp = (str2, flags) => new RegExp(str2, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o9) { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s6 = o9.strict; + const _optz = (_a7 = o9.code) === null || _a7 === void 0 ? void 0 : _a7.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o9.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o9.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e2 = o9.strictSchema) !== null && _e2 !== void 0 ? _e2 : s6) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o9.strictNumbers) !== null && _g !== void 0 ? _g : s6) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o9.strictTypes) !== null && _j !== void 0 ? _j : s6) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o9.strictTuples) !== null && _l !== void 0 ? _l : s6) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o9.strictRequired) !== null && _o !== void 0 ? _o : s6) !== null && _p !== void 0 ? _p : false, + code: o9.code ? { ...o9.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o9.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o9.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o9.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o9.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o9.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o9.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o9.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o9.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o9.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o9.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o9.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v4; + if (typeof schemaKeyRef == "string") { + v4 = this.getSchema(schemaKeyRef); + if (!v4) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v4 = this.compile(schemaKeyRef); + } + const valid = v4(data); + if (!("$async" in v4)) + this.errors = v4.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e9) { + if (!(e9 instanceof ref_error_1.default)) + throw e9; + checkLoaded.call(this, e9); + await loadMissingSchema.call(this, e9.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p4 = this._loading[ref]; + if (p4) + return p4; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t6) => addRule.call(this, k2, definition, t6))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i7 = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i7 >= 0) + group.rules.splice(i7, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e9) => `${dataVar}${e9.instancePath} ${e9.message}`).reduce((text3, msg) => text3 + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger2) { + if (logger2 === false) + return noLogs; + if (logger2 === void 0) + return console; + if (logger2.log && logger2.warn && logger2.error) + return logger2; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a7; + const post2 = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post2) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post2 ? RULES.post : RULES.rules.find(({ type: t6 }) => t6 === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a7 = definition.implements) === null || _a7 === void 0 ? void 0 : _a7.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i7 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i7 >= 0) { + ruleGroup.rules.splice(i7, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util2(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v4 = getValidate(cxt, sch); + callRef(cxt, v4, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v4, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v4, passCxt)}`); + addEvaluatedFrom(v4); + if (!allErrors) + gen.assign(valid, true); + }, (e9) => { + gen.if((0, codegen_1._)`!(${e9} instanceof ${it.ValidationError})`, () => gen.throw(e9)); + addErrorsFrom(e9); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v4, passCxt), () => addEvaluatedFrom(v4), () => addErrorsFrom(v4)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a7; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str2) { + const len = str2.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str2.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str2.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var ucs2length_1 = require_ucs2length(); + var error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op2 = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var util_1 = require_util2(); + var codegen_1 = require_codegen(); + var error = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u5 = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u5}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op2 = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op2 = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var equal_1 = require_equal(); + var error = { + message: ({ params: { i: i7, j: j3 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j3} and ${i7} are identical)`, + params: ({ params: { i: i7, j: j3 } }) => (0, codegen_1._)`{i: ${i7}, j: ${j3}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i7 = gen.let("i", (0, codegen_1._)`${data}.length`); + const j3 = gen.let("j"); + cxt.setParams({ i: i7, j: j3 }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i7} > 1`, () => (canOptimize() ? loopN : loopN2)(i7, j3)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t6) => t6 === "object" || t6 === "array"); + } + function loopN(i7, j3) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i7}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i7}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j3, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i7}`); + }); + } + function loopN2(i7, j3) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i7}--;`, () => gen.for((0, codegen_1._)`${j3} = ${i7}; ${j3}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i7}], ${data}[${j3}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var equal_1 = require_equal(); + var error = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var equal_1 = require_equal(); + var error = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i7) => equalCode(vSchema, i7))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v4) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v4})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i7) { + const sch = schema[i7]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i7}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum2(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i7) => { + cxt.subschema({ keyword, dataProp: i7, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i7) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i7}`, () => cxt.subschema({ + keyword, + schemaProp: i7, + dataProp: i7 + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l5 = schArr.length; + const fullTuple = l5 === sch.minItems && (l5 === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l5}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i7) => { + cxt.subschema({ + keyword: "contains", + dataProp: i7, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util2(); + var error = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p4) => (0, codegen_1._)`${key} === ${p4}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p4) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p4)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util2(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p4) => !(0, util_1.alwaysValidSchema)(it, schema[p4])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var util_2 = require_util2(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p4) => (0, util_1.alwaysValidSchema)(it, schema[p4])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i7) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i7, + compositeRule: true + }, schValid); + } + if (i7 > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i7}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i7); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i7) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i7 }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self2.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format(); + var format = [format_1.default]; + exports.default = format; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types2(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util2(); + var error = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a7; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i7 = 0; i7 < oneOf.length; i7++) { + let sch = oneOf[i7]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a7 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a7 === void 0 ? void 0 : _a7[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i7); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i7) { + if (sch.const) { + addMapping(sch.const, i7); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i7); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i7) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i7; + } + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { + module.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// ../pi-mono/node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "../pi-mono/node_modules/ajv/dist/ajv.js"(exports, module) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v4) => this.addVocabulary(v4)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv2; + module.exports = exports = Ajv2; + module.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// ../pi-mono/node_modules/ajv-formats/dist/formats.js +var require_formats = __commonJS({ + "../pi-mono/node_modules/ajv-formats/dist/formats.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { validate, compare }; + } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date(str2) { + const matches = DATE.exec(str2); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d22) { + if (!(d1 && d22)) + return void 0; + if (d1 > d22) + return 1; + if (d1 < d22) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str2) { + const matches = TIME.exec(str2); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min <= 59 && sec < 60) + return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s22) { + if (!(s1 && s22)) + return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf(); + if (!(t1 && t22)) + return void 0; + return t1 - t22; + } + function compareIsoTime(t1, t22) { + if (!(t1 && t22)) + return void 0; + const a1 = TIME.exec(t1); + const a22 = TIME.exec(t22); + if (!(a1 && a22)) + return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t22 = a22[1] + a22[2] + a22[3]; + if (t1 > t22) + return 1; + if (t1 < t22) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str2) { + const dateTime = str2.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d22 = new Date(dt2).valueOf(); + if (!(d1 && d22)) + return void 0; + return d1 - d22; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d22, t22] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d22); + if (res === void 0) + return void 0; + return res || compareTime(t1, t22); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str2) { + return NOT_URI_FRAGMENT.test(str2) && URI.test(str2); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str2) { + BYTE.lastIndex = 0; + return BYTE.test(str2); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str2) { + if (Z_ANCHOR.test(str2)) + return false; + try { + new RegExp(str2); + return true; + } catch (e9) { + return false; + } + } + } +}); + +// ../pi-mono/node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "../pi-mono/node_modules/ajv-formats/dist/limit.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self: self2 } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self2.formats[format]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv2) => { + ajv2.addKeyword(exports.formatLimitDefinition); + return ajv2; + }; + exports.default = formatLimitPlugin; + } +}); + +// ../pi-mono/node_modules/ajv-formats/dist/index.js +var require_dist2 = __commonJS({ + "../pi-mono/node_modules/ajv-formats/dist/index.js"(exports, module) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv2, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats2(ajv2, opts, formats_1.fullFormats, fullName); + return ajv2; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats2(ajv2, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv2); + return ajv2; + }; + formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f4 = formats[name]; + if (!f4) + throw new Error(`Unknown format "${name}"`); + return f4; + }; + function addFormats2(ajv2, list, fs, exportName) { + var _a7; + var _b; + (_a7 = (_b = ajv2.opts.code).formats) !== null && _a7 !== void 0 ? _a7 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f4 of list) + ajv2.addFormat(f4, fs[f4]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; + } +}); + +// ../pi-mono/node_modules/color-name/index.js +var require_color_name = __commonJS({ + "../pi-mono/node_modules/color-name/index.js"(exports, module) { + "use strict"; + init_process_shim(); + module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + } +}); + +// ../pi-mono/node_modules/color-convert/conversions.js +var require_conversions = __commonJS({ + "../pi-mono/node_modules/color-convert/conversions.js"(exports, module) { + init_process_shim(); + var cssKeywords = require_color_name(); + var reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + var convert = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + lch: { channels: 3, labels: "lch" }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } + }; + module.exports = convert; + for (const model of Object.keys(convert)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + const { channels, labels } = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); + } + convert.rgb.hsl = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const min = Math.min(r8, g3, b4); + const max = Math.max(r8, g3, b4); + const delta = max - min; + let h7; + let s6; + if (max === min) { + h7 = 0; + } else if (r8 === max) { + h7 = (g3 - b4) / delta; + } else if (g3 === max) { + h7 = 2 + (b4 - r8) / delta; + } else if (b4 === max) { + h7 = 4 + (r8 - g3) / delta; + } + h7 = Math.min(h7 * 60, 360); + if (h7 < 0) { + h7 += 360; + } + const l5 = (min + max) / 2; + if (max === min) { + s6 = 0; + } else if (l5 <= 0.5) { + s6 = delta / (max + min); + } else { + s6 = delta / (2 - max - min); + } + return [h7, s6 * 100, l5 * 100]; + }; + convert.rgb.hsv = function(rgb) { + let rdif; + let gdif; + let bdif; + let h7; + let s6; + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const v4 = Math.max(r8, g3, b4); + const diff = v4 - Math.min(r8, g3, b4); + const diffc = function(c6) { + return (v4 - c6) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h7 = 0; + s6 = 0; + } else { + s6 = diff / v4; + rdif = diffc(r8); + gdif = diffc(g3); + bdif = diffc(b4); + if (r8 === v4) { + h7 = bdif - gdif; + } else if (g3 === v4) { + h7 = 1 / 3 + rdif - bdif; + } else if (b4 === v4) { + h7 = 2 / 3 + gdif - rdif; + } + if (h7 < 0) { + h7 += 1; + } else if (h7 > 1) { + h7 -= 1; + } + } + return [ + h7 * 360, + s6 * 100, + v4 * 100 + ]; + }; + convert.rgb.hwb = function(rgb) { + const r8 = rgb[0]; + const g3 = rgb[1]; + let b4 = rgb[2]; + const h7 = convert.rgb.hsl(rgb)[0]; + const w3 = 1 / 255 * Math.min(r8, Math.min(g3, b4)); + b4 = 1 - 1 / 255 * Math.max(r8, Math.max(g3, b4)); + return [h7, w3 * 100, b4 * 100]; + }; + convert.rgb.cmyk = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const k2 = Math.min(1 - r8, 1 - g3, 1 - b4); + const c6 = (1 - r8 - k2) / (1 - k2) || 0; + const m4 = (1 - g3 - k2) / (1 - k2) || 0; + const y4 = (1 - b4 - k2) / (1 - k2) || 0; + return [c6 * 100, m4 * 100, y4 * 100, k2 * 100]; + }; + function comparativeDistance(x2, y4) { + return (x2[0] - y4[0]) ** 2 + (x2[1] - y4[1]) ** 2 + (x2[2] - y4[2]) ** 2; + } + convert.rgb.keyword = function(rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + let currentClosestDistance = Infinity; + let currentClosestKeyword; + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + const distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + return currentClosestKeyword; + }; + convert.keyword.rgb = function(keyword) { + return cssKeywords[keyword]; + }; + convert.rgb.xyz = function(rgb) { + let r8 = rgb[0] / 255; + let g3 = rgb[1] / 255; + let b4 = rgb[2] / 255; + r8 = r8 > 0.04045 ? ((r8 + 0.055) / 1.055) ** 2.4 : r8 / 12.92; + g3 = g3 > 0.04045 ? ((g3 + 0.055) / 1.055) ** 2.4 : g3 / 12.92; + b4 = b4 > 0.04045 ? ((b4 + 0.055) / 1.055) ** 2.4 : b4 / 12.92; + const x2 = r8 * 0.4124 + g3 * 0.3576 + b4 * 0.1805; + const y4 = r8 * 0.2126 + g3 * 0.7152 + b4 * 0.0722; + const z3 = r8 * 0.0193 + g3 * 0.1192 + b4 * 0.9505; + return [x2 * 100, y4 * 100, z3 * 100]; + }; + convert.rgb.lab = function(rgb) { + const xyz = convert.rgb.xyz(rgb); + let x2 = xyz[0]; + let y4 = xyz[1]; + let z3 = xyz[2]; + x2 /= 95.047; + y4 /= 100; + z3 /= 108.883; + x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116; + y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116; + z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116; + const l5 = 116 * y4 - 16; + const a3 = 500 * (x2 - y4); + const b4 = 200 * (y4 - z3); + return [l5, a3, b4]; + }; + convert.hsl.rgb = function(hsl) { + const h7 = hsl[0] / 360; + const s6 = hsl[1] / 100; + const l5 = hsl[2] / 100; + let t22; + let t32; + let val2; + if (s6 === 0) { + val2 = l5 * 255; + return [val2, val2, val2]; + } + if (l5 < 0.5) { + t22 = l5 * (1 + s6); + } else { + t22 = l5 + s6 - l5 * s6; + } + const t1 = 2 * l5 - t22; + const rgb = [0, 0, 0]; + for (let i7 = 0; i7 < 3; i7++) { + t32 = h7 + 1 / 3 * -(i7 - 1); + if (t32 < 0) { + t32++; + } + if (t32 > 1) { + t32--; + } + if (6 * t32 < 1) { + val2 = t1 + (t22 - t1) * 6 * t32; + } else if (2 * t32 < 1) { + val2 = t22; + } else if (3 * t32 < 2) { + val2 = t1 + (t22 - t1) * (2 / 3 - t32) * 6; + } else { + val2 = t1; + } + rgb[i7] = val2 * 255; + } + return rgb; + }; + convert.hsl.hsv = function(hsl) { + const h7 = hsl[0]; + let s6 = hsl[1] / 100; + let l5 = hsl[2] / 100; + let smin = s6; + const lmin = Math.max(l5, 0.01); + l5 *= 2; + s6 *= l5 <= 1 ? l5 : 2 - l5; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v4 = (l5 + s6) / 2; + const sv = l5 === 0 ? 2 * smin / (lmin + smin) : 2 * s6 / (l5 + s6); + return [h7, sv * 100, v4 * 100]; + }; + convert.hsv.rgb = function(hsv) { + const h7 = hsv[0] / 60; + const s6 = hsv[1] / 100; + let v4 = hsv[2] / 100; + const hi = Math.floor(h7) % 6; + const f4 = h7 - Math.floor(h7); + const p4 = 255 * v4 * (1 - s6); + const q2 = 255 * v4 * (1 - s6 * f4); + const t6 = 255 * v4 * (1 - s6 * (1 - f4)); + v4 *= 255; + switch (hi) { + case 0: + return [v4, t6, p4]; + case 1: + return [q2, v4, p4]; + case 2: + return [p4, v4, t6]; + case 3: + return [p4, q2, v4]; + case 4: + return [t6, p4, v4]; + case 5: + return [v4, p4, q2]; + } + }; + convert.hsv.hsl = function(hsv) { + const h7 = hsv[0]; + const s6 = hsv[1] / 100; + const v4 = hsv[2] / 100; + const vmin = Math.max(v4, 0.01); + let sl; + let l5; + l5 = (2 - s6) * v4; + const lmin = (2 - s6) * vmin; + sl = s6 * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l5 /= 2; + return [h7, sl * 100, l5 * 100]; + }; + convert.hwb.rgb = function(hwb) { + const h7 = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f4; + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + const i7 = Math.floor(6 * h7); + const v4 = 1 - bl; + f4 = 6 * h7 - i7; + if ((i7 & 1) !== 0) { + f4 = 1 - f4; + } + const n7 = wh + f4 * (v4 - wh); + let r8; + let g3; + let b4; + switch (i7) { + default: + case 6: + case 0: + r8 = v4; + g3 = n7; + b4 = wh; + break; + case 1: + r8 = n7; + g3 = v4; + b4 = wh; + break; + case 2: + r8 = wh; + g3 = v4; + b4 = n7; + break; + case 3: + r8 = wh; + g3 = n7; + b4 = v4; + break; + case 4: + r8 = n7; + g3 = wh; + b4 = v4; + break; + case 5: + r8 = v4; + g3 = wh; + b4 = n7; + break; + } + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.cmyk.rgb = function(cmyk) { + const c6 = cmyk[0] / 100; + const m4 = cmyk[1] / 100; + const y4 = cmyk[2] / 100; + const k2 = cmyk[3] / 100; + const r8 = 1 - Math.min(1, c6 * (1 - k2) + k2); + const g3 = 1 - Math.min(1, m4 * (1 - k2) + k2); + const b4 = 1 - Math.min(1, y4 * (1 - k2) + k2); + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.xyz.rgb = function(xyz) { + const x2 = xyz[0] / 100; + const y4 = xyz[1] / 100; + const z3 = xyz[2] / 100; + let r8; + let g3; + let b4; + r8 = x2 * 3.2406 + y4 * -1.5372 + z3 * -0.4986; + g3 = x2 * -0.9689 + y4 * 1.8758 + z3 * 0.0415; + b4 = x2 * 0.0557 + y4 * -0.204 + z3 * 1.057; + r8 = r8 > 31308e-7 ? 1.055 * r8 ** (1 / 2.4) - 0.055 : r8 * 12.92; + g3 = g3 > 31308e-7 ? 1.055 * g3 ** (1 / 2.4) - 0.055 : g3 * 12.92; + b4 = b4 > 31308e-7 ? 1.055 * b4 ** (1 / 2.4) - 0.055 : b4 * 12.92; + r8 = Math.min(Math.max(0, r8), 1); + g3 = Math.min(Math.max(0, g3), 1); + b4 = Math.min(Math.max(0, b4), 1); + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.xyz.lab = function(xyz) { + let x2 = xyz[0]; + let y4 = xyz[1]; + let z3 = xyz[2]; + x2 /= 95.047; + y4 /= 100; + z3 /= 108.883; + x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116; + y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116; + z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116; + const l5 = 116 * y4 - 16; + const a3 = 500 * (x2 - y4); + const b4 = 200 * (y4 - z3); + return [l5, a3, b4]; + }; + convert.lab.xyz = function(lab) { + const l5 = lab[0]; + const a3 = lab[1]; + const b4 = lab[2]; + let x2; + let y4; + let z3; + y4 = (l5 + 16) / 116; + x2 = a3 / 500 + y4; + z3 = y4 - b4 / 200; + const y22 = y4 ** 3; + const x22 = x2 ** 3; + const z22 = z3 ** 3; + y4 = y22 > 8856e-6 ? y22 : (y4 - 16 / 116) / 7.787; + x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787; + z3 = z22 > 8856e-6 ? z22 : (z3 - 16 / 116) / 7.787; + x2 *= 95.047; + y4 *= 100; + z3 *= 108.883; + return [x2, y4, z3]; + }; + convert.lab.lch = function(lab) { + const l5 = lab[0]; + const a3 = lab[1]; + const b4 = lab[2]; + let h7; + const hr = Math.atan2(b4, a3); + h7 = hr * 360 / 2 / Math.PI; + if (h7 < 0) { + h7 += 360; + } + const c6 = Math.sqrt(a3 * a3 + b4 * b4); + return [l5, c6, h7]; + }; + convert.lch.lab = function(lch) { + const l5 = lch[0]; + const c6 = lch[1]; + const h7 = lch[2]; + const hr = h7 / 360 * 2 * Math.PI; + const a3 = c6 * Math.cos(hr); + const b4 = c6 * Math.sin(hr); + return [l5, a3, b4]; + }; + convert.rgb.ansi16 = function(args, saturation = null) { + const [r8, g3, b4] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + let ansi = 30 + (Math.round(b4 / 255) << 2 | Math.round(g3 / 255) << 1 | Math.round(r8 / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; + }; + convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + convert.rgb.ansi256 = function(args) { + const r8 = args[0]; + const g3 = args[1]; + const b4 = args[2]; + if (r8 === g3 && g3 === b4) { + if (r8 < 8) { + return 16; + } + if (r8 > 248) { + return 231; + } + return Math.round((r8 - 8) / 247 * 24) + 232; + } + const ansi = 16 + 36 * Math.round(r8 / 255 * 5) + 6 * Math.round(g3 / 255 * 5) + Math.round(b4 / 255 * 5); + return ansi; + }; + convert.ansi16.rgb = function(args) { + let color = args % 10; + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + color = color / 10.5 * 255; + return [color, color, color]; + } + const mult = (~~(args > 50) + 1) * 0.5; + const r8 = (color & 1) * mult * 255; + const g3 = (color >> 1 & 1) * mult * 255; + const b4 = (color >> 2 & 1) * mult * 255; + return [r8, g3, b4]; + }; + convert.ansi256.rgb = function(args) { + if (args >= 232) { + const c6 = (args - 232) * 10 + 8; + return [c6, c6, c6]; + } + args -= 16; + let rem; + const r8 = Math.floor(args / 36) / 5 * 255; + const g3 = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b4 = rem % 6 / 5 * 255; + return [r8, g3, b4]; + }; + convert.rgb.hex = function(args) { + const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + const string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.hex.rgb = function(args) { + const match2 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match2) { + return [0, 0, 0]; + } + let colorString = match2[0]; + if (match2[0].length === 3) { + colorString = colorString.split("").map((char) => { + return char + char; + }).join(""); + } + const integer = parseInt(colorString, 16); + const r8 = integer >> 16 & 255; + const g3 = integer >> 8 & 255; + const b4 = integer & 255; + return [r8, g3, b4]; + }; + convert.rgb.hcg = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const max = Math.max(Math.max(r8, g3), b4); + const min = Math.min(Math.min(r8, g3), b4); + const chroma = max - min; + let grayscale; + let hue; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + if (chroma <= 0) { + hue = 0; + } else if (max === r8) { + hue = (g3 - b4) / chroma % 6; + } else if (max === g3) { + hue = 2 + (b4 - r8) / chroma; + } else { + hue = 4 + (r8 - g3) / chroma; + } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + convert.hsl.hcg = function(hsl) { + const s6 = hsl[1] / 100; + const l5 = hsl[2] / 100; + const c6 = l5 < 0.5 ? 2 * s6 * l5 : 2 * s6 * (1 - l5); + let f4 = 0; + if (c6 < 1) { + f4 = (l5 - 0.5 * c6) / (1 - c6); + } + return [hsl[0], c6 * 100, f4 * 100]; + }; + convert.hsv.hcg = function(hsv) { + const s6 = hsv[1] / 100; + const v4 = hsv[2] / 100; + const c6 = s6 * v4; + let f4 = 0; + if (c6 < 1) { + f4 = (v4 - c6) / (1 - c6); + } + return [hsv[0], c6 * 100, f4 * 100]; + }; + convert.hcg.rgb = function(hcg) { + const h7 = hcg[0] / 360; + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + if (c6 === 0) { + return [g3 * 255, g3 * 255, g3 * 255]; + } + const pure = [0, 0, 0]; + const hi = h7 % 1 * 6; + const v4 = hi % 1; + const w3 = 1 - v4; + let mg = 0; + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v4; + pure[2] = 0; + break; + case 1: + pure[0] = w3; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v4; + break; + case 3: + pure[0] = 0; + pure[1] = w3; + pure[2] = 1; + break; + case 4: + pure[0] = v4; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w3; + } + mg = (1 - c6) * g3; + return [ + (c6 * pure[0] + mg) * 255, + (c6 * pure[1] + mg) * 255, + (c6 * pure[2] + mg) * 255 + ]; + }; + convert.hcg.hsv = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const v4 = c6 + g3 * (1 - c6); + let f4 = 0; + if (v4 > 0) { + f4 = c6 / v4; + } + return [hcg[0], f4 * 100, v4 * 100]; + }; + convert.hcg.hsl = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const l5 = g3 * (1 - c6) + 0.5 * c6; + let s6 = 0; + if (l5 > 0 && l5 < 0.5) { + s6 = c6 / (2 * l5); + } else if (l5 >= 0.5 && l5 < 1) { + s6 = c6 / (2 * (1 - l5)); + } + return [hcg[0], s6 * 100, l5 * 100]; + }; + convert.hcg.hwb = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const v4 = c6 + g3 * (1 - c6); + return [hcg[0], (v4 - c6) * 100, (1 - v4) * 100]; + }; + convert.hwb.hcg = function(hwb) { + const w3 = hwb[1] / 100; + const b4 = hwb[2] / 100; + const v4 = 1 - b4; + const c6 = v4 - w3; + let g3 = 0; + if (c6 < 1) { + g3 = (v4 - c6) / (1 - c6); + } + return [hwb[0], c6 * 100, g3 * 100]; + }; + convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + convert.gray.hsl = function(args) { + return [0, 0, args[0]]; + }; + convert.gray.hsv = convert.gray.hsl; + convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; + }; + convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; + }; + convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; + }; + convert.gray.hex = function(gray) { + const val2 = Math.round(gray[0] / 100 * 255) & 255; + const integer = (val2 << 16) + (val2 << 8) + val2; + const string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.rgb.gray = function(rgb) { + const val2 = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val2 / 255 * 100]; + }; + } +}); + +// ../pi-mono/node_modules/color-convert/route.js +var require_route = __commonJS({ + "../pi-mono/node_modules/color-convert/route.js"(exports, module) { + init_process_shim(); + var conversions2 = require_conversions(); + function buildGraph() { + const graph = {}; + const models2 = Object.keys(conversions2); + for (let len = models2.length, i7 = 0; i7 < len; i7++) { + graph[models2[i7]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; + } + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length) { + const current2 = queue.pop(); + const adjacents = Object.keys(conversions2[current2]); + for (let len = adjacents.length, i7 = 0; i7 < len; i7++) { + const adjacent = adjacents[i7]; + const node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current2].distance + 1; + node.parent = current2; + queue.unshift(adjacent); + } + } + } + return graph; + } + function link(from, to) { + return function(args) { + return to(from(args)); + }; + } + function wrapConversion(toModel, graph) { + const path6 = [graph[toModel].parent, toModel]; + let fn = conversions2[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path6.unshift(graph[cur].parent); + fn = link(conversions2[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path6; + return fn; + } + module.exports = function(fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + const models2 = Object.keys(graph); + for (let len = models2.length, i7 = 0; i7 < len; i7++) { + const toModel = models2[i7]; + const node = graph[toModel]; + if (node.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; + }; + } +}); + +// ../pi-mono/node_modules/color-convert/index.js +var require_color_convert = __commonJS({ + "../pi-mono/node_modules/color-convert/index.js"(exports, module) { + init_process_shim(); + var conversions2 = require_conversions(); + var route2 = require_route(); + var convert = {}; + var models2 = Object.keys(conversions2); + function wrapRaw(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + return fn(args); + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; + } + function wrapRounded(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + const result = fn(args); + if (typeof result === "object") { + for (let len = result.length, i7 = 0; i7 < len; i7++) { + result[i7] = Math.round(result[i7]); + } + } + return result; + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; + } + models2.forEach((fromModel) => { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels }); + Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels }); + const routes = route2(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach((toModel) => { + const fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + module.exports = convert; + } +}); + +// ../pi-mono/node_modules/ansi-styles/index.js +var require_ansi_styles = __commonJS({ + "../pi-mono/node_modules/ansi-styles/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\x1B[${code + offset}m`; + }; + var wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\x1B[${38 + offset};5;${code}m`; + }; + var wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + var ansi2ansi = (n7) => n7; + var rgb2rgb = (r8, g3, b4) => [r8, g3, b4]; + var setLazyProperty = (object, property, get3) => { + Object.defineProperty(object, property, { + get: () => { + const value = get3(); + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + return value; + }, + enumerable: true, + configurable: true + }); + }; + var colorConvert2; + var makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert2 === void 0) { + colorConvert2 = require_color_convert(); + } + const offset = isBackground ? 10 : 0; + const styles2 = {}; + for (const [sourceSpace, suite] of Object.entries(colorConvert2)) { + const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace; + if (sourceSpace === targetSpace) { + styles2[name] = wrap(identity, offset); + } else if (typeof suite === "object") { + styles2[name] = wrap(suite[targetSpace], offset); + } + } + return styles2; + }; + function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + const styles2 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + styles2.color.gray = styles2.color.blackBright; + styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; + styles2.color.grey = styles2.color.blackBright; + styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; + for (const [groupName, group] of Object.entries(styles2)) { + for (const [styleName, style] of Object.entries(group)) { + styles2[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m` + }; + group[styleName] = styles2[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles2, groupName, { + value: group, + enumerable: false + }); + } + Object.defineProperty(styles2, "codes", { + value: codes, + enumerable: false + }); + styles2.color.close = "\x1B[39m"; + styles2.bgColor.close = "\x1B[49m"; + setLazyProperty(styles2.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false)); + setLazyProperty(styles2.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false)); + setLazyProperty(styles2.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false)); + setLazyProperty(styles2.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true)); + setLazyProperty(styles2.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true)); + setLazyProperty(styles2.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true)); + return styles2; + } + Object.defineProperty(module, "exports", { + enumerable: true, + get: assembleStyles + }); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/supports-color/browser.js +var require_browser = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/supports-color/browser.js"(exports, module) { + "use strict"; + init_process_shim(); + module.exports = { + stdout: false, + stderr: false + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/util.js +var require_util3 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/util.js"(exports, module) { + "use strict"; + init_process_shim(); + var stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ""; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + returnValue += string.substr(endIndex); + return returnValue; + }; + var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ""; + do { + const gotCR = string[index - 1] === "\r"; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix; + endIndex = index + 1; + index = string.indexOf("\n", endIndex); + } while (index !== -1); + returnValue += string.substr(endIndex); + return returnValue; + }; + module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/templates.js +var require_templates = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/templates.js"(exports, module) { + "use strict"; + init_process_shim(); + var TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + var ESCAPE_REGEX2 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + var ESCAPES = /* @__PURE__ */ new Map([ + ["n", "\n"], + ["r", "\r"], + ["t", " "], + ["b", "\b"], + ["f", "\f"], + ["v", "\v"], + ["0", "\0"], + ["\\", "\\"], + ["e", "\x1B"], + ["a", "\x07"] + ]); + function unescape3(c6) { + const u5 = c6[0] === "u"; + const bracket = c6[1] === "{"; + if (u5 && !bracket && c6.length === 5 || c6[0] === "x" && c6.length === 3) { + return String.fromCharCode(parseInt(c6.slice(1), 16)); + } + if (u5 && bracket) { + return String.fromCodePoint(parseInt(c6.slice(2, -1), 16)); + } + return ESCAPES.get(c6) || c6; + } + function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX2, (m4, escape4, character) => escape4 ? unescape3(escape4) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + return results; + } + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + const results = []; + let matches; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + return results; + } + function buildStyle(chalk2, styles2) { + const enabled = {}; + for (const layer of styles2) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + let current2 = chalk2; + for (const [styleName, styles3] of Object.entries(enabled)) { + if (!Array.isArray(styles3)) { + continue; + } + if (!(styleName in current2)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + current2 = styles3.length > 0 ? current2[styleName](...styles3) : current2[styleName]; + } + return current2; + } + module.exports = (chalk2, temporary) => { + const styles2 = []; + const chunks = []; + let chunk = []; + temporary.replace(TEMPLATE_REGEX, (m4, escapeCharacter, inverse, style, close2, character) => { + if (escapeCharacter) { + chunk.push(unescape3(escapeCharacter)); + } else if (style) { + const string = chunk.join(""); + chunk = []; + chunks.push(styles2.length === 0 ? string : buildStyle(chalk2, styles2)(string)); + styles2.push({ inverse, styles: parseStyle(style) }); + } else if (close2) { + if (styles2.length === 0) { + throw new Error("Found extraneous } in Chalk template literal"); + } + chunks.push(buildStyle(chalk2, styles2)(chunk.join(""))); + chunk = []; + styles2.pop(); + } else { + chunk.push(character); + } + }); + chunks.push(chunk.join("")); + if (styles2.length > 0) { + const errMessage = `Chalk template literal is missing ${styles2.length} closing bracket${styles2.length === 1 ? "" : "s"} (\`}\`)`; + throw new Error(errMessage); + } + return chunks.join(""); + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/index.js +var require_source2 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var ansiStyles2 = require_ansi_styles(); + var { stdout: stdoutColor, stderr: stderrColor } = require_browser(); + var { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + } = require_util3(); + var { isArray: isArray5 } = Array; + var levelMapping = [ + "ansi", + "ansi", + "ansi256", + "ansi16m" + ]; + var styles2 = /* @__PURE__ */ Object.create(null); + var applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error("The `level` option should be an integer from 0 to 3"); + } + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === void 0 ? colorLevel : options.level; + }; + var ChalkClass = class { + constructor(options) { + return chalkFactory(options); + } + }; + var chalkFactory = (options) => { + const chalk3 = {}; + applyOptions(chalk3, options); + chalk3.template = (...arguments_) => chalkTag(chalk3.template, ...arguments_); + Object.setPrototypeOf(chalk3, Chalk.prototype); + Object.setPrototypeOf(chalk3.template, chalk3); + chalk3.template.constructor = () => { + throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead."); + }; + chalk3.template.Instance = ChalkClass; + return chalk3.template; + }; + function Chalk(options) { + return chalkFactory(options); + } + for (const [styleName, style] of Object.entries(ansiStyles2)) { + styles2[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, { value: builder }); + return builder; + } + }; + } + styles2.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, "visible", { value: builder }); + return builder; + } + }; + var usedModels = ["rgb", "hex", "keyword", "hsl", "hsv", "hwb", "ansi", "ansi256"]; + for (const model of usedModels) { + styles2[model] = { + get() { + const { level } = this; + return function(...arguments_) { + const styler = createStyler(ansiStyles2.color[levelMapping[level]][model](...arguments_), ansiStyles2.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; + } + for (const model of usedModels) { + const bgModel = "bg" + model[0].toUpperCase() + model.slice(1); + styles2[bgModel] = { + get() { + const { level } = this; + return function(...arguments_) { + const styler = createStyler(ansiStyles2.bgColor[levelMapping[level]][model](...arguments_), ansiStyles2.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; + } + var proto = Object.defineProperties(() => { + }, { + ...styles2, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } + }); + var createStyler = (open2, close2, parent) => { + let openAll; + let closeAll; + if (parent === void 0) { + openAll = open2; + closeAll = close2; + } else { + openAll = parent.openAll + open2; + closeAll = close2 + parent.closeAll; + } + return { + open: open2, + close: close2, + openAll, + closeAll, + parent + }; + }; + var createBuilder = (self2, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray5(arguments_[0]) && isArray5(arguments_[0].raw)) { + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + return applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")); + }; + Object.setPrototypeOf(builder, proto); + builder._generator = self2; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + return builder; + }; + var applyStyle = (self2, string) => { + if (self2.level <= 0 || !string) { + return self2._isEmpty ? "" : string; + } + let styler = self2._styler; + if (styler === void 0) { + return string; + } + const { openAll, closeAll } = styler; + if (string.indexOf("\x1B") !== -1) { + while (styler !== void 0) { + string = stringReplaceAll(string, styler.close, styler.open); + styler = styler.parent; + } + } + const lfIndex = string.indexOf("\n"); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + return openAll + string + closeAll; + }; + var template; + var chalkTag = (chalk3, ...strings) => { + const [firstString] = strings; + if (!isArray5(firstString) || !isArray5(firstString.raw)) { + return strings.join(" "); + } + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + for (let i7 = 1; i7 < firstString.length; i7++) { + parts.push( + String(arguments_[i7 - 1]).replace(/[{}\\]/g, "\\$&"), + String(firstString.raw[i7]) + ); + } + if (template === void 0) { + template = require_templates(); + } + return template(chalk3, parts.join("")); + }; + Object.defineProperties(Chalk.prototype, styles2); + var chalk2 = Chalk(); + chalk2.supportsColor = stdoutColor; + chalk2.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 }); + chalk2.stderr.supportsColor = stderrColor; + module.exports = chalk2; + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/generateRandomBase64.js +var require_generateRandomBase64 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/generateRandomBase64.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.generateRandomBase64 = generateRandomBase642; + function generateRandomBase642(bytesOfRandomness = 18) { + const randomBytes = new Uint8Array(bytesOfRandomness); + globalThis.crypto.getRandomValues(randomBytes); + return btoa(String.fromCharCode(...randomBytes)); + } + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/readFileAsBase64.js +var require_readFileAsBase64 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/readFileAsBase64.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readFileAsBase64 = readFileAsBase642; + async function readFileAsBase642(_path) { + return { success: false }; + } + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/terminalSize.js +var require_terminalSize = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/terminalSize.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.terminalSize = terminalSize2; + function terminalSize2() { + return { columns: 80, rows: 24 }; + } + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/WebSocket.js +var require_WebSocket = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/WebSocket.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocket = void 0; + exports.WebSocket = globalThis.WebSocket; + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser.js +var require_browser2 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocket = exports.terminalSize = exports.readFileAsBase64 = exports.generateRandomBase64 = void 0; + var generateRandomBase64_js_1 = require_generateRandomBase64(); + Object.defineProperty(exports, "generateRandomBase64", { enumerable: true, get: function() { + return generateRandomBase64_js_1.generateRandomBase64; + } }); + var readFileAsBase64_js_1 = require_readFileAsBase64(); + Object.defineProperty(exports, "readFileAsBase64", { enumerable: true, get: function() { + return readFileAsBase64_js_1.readFileAsBase64; + } }); + var terminalSize_js_1 = require_terminalSize(); + Object.defineProperty(exports, "terminalSize", { enumerable: true, get: function() { + return terminalSize_js_1.terminalSize; + } }); + var WebSocket_js_1 = require_WebSocket(); + Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function() { + return WebSocket_js_1.WebSocket; + } }); + } +}); + +// ../pi-mono/node_modules/jszip/dist/jszip.min.js +var require_jszip_min = __commonJS({ + "../pi-mono/node_modules/jszip/dist/jszip.min.js"(exports, module) { + init_process_shim(); + !(function(e9) { + if ("object" == typeof exports && "undefined" != typeof module) module.exports = e9(); + else if ("function" == typeof define && define.amd) define([], e9); + else { + ("undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : this).JSZip = e9(); + } + })(function() { + return (function s6(a3, o9, h7) { + function u5(r8, e10) { + if (!o9[r8]) { + if (!a3[r8]) { + var t6 = "function" == typeof __require && __require; + if (!e10 && t6) return t6(r8, true); + if (l5) return l5(r8, true); + var n7 = new Error("Cannot find module '" + r8 + "'"); + throw n7.code = "MODULE_NOT_FOUND", n7; + } + var i7 = o9[r8] = { exports: {} }; + a3[r8][0].call(i7.exports, function(e11) { + var t7 = a3[r8][1][e11]; + return u5(t7 || e11); + }, i7, i7.exports, s6, a3, o9, h7); + } + return o9[r8].exports; + } + for (var l5 = "function" == typeof __require && __require, e9 = 0; e9 < h7.length; e9++) u5(h7[e9]); + return u5; + })({ 1: [function(e9, t6, r8) { + "use strict"; + var d4 = e9("./utils"), c6 = e9("./support"), p4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + r8.encode = function(e10) { + for (var t7, r9, n7, i7, s6, a3, o9, h7 = [], u5 = 0, l5 = e10.length, f4 = l5, c7 = "string" !== d4.getTypeOf(e10); u5 < e10.length; ) f4 = l5 - u5, n7 = c7 ? (t7 = e10[u5++], r9 = u5 < l5 ? e10[u5++] : 0, u5 < l5 ? e10[u5++] : 0) : (t7 = e10.charCodeAt(u5++), r9 = u5 < l5 ? e10.charCodeAt(u5++) : 0, u5 < l5 ? e10.charCodeAt(u5++) : 0), i7 = t7 >> 2, s6 = (3 & t7) << 4 | r9 >> 4, a3 = 1 < f4 ? (15 & r9) << 2 | n7 >> 6 : 64, o9 = 2 < f4 ? 63 & n7 : 64, h7.push(p4.charAt(i7) + p4.charAt(s6) + p4.charAt(a3) + p4.charAt(o9)); + return h7.join(""); + }, r8.decode = function(e10) { + var t7, r9, n7, i7, s6, a3, o9 = 0, h7 = 0, u5 = "data:"; + if (e10.substr(0, u5.length) === u5) throw new Error("Invalid base64 input, it looks like a data url."); + var l5, f4 = 3 * (e10 = e10.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4; + if (e10.charAt(e10.length - 1) === p4.charAt(64) && f4--, e10.charAt(e10.length - 2) === p4.charAt(64) && f4--, f4 % 1 != 0) throw new Error("Invalid base64 input, bad content length."); + for (l5 = c6.uint8array ? new Uint8Array(0 | f4) : new Array(0 | f4); o9 < e10.length; ) t7 = p4.indexOf(e10.charAt(o9++)) << 2 | (i7 = p4.indexOf(e10.charAt(o9++))) >> 4, r9 = (15 & i7) << 4 | (s6 = p4.indexOf(e10.charAt(o9++))) >> 2, n7 = (3 & s6) << 6 | (a3 = p4.indexOf(e10.charAt(o9++))), l5[h7++] = t7, 64 !== s6 && (l5[h7++] = r9), 64 !== a3 && (l5[h7++] = n7); + return l5; + }; + }, { "./support": 30, "./utils": 32 }], 2: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./external"), i7 = e9("./stream/DataWorker"), s6 = e9("./stream/Crc32Probe"), a3 = e9("./stream/DataLengthProbe"); + function o9(e10, t7, r9, n8, i8) { + this.compressedSize = e10, this.uncompressedSize = t7, this.crc32 = r9, this.compression = n8, this.compressedContent = i8; + } + o9.prototype = { getContentWorker: function() { + var e10 = new i7(n7.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a3("data_length")), t7 = this; + return e10.on("end", function() { + if (this.streamInfo.data_length !== t7.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch"); + }), e10; + }, getCompressedWorker: function() { + return new i7(n7.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } }, o9.createWorkerFrom = function(e10, t7, r9) { + return e10.pipe(new s6()).pipe(new a3("uncompressedSize")).pipe(t7.compressWorker(r9)).pipe(new a3("compressedSize")).withStreamInfo("compression", t7); + }, t6.exports = o9; + }, { "./external": 6, "./stream/Crc32Probe": 25, "./stream/DataLengthProbe": 26, "./stream/DataWorker": 27 }], 3: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./stream/GenericWorker"); + r8.STORE = { magic: "\0\0", compressWorker: function() { + return new n7("STORE compression"); + }, uncompressWorker: function() { + return new n7("STORE decompression"); + } }, r8.DEFLATE = e9("./flate"); + }, { "./flate": 7, "./stream/GenericWorker": 28 }], 4: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./utils"); + var o9 = (function() { + for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) { + e10 = r9; + for (var n8 = 0; n8 < 8; n8++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1; + t7[r9] = e10; + } + return t7; + })(); + t6.exports = function(e10, t7) { + return void 0 !== e10 && e10.length ? "string" !== n7.getTypeOf(e10) ? (function(e11, t8, r9, n8) { + var i7 = o9, s6 = n8 + r9; + e11 ^= -1; + for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8[a3])]; + return -1 ^ e11; + })(0 | t7, e10, e10.length, 0) : (function(e11, t8, r9, n8) { + var i7 = o9, s6 = n8 + r9; + e11 ^= -1; + for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8.charCodeAt(a3))]; + return -1 ^ e11; + })(0 | t7, e10, e10.length, 0) : 0; + }; + }, { "./utils": 32 }], 5: [function(e9, t6, r8) { + "use strict"; + r8.base64 = false, r8.binary = false, r8.dir = false, r8.createFolders = true, r8.date = null, r8.compression = null, r8.compressionOptions = null, r8.comment = null, r8.unixPermissions = null, r8.dosPermissions = null; + }, {}], 6: [function(e9, t6, r8) { + "use strict"; + var n7 = null; + n7 = "undefined" != typeof Promise ? Promise : e9("lie"), t6.exports = { Promise: n7 }; + }, { lie: 37 }], 7: [function(e9, t6, r8) { + "use strict"; + var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i7 = e9("pako"), s6 = e9("./utils"), a3 = e9("./stream/GenericWorker"), o9 = n7 ? "uint8array" : "array"; + function h7(e10, t7) { + a3.call(this, "FlateWorker/" + e10), this._pako = null, this._pakoAction = e10, this._pakoOptions = t7, this.meta = {}; + } + r8.magic = "\b\0", s6.inherits(h7, a3), h7.prototype.processChunk = function(e10) { + this.meta = e10.meta, null === this._pako && this._createPako(), this._pako.push(s6.transformTo(o9, e10.data), false); + }, h7.prototype.flush = function() { + a3.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], true); + }, h7.prototype.cleanUp = function() { + a3.prototype.cleanUp.call(this), this._pako = null; + }, h7.prototype._createPako = function() { + this._pako = new i7[this._pakoAction]({ raw: true, level: this._pakoOptions.level || -1 }); + var t7 = this; + this._pako.onData = function(e10) { + t7.push({ data: e10, meta: t7.meta }); + }; + }, r8.compressWorker = function(e10) { + return new h7("Deflate", e10); + }, r8.uncompressWorker = function() { + return new h7("Inflate", {}); + }; + }, { "./stream/GenericWorker": 28, "./utils": 32, pako: 38 }], 8: [function(e9, t6, r8) { + "use strict"; + function A2(e10, t7) { + var r9, n8 = ""; + for (r9 = 0; r9 < t7; r9++) n8 += String.fromCharCode(255 & e10), e10 >>>= 8; + return n8; + } + function n7(e10, t7, r9, n8, i8, s7) { + var a3, o9, h7 = e10.file, u5 = e10.compression, l5 = s7 !== O2.utf8encode, f4 = I3.transformTo("string", s7(h7.name)), c6 = I3.transformTo("string", O2.utf8encode(h7.name)), d4 = h7.comment, p4 = I3.transformTo("string", s7(d4)), m4 = I3.transformTo("string", O2.utf8encode(d4)), _3 = c6.length !== h7.name.length, g3 = m4.length !== d4.length, b4 = "", v4 = "", y4 = "", w3 = h7.dir, k2 = h7.date, x2 = { crc32: 0, compressedSize: 0, uncompressedSize: 0 }; + t7 && !r9 || (x2.crc32 = e10.crc32, x2.compressedSize = e10.compressedSize, x2.uncompressedSize = e10.uncompressedSize); + var S5 = 0; + t7 && (S5 |= 8), l5 || !_3 && !g3 || (S5 |= 2048); + var z3 = 0, C3 = 0; + w3 && (z3 |= 16), "UNIX" === i8 ? (C3 = 798, z3 |= (function(e11, t8) { + var r10 = e11; + return e11 || (r10 = t8 ? 16893 : 33204), (65535 & r10) << 16; + })(h7.unixPermissions, w3)) : (C3 = 20, z3 |= (function(e11) { + return 63 & (e11 || 0); + })(h7.dosPermissions)), a3 = k2.getUTCHours(), a3 <<= 6, a3 |= k2.getUTCMinutes(), a3 <<= 5, a3 |= k2.getUTCSeconds() / 2, o9 = k2.getUTCFullYear() - 1980, o9 <<= 4, o9 |= k2.getUTCMonth() + 1, o9 <<= 5, o9 |= k2.getUTCDate(), _3 && (v4 = A2(1, 1) + A2(B3(f4), 4) + c6, b4 += "up" + A2(v4.length, 2) + v4), g3 && (y4 = A2(1, 1) + A2(B3(p4), 4) + m4, b4 += "uc" + A2(y4.length, 2) + y4); + var E3 = ""; + return E3 += "\n\0", E3 += A2(S5, 2), E3 += u5.magic, E3 += A2(a3, 2), E3 += A2(o9, 2), E3 += A2(x2.crc32, 4), E3 += A2(x2.compressedSize, 4), E3 += A2(x2.uncompressedSize, 4), E3 += A2(f4.length, 2), E3 += A2(b4.length, 2), { fileRecord: R3.LOCAL_FILE_HEADER + E3 + f4 + b4, dirRecord: R3.CENTRAL_FILE_HEADER + A2(C3, 2) + E3 + A2(p4.length, 2) + "\0\0\0\0" + A2(z3, 4) + A2(n8, 4) + f4 + b4 + p4 }; + } + var I3 = e9("../utils"), i7 = e9("../stream/GenericWorker"), O2 = e9("../utf8"), B3 = e9("../crc32"), R3 = e9("../signature"); + function s6(e10, t7, r9, n8) { + i7.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t7, this.zipPlatform = r9, this.encodeFileName = n8, this.streamFiles = e10, this.accumulate = false, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = []; + } + I3.inherits(s6, i7), s6.prototype.push = function(e10) { + var t7 = e10.meta.percent || 0, r9 = this.entriesCount, n8 = this._sources.length; + this.accumulate ? this.contentBuffer.push(e10) : (this.bytesWritten += e10.data.length, i7.prototype.push.call(this, { data: e10.data, meta: { currentFile: this.currentFile, percent: r9 ? (t7 + 100 * (r9 - n8 - 1)) / r9 : 100 } })); + }, s6.prototype.openedSource = function(e10) { + this.currentSourceOffset = this.bytesWritten, this.currentFile = e10.file.name; + var t7 = this.streamFiles && !e10.file.dir; + if (t7) { + var r9 = n7(e10, t7, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ data: r9.fileRecord, meta: { percent: 0 } }); + } else this.accumulate = true; + }, s6.prototype.closedSource = function(e10) { + this.accumulate = false; + var t7 = this.streamFiles && !e10.file.dir, r9 = n7(e10, t7, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + if (this.dirRecords.push(r9.dirRecord), t7) this.push({ data: (function(e11) { + return R3.DATA_DESCRIPTOR + A2(e11.crc32, 4) + A2(e11.compressedSize, 4) + A2(e11.uncompressedSize, 4); + })(e10), meta: { percent: 100 } }); + else for (this.push({ data: r9.fileRecord, meta: { percent: 0 } }); this.contentBuffer.length; ) this.push(this.contentBuffer.shift()); + this.currentFile = null; + }, s6.prototype.flush = function() { + for (var e10 = this.bytesWritten, t7 = 0; t7 < this.dirRecords.length; t7++) this.push({ data: this.dirRecords[t7], meta: { percent: 100 } }); + var r9 = this.bytesWritten - e10, n8 = (function(e11, t8, r10, n9, i8) { + var s7 = I3.transformTo("string", i8(n9)); + return R3.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A2(e11, 2) + A2(e11, 2) + A2(t8, 4) + A2(r10, 4) + A2(s7.length, 2) + s7; + })(this.dirRecords.length, r9, e10, this.zipComment, this.encodeFileName); + this.push({ data: n8, meta: { percent: 100 } }); + }, s6.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume(); + }, s6.prototype.registerPrevious = function(e10) { + this._sources.push(e10); + var t7 = this; + return e10.on("data", function(e11) { + t7.processChunk(e11); + }), e10.on("end", function() { + t7.closedSource(t7.previous.streamInfo), t7._sources.length ? t7.prepareNextSource() : t7.end(); + }), e10.on("error", function(e11) { + t7.error(e11); + }), this; + }, s6.prototype.resume = function() { + return !!i7.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), true) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), true)); + }, s6.prototype.error = function(e10) { + var t7 = this._sources; + if (!i7.prototype.error.call(this, e10)) return false; + for (var r9 = 0; r9 < t7.length; r9++) try { + t7[r9].error(e10); + } catch (e11) { + } + return true; + }, s6.prototype.lock = function() { + i7.prototype.lock.call(this); + for (var e10 = this._sources, t7 = 0; t7 < e10.length; t7++) e10[t7].lock(); + }, t6.exports = s6; + }, { "../crc32": 4, "../signature": 23, "../stream/GenericWorker": 28, "../utf8": 31, "../utils": 32 }], 9: [function(e9, t6, r8) { + "use strict"; + var u5 = e9("../compressions"), n7 = e9("./ZipFileWorker"); + r8.generateWorker = function(e10, a3, t7) { + var o9 = new n7(a3.streamFiles, t7, a3.platform, a3.encodeFileName), h7 = 0; + try { + e10.forEach(function(e11, t8) { + h7++; + var r9 = (function(e12, t9) { + var r10 = e12 || t9, n9 = u5[r10]; + if (!n9) throw new Error(r10 + " is not a valid compression method !"); + return n9; + })(t8.options.compression, a3.compression), n8 = t8.options.compressionOptions || a3.compressionOptions || {}, i7 = t8.dir, s6 = t8.date; + t8._compressWorker(r9, n8).withStreamInfo("file", { name: e11, dir: i7, date: s6, comment: t8.comment || "", unixPermissions: t8.unixPermissions, dosPermissions: t8.dosPermissions }).pipe(o9); + }), o9.entriesCount = h7; + } catch (e11) { + o9.error(e11); + } + return o9; + }; + }, { "../compressions": 3, "./ZipFileWorker": 8 }], 10: [function(e9, t6, r8) { + "use strict"; + function n7() { + if (!(this instanceof n7)) return new n7(); + if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + this.files = /* @__PURE__ */ Object.create(null), this.comment = null, this.root = "", this.clone = function() { + var e10 = new n7(); + for (var t7 in this) "function" != typeof this[t7] && (e10[t7] = this[t7]); + return e10; + }; + } + (n7.prototype = e9("./object")).loadAsync = e9("./load"), n7.support = e9("./support"), n7.defaults = e9("./defaults"), n7.version = "3.10.1", n7.loadAsync = function(e10, t7) { + return new n7().loadAsync(e10, t7); + }, n7.external = e9("./external"), t6.exports = n7; + }, { "./defaults": 5, "./external": 6, "./load": 11, "./object": 15, "./support": 30 }], 11: [function(e9, t6, r8) { + "use strict"; + var u5 = e9("./utils"), i7 = e9("./external"), n7 = e9("./utf8"), s6 = e9("./zipEntries"), a3 = e9("./stream/Crc32Probe"), l5 = e9("./nodejsUtils"); + function f4(n8) { + return new i7.Promise(function(e10, t7) { + var r9 = n8.decompressed.getContentWorker().pipe(new a3()); + r9.on("error", function(e11) { + t7(e11); + }).on("end", function() { + r9.streamInfo.crc32 !== n8.decompressed.crc32 ? t7(new Error("Corrupted zip : CRC32 mismatch")) : e10(); + }).resume(); + }); + } + t6.exports = function(e10, o9) { + var h7 = this; + return o9 = u5.extend(o9 || {}, { base64: false, checkCRC32: false, optimizedBinaryString: false, createFolders: false, decodeFileName: n7.utf8decode }), l5.isNode && l5.isStream(e10) ? i7.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")) : u5.prepareContent("the loaded zip file", e10, true, o9.optimizedBinaryString, o9.base64).then(function(e11) { + var t7 = new s6(o9); + return t7.load(e11), t7; + }).then(function(e11) { + var t7 = [i7.Promise.resolve(e11)], r9 = e11.files; + if (o9.checkCRC32) for (var n8 = 0; n8 < r9.length; n8++) t7.push(f4(r9[n8])); + return i7.Promise.all(t7); + }).then(function(e11) { + for (var t7 = e11.shift(), r9 = t7.files, n8 = 0; n8 < r9.length; n8++) { + var i8 = r9[n8], s7 = i8.fileNameStr, a4 = u5.resolve(i8.fileNameStr); + h7.file(a4, i8.decompressed, { binary: true, optimizedBinaryString: true, date: i8.date, dir: i8.dir, comment: i8.fileCommentStr.length ? i8.fileCommentStr : null, unixPermissions: i8.unixPermissions, dosPermissions: i8.dosPermissions, createFolders: o9.createFolders }), i8.dir || (h7.file(a4).unsafeOriginalName = s7); + } + return t7.zipComment.length && (h7.comment = t7.zipComment), h7; + }); + }; + }, { "./external": 6, "./nodejsUtils": 14, "./stream/Crc32Probe": 25, "./utf8": 31, "./utils": 32, "./zipEntries": 33 }], 12: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("../stream/GenericWorker"); + function s6(e10, t7) { + i7.call(this, "Nodejs stream input adapter for " + e10), this._upstreamEnded = false, this._bindStream(t7); + } + n7.inherits(s6, i7), s6.prototype._bindStream = function(e10) { + var t7 = this; + (this._stream = e10).pause(), e10.on("data", function(e11) { + t7.push({ data: e11, meta: { percent: 0 } }); + }).on("error", function(e11) { + t7.isPaused ? this.generatedError = e11 : t7.error(e11); + }).on("end", function() { + t7.isPaused ? t7._upstreamEnded = true : t7.end(); + }); + }, s6.prototype.pause = function() { + return !!i7.prototype.pause.call(this) && (this._stream.pause(), true); + }, s6.prototype.resume = function() { + return !!i7.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), true); + }, t6.exports = s6; + }, { "../stream/GenericWorker": 28, "../utils": 32 }], 13: [function(e9, t6, r8) { + "use strict"; + var i7 = e9("readable-stream").Readable; + function n7(e10, t7, r9) { + i7.call(this, t7), this._helper = e10; + var n8 = this; + e10.on("data", function(e11, t8) { + n8.push(e11) || n8._helper.pause(), r9 && r9(t8); + }).on("error", function(e11) { + n8.emit("error", e11); + }).on("end", function() { + n8.push(null); + }); + } + e9("../utils").inherits(n7, i7), n7.prototype._read = function() { + this._helper.resume(); + }, t6.exports = n7; + }, { "../utils": 32, "readable-stream": 16 }], 14: [function(e9, t6, r8) { + "use strict"; + t6.exports = { isNode: "undefined" != typeof Buffer, newBufferFrom: function(e10, t7) { + if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e10, t7); + if ("number" == typeof e10) throw new Error('The "data" argument must not be a number'); + return new Buffer(e10, t7); + }, allocBuffer: function(e10) { + if (Buffer.alloc) return Buffer.alloc(e10); + var t7 = new Buffer(e10); + return t7.fill(0), t7; + }, isBuffer: function(e10) { + return Buffer.isBuffer(e10); + }, isStream: function(e10) { + return e10 && "function" == typeof e10.on && "function" == typeof e10.pause && "function" == typeof e10.resume; + } }; + }, {}], 15: [function(e9, t6, r8) { + "use strict"; + function s6(e10, t7, r9) { + var n8, i8 = u5.getTypeOf(t7), s7 = u5.extend(r9 || {}, f4); + s7.date = s7.date || /* @__PURE__ */ new Date(), null !== s7.compression && (s7.compression = s7.compression.toUpperCase()), "string" == typeof s7.unixPermissions && (s7.unixPermissions = parseInt(s7.unixPermissions, 8)), s7.unixPermissions && 16384 & s7.unixPermissions && (s7.dir = true), s7.dosPermissions && 16 & s7.dosPermissions && (s7.dir = true), s7.dir && (e10 = g3(e10)), s7.createFolders && (n8 = _3(e10)) && b4.call(this, n8, true); + var a4 = "string" === i8 && false === s7.binary && false === s7.base64; + r9 && void 0 !== r9.binary || (s7.binary = !a4), (t7 instanceof c6 && 0 === t7.uncompressedSize || s7.dir || !t7 || 0 === t7.length) && (s7.base64 = false, s7.binary = true, t7 = "", s7.compression = "STORE", i8 = "string"); + var o10 = null; + o10 = t7 instanceof c6 || t7 instanceof l5 ? t7 : p4.isNode && p4.isStream(t7) ? new m4(e10, t7) : u5.prepareContent(e10, t7, s7.binary, s7.optimizedBinaryString, s7.base64); + var h8 = new d4(e10, o10, s7); + this.files[e10] = h8; + } + var i7 = e9("./utf8"), u5 = e9("./utils"), l5 = e9("./stream/GenericWorker"), a3 = e9("./stream/StreamHelper"), f4 = e9("./defaults"), c6 = e9("./compressedObject"), d4 = e9("./zipObject"), o9 = e9("./generate"), p4 = e9("./nodejsUtils"), m4 = e9("./nodejs/NodejsStreamInputAdapter"), _3 = function(e10) { + "/" === e10.slice(-1) && (e10 = e10.substring(0, e10.length - 1)); + var t7 = e10.lastIndexOf("/"); + return 0 < t7 ? e10.substring(0, t7) : ""; + }, g3 = function(e10) { + return "/" !== e10.slice(-1) && (e10 += "/"), e10; + }, b4 = function(e10, t7) { + return t7 = void 0 !== t7 ? t7 : f4.createFolders, e10 = g3(e10), this.files[e10] || s6.call(this, e10, null, { dir: true, createFolders: t7 }), this.files[e10]; + }; + function h7(e10) { + return "[object RegExp]" === Object.prototype.toString.call(e10); + } + var n7 = { load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, forEach: function(e10) { + var t7, r9, n8; + for (t7 in this.files) n8 = this.files[t7], (r9 = t7.slice(this.root.length, t7.length)) && t7.slice(0, this.root.length) === this.root && e10(r9, n8); + }, filter: function(r9) { + var n8 = []; + return this.forEach(function(e10, t7) { + r9(e10, t7) && n8.push(t7); + }), n8; + }, file: function(e10, t7, r9) { + if (1 !== arguments.length) return e10 = this.root + e10, s6.call(this, e10, t7, r9), this; + if (h7(e10)) { + var n8 = e10; + return this.filter(function(e11, t8) { + return !t8.dir && n8.test(e11); + }); + } + var i8 = this.files[this.root + e10]; + return i8 && !i8.dir ? i8 : null; + }, folder: function(r9) { + if (!r9) return this; + if (h7(r9)) return this.filter(function(e11, t8) { + return t8.dir && r9.test(e11); + }); + var e10 = this.root + r9, t7 = b4.call(this, e10), n8 = this.clone(); + return n8.root = t7.name, n8; + }, remove: function(r9) { + r9 = this.root + r9; + var e10 = this.files[r9]; + if (e10 || ("/" !== r9.slice(-1) && (r9 += "/"), e10 = this.files[r9]), e10 && !e10.dir) delete this.files[r9]; + else for (var t7 = this.filter(function(e11, t8) { + return t8.name.slice(0, r9.length) === r9; + }), n8 = 0; n8 < t7.length; n8++) delete this.files[t7[n8].name]; + return this; + }, generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, generateInternalStream: function(e10) { + var t7, r9 = {}; + try { + if ((r9 = u5.extend(e10 || {}, { streamFiles: false, compression: "STORE", compressionOptions: null, type: "", platform: "DOS", comment: null, mimeType: "application/zip", encodeFileName: i7.utf8encode })).type = r9.type.toLowerCase(), r9.compression = r9.compression.toUpperCase(), "binarystring" === r9.type && (r9.type = "string"), !r9.type) throw new Error("No output type specified."); + u5.checkSupport(r9.type), "darwin" !== r9.platform && "freebsd" !== r9.platform && "linux" !== r9.platform && "sunos" !== r9.platform || (r9.platform = "UNIX"), "win32" === r9.platform && (r9.platform = "DOS"); + var n8 = r9.comment || this.comment || ""; + t7 = o9.generateWorker(this, r9, n8); + } catch (e11) { + (t7 = new l5("error")).error(e11); + } + return new a3(t7, r9.type || "string", r9.mimeType); + }, generateAsync: function(e10, t7) { + return this.generateInternalStream(e10).accumulate(t7); + }, generateNodeStream: function(e10, t7) { + return (e10 = e10 || {}).type || (e10.type = "nodebuffer"), this.generateInternalStream(e10).toNodejsStream(t7); + } }; + t6.exports = n7; + }, { "./compressedObject": 2, "./defaults": 5, "./generate": 9, "./nodejs/NodejsStreamInputAdapter": 12, "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31, "./utils": 32, "./zipObject": 35 }], 16: [function(e9, t6, r8) { + "use strict"; + t6.exports = e9("stream"); + }, { stream: void 0 }], 17: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./DataReader"); + function i7(e10) { + n7.call(this, e10); + for (var t7 = 0; t7 < this.data.length; t7++) e10[t7] = 255 & e10[t7]; + } + e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) { + return this.data[this.zero + e10]; + }, i7.prototype.lastIndexOfSignature = function(e10) { + for (var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.length - 4; 0 <= s6; --s6) if (this.data[s6] === t7 && this.data[s6 + 1] === r9 && this.data[s6 + 2] === n8 && this.data[s6 + 3] === i8) return s6 - this.zero; + return -1; + }, i7.prototype.readAndCheckSignature = function(e10) { + var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.readData(4); + return t7 === s6[0] && r9 === s6[1] && n8 === s6[2] && i8 === s6[3]; + }, i7.prototype.readData = function(e10) { + if (this.checkOffset(e10), 0 === e10) return []; + var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./DataReader": 18 }], 18: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"); + function i7(e10) { + this.data = e10, this.length = e10.length, this.index = 0, this.zero = 0; + } + i7.prototype = { checkOffset: function(e10) { + this.checkIndex(this.index + e10); + }, checkIndex: function(e10) { + if (this.length < this.zero + e10 || e10 < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e10 + "). Corrupted zip ?"); + }, setIndex: function(e10) { + this.checkIndex(e10), this.index = e10; + }, skip: function(e10) { + this.setIndex(this.index + e10); + }, byteAt: function() { + }, readInt: function(e10) { + var t7, r9 = 0; + for (this.checkOffset(e10), t7 = this.index + e10 - 1; t7 >= this.index; t7--) r9 = (r9 << 8) + this.byteAt(t7); + return this.index += e10, r9; + }, readString: function(e10) { + return n7.transformTo("string", this.readData(e10)); + }, readData: function() { + }, lastIndexOfSignature: function() { + }, readAndCheckSignature: function() { + }, readDate: function() { + var e10 = this.readInt(4); + return new Date(Date.UTC(1980 + (e10 >> 25 & 127), (e10 >> 21 & 15) - 1, e10 >> 16 & 31, e10 >> 11 & 31, e10 >> 5 & 63, (31 & e10) << 1)); + } }, t6.exports = i7; + }, { "../utils": 32 }], 19: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./Uint8ArrayReader"); + function i7(e10) { + n7.call(this, e10); + } + e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) { + this.checkOffset(e10); + var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./Uint8ArrayReader": 21 }], 20: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./DataReader"); + function i7(e10) { + n7.call(this, e10); + } + e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) { + return this.data.charCodeAt(this.zero + e10); + }, i7.prototype.lastIndexOfSignature = function(e10) { + return this.data.lastIndexOf(e10) - this.zero; + }, i7.prototype.readAndCheckSignature = function(e10) { + return e10 === this.readData(4); + }, i7.prototype.readData = function(e10) { + this.checkOffset(e10); + var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./DataReader": 18 }], 21: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./ArrayReader"); + function i7(e10) { + n7.call(this, e10); + } + e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) { + if (this.checkOffset(e10), 0 === e10) return new Uint8Array(0); + var t7 = this.data.subarray(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./ArrayReader": 17 }], 22: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("../support"), s6 = e9("./ArrayReader"), a3 = e9("./StringReader"), o9 = e9("./NodeBufferReader"), h7 = e9("./Uint8ArrayReader"); + t6.exports = function(e10) { + var t7 = n7.getTypeOf(e10); + return n7.checkSupport(t7), "string" !== t7 || i7.uint8array ? "nodebuffer" === t7 ? new o9(e10) : i7.uint8array ? new h7(n7.transformTo("uint8array", e10)) : new s6(n7.transformTo("array", e10)) : new a3(e10); + }; + }, { "../support": 30, "../utils": 32, "./ArrayReader": 17, "./NodeBufferReader": 19, "./StringReader": 20, "./Uint8ArrayReader": 21 }], 23: [function(e9, t6, r8) { + "use strict"; + r8.LOCAL_FILE_HEADER = "PK", r8.CENTRAL_FILE_HEADER = "PK", r8.CENTRAL_DIRECTORY_END = "PK", r8.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r8.ZIP64_CENTRAL_DIRECTORY_END = "PK", r8.DATA_DESCRIPTOR = "PK\x07\b"; + }, {}], 24: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./GenericWorker"), i7 = e9("../utils"); + function s6(e10) { + n7.call(this, "ConvertWorker to " + e10), this.destType = e10; + } + i7.inherits(s6, n7), s6.prototype.processChunk = function(e10) { + this.push({ data: i7.transformTo(this.destType, e10.data), meta: e10.meta }); + }, t6.exports = s6; + }, { "../utils": 32, "./GenericWorker": 28 }], 25: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./GenericWorker"), i7 = e9("../crc32"); + function s6() { + n7.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0); + } + e9("../utils").inherits(s6, n7), s6.prototype.processChunk = function(e10) { + this.streamInfo.crc32 = i7(e10.data, this.streamInfo.crc32 || 0), this.push(e10); + }, t6.exports = s6; + }, { "../crc32": 4, "../utils": 32, "./GenericWorker": 28 }], 26: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("./GenericWorker"); + function s6(e10) { + i7.call(this, "DataLengthProbe for " + e10), this.propName = e10, this.withStreamInfo(e10, 0); + } + n7.inherits(s6, i7), s6.prototype.processChunk = function(e10) { + if (e10) { + var t7 = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = t7 + e10.data.length; + } + i7.prototype.processChunk.call(this, e10); + }, t6.exports = s6; + }, { "../utils": 32, "./GenericWorker": 28 }], 27: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("./GenericWorker"); + function s6(e10) { + i7.call(this, "DataWorker"); + var t7 = this; + this.dataIsReady = false, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = false, e10.then(function(e11) { + t7.dataIsReady = true, t7.data = e11, t7.max = e11 && e11.length || 0, t7.type = n7.getTypeOf(e11), t7.isPaused || t7._tickAndRepeat(); + }, function(e11) { + t7.error(e11); + }); + } + n7.inherits(s6, i7), s6.prototype.cleanUp = function() { + i7.prototype.cleanUp.call(this), this.data = null; + }, s6.prototype.resume = function() { + return !!i7.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = true, n7.delay(this._tickAndRepeat, [], this)), true); + }, s6.prototype._tickAndRepeat = function() { + this._tickScheduled = false, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n7.delay(this._tickAndRepeat, [], this), this._tickScheduled = true)); + }, s6.prototype._tick = function() { + if (this.isPaused || this.isFinished) return false; + var e10 = null, t7 = Math.min(this.max, this.index + 16384); + if (this.index >= this.max) return this.end(); + switch (this.type) { + case "string": + e10 = this.data.substring(this.index, t7); + break; + case "uint8array": + e10 = this.data.subarray(this.index, t7); + break; + case "array": + case "nodebuffer": + e10 = this.data.slice(this.index, t7); + } + return this.index = t7, this.push({ data: e10, meta: { percent: this.max ? this.index / this.max * 100 : 0 } }); + }, t6.exports = s6; + }, { "../utils": 32, "./GenericWorker": 28 }], 28: [function(e9, t6, r8) { + "use strict"; + function n7(e10) { + this.name = e10 || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = true, this.isFinished = false, this.isLocked = false, this._listeners = { data: [], end: [], error: [] }, this.previous = null; + } + n7.prototype = { push: function(e10) { + this.emit("data", e10); + }, end: function() { + if (this.isFinished) return false; + this.flush(); + try { + this.emit("end"), this.cleanUp(), this.isFinished = true; + } catch (e10) { + this.emit("error", e10); + } + return true; + }, error: function(e10) { + return !this.isFinished && (this.isPaused ? this.generatedError = e10 : (this.isFinished = true, this.emit("error", e10), this.previous && this.previous.error(e10), this.cleanUp()), true); + }, on: function(e10, t7) { + return this._listeners[e10].push(t7), this; + }, cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = []; + }, emit: function(e10, t7) { + if (this._listeners[e10]) for (var r9 = 0; r9 < this._listeners[e10].length; r9++) this._listeners[e10][r9].call(this, t7); + }, pipe: function(e10) { + return e10.registerPrevious(this); + }, registerPrevious: function(e10) { + if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); + this.streamInfo = e10.streamInfo, this.mergeStreamInfo(), this.previous = e10; + var t7 = this; + return e10.on("data", function(e11) { + t7.processChunk(e11); + }), e10.on("end", function() { + t7.end(); + }), e10.on("error", function(e11) { + t7.error(e11); + }), this; + }, pause: function() { + return !this.isPaused && !this.isFinished && (this.isPaused = true, this.previous && this.previous.pause(), true); + }, resume: function() { + if (!this.isPaused || this.isFinished) return false; + var e10 = this.isPaused = false; + return this.generatedError && (this.error(this.generatedError), e10 = true), this.previous && this.previous.resume(), !e10; + }, flush: function() { + }, processChunk: function(e10) { + this.push(e10); + }, withStreamInfo: function(e10, t7) { + return this.extraStreamInfo[e10] = t7, this.mergeStreamInfo(), this; + }, mergeStreamInfo: function() { + for (var e10 in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e10) && (this.streamInfo[e10] = this.extraStreamInfo[e10]); + }, lock: function() { + if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); + this.isLocked = true, this.previous && this.previous.lock(); + }, toString: function() { + var e10 = "Worker " + this.name; + return this.previous ? this.previous + " -> " + e10 : e10; + } }, t6.exports = n7; + }, {}], 29: [function(e9, t6, r8) { + "use strict"; + var h7 = e9("../utils"), i7 = e9("./ConvertWorker"), s6 = e9("./GenericWorker"), u5 = e9("../base64"), n7 = e9("../support"), a3 = e9("../external"), o9 = null; + if (n7.nodestream) try { + o9 = e9("../nodejs/NodejsStreamOutputAdapter"); + } catch (e10) { + } + function l5(e10, o10) { + return new a3.Promise(function(t7, r9) { + var n8 = [], i8 = e10._internalType, s7 = e10._outputType, a4 = e10._mimeType; + e10.on("data", function(e11, t8) { + n8.push(e11), o10 && o10(t8); + }).on("error", function(e11) { + n8 = [], r9(e11); + }).on("end", function() { + try { + var e11 = (function(e12, t8, r10) { + switch (e12) { + case "blob": + return h7.newBlob(h7.transformTo("arraybuffer", t8), r10); + case "base64": + return u5.encode(t8); + default: + return h7.transformTo(e12, t8); + } + })(s7, (function(e12, t8) { + var r10, n9 = 0, i9 = null, s8 = 0; + for (r10 = 0; r10 < t8.length; r10++) s8 += t8[r10].length; + switch (e12) { + case "string": + return t8.join(""); + case "array": + return Array.prototype.concat.apply([], t8); + case "uint8array": + for (i9 = new Uint8Array(s8), r10 = 0; r10 < t8.length; r10++) i9.set(t8[r10], n9), n9 += t8[r10].length; + return i9; + case "nodebuffer": + return Buffer.concat(t8); + default: + throw new Error("concat : unsupported type '" + e12 + "'"); + } + })(i8, n8), a4); + t7(e11); + } catch (e12) { + r9(e12); + } + n8 = []; + }).resume(); + }); + } + function f4(e10, t7, r9) { + var n8 = t7; + switch (t7) { + case "blob": + case "arraybuffer": + n8 = "uint8array"; + break; + case "base64": + n8 = "string"; + } + try { + this._internalType = n8, this._outputType = t7, this._mimeType = r9, h7.checkSupport(n8), this._worker = e10.pipe(new i7(n8)), e10.lock(); + } catch (e11) { + this._worker = new s6("error"), this._worker.error(e11); + } + } + f4.prototype = { accumulate: function(e10) { + return l5(this, e10); + }, on: function(e10, t7) { + var r9 = this; + return "data" === e10 ? this._worker.on(e10, function(e11) { + t7.call(r9, e11.data, e11.meta); + }) : this._worker.on(e10, function() { + h7.delay(t7, arguments, r9); + }), this; + }, resume: function() { + return h7.delay(this._worker.resume, [], this._worker), this; + }, pause: function() { + return this._worker.pause(), this; + }, toNodejsStream: function(e10) { + if (h7.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method"); + return new o9(this, { objectMode: "nodebuffer" !== this._outputType }, e10); + } }, t6.exports = f4; + }, { "../base64": 1, "../external": 6, "../nodejs/NodejsStreamOutputAdapter": 13, "../support": 30, "../utils": 32, "./ConvertWorker": 24, "./GenericWorker": 28 }], 30: [function(e9, t6, r8) { + "use strict"; + if (r8.base64 = true, r8.array = true, r8.string = true, r8.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r8.nodebuffer = "undefined" != typeof Buffer, r8.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r8.blob = false; + else { + var n7 = new ArrayBuffer(0); + try { + r8.blob = 0 === new Blob([n7], { type: "application/zip" }).size; + } catch (e10) { + try { + var i7 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); + i7.append(n7), r8.blob = 0 === i7.getBlob("application/zip").size; + } catch (e11) { + r8.blob = false; + } + } + } + try { + r8.nodestream = !!e9("readable-stream").Readable; + } catch (e10) { + r8.nodestream = false; + } + }, { "readable-stream": 16 }], 31: [function(e9, t6, s6) { + "use strict"; + for (var o9 = e9("./utils"), h7 = e9("./support"), r8 = e9("./nodejsUtils"), n7 = e9("./stream/GenericWorker"), u5 = new Array(256), i7 = 0; i7 < 256; i7++) u5[i7] = 252 <= i7 ? 6 : 248 <= i7 ? 5 : 240 <= i7 ? 4 : 224 <= i7 ? 3 : 192 <= i7 ? 2 : 1; + u5[254] = u5[254] = 1; + function a3() { + n7.call(this, "utf-8 decode"), this.leftOver = null; + } + function l5() { + n7.call(this, "utf-8 encode"); + } + s6.utf8encode = function(e10) { + return h7.nodebuffer ? r8.newBufferFrom(e10, "utf-8") : (function(e11) { + var t7, r9, n8, i8, s7, a4 = e11.length, o10 = 0; + for (i8 = 0; i8 < a4; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o10 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4; + for (t7 = h7.uint8array ? new Uint8Array(o10) : new Array(o10), i8 = s7 = 0; s7 < o10; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9); + return t7; + })(e10); + }, s6.utf8decode = function(e10) { + return h7.nodebuffer ? o9.transformTo("nodebuffer", e10).toString("utf-8") : (function(e11) { + var t7, r9, n8, i8, s7 = e11.length, a4 = new Array(2 * s7); + for (t7 = r9 = 0; t7 < s7; ) if ((n8 = e11[t7++]) < 128) a4[r9++] = n8; + else if (4 < (i8 = u5[n8])) a4[r9++] = 65533, t7 += i8 - 1; + else { + for (n8 &= 2 === i8 ? 31 : 3 === i8 ? 15 : 7; 1 < i8 && t7 < s7; ) n8 = n8 << 6 | 63 & e11[t7++], i8--; + 1 < i8 ? a4[r9++] = 65533 : n8 < 65536 ? a4[r9++] = n8 : (n8 -= 65536, a4[r9++] = 55296 | n8 >> 10 & 1023, a4[r9++] = 56320 | 1023 & n8); + } + return a4.length !== r9 && (a4.subarray ? a4 = a4.subarray(0, r9) : a4.length = r9), o9.applyFromCharCode(a4); + })(e10 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10)); + }, o9.inherits(a3, n7), a3.prototype.processChunk = function(e10) { + var t7 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10.data); + if (this.leftOver && this.leftOver.length) { + if (h7.uint8array) { + var r9 = t7; + (t7 = new Uint8Array(r9.length + this.leftOver.length)).set(this.leftOver, 0), t7.set(r9, this.leftOver.length); + } else t7 = this.leftOver.concat(t7); + this.leftOver = null; + } + var n8 = (function(e11, t8) { + var r10; + for ((t8 = t8 || e11.length) > e11.length && (t8 = e11.length), r10 = t8 - 1; 0 <= r10 && 128 == (192 & e11[r10]); ) r10--; + return r10 < 0 ? t8 : 0 === r10 ? t8 : r10 + u5[e11[r10]] > t8 ? r10 : t8; + })(t7), i8 = t7; + n8 !== t7.length && (h7.uint8array ? (i8 = t7.subarray(0, n8), this.leftOver = t7.subarray(n8, t7.length)) : (i8 = t7.slice(0, n8), this.leftOver = t7.slice(n8, t7.length))), this.push({ data: s6.utf8decode(i8), meta: e10.meta }); + }, a3.prototype.flush = function() { + this.leftOver && this.leftOver.length && (this.push({ data: s6.utf8decode(this.leftOver), meta: {} }), this.leftOver = null); + }, s6.Utf8DecodeWorker = a3, o9.inherits(l5, n7), l5.prototype.processChunk = function(e10) { + this.push({ data: s6.utf8encode(e10.data), meta: e10.meta }); + }, s6.Utf8EncodeWorker = l5; + }, { "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./support": 30, "./utils": 32 }], 32: [function(e9, t6, a3) { + "use strict"; + var o9 = e9("./support"), h7 = e9("./base64"), r8 = e9("./nodejsUtils"), u5 = e9("./external"); + function n7(e10) { + return e10; + } + function l5(e10, t7) { + for (var r9 = 0; r9 < e10.length; ++r9) t7[r9] = 255 & e10.charCodeAt(r9); + return t7; + } + e9("setimmediate"), a3.newBlob = function(t7, r9) { + a3.checkSupport("blob"); + try { + return new Blob([t7], { type: r9 }); + } catch (e10) { + try { + var n8 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); + return n8.append(t7), n8.getBlob(r9); + } catch (e11) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + var i7 = { stringifyByChunk: function(e10, t7, r9) { + var n8 = [], i8 = 0, s7 = e10.length; + if (s7 <= r9) return String.fromCharCode.apply(null, e10); + for (; i8 < s7; ) "array" === t7 || "nodebuffer" === t7 ? n8.push(String.fromCharCode.apply(null, e10.slice(i8, Math.min(i8 + r9, s7)))) : n8.push(String.fromCharCode.apply(null, e10.subarray(i8, Math.min(i8 + r9, s7)))), i8 += r9; + return n8.join(""); + }, stringifyByChar: function(e10) { + for (var t7 = "", r9 = 0; r9 < e10.length; r9++) t7 += String.fromCharCode(e10[r9]); + return t7; + }, applyCanBeUsed: { uint8array: (function() { + try { + return o9.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length; + } catch (e10) { + return false; + } + })(), nodebuffer: (function() { + try { + return o9.nodebuffer && 1 === String.fromCharCode.apply(null, r8.allocBuffer(1)).length; + } catch (e10) { + return false; + } + })() } }; + function s6(e10) { + var t7 = 65536, r9 = a3.getTypeOf(e10), n8 = true; + if ("uint8array" === r9 ? n8 = i7.applyCanBeUsed.uint8array : "nodebuffer" === r9 && (n8 = i7.applyCanBeUsed.nodebuffer), n8) for (; 1 < t7; ) try { + return i7.stringifyByChunk(e10, r9, t7); + } catch (e11) { + t7 = Math.floor(t7 / 2); + } + return i7.stringifyByChar(e10); + } + function f4(e10, t7) { + for (var r9 = 0; r9 < e10.length; r9++) t7[r9] = e10[r9]; + return t7; + } + a3.applyFromCharCode = s6; + var c6 = {}; + c6.string = { string: n7, array: function(e10) { + return l5(e10, new Array(e10.length)); + }, arraybuffer: function(e10) { + return c6.string.uint8array(e10).buffer; + }, uint8array: function(e10) { + return l5(e10, new Uint8Array(e10.length)); + }, nodebuffer: function(e10) { + return l5(e10, r8.allocBuffer(e10.length)); + } }, c6.array = { string: s6, array: n7, arraybuffer: function(e10) { + return new Uint8Array(e10).buffer; + }, uint8array: function(e10) { + return new Uint8Array(e10); + }, nodebuffer: function(e10) { + return r8.newBufferFrom(e10); + } }, c6.arraybuffer = { string: function(e10) { + return s6(new Uint8Array(e10)); + }, array: function(e10) { + return f4(new Uint8Array(e10), new Array(e10.byteLength)); + }, arraybuffer: n7, uint8array: function(e10) { + return new Uint8Array(e10); + }, nodebuffer: function(e10) { + return r8.newBufferFrom(new Uint8Array(e10)); + } }, c6.uint8array = { string: s6, array: function(e10) { + return f4(e10, new Array(e10.length)); + }, arraybuffer: function(e10) { + return e10.buffer; + }, uint8array: n7, nodebuffer: function(e10) { + return r8.newBufferFrom(e10); + } }, c6.nodebuffer = { string: s6, array: function(e10) { + return f4(e10, new Array(e10.length)); + }, arraybuffer: function(e10) { + return c6.nodebuffer.uint8array(e10).buffer; + }, uint8array: function(e10) { + return f4(e10, new Uint8Array(e10.length)); + }, nodebuffer: n7 }, a3.transformTo = function(e10, t7) { + if (t7 = t7 || "", !e10) return t7; + a3.checkSupport(e10); + var r9 = a3.getTypeOf(t7); + return c6[r9][e10](t7); + }, a3.resolve = function(e10) { + for (var t7 = e10.split("/"), r9 = [], n8 = 0; n8 < t7.length; n8++) { + var i8 = t7[n8]; + "." === i8 || "" === i8 && 0 !== n8 && n8 !== t7.length - 1 || (".." === i8 ? r9.pop() : r9.push(i8)); + } + return r9.join("/"); + }, a3.getTypeOf = function(e10) { + return "string" == typeof e10 ? "string" : "[object Array]" === Object.prototype.toString.call(e10) ? "array" : o9.nodebuffer && r8.isBuffer(e10) ? "nodebuffer" : o9.uint8array && e10 instanceof Uint8Array ? "uint8array" : o9.arraybuffer && e10 instanceof ArrayBuffer ? "arraybuffer" : void 0; + }, a3.checkSupport = function(e10) { + if (!o9[e10.toLowerCase()]) throw new Error(e10 + " is not supported by this platform"); + }, a3.MAX_VALUE_16BITS = 65535, a3.MAX_VALUE_32BITS = -1, a3.pretty = function(e10) { + var t7, r9, n8 = ""; + for (r9 = 0; r9 < (e10 || "").length; r9++) n8 += "\\x" + ((t7 = e10.charCodeAt(r9)) < 16 ? "0" : "") + t7.toString(16).toUpperCase(); + return n8; + }, a3.delay = function(e10, t7, r9) { + setImmediate(function() { + e10.apply(r9 || null, t7 || []); + }); + }, a3.inherits = function(e10, t7) { + function r9() { + } + r9.prototype = t7.prototype, e10.prototype = new r9(); + }, a3.extend = function() { + var e10, t7, r9 = {}; + for (e10 = 0; e10 < arguments.length; e10++) for (t7 in arguments[e10]) Object.prototype.hasOwnProperty.call(arguments[e10], t7) && void 0 === r9[t7] && (r9[t7] = arguments[e10][t7]); + return r9; + }, a3.prepareContent = function(r9, e10, n8, i8, s7) { + return u5.Promise.resolve(e10).then(function(n9) { + return o9.blob && (n9 instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n9))) && "undefined" != typeof FileReader ? new u5.Promise(function(t7, r10) { + var e11 = new FileReader(); + e11.onload = function(e12) { + t7(e12.target.result); + }, e11.onerror = function(e12) { + r10(e12.target.error); + }, e11.readAsArrayBuffer(n9); + }) : n9; + }).then(function(e11) { + var t7 = a3.getTypeOf(e11); + return t7 ? ("arraybuffer" === t7 ? e11 = a3.transformTo("uint8array", e11) : "string" === t7 && (s7 ? e11 = h7.decode(e11) : n8 && true !== i8 && (e11 = (function(e12) { + return l5(e12, o9.uint8array ? new Uint8Array(e12.length) : new Array(e12.length)); + })(e11))), e11) : u5.Promise.reject(new Error("Can't read the data of '" + r9 + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); + }); + }; + }, { "./base64": 1, "./external": 6, "./nodejsUtils": 14, "./support": 30, setimmediate: 54 }], 33: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./reader/readerFor"), i7 = e9("./utils"), s6 = e9("./signature"), a3 = e9("./zipEntry"), o9 = e9("./support"); + function h7(e10) { + this.files = [], this.loadOptions = e10; + } + h7.prototype = { checkSignature: function(e10) { + if (!this.reader.readAndCheckSignature(e10)) { + this.reader.index -= 4; + var t7 = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature (" + i7.pretty(t7) + ", expected " + i7.pretty(e10) + ")"); + } + }, isSignature: function(e10, t7) { + var r9 = this.reader.index; + this.reader.setIndex(e10); + var n8 = this.reader.readString(4) === t7; + return this.reader.setIndex(r9), n8; + }, readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2); + var e10 = this.reader.readData(this.zipCommentLength), t7 = o9.uint8array ? "uint8array" : "array", r9 = i7.transformTo(t7, e10); + this.zipComment = this.loadOptions.decodeFileName(r9); + }, readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {}; + for (var e10, t7, r9, n8 = this.zip64EndOfCentralSize - 44; 0 < n8; ) e10 = this.reader.readInt(2), t7 = this.reader.readInt(4), r9 = this.reader.readData(t7), this.zip64ExtensibleData[e10] = { id: e10, length: t7, value: r9 }; + }, readBlockZip64EndOfCentralLocator: function() { + if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported"); + }, readLocalFiles: function() { + var e10, t7; + for (e10 = 0; e10 < this.files.length; e10++) t7 = this.files[e10], this.reader.setIndex(t7.localHeaderOffset), this.checkSignature(s6.LOCAL_FILE_HEADER), t7.readLocalPart(this.reader), t7.handleUTF8(), t7.processAttributes(); + }, readCentralDir: function() { + var e10; + for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s6.CENTRAL_FILE_HEADER); ) (e10 = new a3({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e10); + if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + }, readEndOfCentral: function() { + var e10 = this.reader.lastIndexOfSignature(s6.CENTRAL_DIRECTORY_END); + if (e10 < 0) throw !this.isSignature(0, s6.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory"); + this.reader.setIndex(e10); + var t7 = e10; + if (this.checkSignature(s6.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i7.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i7.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i7.MAX_VALUE_16BITS || this.centralDirRecords === i7.MAX_VALUE_16BITS || this.centralDirSize === i7.MAX_VALUE_32BITS || this.centralDirOffset === i7.MAX_VALUE_32BITS) { + if (this.zip64 = true, (e10 = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + if (this.reader.setIndex(e10), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s6.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral(); + } + var r9 = this.centralDirOffset + this.centralDirSize; + this.zip64 && (r9 += 20, r9 += 12 + this.zip64EndOfCentralSize); + var n8 = t7 - r9; + if (0 < n8) this.isSignature(t7, s6.CENTRAL_FILE_HEADER) || (this.reader.zero = n8); + else if (n8 < 0) throw new Error("Corrupted zip: missing " + Math.abs(n8) + " bytes."); + }, prepareReader: function(e10) { + this.reader = n7(e10); + }, load: function(e10) { + this.prepareReader(e10), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles(); + } }, t6.exports = h7; + }, { "./reader/readerFor": 22, "./signature": 23, "./support": 30, "./utils": 32, "./zipEntry": 34 }], 34: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./reader/readerFor"), s6 = e9("./utils"), i7 = e9("./compressedObject"), a3 = e9("./crc32"), o9 = e9("./utf8"), h7 = e9("./compressions"), u5 = e9("./support"); + function l5(e10, t7) { + this.options = e10, this.loadOptions = t7; + } + l5.prototype = { isEncrypted: function() { + return 1 == (1 & this.bitFlag); + }, useUTF8: function() { + return 2048 == (2048 & this.bitFlag); + }, readLocalPart: function(e10) { + var t7, r9; + if (e10.skip(22), this.fileNameLength = e10.readInt(2), r9 = e10.readInt(2), this.fileName = e10.readData(this.fileNameLength), e10.skip(r9), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)"); + if (null === (t7 = (function(e11) { + for (var t8 in h7) if (Object.prototype.hasOwnProperty.call(h7, t8) && h7[t8].magic === e11) return h7[t8]; + return null; + })(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s6.pretty(this.compressionMethod) + " unknown (inner file : " + s6.transformTo("string", this.fileName) + ")"); + this.decompressed = new i7(this.compressedSize, this.uncompressedSize, this.crc32, t7, e10.readData(this.compressedSize)); + }, readCentralPart: function(e10) { + this.versionMadeBy = e10.readInt(2), e10.skip(2), this.bitFlag = e10.readInt(2), this.compressionMethod = e10.readString(2), this.date = e10.readDate(), this.crc32 = e10.readInt(4), this.compressedSize = e10.readInt(4), this.uncompressedSize = e10.readInt(4); + var t7 = e10.readInt(2); + if (this.extraFieldsLength = e10.readInt(2), this.fileCommentLength = e10.readInt(2), this.diskNumberStart = e10.readInt(2), this.internalFileAttributes = e10.readInt(2), this.externalFileAttributes = e10.readInt(4), this.localHeaderOffset = e10.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported"); + e10.skip(t7), this.readExtraFields(e10), this.parseZIP64ExtraField(e10), this.fileComment = e10.readData(this.fileCommentLength); + }, processAttributes: function() { + this.unixPermissions = null, this.dosPermissions = null; + var e10 = this.versionMadeBy >> 8; + this.dir = !!(16 & this.externalFileAttributes), 0 == e10 && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e10 && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = true); + }, parseZIP64ExtraField: function() { + if (this.extraFields[1]) { + var e10 = n7(this.extraFields[1].value); + this.uncompressedSize === s6.MAX_VALUE_32BITS && (this.uncompressedSize = e10.readInt(8)), this.compressedSize === s6.MAX_VALUE_32BITS && (this.compressedSize = e10.readInt(8)), this.localHeaderOffset === s6.MAX_VALUE_32BITS && (this.localHeaderOffset = e10.readInt(8)), this.diskNumberStart === s6.MAX_VALUE_32BITS && (this.diskNumberStart = e10.readInt(4)); + } + }, readExtraFields: function(e10) { + var t7, r9, n8, i8 = e10.index + this.extraFieldsLength; + for (this.extraFields || (this.extraFields = {}); e10.index + 4 < i8; ) t7 = e10.readInt(2), r9 = e10.readInt(2), n8 = e10.readData(r9), this.extraFields[t7] = { id: t7, length: r9, value: n8 }; + e10.setIndex(i8); + }, handleUTF8: function() { + var e10 = u5.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) this.fileNameStr = o9.utf8decode(this.fileName), this.fileCommentStr = o9.utf8decode(this.fileComment); + else { + var t7 = this.findExtraFieldUnicodePath(); + if (null !== t7) this.fileNameStr = t7; + else { + var r9 = s6.transformTo(e10, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(r9); + } + var n8 = this.findExtraFieldUnicodeComment(); + if (null !== n8) this.fileCommentStr = n8; + else { + var i8 = s6.transformTo(e10, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(i8); + } + } + }, findExtraFieldUnicodePath: function() { + var e10 = this.extraFields[28789]; + if (e10) { + var t7 = n7(e10.value); + return 1 !== t7.readInt(1) ? null : a3(this.fileName) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5)); + } + return null; + }, findExtraFieldUnicodeComment: function() { + var e10 = this.extraFields[25461]; + if (e10) { + var t7 = n7(e10.value); + return 1 !== t7.readInt(1) ? null : a3(this.fileComment) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5)); + } + return null; + } }, t6.exports = l5; + }, { "./compressedObject": 2, "./compressions": 3, "./crc32": 4, "./reader/readerFor": 22, "./support": 30, "./utf8": 31, "./utils": 32 }], 35: [function(e9, t6, r8) { + "use strict"; + function n7(e10, t7, r9) { + this.name = e10, this.dir = r9.dir, this.date = r9.date, this.comment = r9.comment, this.unixPermissions = r9.unixPermissions, this.dosPermissions = r9.dosPermissions, this._data = t7, this._dataBinary = r9.binary, this.options = { compression: r9.compression, compressionOptions: r9.compressionOptions }; + } + var s6 = e9("./stream/StreamHelper"), i7 = e9("./stream/DataWorker"), a3 = e9("./utf8"), o9 = e9("./compressedObject"), h7 = e9("./stream/GenericWorker"); + n7.prototype = { internalStream: function(e10) { + var t7 = null, r9 = "string"; + try { + if (!e10) throw new Error("No output type specified."); + var n8 = "string" === (r9 = e10.toLowerCase()) || "text" === r9; + "binarystring" !== r9 && "text" !== r9 || (r9 = "string"), t7 = this._decompressWorker(); + var i8 = !this._dataBinary; + i8 && !n8 && (t7 = t7.pipe(new a3.Utf8EncodeWorker())), !i8 && n8 && (t7 = t7.pipe(new a3.Utf8DecodeWorker())); + } catch (e11) { + (t7 = new h7("error")).error(e11); + } + return new s6(t7, r9, ""); + }, async: function(e10, t7) { + return this.internalStream(e10).accumulate(t7); + }, nodeStream: function(e10, t7) { + return this.internalStream(e10 || "nodebuffer").toNodejsStream(t7); + }, _compressWorker: function(e10, t7) { + if (this._data instanceof o9 && this._data.compression.magic === e10.magic) return this._data.getCompressedWorker(); + var r9 = this._decompressWorker(); + return this._dataBinary || (r9 = r9.pipe(new a3.Utf8EncodeWorker())), o9.createWorkerFrom(r9, e10, t7); + }, _decompressWorker: function() { + return this._data instanceof o9 ? this._data.getContentWorker() : this._data instanceof h7 ? this._data : new i7(this._data); + } }; + for (var u5 = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"], l5 = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, f4 = 0; f4 < u5.length; f4++) n7.prototype[u5[f4]] = l5; + t6.exports = n7; + }, { "./compressedObject": 2, "./stream/DataWorker": 27, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31 }], 36: [function(e9, l5, t6) { + (function(t7) { + "use strict"; + var r8, n7, e10 = t7.MutationObserver || t7.WebKitMutationObserver; + if (e10) { + var i7 = 0, s6 = new e10(u5), a3 = t7.document.createTextNode(""); + s6.observe(a3, { characterData: true }), r8 = function() { + a3.data = i7 = ++i7 % 2; + }; + } else if (t7.setImmediate || void 0 === t7.MessageChannel) r8 = "document" in t7 && "onreadystatechange" in t7.document.createElement("script") ? function() { + var e11 = t7.document.createElement("script"); + e11.onreadystatechange = function() { + u5(), e11.onreadystatechange = null, e11.parentNode.removeChild(e11), e11 = null; + }, t7.document.documentElement.appendChild(e11); + } : function() { + setTimeout(u5, 0); + }; + else { + var o9 = new t7.MessageChannel(); + o9.port1.onmessage = u5, r8 = function() { + o9.port2.postMessage(0); + }; + } + var h7 = []; + function u5() { + var e11, t8; + n7 = true; + for (var r9 = h7.length; r9; ) { + for (t8 = h7, h7 = [], e11 = -1; ++e11 < r9; ) t8[e11](); + r9 = h7.length; + } + n7 = false; + } + l5.exports = function(e11) { + 1 !== h7.push(e11) || n7 || r8(); + }; + }).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); + }, {}], 37: [function(e9, t6, r8) { + "use strict"; + var i7 = e9("immediate"); + function u5() { + } + var l5 = {}, s6 = ["REJECTED"], a3 = ["FULFILLED"], n7 = ["PENDING"]; + function o9(e10) { + if ("function" != typeof e10) throw new TypeError("resolver must be a function"); + this.state = n7, this.queue = [], this.outcome = void 0, e10 !== u5 && d4(this, e10); + } + function h7(e10, t7, r9) { + this.promise = e10, "function" == typeof t7 && (this.onFulfilled = t7, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r9 && (this.onRejected = r9, this.callRejected = this.otherCallRejected); + } + function f4(t7, r9, n8) { + i7(function() { + var e10; + try { + e10 = r9(n8); + } catch (e11) { + return l5.reject(t7, e11); + } + e10 === t7 ? l5.reject(t7, new TypeError("Cannot resolve promise with itself")) : l5.resolve(t7, e10); + }); + } + function c6(e10) { + var t7 = e10 && e10.then; + if (e10 && ("object" == typeof e10 || "function" == typeof e10) && "function" == typeof t7) return function() { + t7.apply(e10, arguments); + }; + } + function d4(t7, e10) { + var r9 = false; + function n8(e11) { + r9 || (r9 = true, l5.reject(t7, e11)); + } + function i8(e11) { + r9 || (r9 = true, l5.resolve(t7, e11)); + } + var s7 = p4(function() { + e10(i8, n8); + }); + "error" === s7.status && n8(s7.value); + } + function p4(e10, t7) { + var r9 = {}; + try { + r9.value = e10(t7), r9.status = "success"; + } catch (e11) { + r9.status = "error", r9.value = e11; + } + return r9; + } + (t6.exports = o9).prototype.finally = function(t7) { + if ("function" != typeof t7) return this; + var r9 = this.constructor; + return this.then(function(e10) { + return r9.resolve(t7()).then(function() { + return e10; + }); + }, function(e10) { + return r9.resolve(t7()).then(function() { + throw e10; + }); + }); + }, o9.prototype.catch = function(e10) { + return this.then(null, e10); + }, o9.prototype.then = function(e10, t7) { + if ("function" != typeof e10 && this.state === a3 || "function" != typeof t7 && this.state === s6) return this; + var r9 = new this.constructor(u5); + this.state !== n7 ? f4(r9, this.state === a3 ? e10 : t7, this.outcome) : this.queue.push(new h7(r9, e10, t7)); + return r9; + }, h7.prototype.callFulfilled = function(e10) { + l5.resolve(this.promise, e10); + }, h7.prototype.otherCallFulfilled = function(e10) { + f4(this.promise, this.onFulfilled, e10); + }, h7.prototype.callRejected = function(e10) { + l5.reject(this.promise, e10); + }, h7.prototype.otherCallRejected = function(e10) { + f4(this.promise, this.onRejected, e10); + }, l5.resolve = function(e10, t7) { + var r9 = p4(c6, t7); + if ("error" === r9.status) return l5.reject(e10, r9.value); + var n8 = r9.value; + if (n8) d4(e10, n8); + else { + e10.state = a3, e10.outcome = t7; + for (var i8 = -1, s7 = e10.queue.length; ++i8 < s7; ) e10.queue[i8].callFulfilled(t7); + } + return e10; + }, l5.reject = function(e10, t7) { + e10.state = s6, e10.outcome = t7; + for (var r9 = -1, n8 = e10.queue.length; ++r9 < n8; ) e10.queue[r9].callRejected(t7); + return e10; + }, o9.resolve = function(e10) { + if (e10 instanceof this) return e10; + return l5.resolve(new this(u5), e10); + }, o9.reject = function(e10) { + var t7 = new this(u5); + return l5.reject(t7, e10); + }, o9.all = function(e10) { + var r9 = this; + if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array")); + var n8 = e10.length, i8 = false; + if (!n8) return this.resolve([]); + var s7 = new Array(n8), a4 = 0, t7 = -1, o10 = new this(u5); + for (; ++t7 < n8; ) h8(e10[t7], t7); + return o10; + function h8(e11, t8) { + r9.resolve(e11).then(function(e12) { + s7[t8] = e12, ++a4 !== n8 || i8 || (i8 = true, l5.resolve(o10, s7)); + }, function(e12) { + i8 || (i8 = true, l5.reject(o10, e12)); + }); + } + }, o9.race = function(e10) { + var t7 = this; + if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array")); + var r9 = e10.length, n8 = false; + if (!r9) return this.resolve([]); + var i8 = -1, s7 = new this(u5); + for (; ++i8 < r9; ) a4 = e10[i8], t7.resolve(a4).then(function(e11) { + n8 || (n8 = true, l5.resolve(s7, e11)); + }, function(e11) { + n8 || (n8 = true, l5.reject(s7, e11)); + }); + var a4; + return s7; + }; + }, { immediate: 36 }], 38: [function(e9, t6, r8) { + "use strict"; + var n7 = {}; + (0, e9("./lib/utils/common").assign)(n7, e9("./lib/deflate"), e9("./lib/inflate"), e9("./lib/zlib/constants")), t6.exports = n7; + }, { "./lib/deflate": 39, "./lib/inflate": 40, "./lib/utils/common": 41, "./lib/zlib/constants": 44 }], 39: [function(e9, t6, r8) { + "use strict"; + var a3 = e9("./zlib/deflate"), o9 = e9("./utils/common"), h7 = e9("./utils/strings"), i7 = e9("./zlib/messages"), s6 = e9("./zlib/zstream"), u5 = Object.prototype.toString, l5 = 0, f4 = -1, c6 = 0, d4 = 8; + function p4(e10) { + if (!(this instanceof p4)) return new p4(e10); + this.options = o9.assign({ level: f4, method: d4, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: c6, to: "" }, e10 || {}); + var t7 = this.options; + t7.raw && 0 < t7.windowBits ? t7.windowBits = -t7.windowBits : t7.gzip && 0 < t7.windowBits && t7.windowBits < 16 && (t7.windowBits += 16), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new s6(), this.strm.avail_out = 0; + var r9 = a3.deflateInit2(this.strm, t7.level, t7.method, t7.windowBits, t7.memLevel, t7.strategy); + if (r9 !== l5) throw new Error(i7[r9]); + if (t7.header && a3.deflateSetHeader(this.strm, t7.header), t7.dictionary) { + var n8; + if (n8 = "string" == typeof t7.dictionary ? h7.string2buf(t7.dictionary) : "[object ArrayBuffer]" === u5.call(t7.dictionary) ? new Uint8Array(t7.dictionary) : t7.dictionary, (r9 = a3.deflateSetDictionary(this.strm, n8)) !== l5) throw new Error(i7[r9]); + this._dict_set = true; + } + } + function n7(e10, t7) { + var r9 = new p4(t7); + if (r9.push(e10, true), r9.err) throw r9.msg || i7[r9.err]; + return r9.result; + } + p4.prototype.push = function(e10, t7) { + var r9, n8, i8 = this.strm, s7 = this.options.chunkSize; + if (this.ended) return false; + n8 = t7 === ~~t7 ? t7 : true === t7 ? 4 : 0, "string" == typeof e10 ? i8.input = h7.string2buf(e10) : "[object ArrayBuffer]" === u5.call(e10) ? i8.input = new Uint8Array(e10) : i8.input = e10, i8.next_in = 0, i8.avail_in = i8.input.length; + do { + if (0 === i8.avail_out && (i8.output = new o9.Buf8(s7), i8.next_out = 0, i8.avail_out = s7), 1 !== (r9 = a3.deflate(i8, n8)) && r9 !== l5) return this.onEnd(r9), !(this.ended = true); + 0 !== i8.avail_out && (0 !== i8.avail_in || 4 !== n8 && 2 !== n8) || ("string" === this.options.to ? this.onData(h7.buf2binstring(o9.shrinkBuf(i8.output, i8.next_out))) : this.onData(o9.shrinkBuf(i8.output, i8.next_out))); + } while ((0 < i8.avail_in || 0 === i8.avail_out) && 1 !== r9); + return 4 === n8 ? (r9 = a3.deflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === l5) : 2 !== n8 || (this.onEnd(l5), !(i8.avail_out = 0)); + }, p4.prototype.onData = function(e10) { + this.chunks.push(e10); + }, p4.prototype.onEnd = function(e10) { + e10 === l5 && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o9.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg; + }, r8.Deflate = p4, r8.deflate = n7, r8.deflateRaw = function(e10, t7) { + return (t7 = t7 || {}).raw = true, n7(e10, t7); + }, r8.gzip = function(e10, t7) { + return (t7 = t7 || {}).gzip = true, n7(e10, t7); + }; + }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/deflate": 46, "./zlib/messages": 51, "./zlib/zstream": 53 }], 40: [function(e9, t6, r8) { + "use strict"; + var c6 = e9("./zlib/inflate"), d4 = e9("./utils/common"), p4 = e9("./utils/strings"), m4 = e9("./zlib/constants"), n7 = e9("./zlib/messages"), i7 = e9("./zlib/zstream"), s6 = e9("./zlib/gzheader"), _3 = Object.prototype.toString; + function a3(e10) { + if (!(this instanceof a3)) return new a3(e10); + this.options = d4.assign({ chunkSize: 16384, windowBits: 0, to: "" }, e10 || {}); + var t7 = this.options; + t7.raw && 0 <= t7.windowBits && t7.windowBits < 16 && (t7.windowBits = -t7.windowBits, 0 === t7.windowBits && (t7.windowBits = -15)), !(0 <= t7.windowBits && t7.windowBits < 16) || e10 && e10.windowBits || (t7.windowBits += 32), 15 < t7.windowBits && t7.windowBits < 48 && 0 == (15 & t7.windowBits) && (t7.windowBits |= 15), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new i7(), this.strm.avail_out = 0; + var r9 = c6.inflateInit2(this.strm, t7.windowBits); + if (r9 !== m4.Z_OK) throw new Error(n7[r9]); + this.header = new s6(), c6.inflateGetHeader(this.strm, this.header); + } + function o9(e10, t7) { + var r9 = new a3(t7); + if (r9.push(e10, true), r9.err) throw r9.msg || n7[r9.err]; + return r9.result; + } + a3.prototype.push = function(e10, t7) { + var r9, n8, i8, s7, a4, o10, h7 = this.strm, u5 = this.options.chunkSize, l5 = this.options.dictionary, f4 = false; + if (this.ended) return false; + n8 = t7 === ~~t7 ? t7 : true === t7 ? m4.Z_FINISH : m4.Z_NO_FLUSH, "string" == typeof e10 ? h7.input = p4.binstring2buf(e10) : "[object ArrayBuffer]" === _3.call(e10) ? h7.input = new Uint8Array(e10) : h7.input = e10, h7.next_in = 0, h7.avail_in = h7.input.length; + do { + if (0 === h7.avail_out && (h7.output = new d4.Buf8(u5), h7.next_out = 0, h7.avail_out = u5), (r9 = c6.inflate(h7, m4.Z_NO_FLUSH)) === m4.Z_NEED_DICT && l5 && (o10 = "string" == typeof l5 ? p4.string2buf(l5) : "[object ArrayBuffer]" === _3.call(l5) ? new Uint8Array(l5) : l5, r9 = c6.inflateSetDictionary(this.strm, o10)), r9 === m4.Z_BUF_ERROR && true === f4 && (r9 = m4.Z_OK, f4 = false), r9 !== m4.Z_STREAM_END && r9 !== m4.Z_OK) return this.onEnd(r9), !(this.ended = true); + h7.next_out && (0 !== h7.avail_out && r9 !== m4.Z_STREAM_END && (0 !== h7.avail_in || n8 !== m4.Z_FINISH && n8 !== m4.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i8 = p4.utf8border(h7.output, h7.next_out), s7 = h7.next_out - i8, a4 = p4.buf2string(h7.output, i8), h7.next_out = s7, h7.avail_out = u5 - s7, s7 && d4.arraySet(h7.output, h7.output, i8, s7, 0), this.onData(a4)) : this.onData(d4.shrinkBuf(h7.output, h7.next_out)))), 0 === h7.avail_in && 0 === h7.avail_out && (f4 = true); + } while ((0 < h7.avail_in || 0 === h7.avail_out) && r9 !== m4.Z_STREAM_END); + return r9 === m4.Z_STREAM_END && (n8 = m4.Z_FINISH), n8 === m4.Z_FINISH ? (r9 = c6.inflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === m4.Z_OK) : n8 !== m4.Z_SYNC_FLUSH || (this.onEnd(m4.Z_OK), !(h7.avail_out = 0)); + }, a3.prototype.onData = function(e10) { + this.chunks.push(e10); + }, a3.prototype.onEnd = function(e10) { + e10 === m4.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d4.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg; + }, r8.Inflate = a3, r8.inflate = o9, r8.inflateRaw = function(e10, t7) { + return (t7 = t7 || {}).raw = true, o9(e10, t7); + }, r8.ungzip = o9; + }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/constants": 44, "./zlib/gzheader": 47, "./zlib/inflate": 49, "./zlib/messages": 51, "./zlib/zstream": 53 }], 41: [function(e9, t6, r8) { + "use strict"; + var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array; + r8.assign = function(e10) { + for (var t7 = Array.prototype.slice.call(arguments, 1); t7.length; ) { + var r9 = t7.shift(); + if (r9) { + if ("object" != typeof r9) throw new TypeError(r9 + "must be non-object"); + for (var n8 in r9) r9.hasOwnProperty(n8) && (e10[n8] = r9[n8]); + } + } + return e10; + }, r8.shrinkBuf = function(e10, t7) { + return e10.length === t7 ? e10 : e10.subarray ? e10.subarray(0, t7) : (e10.length = t7, e10); + }; + var i7 = { arraySet: function(e10, t7, r9, n8, i8) { + if (t7.subarray && e10.subarray) e10.set(t7.subarray(r9, r9 + n8), i8); + else for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7]; + }, flattenChunks: function(e10) { + var t7, r9, n8, i8, s7, a3; + for (t7 = n8 = 0, r9 = e10.length; t7 < r9; t7++) n8 += e10[t7].length; + for (a3 = new Uint8Array(n8), t7 = i8 = 0, r9 = e10.length; t7 < r9; t7++) s7 = e10[t7], a3.set(s7, i8), i8 += s7.length; + return a3; + } }, s6 = { arraySet: function(e10, t7, r9, n8, i8) { + for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7]; + }, flattenChunks: function(e10) { + return [].concat.apply([], e10); + } }; + r8.setTyped = function(e10) { + e10 ? (r8.Buf8 = Uint8Array, r8.Buf16 = Uint16Array, r8.Buf32 = Int32Array, r8.assign(r8, i7)) : (r8.Buf8 = Array, r8.Buf16 = Array, r8.Buf32 = Array, r8.assign(r8, s6)); + }, r8.setTyped(n7); + }, {}], 42: [function(e9, t6, r8) { + "use strict"; + var h7 = e9("./common"), i7 = true, s6 = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (e10) { + i7 = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (e10) { + s6 = false; + } + for (var u5 = new h7.Buf8(256), n7 = 0; n7 < 256; n7++) u5[n7] = 252 <= n7 ? 6 : 248 <= n7 ? 5 : 240 <= n7 ? 4 : 224 <= n7 ? 3 : 192 <= n7 ? 2 : 1; + function l5(e10, t7) { + if (t7 < 65537 && (e10.subarray && s6 || !e10.subarray && i7)) return String.fromCharCode.apply(null, h7.shrinkBuf(e10, t7)); + for (var r9 = "", n8 = 0; n8 < t7; n8++) r9 += String.fromCharCode(e10[n8]); + return r9; + } + u5[254] = u5[254] = 1, r8.string2buf = function(e10) { + var t7, r9, n8, i8, s7, a3 = e10.length, o9 = 0; + for (i8 = 0; i8 < a3; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o9 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4; + for (t7 = new h7.Buf8(o9), i8 = s7 = 0; s7 < o9; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9); + return t7; + }, r8.buf2binstring = function(e10) { + return l5(e10, e10.length); + }, r8.binstring2buf = function(e10) { + for (var t7 = new h7.Buf8(e10.length), r9 = 0, n8 = t7.length; r9 < n8; r9++) t7[r9] = e10.charCodeAt(r9); + return t7; + }, r8.buf2string = function(e10, t7) { + var r9, n8, i8, s7, a3 = t7 || e10.length, o9 = new Array(2 * a3); + for (r9 = n8 = 0; r9 < a3; ) if ((i8 = e10[r9++]) < 128) o9[n8++] = i8; + else if (4 < (s7 = u5[i8])) o9[n8++] = 65533, r9 += s7 - 1; + else { + for (i8 &= 2 === s7 ? 31 : 3 === s7 ? 15 : 7; 1 < s7 && r9 < a3; ) i8 = i8 << 6 | 63 & e10[r9++], s7--; + 1 < s7 ? o9[n8++] = 65533 : i8 < 65536 ? o9[n8++] = i8 : (i8 -= 65536, o9[n8++] = 55296 | i8 >> 10 & 1023, o9[n8++] = 56320 | 1023 & i8); + } + return l5(o9, n8); + }, r8.utf8border = function(e10, t7) { + var r9; + for ((t7 = t7 || e10.length) > e10.length && (t7 = e10.length), r9 = t7 - 1; 0 <= r9 && 128 == (192 & e10[r9]); ) r9--; + return r9 < 0 ? t7 : 0 === r9 ? t7 : r9 + u5[e10[r9]] > t7 ? r9 : t7; + }; + }, { "./common": 41 }], 43: [function(e9, t6, r8) { + "use strict"; + t6.exports = function(e10, t7, r9, n7) { + for (var i7 = 65535 & e10 | 0, s6 = e10 >>> 16 & 65535 | 0, a3 = 0; 0 !== r9; ) { + for (r9 -= a3 = 2e3 < r9 ? 2e3 : r9; s6 = s6 + (i7 = i7 + t7[n7++] | 0) | 0, --a3; ) ; + i7 %= 65521, s6 %= 65521; + } + return i7 | s6 << 16 | 0; + }; + }, {}], 44: [function(e9, t6, r8) { + "use strict"; + t6.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 }; + }, {}], 45: [function(e9, t6, r8) { + "use strict"; + var o9 = (function() { + for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) { + e10 = r9; + for (var n7 = 0; n7 < 8; n7++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1; + t7[r9] = e10; + } + return t7; + })(); + t6.exports = function(e10, t7, r9, n7) { + var i7 = o9, s6 = n7 + r9; + e10 ^= -1; + for (var a3 = n7; a3 < s6; a3++) e10 = e10 >>> 8 ^ i7[255 & (e10 ^ t7[a3])]; + return -1 ^ e10; + }; + }, {}], 46: [function(e9, t6, r8) { + "use strict"; + var h7, c6 = e9("../utils/common"), u5 = e9("./trees"), d4 = e9("./adler32"), p4 = e9("./crc32"), n7 = e9("./messages"), l5 = 0, f4 = 4, m4 = 0, _3 = -2, g3 = -1, b4 = 4, i7 = 2, v4 = 8, y4 = 9, s6 = 286, a3 = 30, o9 = 19, w3 = 2 * s6 + 1, k2 = 15, x2 = 3, S5 = 258, z3 = S5 + x2 + 1, C3 = 42, E3 = 113, A2 = 1, I3 = 2, O2 = 3, B3 = 4; + function R3(e10, t7) { + return e10.msg = n7[t7], t7; + } + function T3(e10) { + return (e10 << 1) - (4 < e10 ? 9 : 0); + } + function D4(e10) { + for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0; + } + function F2(e10) { + var t7 = e10.state, r9 = t7.pending; + r9 > e10.avail_out && (r9 = e10.avail_out), 0 !== r9 && (c6.arraySet(e10.output, t7.pending_buf, t7.pending_out, r9, e10.next_out), e10.next_out += r9, t7.pending_out += r9, e10.total_out += r9, e10.avail_out -= r9, t7.pending -= r9, 0 === t7.pending && (t7.pending_out = 0)); + } + function N3(e10, t7) { + u5._tr_flush_block(e10, 0 <= e10.block_start ? e10.block_start : -1, e10.strstart - e10.block_start, t7), e10.block_start = e10.strstart, F2(e10.strm); + } + function U2(e10, t7) { + e10.pending_buf[e10.pending++] = t7; + } + function P3(e10, t7) { + e10.pending_buf[e10.pending++] = t7 >>> 8 & 255, e10.pending_buf[e10.pending++] = 255 & t7; + } + function L3(e10, t7) { + var r9, n8, i8 = e10.max_chain_length, s7 = e10.strstart, a4 = e10.prev_length, o10 = e10.nice_match, h8 = e10.strstart > e10.w_size - z3 ? e10.strstart - (e10.w_size - z3) : 0, u6 = e10.window, l6 = e10.w_mask, f5 = e10.prev, c7 = e10.strstart + S5, d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4]; + e10.prev_length >= e10.good_match && (i8 >>= 2), o10 > e10.lookahead && (o10 = e10.lookahead); + do { + if (u6[(r9 = t7) + a4] === p5 && u6[r9 + a4 - 1] === d5 && u6[r9] === u6[s7] && u6[++r9] === u6[s7 + 1]) { + s7 += 2, r9++; + do { + } while (u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && s7 < c7); + if (n8 = S5 - (c7 - s7), s7 = c7 - S5, a4 < n8) { + if (e10.match_start = t7, o10 <= (a4 = n8)) break; + d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4]; + } + } + } while ((t7 = f5[t7 & l6]) > h8 && 0 != --i8); + return a4 <= e10.lookahead ? a4 : e10.lookahead; + } + function j3(e10) { + var t7, r9, n8, i8, s7, a4, o10, h8, u6, l6, f5 = e10.w_size; + do { + if (i8 = e10.window_size - e10.lookahead - e10.strstart, e10.strstart >= f5 + (f5 - z3)) { + for (c6.arraySet(e10.window, e10.window, f5, f5, 0), e10.match_start -= f5, e10.strstart -= f5, e10.block_start -= f5, t7 = r9 = e10.hash_size; n8 = e10.head[--t7], e10.head[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ; + for (t7 = r9 = f5; n8 = e10.prev[--t7], e10.prev[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ; + i8 += f5; + } + if (0 === e10.strm.avail_in) break; + if (a4 = e10.strm, o10 = e10.window, h8 = e10.strstart + e10.lookahead, u6 = i8, l6 = void 0, l6 = a4.avail_in, u6 < l6 && (l6 = u6), r9 = 0 === l6 ? 0 : (a4.avail_in -= l6, c6.arraySet(o10, a4.input, a4.next_in, l6, h8), 1 === a4.state.wrap ? a4.adler = d4(a4.adler, o10, l6, h8) : 2 === a4.state.wrap && (a4.adler = p4(a4.adler, o10, l6, h8)), a4.next_in += l6, a4.total_in += l6, l6), e10.lookahead += r9, e10.lookahead + e10.insert >= x2) for (s7 = e10.strstart - e10.insert, e10.ins_h = e10.window[s7], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + 1]) & e10.hash_mask; e10.insert && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + x2 - 1]) & e10.hash_mask, e10.prev[s7 & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = s7, s7++, e10.insert--, !(e10.lookahead + e10.insert < x2)); ) ; + } while (e10.lookahead < z3 && 0 !== e10.strm.avail_in); + } + function Z2(e10, t7) { + for (var r9, n8; ; ) { + if (e10.lookahead < z3) { + if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2; + if (0 === e10.lookahead) break; + } + if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 !== r9 && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9)), e10.match_length >= x2) if (n8 = u5._tr_tally(e10, e10.strstart - e10.match_start, e10.match_length - x2), e10.lookahead -= e10.match_length, e10.match_length <= e10.max_lazy_match && e10.lookahead >= x2) { + for (e10.match_length--; e10.strstart++, e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart, 0 != --e10.match_length; ) ; + e10.strstart++; + } else e10.strstart += e10.match_length, e10.match_length = 0, e10.ins_h = e10.window[e10.strstart], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + 1]) & e10.hash_mask; + else n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart]), e10.lookahead--, e10.strstart++; + if (n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2; + } + return e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3; + } + function W2(e10, t7) { + for (var r9, n8, i8; ; ) { + if (e10.lookahead < z3) { + if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2; + if (0 === e10.lookahead) break; + } + if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), e10.prev_length = e10.match_length, e10.prev_match = e10.match_start, e10.match_length = x2 - 1, 0 !== r9 && e10.prev_length < e10.max_lazy_match && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9), e10.match_length <= 5 && (1 === e10.strategy || e10.match_length === x2 && 4096 < e10.strstart - e10.match_start) && (e10.match_length = x2 - 1)), e10.prev_length >= x2 && e10.match_length <= e10.prev_length) { + for (i8 = e10.strstart + e10.lookahead - x2, n8 = u5._tr_tally(e10, e10.strstart - 1 - e10.prev_match, e10.prev_length - x2), e10.lookahead -= e10.prev_length - 1, e10.prev_length -= 2; ++e10.strstart <= i8 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 != --e10.prev_length; ) ; + if (e10.match_available = 0, e10.match_length = x2 - 1, e10.strstart++, n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2; + } else if (e10.match_available) { + if ((n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1])) && N3(e10, false), e10.strstart++, e10.lookahead--, 0 === e10.strm.avail_out) return A2; + } else e10.match_available = 1, e10.strstart++, e10.lookahead--; + } + return e10.match_available && (n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1]), e10.match_available = 0), e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3; + } + function M4(e10, t7, r9, n8, i8) { + this.good_length = e10, this.max_lazy = t7, this.nice_length = r9, this.max_chain = n8, this.func = i8; + } + function H2() { + this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v4, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c6.Buf16(2 * w3), this.dyn_dtree = new c6.Buf16(2 * (2 * a3 + 1)), this.bl_tree = new c6.Buf16(2 * (2 * o9 + 1)), D4(this.dyn_ltree), D4(this.dyn_dtree), D4(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c6.Buf16(k2 + 1), this.heap = new c6.Buf16(2 * s6 + 1), D4(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c6.Buf16(2 * s6 + 1), D4(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0; + } + function G2(e10) { + var t7; + return e10 && e10.state ? (e10.total_in = e10.total_out = 0, e10.data_type = i7, (t7 = e10.state).pending = 0, t7.pending_out = 0, t7.wrap < 0 && (t7.wrap = -t7.wrap), t7.status = t7.wrap ? C3 : E3, e10.adler = 2 === t7.wrap ? 0 : 1, t7.last_flush = l5, u5._tr_init(t7), m4) : R3(e10, _3); + } + function K2(e10) { + var t7 = G2(e10); + return t7 === m4 && (function(e11) { + e11.window_size = 2 * e11.w_size, D4(e11.head), e11.max_lazy_match = h7[e11.level].max_lazy, e11.good_match = h7[e11.level].good_length, e11.nice_match = h7[e11.level].nice_length, e11.max_chain_length = h7[e11.level].max_chain, e11.strstart = 0, e11.block_start = 0, e11.lookahead = 0, e11.insert = 0, e11.match_length = e11.prev_length = x2 - 1, e11.match_available = 0, e11.ins_h = 0; + })(e10.state), t7; + } + function Y(e10, t7, r9, n8, i8, s7) { + if (!e10) return _3; + var a4 = 1; + if (t7 === g3 && (t7 = 6), n8 < 0 ? (a4 = 0, n8 = -n8) : 15 < n8 && (a4 = 2, n8 -= 16), i8 < 1 || y4 < i8 || r9 !== v4 || n8 < 8 || 15 < n8 || t7 < 0 || 9 < t7 || s7 < 0 || b4 < s7) return R3(e10, _3); + 8 === n8 && (n8 = 9); + var o10 = new H2(); + return (e10.state = o10).strm = e10, o10.wrap = a4, o10.gzhead = null, o10.w_bits = n8, o10.w_size = 1 << o10.w_bits, o10.w_mask = o10.w_size - 1, o10.hash_bits = i8 + 7, o10.hash_size = 1 << o10.hash_bits, o10.hash_mask = o10.hash_size - 1, o10.hash_shift = ~~((o10.hash_bits + x2 - 1) / x2), o10.window = new c6.Buf8(2 * o10.w_size), o10.head = new c6.Buf16(o10.hash_size), o10.prev = new c6.Buf16(o10.w_size), o10.lit_bufsize = 1 << i8 + 6, o10.pending_buf_size = 4 * o10.lit_bufsize, o10.pending_buf = new c6.Buf8(o10.pending_buf_size), o10.d_buf = 1 * o10.lit_bufsize, o10.l_buf = 3 * o10.lit_bufsize, o10.level = t7, o10.strategy = s7, o10.method = r9, K2(e10); + } + h7 = [new M4(0, 0, 0, 0, function(e10, t7) { + var r9 = 65535; + for (r9 > e10.pending_buf_size - 5 && (r9 = e10.pending_buf_size - 5); ; ) { + if (e10.lookahead <= 1) { + if (j3(e10), 0 === e10.lookahead && t7 === l5) return A2; + if (0 === e10.lookahead) break; + } + e10.strstart += e10.lookahead, e10.lookahead = 0; + var n8 = e10.block_start + r9; + if ((0 === e10.strstart || e10.strstart >= n8) && (e10.lookahead = e10.strstart - n8, e10.strstart = n8, N3(e10, false), 0 === e10.strm.avail_out)) return A2; + if (e10.strstart - e10.block_start >= e10.w_size - z3 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2; + } + return e10.insert = 0, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : (e10.strstart > e10.block_start && (N3(e10, false), e10.strm.avail_out), A2); + }), new M4(4, 4, 8, 4, Z2), new M4(4, 5, 16, 8, Z2), new M4(4, 6, 32, 32, Z2), new M4(4, 4, 16, 16, W2), new M4(8, 16, 32, 32, W2), new M4(8, 16, 128, 128, W2), new M4(8, 32, 128, 256, W2), new M4(32, 128, 258, 1024, W2), new M4(32, 258, 258, 4096, W2)], r8.deflateInit = function(e10, t7) { + return Y(e10, t7, v4, 15, 8, 0); + }, r8.deflateInit2 = Y, r8.deflateReset = K2, r8.deflateResetKeep = G2, r8.deflateSetHeader = function(e10, t7) { + return e10 && e10.state ? 2 !== e10.state.wrap ? _3 : (e10.state.gzhead = t7, m4) : _3; + }, r8.deflate = function(e10, t7) { + var r9, n8, i8, s7; + if (!e10 || !e10.state || 5 < t7 || t7 < 0) return e10 ? R3(e10, _3) : _3; + if (n8 = e10.state, !e10.output || !e10.input && 0 !== e10.avail_in || 666 === n8.status && t7 !== f4) return R3(e10, 0 === e10.avail_out ? -5 : _3); + if (n8.strm = e10, r9 = n8.last_flush, n8.last_flush = t7, n8.status === C3) if (2 === n8.wrap) e10.adler = 0, U2(n8, 31), U2(n8, 139), U2(n8, 8), n8.gzhead ? (U2(n8, (n8.gzhead.text ? 1 : 0) + (n8.gzhead.hcrc ? 2 : 0) + (n8.gzhead.extra ? 4 : 0) + (n8.gzhead.name ? 8 : 0) + (n8.gzhead.comment ? 16 : 0)), U2(n8, 255 & n8.gzhead.time), U2(n8, n8.gzhead.time >> 8 & 255), U2(n8, n8.gzhead.time >> 16 & 255), U2(n8, n8.gzhead.time >> 24 & 255), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 255 & n8.gzhead.os), n8.gzhead.extra && n8.gzhead.extra.length && (U2(n8, 255 & n8.gzhead.extra.length), U2(n8, n8.gzhead.extra.length >> 8 & 255)), n8.gzhead.hcrc && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending, 0)), n8.gzindex = 0, n8.status = 69) : (U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 3), n8.status = E3); + else { + var a4 = v4 + (n8.w_bits - 8 << 4) << 8; + a4 |= (2 <= n8.strategy || n8.level < 2 ? 0 : n8.level < 6 ? 1 : 6 === n8.level ? 2 : 3) << 6, 0 !== n8.strstart && (a4 |= 32), a4 += 31 - a4 % 31, n8.status = E3, P3(n8, a4), 0 !== n8.strstart && (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), e10.adler = 1; + } + if (69 === n8.status) if (n8.gzhead.extra) { + for (i8 = n8.pending; n8.gzindex < (65535 & n8.gzhead.extra.length) && (n8.pending !== n8.pending_buf_size || (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending !== n8.pending_buf_size)); ) U2(n8, 255 & n8.gzhead.extra[n8.gzindex]), n8.gzindex++; + n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), n8.gzindex === n8.gzhead.extra.length && (n8.gzindex = 0, n8.status = 73); + } else n8.status = 73; + if (73 === n8.status) if (n8.gzhead.name) { + i8 = n8.pending; + do { + if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) { + s7 = 1; + break; + } + s7 = n8.gzindex < n8.gzhead.name.length ? 255 & n8.gzhead.name.charCodeAt(n8.gzindex++) : 0, U2(n8, s7); + } while (0 !== s7); + n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.gzindex = 0, n8.status = 91); + } else n8.status = 91; + if (91 === n8.status) if (n8.gzhead.comment) { + i8 = n8.pending; + do { + if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) { + s7 = 1; + break; + } + s7 = n8.gzindex < n8.gzhead.comment.length ? 255 & n8.gzhead.comment.charCodeAt(n8.gzindex++) : 0, U2(n8, s7); + } while (0 !== s7); + n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.status = 103); + } else n8.status = 103; + if (103 === n8.status && (n8.gzhead.hcrc ? (n8.pending + 2 > n8.pending_buf_size && F2(e10), n8.pending + 2 <= n8.pending_buf_size && (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), e10.adler = 0, n8.status = E3)) : n8.status = E3), 0 !== n8.pending) { + if (F2(e10), 0 === e10.avail_out) return n8.last_flush = -1, m4; + } else if (0 === e10.avail_in && T3(t7) <= T3(r9) && t7 !== f4) return R3(e10, -5); + if (666 === n8.status && 0 !== e10.avail_in) return R3(e10, -5); + if (0 !== e10.avail_in || 0 !== n8.lookahead || t7 !== l5 && 666 !== n8.status) { + var o10 = 2 === n8.strategy ? (function(e11, t8) { + for (var r10; ; ) { + if (0 === e11.lookahead && (j3(e11), 0 === e11.lookahead)) { + if (t8 === l5) return A2; + break; + } + if (e11.match_length = 0, r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++, r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2; + } + return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3; + })(n8, t7) : 3 === n8.strategy ? (function(e11, t8) { + for (var r10, n9, i9, s8, a5 = e11.window; ; ) { + if (e11.lookahead <= S5) { + if (j3(e11), e11.lookahead <= S5 && t8 === l5) return A2; + if (0 === e11.lookahead) break; + } + if (e11.match_length = 0, e11.lookahead >= x2 && 0 < e11.strstart && (n9 = a5[i9 = e11.strstart - 1]) === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9]) { + s8 = e11.strstart + S5; + do { + } while (n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && i9 < s8); + e11.match_length = S5 - (s8 - i9), e11.match_length > e11.lookahead && (e11.match_length = e11.lookahead); + } + if (e11.match_length >= x2 ? (r10 = u5._tr_tally(e11, 1, e11.match_length - x2), e11.lookahead -= e11.match_length, e11.strstart += e11.match_length, e11.match_length = 0) : (r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++), r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2; + } + return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3; + })(n8, t7) : h7[n8.level].func(n8, t7); + if (o10 !== O2 && o10 !== B3 || (n8.status = 666), o10 === A2 || o10 === O2) return 0 === e10.avail_out && (n8.last_flush = -1), m4; + if (o10 === I3 && (1 === t7 ? u5._tr_align(n8) : 5 !== t7 && (u5._tr_stored_block(n8, 0, 0, false), 3 === t7 && (D4(n8.head), 0 === n8.lookahead && (n8.strstart = 0, n8.block_start = 0, n8.insert = 0))), F2(e10), 0 === e10.avail_out)) return n8.last_flush = -1, m4; + } + return t7 !== f4 ? m4 : n8.wrap <= 0 ? 1 : (2 === n8.wrap ? (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), U2(n8, e10.adler >> 16 & 255), U2(n8, e10.adler >> 24 & 255), U2(n8, 255 & e10.total_in), U2(n8, e10.total_in >> 8 & 255), U2(n8, e10.total_in >> 16 & 255), U2(n8, e10.total_in >> 24 & 255)) : (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), F2(e10), 0 < n8.wrap && (n8.wrap = -n8.wrap), 0 !== n8.pending ? m4 : 1); + }, r8.deflateEnd = function(e10) { + var t7; + return e10 && e10.state ? (t7 = e10.state.status) !== C3 && 69 !== t7 && 73 !== t7 && 91 !== t7 && 103 !== t7 && t7 !== E3 && 666 !== t7 ? R3(e10, _3) : (e10.state = null, t7 === E3 ? R3(e10, -3) : m4) : _3; + }, r8.deflateSetDictionary = function(e10, t7) { + var r9, n8, i8, s7, a4, o10, h8, u6, l6 = t7.length; + if (!e10 || !e10.state) return _3; + if (2 === (s7 = (r9 = e10.state).wrap) || 1 === s7 && r9.status !== C3 || r9.lookahead) return _3; + for (1 === s7 && (e10.adler = d4(e10.adler, t7, l6, 0)), r9.wrap = 0, l6 >= r9.w_size && (0 === s7 && (D4(r9.head), r9.strstart = 0, r9.block_start = 0, r9.insert = 0), u6 = new c6.Buf8(r9.w_size), c6.arraySet(u6, t7, l6 - r9.w_size, r9.w_size, 0), t7 = u6, l6 = r9.w_size), a4 = e10.avail_in, o10 = e10.next_in, h8 = e10.input, e10.avail_in = l6, e10.next_in = 0, e10.input = t7, j3(r9); r9.lookahead >= x2; ) { + for (n8 = r9.strstart, i8 = r9.lookahead - (x2 - 1); r9.ins_h = (r9.ins_h << r9.hash_shift ^ r9.window[n8 + x2 - 1]) & r9.hash_mask, r9.prev[n8 & r9.w_mask] = r9.head[r9.ins_h], r9.head[r9.ins_h] = n8, n8++, --i8; ) ; + r9.strstart = n8, r9.lookahead = x2 - 1, j3(r9); + } + return r9.strstart += r9.lookahead, r9.block_start = r9.strstart, r9.insert = r9.lookahead, r9.lookahead = 0, r9.match_length = r9.prev_length = x2 - 1, r9.match_available = 0, e10.next_in = o10, e10.input = h8, e10.avail_in = a4, r9.wrap = s7, m4; + }, r8.deflateInfo = "pako deflate (from Nodeca project)"; + }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./messages": 51, "./trees": 52 }], 47: [function(e9, t6, r8) { + "use strict"; + t6.exports = function() { + this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = false; + }; + }, {}], 48: [function(e9, t6, r8) { + "use strict"; + t6.exports = function(e10, t7) { + var r9, n7, i7, s6, a3, o9, h7, u5, l5, f4, c6, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3; + r9 = e10.state, n7 = e10.next_in, z3 = e10.input, i7 = n7 + (e10.avail_in - 5), s6 = e10.next_out, C3 = e10.output, a3 = s6 - (t7 - e10.avail_out), o9 = s6 + (e10.avail_out - 257), h7 = r9.dmax, u5 = r9.wsize, l5 = r9.whave, f4 = r9.wnext, c6 = r9.window, d4 = r9.hold, p4 = r9.bits, m4 = r9.lencode, _3 = r9.distcode, g3 = (1 << r9.lenbits) - 1, b4 = (1 << r9.distbits) - 1; + e: do { + p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = m4[d4 & g3]; + t: for (; ; ) { + if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, 0 === (y4 = v4 >>> 16 & 255)) C3[s6++] = 65535 & v4; + else { + if (!(16 & y4)) { + if (0 == (64 & y4)) { + v4 = m4[(65535 & v4) + (d4 & (1 << y4) - 1)]; + continue t; + } + if (32 & y4) { + r9.mode = 12; + break e; + } + e10.msg = "invalid literal/length code", r9.mode = 30; + break e; + } + w3 = 65535 & v4, (y4 &= 15) && (p4 < y4 && (d4 += z3[n7++] << p4, p4 += 8), w3 += d4 & (1 << y4) - 1, d4 >>>= y4, p4 -= y4), p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = _3[d4 & b4]; + r: for (; ; ) { + if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, !(16 & (y4 = v4 >>> 16 & 255))) { + if (0 == (64 & y4)) { + v4 = _3[(65535 & v4) + (d4 & (1 << y4) - 1)]; + continue r; + } + e10.msg = "invalid distance code", r9.mode = 30; + break e; + } + if (k2 = 65535 & v4, p4 < (y4 &= 15) && (d4 += z3[n7++] << p4, (p4 += 8) < y4 && (d4 += z3[n7++] << p4, p4 += 8)), h7 < (k2 += d4 & (1 << y4) - 1)) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break e; + } + if (d4 >>>= y4, p4 -= y4, (y4 = s6 - a3) < k2) { + if (l5 < (y4 = k2 - y4) && r9.sane) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break e; + } + if (S5 = c6, (x2 = 0) === f4) { + if (x2 += u5 - y4, y4 < w3) { + for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ; + x2 = s6 - k2, S5 = C3; + } + } else if (f4 < y4) { + if (x2 += u5 + f4 - y4, (y4 -= f4) < w3) { + for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ; + if (x2 = 0, f4 < w3) { + for (w3 -= y4 = f4; C3[s6++] = c6[x2++], --y4; ) ; + x2 = s6 - k2, S5 = C3; + } + } + } else if (x2 += f4 - y4, y4 < w3) { + for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ; + x2 = s6 - k2, S5 = C3; + } + for (; 2 < w3; ) C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], w3 -= 3; + w3 && (C3[s6++] = S5[x2++], 1 < w3 && (C3[s6++] = S5[x2++])); + } else { + for (x2 = s6 - k2; C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], 2 < (w3 -= 3); ) ; + w3 && (C3[s6++] = C3[x2++], 1 < w3 && (C3[s6++] = C3[x2++])); + } + break; + } + } + break; + } + } while (n7 < i7 && s6 < o9); + n7 -= w3 = p4 >> 3, d4 &= (1 << (p4 -= w3 << 3)) - 1, e10.next_in = n7, e10.next_out = s6, e10.avail_in = n7 < i7 ? i7 - n7 + 5 : 5 - (n7 - i7), e10.avail_out = s6 < o9 ? o9 - s6 + 257 : 257 - (s6 - o9), r9.hold = d4, r9.bits = p4; + }; + }, {}], 49: [function(e9, t6, r8) { + "use strict"; + var I3 = e9("../utils/common"), O2 = e9("./adler32"), B3 = e9("./crc32"), R3 = e9("./inffast"), T3 = e9("./inftrees"), D4 = 1, F2 = 2, N3 = 0, U2 = -2, P3 = 1, n7 = 852, i7 = 592; + function L3(e10) { + return (e10 >>> 24 & 255) + (e10 >>> 8 & 65280) + ((65280 & e10) << 8) + ((255 & e10) << 24); + } + function s6() { + this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I3.Buf16(320), this.work = new I3.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0; + } + function a3(e10) { + var t7; + return e10 && e10.state ? (t7 = e10.state, e10.total_in = e10.total_out = t7.total = 0, e10.msg = "", t7.wrap && (e10.adler = 1 & t7.wrap), t7.mode = P3, t7.last = 0, t7.havedict = 0, t7.dmax = 32768, t7.head = null, t7.hold = 0, t7.bits = 0, t7.lencode = t7.lendyn = new I3.Buf32(n7), t7.distcode = t7.distdyn = new I3.Buf32(i7), t7.sane = 1, t7.back = -1, N3) : U2; + } + function o9(e10) { + var t7; + return e10 && e10.state ? ((t7 = e10.state).wsize = 0, t7.whave = 0, t7.wnext = 0, a3(e10)) : U2; + } + function h7(e10, t7) { + var r9, n8; + return e10 && e10.state ? (n8 = e10.state, t7 < 0 ? (r9 = 0, t7 = -t7) : (r9 = 1 + (t7 >> 4), t7 < 48 && (t7 &= 15)), t7 && (t7 < 8 || 15 < t7) ? U2 : (null !== n8.window && n8.wbits !== t7 && (n8.window = null), n8.wrap = r9, n8.wbits = t7, o9(e10))) : U2; + } + function u5(e10, t7) { + var r9, n8; + return e10 ? (n8 = new s6(), (e10.state = n8).window = null, (r9 = h7(e10, t7)) !== N3 && (e10.state = null), r9) : U2; + } + var l5, f4, c6 = true; + function j3(e10) { + if (c6) { + var t7; + for (l5 = new I3.Buf32(512), f4 = new I3.Buf32(32), t7 = 0; t7 < 144; ) e10.lens[t7++] = 8; + for (; t7 < 256; ) e10.lens[t7++] = 9; + for (; t7 < 280; ) e10.lens[t7++] = 7; + for (; t7 < 288; ) e10.lens[t7++] = 8; + for (T3(D4, e10.lens, 0, 288, l5, 0, e10.work, { bits: 9 }), t7 = 0; t7 < 32; ) e10.lens[t7++] = 5; + T3(F2, e10.lens, 0, 32, f4, 0, e10.work, { bits: 5 }), c6 = false; + } + e10.lencode = l5, e10.lenbits = 9, e10.distcode = f4, e10.distbits = 5; + } + function Z2(e10, t7, r9, n8) { + var i8, s7 = e10.state; + return null === s7.window && (s7.wsize = 1 << s7.wbits, s7.wnext = 0, s7.whave = 0, s7.window = new I3.Buf8(s7.wsize)), n8 >= s7.wsize ? (I3.arraySet(s7.window, t7, r9 - s7.wsize, s7.wsize, 0), s7.wnext = 0, s7.whave = s7.wsize) : (n8 < (i8 = s7.wsize - s7.wnext) && (i8 = n8), I3.arraySet(s7.window, t7, r9 - n8, i8, s7.wnext), (n8 -= i8) ? (I3.arraySet(s7.window, t7, r9 - n8, n8, 0), s7.wnext = n8, s7.whave = s7.wsize) : (s7.wnext += i8, s7.wnext === s7.wsize && (s7.wnext = 0), s7.whave < s7.wsize && (s7.whave += i8))), 0; + } + r8.inflateReset = o9, r8.inflateReset2 = h7, r8.inflateResetKeep = a3, r8.inflateInit = function(e10) { + return u5(e10, 15); + }, r8.inflateInit2 = u5, r8.inflate = function(e10, t7) { + var r9, n8, i8, s7, a4, o10, h8, u6, l6, f5, c7, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3 = 0, E3 = new I3.Buf8(4), A2 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + if (!e10 || !e10.state || !e10.output || !e10.input && 0 !== e10.avail_in) return U2; + 12 === (r9 = e10.state).mode && (r9.mode = 13), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, f5 = o10, c7 = h8, x2 = N3; + e: for (; ; ) switch (r9.mode) { + case P3: + if (0 === r9.wrap) { + r9.mode = 13; + break; + } + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (2 & r9.wrap && 35615 === u6) { + E3[r9.check = 0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0), l6 = u6 = 0, r9.mode = 2; + break; + } + if (r9.flags = 0, r9.head && (r9.head.done = false), !(1 & r9.wrap) || (((255 & u6) << 8) + (u6 >> 8)) % 31) { + e10.msg = "incorrect header check", r9.mode = 30; + break; + } + if (8 != (15 & u6)) { + e10.msg = "unknown compression method", r9.mode = 30; + break; + } + if (l6 -= 4, k2 = 8 + (15 & (u6 >>>= 4)), 0 === r9.wbits) r9.wbits = k2; + else if (k2 > r9.wbits) { + e10.msg = "invalid window size", r9.mode = 30; + break; + } + r9.dmax = 1 << k2, e10.adler = r9.check = 1, r9.mode = 512 & u6 ? 10 : 12, l6 = u6 = 0; + break; + case 2: + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (r9.flags = u6, 8 != (255 & r9.flags)) { + e10.msg = "unknown compression method", r9.mode = 30; + break; + } + if (57344 & r9.flags) { + e10.msg = "unknown header flags set", r9.mode = 30; + break; + } + r9.head && (r9.head.text = u6 >> 8 & 1), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 3; + case 3: + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.head && (r9.head.time = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, E3[2] = u6 >>> 16 & 255, E3[3] = u6 >>> 24 & 255, r9.check = B3(r9.check, E3, 4, 0)), l6 = u6 = 0, r9.mode = 4; + case 4: + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.head && (r9.head.xflags = 255 & u6, r9.head.os = u6 >> 8), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 5; + case 5: + if (1024 & r9.flags) { + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.length = u6, r9.head && (r9.head.extra_len = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0; + } else r9.head && (r9.head.extra = null); + r9.mode = 6; + case 6: + if (1024 & r9.flags && (o10 < (d4 = r9.length) && (d4 = o10), d4 && (r9.head && (k2 = r9.head.extra_len - r9.length, r9.head.extra || (r9.head.extra = new Array(r9.head.extra_len)), I3.arraySet(r9.head.extra, n8, s7, d4, k2)), 512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, r9.length -= d4), r9.length)) break e; + r9.length = 0, r9.mode = 7; + case 7: + if (2048 & r9.flags) { + if (0 === o10) break e; + for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.name += String.fromCharCode(k2)), k2 && d4 < o10; ) ; + if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e; + } else r9.head && (r9.head.name = null); + r9.length = 0, r9.mode = 8; + case 8: + if (4096 & r9.flags) { + if (0 === o10) break e; + for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.comment += String.fromCharCode(k2)), k2 && d4 < o10; ) ; + if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e; + } else r9.head && (r9.head.comment = null); + r9.mode = 9; + case 9: + if (512 & r9.flags) { + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (u6 !== (65535 & r9.check)) { + e10.msg = "header crc mismatch", r9.mode = 30; + break; + } + l6 = u6 = 0; + } + r9.head && (r9.head.hcrc = r9.flags >> 9 & 1, r9.head.done = true), e10.adler = r9.check = 0, r9.mode = 12; + break; + case 10: + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + e10.adler = r9.check = L3(u6), l6 = u6 = 0, r9.mode = 11; + case 11: + if (0 === r9.havedict) return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, 2; + e10.adler = r9.check = 1, r9.mode = 12; + case 12: + if (5 === t7 || 6 === t7) break e; + case 13: + if (r9.last) { + u6 >>>= 7 & l6, l6 -= 7 & l6, r9.mode = 27; + break; + } + for (; l6 < 3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + switch (r9.last = 1 & u6, l6 -= 1, 3 & (u6 >>>= 1)) { + case 0: + r9.mode = 14; + break; + case 1: + if (j3(r9), r9.mode = 20, 6 !== t7) break; + u6 >>>= 2, l6 -= 2; + break e; + case 2: + r9.mode = 17; + break; + case 3: + e10.msg = "invalid block type", r9.mode = 30; + } + u6 >>>= 2, l6 -= 2; + break; + case 14: + for (u6 >>>= 7 & l6, l6 -= 7 & l6; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if ((65535 & u6) != (u6 >>> 16 ^ 65535)) { + e10.msg = "invalid stored block lengths", r9.mode = 30; + break; + } + if (r9.length = 65535 & u6, l6 = u6 = 0, r9.mode = 15, 6 === t7) break e; + case 15: + r9.mode = 16; + case 16: + if (d4 = r9.length) { + if (o10 < d4 && (d4 = o10), h8 < d4 && (d4 = h8), 0 === d4) break e; + I3.arraySet(i8, n8, s7, d4, a4), o10 -= d4, s7 += d4, h8 -= d4, a4 += d4, r9.length -= d4; + break; + } + r9.mode = 12; + break; + case 17: + for (; l6 < 14; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (r9.nlen = 257 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ndist = 1 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ncode = 4 + (15 & u6), u6 >>>= 4, l6 -= 4, 286 < r9.nlen || 30 < r9.ndist) { + e10.msg = "too many length or distance symbols", r9.mode = 30; + break; + } + r9.have = 0, r9.mode = 18; + case 18: + for (; r9.have < r9.ncode; ) { + for (; l6 < 3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.lens[A2[r9.have++]] = 7 & u6, u6 >>>= 3, l6 -= 3; + } + for (; r9.have < 19; ) r9.lens[A2[r9.have++]] = 0; + if (r9.lencode = r9.lendyn, r9.lenbits = 7, S5 = { bits: r9.lenbits }, x2 = T3(0, r9.lens, 0, 19, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) { + e10.msg = "invalid code lengths set", r9.mode = 30; + break; + } + r9.have = 0, r9.mode = 19; + case 19: + for (; r9.have < r9.nlen + r9.ndist; ) { + for (; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (b4 < 16) u6 >>>= _3, l6 -= _3, r9.lens[r9.have++] = b4; + else { + if (16 === b4) { + for (z3 = _3 + 2; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (u6 >>>= _3, l6 -= _3, 0 === r9.have) { + e10.msg = "invalid bit length repeat", r9.mode = 30; + break; + } + k2 = r9.lens[r9.have - 1], d4 = 3 + (3 & u6), u6 >>>= 2, l6 -= 2; + } else if (17 === b4) { + for (z3 = _3 + 3; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + l6 -= _3, k2 = 0, d4 = 3 + (7 & (u6 >>>= _3)), u6 >>>= 3, l6 -= 3; + } else { + for (z3 = _3 + 7; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + l6 -= _3, k2 = 0, d4 = 11 + (127 & (u6 >>>= _3)), u6 >>>= 7, l6 -= 7; + } + if (r9.have + d4 > r9.nlen + r9.ndist) { + e10.msg = "invalid bit length repeat", r9.mode = 30; + break; + } + for (; d4--; ) r9.lens[r9.have++] = k2; + } + } + if (30 === r9.mode) break; + if (0 === r9.lens[256]) { + e10.msg = "invalid code -- missing end-of-block", r9.mode = 30; + break; + } + if (r9.lenbits = 9, S5 = { bits: r9.lenbits }, x2 = T3(D4, r9.lens, 0, r9.nlen, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) { + e10.msg = "invalid literal/lengths set", r9.mode = 30; + break; + } + if (r9.distbits = 6, r9.distcode = r9.distdyn, S5 = { bits: r9.distbits }, x2 = T3(F2, r9.lens, r9.nlen, r9.ndist, r9.distcode, 0, r9.work, S5), r9.distbits = S5.bits, x2) { + e10.msg = "invalid distances set", r9.mode = 30; + break; + } + if (r9.mode = 20, 6 === t7) break e; + case 20: + r9.mode = 21; + case 21: + if (6 <= o10 && 258 <= h8) { + e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, R3(e10, c7), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, 12 === r9.mode && (r9.back = -1); + break; + } + for (r9.back = 0; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (g3 && 0 == (240 & g3)) { + for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.lencode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + u6 >>>= v4, l6 -= v4, r9.back += v4; + } + if (u6 >>>= _3, l6 -= _3, r9.back += _3, r9.length = b4, 0 === g3) { + r9.mode = 26; + break; + } + if (32 & g3) { + r9.back = -1, r9.mode = 12; + break; + } + if (64 & g3) { + e10.msg = "invalid literal/length code", r9.mode = 30; + break; + } + r9.extra = 15 & g3, r9.mode = 22; + case 22: + if (r9.extra) { + for (z3 = r9.extra; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.length += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra; + } + r9.was = r9.length, r9.mode = 23; + case 23: + for (; g3 = (C3 = r9.distcode[u6 & (1 << r9.distbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (0 == (240 & g3)) { + for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.distcode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + u6 >>>= v4, l6 -= v4, r9.back += v4; + } + if (u6 >>>= _3, l6 -= _3, r9.back += _3, 64 & g3) { + e10.msg = "invalid distance code", r9.mode = 30; + break; + } + r9.offset = b4, r9.extra = 15 & g3, r9.mode = 24; + case 24: + if (r9.extra) { + for (z3 = r9.extra; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.offset += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra; + } + if (r9.offset > r9.dmax) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break; + } + r9.mode = 25; + case 25: + if (0 === h8) break e; + if (d4 = c7 - h8, r9.offset > d4) { + if ((d4 = r9.offset - d4) > r9.whave && r9.sane) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break; + } + p4 = d4 > r9.wnext ? (d4 -= r9.wnext, r9.wsize - d4) : r9.wnext - d4, d4 > r9.length && (d4 = r9.length), m4 = r9.window; + } else m4 = i8, p4 = a4 - r9.offset, d4 = r9.length; + for (h8 < d4 && (d4 = h8), h8 -= d4, r9.length -= d4; i8[a4++] = m4[p4++], --d4; ) ; + 0 === r9.length && (r9.mode = 21); + break; + case 26: + if (0 === h8) break e; + i8[a4++] = r9.length, h8--, r9.mode = 21; + break; + case 27: + if (r9.wrap) { + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 |= n8[s7++] << l6, l6 += 8; + } + if (c7 -= h8, e10.total_out += c7, r9.total += c7, c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, a4 - c7) : O2(r9.check, i8, c7, a4 - c7)), c7 = h8, (r9.flags ? u6 : L3(u6)) !== r9.check) { + e10.msg = "incorrect data check", r9.mode = 30; + break; + } + l6 = u6 = 0; + } + r9.mode = 28; + case 28: + if (r9.wrap && r9.flags) { + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (u6 !== (4294967295 & r9.total)) { + e10.msg = "incorrect length check", r9.mode = 30; + break; + } + l6 = u6 = 0; + } + r9.mode = 29; + case 29: + x2 = 1; + break e; + case 30: + x2 = -3; + break e; + case 31: + return -4; + case 32: + default: + return U2; + } + return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, (r9.wsize || c7 !== e10.avail_out && r9.mode < 30 && (r9.mode < 27 || 4 !== t7)) && Z2(e10, e10.output, e10.next_out, c7 - e10.avail_out) ? (r9.mode = 31, -4) : (f5 -= e10.avail_in, c7 -= e10.avail_out, e10.total_in += f5, e10.total_out += c7, r9.total += c7, r9.wrap && c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, e10.next_out - c7) : O2(r9.check, i8, c7, e10.next_out - c7)), e10.data_type = r9.bits + (r9.last ? 64 : 0) + (12 === r9.mode ? 128 : 0) + (20 === r9.mode || 15 === r9.mode ? 256 : 0), (0 == f5 && 0 === c7 || 4 === t7) && x2 === N3 && (x2 = -5), x2); + }, r8.inflateEnd = function(e10) { + if (!e10 || !e10.state) return U2; + var t7 = e10.state; + return t7.window && (t7.window = null), e10.state = null, N3; + }, r8.inflateGetHeader = function(e10, t7) { + var r9; + return e10 && e10.state ? 0 == (2 & (r9 = e10.state).wrap) ? U2 : ((r9.head = t7).done = false, N3) : U2; + }, r8.inflateSetDictionary = function(e10, t7) { + var r9, n8 = t7.length; + return e10 && e10.state ? 0 !== (r9 = e10.state).wrap && 11 !== r9.mode ? U2 : 11 === r9.mode && O2(1, t7, n8, 0) !== r9.check ? -3 : Z2(e10, t7, n8, n8) ? (r9.mode = 31, -4) : (r9.havedict = 1, N3) : U2; + }, r8.inflateInfo = "pako inflate (from Nodeca project)"; + }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./inffast": 48, "./inftrees": 50 }], 50: [function(e9, t6, r8) { + "use strict"; + var D4 = e9("../utils/common"), F2 = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], N3 = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], U2 = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], P3 = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64]; + t6.exports = function(e10, t7, r9, n7, i7, s6, a3, o9) { + var h7, u5, l5, f4, c6, d4, p4, m4, _3, g3 = o9.bits, b4 = 0, v4 = 0, y4 = 0, w3 = 0, k2 = 0, x2 = 0, S5 = 0, z3 = 0, C3 = 0, E3 = 0, A2 = null, I3 = 0, O2 = new D4.Buf16(16), B3 = new D4.Buf16(16), R3 = null, T3 = 0; + for (b4 = 0; b4 <= 15; b4++) O2[b4] = 0; + for (v4 = 0; v4 < n7; v4++) O2[t7[r9 + v4]]++; + for (k2 = g3, w3 = 15; 1 <= w3 && 0 === O2[w3]; w3--) ; + if (w3 < k2 && (k2 = w3), 0 === w3) return i7[s6++] = 20971520, i7[s6++] = 20971520, o9.bits = 1, 0; + for (y4 = 1; y4 < w3 && 0 === O2[y4]; y4++) ; + for (k2 < y4 && (k2 = y4), b4 = z3 = 1; b4 <= 15; b4++) if (z3 <<= 1, (z3 -= O2[b4]) < 0) return -1; + if (0 < z3 && (0 === e10 || 1 !== w3)) return -1; + for (B3[1] = 0, b4 = 1; b4 < 15; b4++) B3[b4 + 1] = B3[b4] + O2[b4]; + for (v4 = 0; v4 < n7; v4++) 0 !== t7[r9 + v4] && (a3[B3[t7[r9 + v4]]++] = v4); + if (d4 = 0 === e10 ? (A2 = R3 = a3, 19) : 1 === e10 ? (A2 = F2, I3 -= 257, R3 = N3, T3 -= 257, 256) : (A2 = U2, R3 = P3, -1), b4 = y4, c6 = s6, S5 = v4 = E3 = 0, l5 = -1, f4 = (C3 = 1 << (x2 = k2)) - 1, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1; + for (; ; ) { + for (p4 = b4 - S5, _3 = a3[v4] < d4 ? (m4 = 0, a3[v4]) : a3[v4] > d4 ? (m4 = R3[T3 + a3[v4]], A2[I3 + a3[v4]]) : (m4 = 96, 0), h7 = 1 << b4 - S5, y4 = u5 = 1 << x2; i7[c6 + (E3 >> S5) + (u5 -= h7)] = p4 << 24 | m4 << 16 | _3 | 0, 0 !== u5; ) ; + for (h7 = 1 << b4 - 1; E3 & h7; ) h7 >>= 1; + if (0 !== h7 ? (E3 &= h7 - 1, E3 += h7) : E3 = 0, v4++, 0 == --O2[b4]) { + if (b4 === w3) break; + b4 = t7[r9 + a3[v4]]; + } + if (k2 < b4 && (E3 & f4) !== l5) { + for (0 === S5 && (S5 = k2), c6 += y4, z3 = 1 << (x2 = b4 - S5); x2 + S5 < w3 && !((z3 -= O2[x2 + S5]) <= 0); ) x2++, z3 <<= 1; + if (C3 += 1 << x2, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1; + i7[l5 = E3 & f4] = k2 << 24 | x2 << 16 | c6 - s6 | 0; + } + } + return 0 !== E3 && (i7[c6 + E3] = b4 - S5 << 24 | 64 << 16 | 0), o9.bits = k2, 0; + }; + }, { "../utils/common": 41 }], 51: [function(e9, t6, r8) { + "use strict"; + t6.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" }; + }, {}], 52: [function(e9, t6, r8) { + "use strict"; + var i7 = e9("../utils/common"), o9 = 0, h7 = 1; + function n7(e10) { + for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0; + } + var s6 = 0, a3 = 29, u5 = 256, l5 = u5 + 1 + a3, f4 = 30, c6 = 19, _3 = 2 * l5 + 1, g3 = 15, d4 = 16, p4 = 7, m4 = 256, b4 = 16, v4 = 17, y4 = 18, w3 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], k2 = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], x2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], S5 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], z3 = new Array(2 * (l5 + 2)); + n7(z3); + var C3 = new Array(2 * f4); + n7(C3); + var E3 = new Array(512); + n7(E3); + var A2 = new Array(256); + n7(A2); + var I3 = new Array(a3); + n7(I3); + var O2, B3, R3, T3 = new Array(f4); + function D4(e10, t7, r9, n8, i8) { + this.static_tree = e10, this.extra_bits = t7, this.extra_base = r9, this.elems = n8, this.max_length = i8, this.has_stree = e10 && e10.length; + } + function F2(e10, t7) { + this.dyn_tree = e10, this.max_code = 0, this.stat_desc = t7; + } + function N3(e10) { + return e10 < 256 ? E3[e10] : E3[256 + (e10 >>> 7)]; + } + function U2(e10, t7) { + e10.pending_buf[e10.pending++] = 255 & t7, e10.pending_buf[e10.pending++] = t7 >>> 8 & 255; + } + function P3(e10, t7, r9) { + e10.bi_valid > d4 - r9 ? (e10.bi_buf |= t7 << e10.bi_valid & 65535, U2(e10, e10.bi_buf), e10.bi_buf = t7 >> d4 - e10.bi_valid, e10.bi_valid += r9 - d4) : (e10.bi_buf |= t7 << e10.bi_valid & 65535, e10.bi_valid += r9); + } + function L3(e10, t7, r9) { + P3(e10, r9[2 * t7], r9[2 * t7 + 1]); + } + function j3(e10, t7) { + for (var r9 = 0; r9 |= 1 & e10, e10 >>>= 1, r9 <<= 1, 0 < --t7; ) ; + return r9 >>> 1; + } + function Z2(e10, t7, r9) { + var n8, i8, s7 = new Array(g3 + 1), a4 = 0; + for (n8 = 1; n8 <= g3; n8++) s7[n8] = a4 = a4 + r9[n8 - 1] << 1; + for (i8 = 0; i8 <= t7; i8++) { + var o10 = e10[2 * i8 + 1]; + 0 !== o10 && (e10[2 * i8] = j3(s7[o10]++, o10)); + } + } + function W2(e10) { + var t7; + for (t7 = 0; t7 < l5; t7++) e10.dyn_ltree[2 * t7] = 0; + for (t7 = 0; t7 < f4; t7++) e10.dyn_dtree[2 * t7] = 0; + for (t7 = 0; t7 < c6; t7++) e10.bl_tree[2 * t7] = 0; + e10.dyn_ltree[2 * m4] = 1, e10.opt_len = e10.static_len = 0, e10.last_lit = e10.matches = 0; + } + function M4(e10) { + 8 < e10.bi_valid ? U2(e10, e10.bi_buf) : 0 < e10.bi_valid && (e10.pending_buf[e10.pending++] = e10.bi_buf), e10.bi_buf = 0, e10.bi_valid = 0; + } + function H2(e10, t7, r9, n8) { + var i8 = 2 * t7, s7 = 2 * r9; + return e10[i8] < e10[s7] || e10[i8] === e10[s7] && n8[t7] <= n8[r9]; + } + function G2(e10, t7, r9) { + for (var n8 = e10.heap[r9], i8 = r9 << 1; i8 <= e10.heap_len && (i8 < e10.heap_len && H2(t7, e10.heap[i8 + 1], e10.heap[i8], e10.depth) && i8++, !H2(t7, n8, e10.heap[i8], e10.depth)); ) e10.heap[r9] = e10.heap[i8], r9 = i8, i8 <<= 1; + e10.heap[r9] = n8; + } + function K2(e10, t7, r9) { + var n8, i8, s7, a4, o10 = 0; + if (0 !== e10.last_lit) for (; n8 = e10.pending_buf[e10.d_buf + 2 * o10] << 8 | e10.pending_buf[e10.d_buf + 2 * o10 + 1], i8 = e10.pending_buf[e10.l_buf + o10], o10++, 0 === n8 ? L3(e10, i8, t7) : (L3(e10, (s7 = A2[i8]) + u5 + 1, t7), 0 !== (a4 = w3[s7]) && P3(e10, i8 -= I3[s7], a4), L3(e10, s7 = N3(--n8), r9), 0 !== (a4 = k2[s7]) && P3(e10, n8 -= T3[s7], a4)), o10 < e10.last_lit; ) ; + L3(e10, m4, t7); + } + function Y(e10, t7) { + var r9, n8, i8, s7 = t7.dyn_tree, a4 = t7.stat_desc.static_tree, o10 = t7.stat_desc.has_stree, h8 = t7.stat_desc.elems, u6 = -1; + for (e10.heap_len = 0, e10.heap_max = _3, r9 = 0; r9 < h8; r9++) 0 !== s7[2 * r9] ? (e10.heap[++e10.heap_len] = u6 = r9, e10.depth[r9] = 0) : s7[2 * r9 + 1] = 0; + for (; e10.heap_len < 2; ) s7[2 * (i8 = e10.heap[++e10.heap_len] = u6 < 2 ? ++u6 : 0)] = 1, e10.depth[i8] = 0, e10.opt_len--, o10 && (e10.static_len -= a4[2 * i8 + 1]); + for (t7.max_code = u6, r9 = e10.heap_len >> 1; 1 <= r9; r9--) G2(e10, s7, r9); + for (i8 = h8; r9 = e10.heap[1], e10.heap[1] = e10.heap[e10.heap_len--], G2(e10, s7, 1), n8 = e10.heap[1], e10.heap[--e10.heap_max] = r9, e10.heap[--e10.heap_max] = n8, s7[2 * i8] = s7[2 * r9] + s7[2 * n8], e10.depth[i8] = (e10.depth[r9] >= e10.depth[n8] ? e10.depth[r9] : e10.depth[n8]) + 1, s7[2 * r9 + 1] = s7[2 * n8 + 1] = i8, e10.heap[1] = i8++, G2(e10, s7, 1), 2 <= e10.heap_len; ) ; + e10.heap[--e10.heap_max] = e10.heap[1], (function(e11, t8) { + var r10, n9, i9, s8, a5, o11, h9 = t8.dyn_tree, u7 = t8.max_code, l6 = t8.stat_desc.static_tree, f5 = t8.stat_desc.has_stree, c7 = t8.stat_desc.extra_bits, d5 = t8.stat_desc.extra_base, p5 = t8.stat_desc.max_length, m5 = 0; + for (s8 = 0; s8 <= g3; s8++) e11.bl_count[s8] = 0; + for (h9[2 * e11.heap[e11.heap_max] + 1] = 0, r10 = e11.heap_max + 1; r10 < _3; r10++) p5 < (s8 = h9[2 * h9[2 * (n9 = e11.heap[r10]) + 1] + 1] + 1) && (s8 = p5, m5++), h9[2 * n9 + 1] = s8, u7 < n9 || (e11.bl_count[s8]++, a5 = 0, d5 <= n9 && (a5 = c7[n9 - d5]), o11 = h9[2 * n9], e11.opt_len += o11 * (s8 + a5), f5 && (e11.static_len += o11 * (l6[2 * n9 + 1] + a5))); + if (0 !== m5) { + do { + for (s8 = p5 - 1; 0 === e11.bl_count[s8]; ) s8--; + e11.bl_count[s8]--, e11.bl_count[s8 + 1] += 2, e11.bl_count[p5]--, m5 -= 2; + } while (0 < m5); + for (s8 = p5; 0 !== s8; s8--) for (n9 = e11.bl_count[s8]; 0 !== n9; ) u7 < (i9 = e11.heap[--r10]) || (h9[2 * i9 + 1] !== s8 && (e11.opt_len += (s8 - h9[2 * i9 + 1]) * h9[2 * i9], h9[2 * i9 + 1] = s8), n9--); + } + })(e10, t7), Z2(s7, u6, e10.bl_count); + } + function X3(e10, t7, r9) { + var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4; + for (0 === a4 && (h8 = 138, u6 = 3), t7[2 * (r9 + 1) + 1] = 65535, n8 = 0; n8 <= r9; n8++) i8 = a4, a4 = t7[2 * (n8 + 1) + 1], ++o10 < h8 && i8 === a4 || (o10 < u6 ? e10.bl_tree[2 * i8] += o10 : 0 !== i8 ? (i8 !== s7 && e10.bl_tree[2 * i8]++, e10.bl_tree[2 * b4]++) : o10 <= 10 ? e10.bl_tree[2 * v4]++ : e10.bl_tree[2 * y4]++, s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4)); + } + function V3(e10, t7, r9) { + var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4; + for (0 === a4 && (h8 = 138, u6 = 3), n8 = 0; n8 <= r9; n8++) if (i8 = a4, a4 = t7[2 * (n8 + 1) + 1], !(++o10 < h8 && i8 === a4)) { + if (o10 < u6) for (; L3(e10, i8, e10.bl_tree), 0 != --o10; ) ; + else 0 !== i8 ? (i8 !== s7 && (L3(e10, i8, e10.bl_tree), o10--), L3(e10, b4, e10.bl_tree), P3(e10, o10 - 3, 2)) : o10 <= 10 ? (L3(e10, v4, e10.bl_tree), P3(e10, o10 - 3, 3)) : (L3(e10, y4, e10.bl_tree), P3(e10, o10 - 11, 7)); + s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4); + } + } + n7(T3); + var q2 = false; + function J2(e10, t7, r9, n8) { + P3(e10, (s6 << 1) + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) { + M4(e11), n9 && (U2(e11, r10), U2(e11, ~r10)), i7.arraySet(e11.pending_buf, e11.window, t8, r10, e11.pending), e11.pending += r10; + })(e10, t7, r9, true); + } + r8._tr_init = function(e10) { + q2 || ((function() { + var e11, t7, r9, n8, i8, s7 = new Array(g3 + 1); + for (n8 = r9 = 0; n8 < a3 - 1; n8++) for (I3[n8] = r9, e11 = 0; e11 < 1 << w3[n8]; e11++) A2[r9++] = n8; + for (A2[r9 - 1] = n8, n8 = i8 = 0; n8 < 16; n8++) for (T3[n8] = i8, e11 = 0; e11 < 1 << k2[n8]; e11++) E3[i8++] = n8; + for (i8 >>= 7; n8 < f4; n8++) for (T3[n8] = i8 << 7, e11 = 0; e11 < 1 << k2[n8] - 7; e11++) E3[256 + i8++] = n8; + for (t7 = 0; t7 <= g3; t7++) s7[t7] = 0; + for (e11 = 0; e11 <= 143; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++; + for (; e11 <= 255; ) z3[2 * e11 + 1] = 9, e11++, s7[9]++; + for (; e11 <= 279; ) z3[2 * e11 + 1] = 7, e11++, s7[7]++; + for (; e11 <= 287; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++; + for (Z2(z3, l5 + 1, s7), e11 = 0; e11 < f4; e11++) C3[2 * e11 + 1] = 5, C3[2 * e11] = j3(e11, 5); + O2 = new D4(z3, w3, u5 + 1, l5, g3), B3 = new D4(C3, k2, 0, f4, g3), R3 = new D4(new Array(0), x2, 0, c6, p4); + })(), q2 = true), e10.l_desc = new F2(e10.dyn_ltree, O2), e10.d_desc = new F2(e10.dyn_dtree, B3), e10.bl_desc = new F2(e10.bl_tree, R3), e10.bi_buf = 0, e10.bi_valid = 0, W2(e10); + }, r8._tr_stored_block = J2, r8._tr_flush_block = function(e10, t7, r9, n8) { + var i8, s7, a4 = 0; + 0 < e10.level ? (2 === e10.strm.data_type && (e10.strm.data_type = (function(e11) { + var t8, r10 = 4093624447; + for (t8 = 0; t8 <= 31; t8++, r10 >>>= 1) if (1 & r10 && 0 !== e11.dyn_ltree[2 * t8]) return o9; + if (0 !== e11.dyn_ltree[18] || 0 !== e11.dyn_ltree[20] || 0 !== e11.dyn_ltree[26]) return h7; + for (t8 = 32; t8 < u5; t8++) if (0 !== e11.dyn_ltree[2 * t8]) return h7; + return o9; + })(e10)), Y(e10, e10.l_desc), Y(e10, e10.d_desc), a4 = (function(e11) { + var t8; + for (X3(e11, e11.dyn_ltree, e11.l_desc.max_code), X3(e11, e11.dyn_dtree, e11.d_desc.max_code), Y(e11, e11.bl_desc), t8 = c6 - 1; 3 <= t8 && 0 === e11.bl_tree[2 * S5[t8] + 1]; t8--) ; + return e11.opt_len += 3 * (t8 + 1) + 5 + 5 + 4, t8; + })(e10), i8 = e10.opt_len + 3 + 7 >>> 3, (s7 = e10.static_len + 3 + 7 >>> 3) <= i8 && (i8 = s7)) : i8 = s7 = r9 + 5, r9 + 4 <= i8 && -1 !== t7 ? J2(e10, t7, r9, n8) : 4 === e10.strategy || s7 === i8 ? (P3(e10, 2 + (n8 ? 1 : 0), 3), K2(e10, z3, C3)) : (P3(e10, 4 + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) { + var i9; + for (P3(e11, t8 - 257, 5), P3(e11, r10 - 1, 5), P3(e11, n9 - 4, 4), i9 = 0; i9 < n9; i9++) P3(e11, e11.bl_tree[2 * S5[i9] + 1], 3); + V3(e11, e11.dyn_ltree, t8 - 1), V3(e11, e11.dyn_dtree, r10 - 1); + })(e10, e10.l_desc.max_code + 1, e10.d_desc.max_code + 1, a4 + 1), K2(e10, e10.dyn_ltree, e10.dyn_dtree)), W2(e10), n8 && M4(e10); + }, r8._tr_tally = function(e10, t7, r9) { + return e10.pending_buf[e10.d_buf + 2 * e10.last_lit] = t7 >>> 8 & 255, e10.pending_buf[e10.d_buf + 2 * e10.last_lit + 1] = 255 & t7, e10.pending_buf[e10.l_buf + e10.last_lit] = 255 & r9, e10.last_lit++, 0 === t7 ? e10.dyn_ltree[2 * r9]++ : (e10.matches++, t7--, e10.dyn_ltree[2 * (A2[r9] + u5 + 1)]++, e10.dyn_dtree[2 * N3(t7)]++), e10.last_lit === e10.lit_bufsize - 1; + }, r8._tr_align = function(e10) { + P3(e10, 2, 3), L3(e10, m4, z3), (function(e11) { + 16 === e11.bi_valid ? (U2(e11, e11.bi_buf), e11.bi_buf = 0, e11.bi_valid = 0) : 8 <= e11.bi_valid && (e11.pending_buf[e11.pending++] = 255 & e11.bi_buf, e11.bi_buf >>= 8, e11.bi_valid -= 8); + })(e10); + }; + }, { "../utils/common": 41 }], 53: [function(e9, t6, r8) { + "use strict"; + t6.exports = function() { + this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0; + }; + }, {}], 54: [function(e9, t6, r8) { + (function(e10) { + !(function(r9, n7) { + "use strict"; + if (!r9.setImmediate) { + var i7, s6, t7, a3, o9 = 1, h7 = {}, u5 = false, l5 = r9.document, e11 = Object.getPrototypeOf && Object.getPrototypeOf(r9); + e11 = e11 && e11.setTimeout ? e11 : r9, i7 = "[object process]" === {}.toString.call(r9.process) ? function(e12) { + process.nextTick(function() { + c6(e12); + }); + } : (function() { + if (r9.postMessage && !r9.importScripts) { + var e12 = true, t8 = r9.onmessage; + return r9.onmessage = function() { + e12 = false; + }, r9.postMessage("", "*"), r9.onmessage = t8, e12; + } + })() ? (a3 = "setImmediate$" + Math.random() + "$", r9.addEventListener ? r9.addEventListener("message", d4, false) : r9.attachEvent("onmessage", d4), function(e12) { + r9.postMessage(a3 + e12, "*"); + }) : r9.MessageChannel ? ((t7 = new MessageChannel()).port1.onmessage = function(e12) { + c6(e12.data); + }, function(e12) { + t7.port2.postMessage(e12); + }) : l5 && "onreadystatechange" in l5.createElement("script") ? (s6 = l5.documentElement, function(e12) { + var t8 = l5.createElement("script"); + t8.onreadystatechange = function() { + c6(e12), t8.onreadystatechange = null, s6.removeChild(t8), t8 = null; + }, s6.appendChild(t8); + }) : function(e12) { + setTimeout(c6, 0, e12); + }, e11.setImmediate = function(e12) { + "function" != typeof e12 && (e12 = new Function("" + e12)); + for (var t8 = new Array(arguments.length - 1), r10 = 0; r10 < t8.length; r10++) t8[r10] = arguments[r10 + 1]; + var n8 = { callback: e12, args: t8 }; + return h7[o9] = n8, i7(o9), o9++; + }, e11.clearImmediate = f4; + } + function f4(e12) { + delete h7[e12]; + } + function c6(e12) { + if (u5) setTimeout(c6, 0, e12); + else { + var t8 = h7[e12]; + if (t8) { + u5 = true; + try { + !(function(e13) { + var t9 = e13.callback, r10 = e13.args; + switch (r10.length) { + case 0: + t9(); + break; + case 1: + t9(r10[0]); + break; + case 2: + t9(r10[0], r10[1]); + break; + case 3: + t9(r10[0], r10[1], r10[2]); + break; + default: + t9.apply(n7, r10); + } + })(t8); + } finally { + f4(e12), u5 = false; + } + } + } + } + function d4(e12) { + e12.source === r9 && "string" == typeof e12.data && 0 === e12.data.indexOf(a3) && c6(+e12.data.slice(a3.length)); + } + })("undefined" == typeof self ? void 0 === e10 ? this : e10 : self); + }).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); + }, {}] }, {}, [10])(10); + }); + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/core.js +var require_core3 = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/core.js"(exports, module) { + init_process_shim(); + function deepFreeze(obj) { + if (obj instanceof Map) { + obj.clear = obj.delete = obj.set = function() { + throw new Error("map is read-only"); + }; + } else if (obj instanceof Set) { + obj.add = obj.clear = obj.delete = function() { + throw new Error("set is read-only"); + }; + } + Object.freeze(obj); + Object.getOwnPropertyNames(obj).forEach(function(name) { + var prop = obj[name]; + if (typeof prop == "object" && !Object.isFrozen(prop)) { + deepFreeze(prop); + } + }); + return obj; + } + var deepFreezeEs6 = deepFreeze; + var _default = deepFreeze; + deepFreezeEs6.default = _default; + var Response3 = class { + /** + * @param {CompiledMode} mode + */ + constructor(mode) { + if (mode.data === void 0) mode.data = {}; + this.data = mode.data; + this.isMatchIgnored = false; + } + ignoreMatch() { + this.isMatchIgnored = true; + } + }; + function escapeHTML(value) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); + } + function inherit(original, ...objects) { + const result = /* @__PURE__ */ Object.create(null); + for (const key in original) { + result[key] = original[key]; + } + objects.forEach(function(obj) { + for (const key in obj) { + result[key] = obj[key]; + } + }); + return ( + /** @type {T} */ + result + ); + } + var SPAN_CLOSE = ""; + var emitsWrappingTags = (node) => { + return !!node.kind; + }; + var HTMLRenderer = class { + /** + * Creates a new HTMLRenderer + * + * @param {Tree} parseTree - the parse tree (must support `walk` API) + * @param {{classPrefix: string}} options + */ + constructor(parseTree3, options) { + this.buffer = ""; + this.classPrefix = options.classPrefix; + parseTree3.walk(this); + } + /** + * Adds texts to the output stream + * + * @param {string} text */ + addText(text3) { + this.buffer += escapeHTML(text3); + } + /** + * Adds a node open to the output stream (if needed) + * + * @param {Node} node */ + openNode(node) { + if (!emitsWrappingTags(node)) return; + let className = node.kind; + if (!node.sublanguage) { + className = `${this.classPrefix}${className}`; + } + this.span(className); + } + /** + * Adds a node close to the output stream (if needed) + * + * @param {Node} node */ + closeNode(node) { + if (!emitsWrappingTags(node)) return; + this.buffer += SPAN_CLOSE; + } + /** + * returns the accumulated buffer + */ + value() { + return this.buffer; + } + // helpers + /** + * Builds a span element + * + * @param {string} className */ + span(className) { + this.buffer += ``; + } + }; + var TokenTree = class _TokenTree { + constructor() { + this.rootNode = { children: [] }; + this.stack = [this.rootNode]; + } + get top() { + return this.stack[this.stack.length - 1]; + } + get root() { + return this.rootNode; + } + /** @param {Node} node */ + add(node) { + this.top.children.push(node); + } + /** @param {string} kind */ + openNode(kind) { + const node = { kind, children: [] }; + this.add(node); + this.stack.push(node); + } + closeNode() { + if (this.stack.length > 1) { + return this.stack.pop(); + } + return void 0; + } + closeAllNodes() { + while (this.closeNode()) ; + } + toJSON() { + return JSON.stringify(this.rootNode, null, 4); + } + /** + * @typedef { import("./html_renderer").Renderer } Renderer + * @param {Renderer} builder + */ + walk(builder) { + return this.constructor._walk(builder, this.rootNode); + } + /** + * @param {Renderer} builder + * @param {Node} node + */ + static _walk(builder, node) { + if (typeof node === "string") { + builder.addText(node); + } else if (node.children) { + builder.openNode(node); + node.children.forEach((child) => this._walk(builder, child)); + builder.closeNode(node); + } + return builder; + } + /** + * @param {Node} node + */ + static _collapse(node) { + if (typeof node === "string") return; + if (!node.children) return; + if (node.children.every((el) => typeof el === "string")) { + node.children = [node.children.join("")]; + } else { + node.children.forEach((child) => { + _TokenTree._collapse(child); + }); + } + } + }; + var TokenTreeEmitter = class extends TokenTree { + /** + * @param {*} options + */ + constructor(options) { + super(); + this.options = options; + } + /** + * @param {string} text + * @param {string} kind + */ + addKeyword(text3, kind) { + if (text3 === "") { + return; + } + this.openNode(kind); + this.addText(text3); + this.closeNode(); + } + /** + * @param {string} text + */ + addText(text3) { + if (text3 === "") { + return; + } + this.add(text3); + } + /** + * @param {Emitter & {root: DataNode}} emitter + * @param {string} name + */ + addSublanguage(emitter, name) { + const node = emitter.root; + node.kind = name; + node.sublanguage = true; + this.add(node); + } + toHTML() { + const renderer = new HTMLRenderer(this, this.options); + return renderer.value(); + } + finalize() { + return true; + } + }; + function escape4(value) { + return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"), "m"); + } + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function either(...args) { + const joined = "(" + args.map((x2) => source(x2)).join("|") + ")"; + return joined; + } + function countMatchGroups(re2) { + return new RegExp(re2.toString() + "|").exec("").length - 1; + } + function startsWith(re2, lexeme) { + const match2 = re2 && re2.exec(lexeme); + return match2 && match2.index === 0; + } + var BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./; + function join(regexps, separator = "|") { + let numCaptures = 0; + return regexps.map((regex) => { + numCaptures += 1; + const offset = numCaptures; + let re2 = source(regex); + let out = ""; + while (re2.length > 0) { + const match2 = BACKREF_RE.exec(re2); + if (!match2) { + out += re2; + break; + } + out += re2.substring(0, match2.index); + re2 = re2.substring(match2.index + match2[0].length); + if (match2[0][0] === "\\" && match2[1]) { + out += "\\" + String(Number(match2[1]) + offset); + } else { + out += match2[0]; + if (match2[0] === "(") { + numCaptures++; + } + } + } + return out; + }).map((re2) => `(${re2})`).join(separator); + } + var MATCH_NOTHING_RE = /\b\B/; + var IDENT_RE3 = "[a-zA-Z]\\w*"; + var UNDERSCORE_IDENT_RE = "[a-zA-Z_]\\w*"; + var NUMBER_RE = "\\b\\d+(\\.\\d+)?"; + var C_NUMBER_RE = "(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)"; + var BINARY_NUMBER_RE = "\\b(0b[01]+)"; + var RE_STARTERS_RE = "!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~"; + var SHEBANG = (opts = {}) => { + const beginShebang = /^#![ ]*\//; + if (opts.binary) { + opts.begin = concat( + beginShebang, + /.*\b/, + opts.binary, + /\b.*/ + ); + } + return inherit({ + className: "meta", + begin: beginShebang, + end: /$/, + relevance: 0, + /** @type {ModeCallback} */ + "on:begin": (m4, resp) => { + if (m4.index !== 0) resp.ignoreMatch(); + } + }, opts); + }; + var BACKSLASH_ESCAPE = { + begin: "\\\\[\\s\\S]", + relevance: 0 + }; + var APOS_STRING_MODE = { + className: "string", + begin: "'", + end: "'", + illegal: "\\n", + contains: [BACKSLASH_ESCAPE] + }; + var QUOTE_STRING_MODE = { + className: "string", + begin: '"', + end: '"', + illegal: "\\n", + contains: [BACKSLASH_ESCAPE] + }; + var PHRASAL_WORDS_MODE = { + begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ + }; + var COMMENT = function(begin, end, modeOptions = {}) { + const mode = inherit( + { + className: "comment", + begin, + end, + contains: [] + }, + modeOptions + ); + mode.contains.push(PHRASAL_WORDS_MODE); + mode.contains.push({ + className: "doctag", + begin: "(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):", + relevance: 0 + }); + return mode; + }; + var C_LINE_COMMENT_MODE = COMMENT("//", "$"); + var C_BLOCK_COMMENT_MODE = COMMENT("/\\*", "\\*/"); + var HASH_COMMENT_MODE = COMMENT("#", "$"); + var NUMBER_MODE = { + className: "number", + begin: NUMBER_RE, + relevance: 0 + }; + var C_NUMBER_MODE = { + className: "number", + begin: C_NUMBER_RE, + relevance: 0 + }; + var BINARY_NUMBER_MODE = { + className: "number", + begin: BINARY_NUMBER_RE, + relevance: 0 + }; + var CSS_NUMBER_MODE = { + className: "number", + begin: NUMBER_RE + "(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?", + relevance: 0 + }; + var REGEXP_MODE = { + // this outer rule makes sure we actually have a WHOLE regex and not simply + // an expression such as: + // + // 3 / something + // + // (which will then blow up when regex's `illegal` sees the newline) + begin: /(?=\/[^/\n]*\/)/, + contains: [{ + className: "regexp", + begin: /\//, + end: /\/[gimuy]*/, + illegal: /\n/, + contains: [ + BACKSLASH_ESCAPE, + { + begin: /\[/, + end: /\]/, + relevance: 0, + contains: [BACKSLASH_ESCAPE] + } + ] + }] + }; + var TITLE_MODE = { + className: "title", + begin: IDENT_RE3, + relevance: 0 + }; + var UNDERSCORE_TITLE_MODE = { + className: "title", + begin: UNDERSCORE_IDENT_RE, + relevance: 0 + }; + var METHOD_GUARD = { + // excludes method names from keyword processing + begin: "\\.\\s*" + UNDERSCORE_IDENT_RE, + relevance: 0 + }; + var END_SAME_AS_BEGIN = function(mode) { + return Object.assign( + mode, + { + /** @type {ModeCallback} */ + "on:begin": (m4, resp) => { + resp.data._beginMatch = m4[1]; + }, + /** @type {ModeCallback} */ + "on:end": (m4, resp) => { + if (resp.data._beginMatch !== m4[1]) resp.ignoreMatch(); + } + } + ); + }; + var MODES2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + MATCH_NOTHING_RE, + IDENT_RE: IDENT_RE3, + UNDERSCORE_IDENT_RE, + NUMBER_RE, + C_NUMBER_RE, + BINARY_NUMBER_RE, + RE_STARTERS_RE, + SHEBANG, + BACKSLASH_ESCAPE, + APOS_STRING_MODE, + QUOTE_STRING_MODE, + PHRASAL_WORDS_MODE, + COMMENT, + C_LINE_COMMENT_MODE, + C_BLOCK_COMMENT_MODE, + HASH_COMMENT_MODE, + NUMBER_MODE, + C_NUMBER_MODE, + BINARY_NUMBER_MODE, + CSS_NUMBER_MODE, + REGEXP_MODE, + TITLE_MODE, + UNDERSCORE_TITLE_MODE, + METHOD_GUARD, + END_SAME_AS_BEGIN + }); + function skipIfhasPrecedingDot(match2, response) { + const before = match2.input[match2.index - 1]; + if (before === ".") { + response.ignoreMatch(); + } + } + function beginKeywords(mode, parent) { + if (!parent) return; + if (!mode.beginKeywords) return; + mode.begin = "\\b(" + mode.beginKeywords.split(" ").join("|") + ")(?!\\.)(?=\\b|\\s)"; + mode.__beforeBegin = skipIfhasPrecedingDot; + mode.keywords = mode.keywords || mode.beginKeywords; + delete mode.beginKeywords; + if (mode.relevance === void 0) mode.relevance = 0; + } + function compileIllegal(mode, _parent) { + if (!Array.isArray(mode.illegal)) return; + mode.illegal = either(...mode.illegal); + } + function compileMatch(mode, _parent) { + if (!mode.match) return; + if (mode.begin || mode.end) throw new Error("begin & end are not supported with match"); + mode.begin = mode.match; + delete mode.match; + } + function compileRelevance(mode, _parent) { + if (mode.relevance === void 0) mode.relevance = 1; + } + var COMMON_KEYWORDS = [ + "of", + "and", + "for", + "in", + "not", + "or", + "if", + "then", + "parent", + // common variable name + "list", + // common variable name + "value" + // common variable name + ]; + var DEFAULT_KEYWORD_CLASSNAME = "keyword"; + function compileKeywords(rawKeywords, caseInsensitive, className = DEFAULT_KEYWORD_CLASSNAME) { + const compiledKeywords = {}; + if (typeof rawKeywords === "string") { + compileList(className, rawKeywords.split(" ")); + } else if (Array.isArray(rawKeywords)) { + compileList(className, rawKeywords); + } else { + Object.keys(rawKeywords).forEach(function(className2) { + Object.assign( + compiledKeywords, + compileKeywords(rawKeywords[className2], caseInsensitive, className2) + ); + }); + } + return compiledKeywords; + function compileList(className2, keywordList) { + if (caseInsensitive) { + keywordList = keywordList.map((x2) => x2.toLowerCase()); + } + keywordList.forEach(function(keyword) { + const pair = keyword.split("|"); + compiledKeywords[pair[0]] = [className2, scoreForKeyword(pair[0], pair[1])]; + }); + } + } + function scoreForKeyword(keyword, providedScore) { + if (providedScore) { + return Number(providedScore); + } + return commonKeyword(keyword) ? 0 : 1; + } + function commonKeyword(keyword) { + return COMMON_KEYWORDS.includes(keyword.toLowerCase()); + } + function compileLanguage(language, { plugins: plugins2 }) { + function langRe(value, global2) { + return new RegExp( + source(value), + "m" + (language.case_insensitive ? "i" : "") + (global2 ? "g" : "") + ); + } + class MultiRegex { + constructor() { + this.matchIndexes = {}; + this.regexes = []; + this.matchAt = 1; + this.position = 0; + } + // @ts-ignore + addRule(re2, opts) { + opts.position = this.position++; + this.matchIndexes[this.matchAt] = opts; + this.regexes.push([opts, re2]); + this.matchAt += countMatchGroups(re2) + 1; + } + compile() { + if (this.regexes.length === 0) { + this.exec = () => null; + } + const terminators = this.regexes.map((el) => el[1]); + this.matcherRe = langRe(join(terminators), true); + this.lastIndex = 0; + } + /** @param {string} s */ + exec(s6) { + this.matcherRe.lastIndex = this.lastIndex; + const match2 = this.matcherRe.exec(s6); + if (!match2) { + return null; + } + const i7 = match2.findIndex((el, i8) => i8 > 0 && el !== void 0); + const matchData = this.matchIndexes[i7]; + match2.splice(0, i7); + return Object.assign(match2, matchData); + } + } + class ResumableMultiRegex { + constructor() { + this.rules = []; + this.multiRegexes = []; + this.count = 0; + this.lastIndex = 0; + this.regexIndex = 0; + } + // @ts-ignore + getMatcher(index) { + if (this.multiRegexes[index]) return this.multiRegexes[index]; + const matcher = new MultiRegex(); + this.rules.slice(index).forEach(([re2, opts]) => matcher.addRule(re2, opts)); + matcher.compile(); + this.multiRegexes[index] = matcher; + return matcher; + } + resumingScanAtSamePosition() { + return this.regexIndex !== 0; + } + considerAll() { + this.regexIndex = 0; + } + // @ts-ignore + addRule(re2, opts) { + this.rules.push([re2, opts]); + if (opts.type === "begin") this.count++; + } + /** @param {string} s */ + exec(s6) { + const m4 = this.getMatcher(this.regexIndex); + m4.lastIndex = this.lastIndex; + let result = m4.exec(s6); + if (this.resumingScanAtSamePosition()) { + if (result && result.index === this.lastIndex) ; + else { + const m22 = this.getMatcher(0); + m22.lastIndex = this.lastIndex + 1; + result = m22.exec(s6); + } + } + if (result) { + this.regexIndex += result.position + 1; + if (this.regexIndex === this.count) { + this.considerAll(); + } + } + return result; + } + } + function buildModeRegex(mode) { + const mm = new ResumableMultiRegex(); + mode.contains.forEach((term) => mm.addRule(term.begin, { rule: term, type: "begin" })); + if (mode.terminatorEnd) { + mm.addRule(mode.terminatorEnd, { type: "end" }); + } + if (mode.illegal) { + mm.addRule(mode.illegal, { type: "illegal" }); + } + return mm; + } + function compileMode(mode, parent) { + const cmode = ( + /** @type CompiledMode */ + mode + ); + if (mode.isCompiled) return cmode; + [ + // do this early so compiler extensions generally don't have to worry about + // the distinction between match/begin + compileMatch + ].forEach((ext2) => ext2(mode, parent)); + language.compilerExtensions.forEach((ext2) => ext2(mode, parent)); + mode.__beforeBegin = null; + [ + beginKeywords, + // do this later so compiler extensions that come earlier have access to the + // raw array if they wanted to perhaps manipulate it, etc. + compileIllegal, + // default to 1 relevance if not specified + compileRelevance + ].forEach((ext2) => ext2(mode, parent)); + mode.isCompiled = true; + let keywordPattern = null; + if (typeof mode.keywords === "object") { + keywordPattern = mode.keywords.$pattern; + delete mode.keywords.$pattern; + } + if (mode.keywords) { + mode.keywords = compileKeywords(mode.keywords, language.case_insensitive); + } + if (mode.lexemes && keywordPattern) { + throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) "); + } + keywordPattern = keywordPattern || mode.lexemes || /\w+/; + cmode.keywordPatternRe = langRe(keywordPattern, true); + if (parent) { + if (!mode.begin) mode.begin = /\B|\b/; + cmode.beginRe = langRe(mode.begin); + if (mode.endSameAsBegin) mode.end = mode.begin; + if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/; + if (mode.end) cmode.endRe = langRe(mode.end); + cmode.terminatorEnd = source(mode.end) || ""; + if (mode.endsWithParent && parent.terminatorEnd) { + cmode.terminatorEnd += (mode.end ? "|" : "") + parent.terminatorEnd; + } + } + if (mode.illegal) cmode.illegalRe = langRe( + /** @type {RegExp | string} */ + mode.illegal + ); + if (!mode.contains) mode.contains = []; + mode.contains = [].concat(...mode.contains.map(function(c6) { + return expandOrCloneMode(c6 === "self" ? mode : c6); + })); + mode.contains.forEach(function(c6) { + compileMode( + /** @type Mode */ + c6, + cmode + ); + }); + if (mode.starts) { + compileMode(mode.starts, parent); + } + cmode.matcher = buildModeRegex(cmode); + return cmode; + } + if (!language.compilerExtensions) language.compilerExtensions = []; + if (language.contains && language.contains.includes("self")) { + throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation."); + } + language.classNameAliases = inherit(language.classNameAliases || {}); + return compileMode( + /** @type Mode */ + language + ); + } + function dependencyOnParent(mode) { + if (!mode) return false; + return mode.endsWithParent || dependencyOnParent(mode.starts); + } + function expandOrCloneMode(mode) { + if (mode.variants && !mode.cachedVariants) { + mode.cachedVariants = mode.variants.map(function(variant) { + return inherit(mode, { variants: null }, variant); + }); + } + if (mode.cachedVariants) { + return mode.cachedVariants; + } + if (dependencyOnParent(mode)) { + return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null }); + } + if (Object.isFrozen(mode)) { + return inherit(mode); + } + return mode; + } + var version5 = "10.7.3"; + function hasValueOrEmptyAttribute(value) { + return Boolean(value || value === ""); + } + function BuildVuePlugin(hljs5) { + const Component = { + props: ["language", "code", "autodetect"], + data: function() { + return { + detectedLanguage: "", + unknownLanguage: false + }; + }, + computed: { + className() { + if (this.unknownLanguage) return ""; + return "hljs " + this.detectedLanguage; + }, + highlighted() { + if (!this.autoDetect && !hljs5.getLanguage(this.language)) { + console.warn(`The language "${this.language}" you specified could not be found.`); + this.unknownLanguage = true; + return escapeHTML(this.code); + } + let result = {}; + if (this.autoDetect) { + result = hljs5.highlightAuto(this.code); + this.detectedLanguage = result.language; + } else { + result = hljs5.highlight(this.language, this.code, this.ignoreIllegals); + this.detectedLanguage = this.language; + } + return result.value; + }, + autoDetect() { + return !this.language || hasValueOrEmptyAttribute(this.autodetect); + }, + ignoreIllegals() { + return true; + } + }, + // this avoids needing to use a whole Vue compilation pipeline just + // to build Highlight.js + render(createElement2) { + return createElement2("pre", {}, [ + createElement2("code", { + class: this.className, + domProps: { innerHTML: this.highlighted } + }) + ]); + } + // template: `
` + }; + const VuePlugin = { + install(Vue) { + Vue.component("highlightjs", Component); + } + }; + return { Component, VuePlugin }; + } + var mergeHTMLPlugin = { + "after:highlightElement": ({ el, result, text: text3 }) => { + const originalStream = nodeStream(el); + if (!originalStream.length) return; + const resultNode = document.createElement("div"); + resultNode.innerHTML = result.value; + result.value = mergeStreams(originalStream, nodeStream(resultNode), text3); + } + }; + function tag(node) { + return node.nodeName.toLowerCase(); + } + function nodeStream(node) { + const result = []; + (function _nodeStream(node2, offset) { + for (let child = node2.firstChild; child; child = child.nextSibling) { + if (child.nodeType === 3) { + offset += child.nodeValue.length; + } else if (child.nodeType === 1) { + result.push({ + event: "start", + offset, + node: child + }); + offset = _nodeStream(child, offset); + if (!tag(child).match(/br|hr|img|input/)) { + result.push({ + event: "stop", + offset, + node: child + }); + } + } + } + return offset; + })(node, 0); + return result; + } + function mergeStreams(original, highlighted, value) { + let processed = 0; + let result = ""; + const nodeStack = []; + function selectStream() { + if (!original.length || !highlighted.length) { + return original.length ? original : highlighted; + } + if (original[0].offset !== highlighted[0].offset) { + return original[0].offset < highlighted[0].offset ? original : highlighted; + } + return highlighted[0].event === "start" ? original : highlighted; + } + function open2(node) { + function attributeString(attr) { + return " " + attr.nodeName + '="' + escapeHTML(attr.value) + '"'; + } + result += "<" + tag(node) + [].map.call(node.attributes, attributeString).join("") + ">"; + } + function close2(node) { + result += ""; + } + function render3(event) { + (event.event === "start" ? open2 : close2)(event.node); + } + while (original.length || highlighted.length) { + let stream2 = selectStream(); + result += escapeHTML(value.substring(processed, stream2[0].offset)); + processed = stream2[0].offset; + if (stream2 === original) { + nodeStack.reverse().forEach(close2); + do { + render3(stream2.splice(0, 1)[0]); + stream2 = selectStream(); + } while (stream2 === original && stream2.length && stream2[0].offset === processed); + nodeStack.reverse().forEach(open2); + } else { + if (stream2[0].event === "start") { + nodeStack.push(stream2[0].node); + } else { + nodeStack.pop(); + } + render3(stream2.splice(0, 1)[0]); + } + } + return result + escapeHTML(value.substr(processed)); + } + var seenDeprecations = {}; + var error = (message) => { + console.error(message); + }; + var warn2 = (message, ...args) => { + console.log(`WARN: ${message}`, ...args); + }; + var deprecated2 = (version6, message) => { + if (seenDeprecations[`${version6}/${message}`]) return; + console.log(`Deprecated as of ${version6}. ${message}`); + seenDeprecations[`${version6}/${message}`] = true; + }; + var escape$1 = escapeHTML; + var inherit$1 = inherit; + var NO_MATCH = Symbol("nomatch"); + var HLJS = function(hljs5) { + const languages = /* @__PURE__ */ Object.create(null); + const aliases = /* @__PURE__ */ Object.create(null); + const plugins2 = []; + let SAFE_MODE = true; + const fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm; + const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?"; + const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: "Plain text", contains: [] }; + let options = { + noHighlightRe: /^(no-?highlight)$/i, + languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i, + classPrefix: "hljs-", + tabReplace: null, + useBR: false, + languages: null, + // beta configuration options, subject to change, welcome to discuss + // https://github.com/highlightjs/highlight.js/issues/1086 + __emitter: TokenTreeEmitter + }; + function shouldNotHighlight(languageName) { + return options.noHighlightRe.test(languageName); + } + function blockLanguage(block) { + let classes = block.className + " "; + classes += block.parentNode ? block.parentNode.className : ""; + const match2 = options.languageDetectRe.exec(classes); + if (match2) { + const language = getLanguage(match2[1]); + if (!language) { + warn2(LANGUAGE_NOT_FOUND.replace("{}", match2[1])); + warn2("Falling back to no-highlight mode for this block.", block); + } + return language ? match2[1] : "no-highlight"; + } + return classes.split(/\s+/).find((_class) => shouldNotHighlight(_class) || getLanguage(_class)); + } + function highlight2(codeOrlanguageName, optionsOrCode, ignoreIllegals, continuation) { + let code = ""; + let languageName = ""; + if (typeof optionsOrCode === "object") { + code = codeOrlanguageName; + ignoreIllegals = optionsOrCode.ignoreIllegals; + languageName = optionsOrCode.language; + continuation = void 0; + } else { + deprecated2("10.7.0", "highlight(lang, code, ...args) has been deprecated."); + deprecated2("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"); + languageName = codeOrlanguageName; + code = optionsOrCode; + } + const context = { + code, + language: languageName + }; + fire("before:highlight", context); + const result = context.result ? context.result : _highlight(context.language, context.code, ignoreIllegals, continuation); + result.code = context.code; + fire("after:highlight", result); + return result; + } + function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) { + function keywordData(mode, match2) { + const matchText = language.case_insensitive ? match2[0].toLowerCase() : match2[0]; + return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText]; + } + function processKeywords() { + if (!top.keywords) { + emitter.addText(modeBuffer); + return; + } + let lastIndex = 0; + top.keywordPatternRe.lastIndex = 0; + let match2 = top.keywordPatternRe.exec(modeBuffer); + let buf = ""; + while (match2) { + buf += modeBuffer.substring(lastIndex, match2.index); + const data = keywordData(top, match2); + if (data) { + const [kind, keywordRelevance] = data; + emitter.addText(buf); + buf = ""; + relevance += keywordRelevance; + if (kind.startsWith("_")) { + buf += match2[0]; + } else { + const cssClass = language.classNameAliases[kind] || kind; + emitter.addKeyword(match2[0], cssClass); + } + } else { + buf += match2[0]; + } + lastIndex = top.keywordPatternRe.lastIndex; + match2 = top.keywordPatternRe.exec(modeBuffer); + } + buf += modeBuffer.substr(lastIndex); + emitter.addText(buf); + } + function processSubLanguage() { + if (modeBuffer === "") return; + let result2 = null; + if (typeof top.subLanguage === "string") { + if (!languages[top.subLanguage]) { + emitter.addText(modeBuffer); + return; + } + result2 = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]); + continuations[top.subLanguage] = /** @type {CompiledMode} */ + result2.top; + } else { + result2 = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null); + } + if (top.relevance > 0) { + relevance += result2.relevance; + } + emitter.addSublanguage(result2.emitter, result2.language); + } + function processBuffer() { + if (top.subLanguage != null) { + processSubLanguage(); + } else { + processKeywords(); + } + modeBuffer = ""; + } + function startNewMode(mode) { + if (mode.className) { + emitter.openNode(language.classNameAliases[mode.className] || mode.className); + } + top = Object.create(mode, { parent: { value: top } }); + return top; + } + function endOfMode(mode, match2, matchPlusRemainder) { + let matched = startsWith(mode.endRe, matchPlusRemainder); + if (matched) { + if (mode["on:end"]) { + const resp = new Response3(mode); + mode["on:end"](match2, resp); + if (resp.isMatchIgnored) matched = false; + } + if (matched) { + while (mode.endsParent && mode.parent) { + mode = mode.parent; + } + return mode; + } + } + if (mode.endsWithParent) { + return endOfMode(mode.parent, match2, matchPlusRemainder); + } + } + function doIgnore(lexeme) { + if (top.matcher.regexIndex === 0) { + modeBuffer += lexeme[0]; + return 1; + } else { + resumeScanAtSamePosition = true; + return 0; + } + } + function doBeginMatch(match2) { + const lexeme = match2[0]; + const newMode = match2.rule; + const resp = new Response3(newMode); + const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]]; + for (const cb of beforeCallbacks) { + if (!cb) continue; + cb(match2, resp); + if (resp.isMatchIgnored) return doIgnore(lexeme); + } + if (newMode && newMode.endSameAsBegin) { + newMode.endRe = escape4(lexeme); + } + if (newMode.skip) { + modeBuffer += lexeme; + } else { + if (newMode.excludeBegin) { + modeBuffer += lexeme; + } + processBuffer(); + if (!newMode.returnBegin && !newMode.excludeBegin) { + modeBuffer = lexeme; + } + } + startNewMode(newMode); + return newMode.returnBegin ? 0 : lexeme.length; + } + function doEndMatch(match2) { + const lexeme = match2[0]; + const matchPlusRemainder = codeToHighlight.substr(match2.index); + const endMode = endOfMode(top, match2, matchPlusRemainder); + if (!endMode) { + return NO_MATCH; + } + const origin = top; + if (origin.skip) { + modeBuffer += lexeme; + } else { + if (!(origin.returnEnd || origin.excludeEnd)) { + modeBuffer += lexeme; + } + processBuffer(); + if (origin.excludeEnd) { + modeBuffer = lexeme; + } + } + do { + if (top.className) { + emitter.closeNode(); + } + if (!top.skip && !top.subLanguage) { + relevance += top.relevance; + } + top = top.parent; + } while (top !== endMode.parent); + if (endMode.starts) { + if (endMode.endSameAsBegin) { + endMode.starts.endRe = endMode.endRe; + } + startNewMode(endMode.starts); + } + return origin.returnEnd ? 0 : lexeme.length; + } + function processContinuations() { + const list = []; + for (let current2 = top; current2 !== language; current2 = current2.parent) { + if (current2.className) { + list.unshift(current2.className); + } + } + list.forEach((item) => emitter.openNode(item)); + } + let lastMatch = {}; + function processLexeme(textBeforeMatch, match2) { + const lexeme = match2 && match2[0]; + modeBuffer += textBeforeMatch; + if (lexeme == null) { + processBuffer(); + return 0; + } + if (lastMatch.type === "begin" && match2.type === "end" && lastMatch.index === match2.index && lexeme === "") { + modeBuffer += codeToHighlight.slice(match2.index, match2.index + 1); + if (!SAFE_MODE) { + const err = new Error("0 width match regex"); + err.languageName = languageName; + err.badRule = lastMatch.rule; + throw err; + } + return 1; + } + lastMatch = match2; + if (match2.type === "begin") { + return doBeginMatch(match2); + } else if (match2.type === "illegal" && !ignoreIllegals) { + const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || "") + '"'); + err.mode = top; + throw err; + } else if (match2.type === "end") { + const processed = doEndMatch(match2); + if (processed !== NO_MATCH) { + return processed; + } + } + if (match2.type === "illegal" && lexeme === "") { + return 1; + } + if (iterations > 1e5 && iterations > match2.index * 3) { + const err = new Error("potential infinite loop, way more iterations than matches"); + throw err; + } + modeBuffer += lexeme; + return lexeme.length; + } + const language = getLanguage(languageName); + if (!language) { + error(LANGUAGE_NOT_FOUND.replace("{}", languageName)); + throw new Error('Unknown language: "' + languageName + '"'); + } + const md = compileLanguage(language, { plugins: plugins2 }); + let result = ""; + let top = continuation || md; + const continuations = {}; + const emitter = new options.__emitter(options); + processContinuations(); + let modeBuffer = ""; + let relevance = 0; + let index = 0; + let iterations = 0; + let resumeScanAtSamePosition = false; + try { + top.matcher.considerAll(); + for (; ; ) { + iterations++; + if (resumeScanAtSamePosition) { + resumeScanAtSamePosition = false; + } else { + top.matcher.considerAll(); + } + top.matcher.lastIndex = index; + const match2 = top.matcher.exec(codeToHighlight); + if (!match2) break; + const beforeMatch = codeToHighlight.substring(index, match2.index); + const processedCount = processLexeme(beforeMatch, match2); + index = match2.index + processedCount; + } + processLexeme(codeToHighlight.substr(index)); + emitter.closeAllNodes(); + emitter.finalize(); + result = emitter.toHTML(); + return { + // avoid possible breakage with v10 clients expecting + // this to always be an integer + relevance: Math.floor(relevance), + value: result, + language: languageName, + illegal: false, + emitter, + top + }; + } catch (err) { + if (err.message && err.message.includes("Illegal")) { + return { + illegal: true, + illegalBy: { + msg: err.message, + context: codeToHighlight.slice(index - 100, index + 100), + mode: err.mode + }, + sofar: result, + relevance: 0, + value: escape$1(codeToHighlight), + emitter + }; + } else if (SAFE_MODE) { + return { + illegal: false, + relevance: 0, + value: escape$1(codeToHighlight), + emitter, + language: languageName, + top, + errorRaised: err + }; + } else { + throw err; + } + } + } + function justTextHighlightResult(code) { + const result = { + relevance: 0, + emitter: new options.__emitter(options), + value: escape$1(code), + illegal: false, + top: PLAINTEXT_LANGUAGE + }; + result.emitter.addText(code); + return result; + } + function highlightAuto(code, languageSubset) { + languageSubset = languageSubset || options.languages || Object.keys(languages); + const plaintext = justTextHighlightResult(code); + const results = languageSubset.filter(getLanguage).filter(autoDetection).map( + (name) => _highlight(name, code, false) + ); + results.unshift(plaintext); + const sorted = results.sort((a3, b4) => { + if (a3.relevance !== b4.relevance) return b4.relevance - a3.relevance; + if (a3.language && b4.language) { + if (getLanguage(a3.language).supersetOf === b4.language) { + return 1; + } else if (getLanguage(b4.language).supersetOf === a3.language) { + return -1; + } + } + return 0; + }); + const [best, secondBest] = sorted; + const result = best; + result.second_best = secondBest; + return result; + } + function fixMarkup(html) { + if (!(options.tabReplace || options.useBR)) { + return html; + } + return html.replace(fixMarkupRe, (match2) => { + if (match2 === "\n") { + return options.useBR ? "
" : match2; + } else if (options.tabReplace) { + return match2.replace(/\t/g, options.tabReplace); + } + return match2; + }); + } + function updateClassName(element, currentLang, resultLang) { + const language = currentLang ? aliases[currentLang] : resultLang; + element.classList.add("hljs"); + if (language) element.classList.add(language); + } + const brPlugin = { + "before:highlightElement": ({ el }) => { + if (options.useBR) { + el.innerHTML = el.innerHTML.replace(/\n/g, "").replace(//g, "\n"); + } + }, + "after:highlightElement": ({ result }) => { + if (options.useBR) { + result.value = result.value.replace(/\n/g, "
"); + } + } + }; + const TAB_REPLACE_RE = /^(<[^>]+>|\t)+/gm; + const tabReplacePlugin = { + "after:highlightElement": ({ result }) => { + if (options.tabReplace) { + result.value = result.value.replace( + TAB_REPLACE_RE, + (m4) => m4.replace(/\t/g, options.tabReplace) + ); + } + } + }; + function highlightElement(element) { + let node = null; + const language = blockLanguage(element); + if (shouldNotHighlight(language)) return; + fire( + "before:highlightElement", + { el: element, language } + ); + node = element; + const text3 = node.textContent; + const result = language ? highlight2(text3, { language, ignoreIllegals: true }) : highlightAuto(text3); + fire("after:highlightElement", { el: element, result, text: text3 }); + element.innerHTML = result.value; + updateClassName(element, language, result.language); + element.result = { + language: result.language, + // TODO: remove with version 11.0 + re: result.relevance, + relavance: result.relevance + }; + if (result.second_best) { + element.second_best = { + language: result.second_best.language, + // TODO: remove with version 11.0 + re: result.second_best.relevance, + relavance: result.second_best.relevance + }; + } + } + function configure(userOptions) { + if (userOptions.useBR) { + deprecated2("10.3.0", "'useBR' will be removed entirely in v11.0"); + deprecated2("10.3.0", "Please see https://github.com/highlightjs/highlight.js/issues/2559"); + } + options = inherit$1(options, userOptions); + } + const initHighlighting = () => { + if (initHighlighting.called) return; + initHighlighting.called = true; + deprecated2("10.6.0", "initHighlighting() is deprecated. Use highlightAll() instead."); + const blocks = document.querySelectorAll("pre code"); + blocks.forEach(highlightElement); + }; + function initHighlightingOnLoad() { + deprecated2("10.6.0", "initHighlightingOnLoad() is deprecated. Use highlightAll() instead."); + wantsHighlight = true; + } + let wantsHighlight = false; + function highlightAll() { + if (document.readyState === "loading") { + wantsHighlight = true; + return; + } + const blocks = document.querySelectorAll("pre code"); + blocks.forEach(highlightElement); + } + function boot() { + if (wantsHighlight) highlightAll(); + } + if (typeof window !== "undefined" && window.addEventListener) { + window.addEventListener("DOMContentLoaded", boot, false); + } + function registerLanguage(languageName, languageDefinition) { + let lang = null; + try { + lang = languageDefinition(hljs5); + } catch (error$1) { + error("Language definition for '{}' could not be registered.".replace("{}", languageName)); + if (!SAFE_MODE) { + throw error$1; + } else { + error(error$1); + } + lang = PLAINTEXT_LANGUAGE; + } + if (!lang.name) lang.name = languageName; + languages[languageName] = lang; + lang.rawDefinition = languageDefinition.bind(null, hljs5); + if (lang.aliases) { + registerAliases(lang.aliases, { languageName }); + } + } + function unregisterLanguage(languageName) { + delete languages[languageName]; + for (const alias of Object.keys(aliases)) { + if (aliases[alias] === languageName) { + delete aliases[alias]; + } + } + } + function listLanguages() { + return Object.keys(languages); + } + function requireLanguage(name) { + deprecated2("10.4.0", "requireLanguage will be removed entirely in v11."); + deprecated2("10.4.0", "Please see https://github.com/highlightjs/highlight.js/pull/2844"); + const lang = getLanguage(name); + if (lang) { + return lang; + } + const err = new Error("The '{}' language is required, but not loaded.".replace("{}", name)); + throw err; + } + function getLanguage(name) { + name = (name || "").toLowerCase(); + return languages[name] || languages[aliases[name]]; + } + function registerAliases(aliasList, { languageName }) { + if (typeof aliasList === "string") { + aliasList = [aliasList]; + } + aliasList.forEach((alias) => { + aliases[alias.toLowerCase()] = languageName; + }); + } + function autoDetection(name) { + const lang = getLanguage(name); + return lang && !lang.disableAutodetect; + } + function upgradePluginAPI(plugin) { + if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) { + plugin["before:highlightElement"] = (data) => { + plugin["before:highlightBlock"]( + Object.assign({ block: data.el }, data) + ); + }; + } + if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) { + plugin["after:highlightElement"] = (data) => { + plugin["after:highlightBlock"]( + Object.assign({ block: data.el }, data) + ); + }; + } + } + function addPlugin(plugin) { + upgradePluginAPI(plugin); + plugins2.push(plugin); + } + function fire(event, args) { + const cb = event; + plugins2.forEach(function(plugin) { + if (plugin[cb]) { + plugin[cb](args); + } + }); + } + function deprecateFixMarkup(arg) { + deprecated2("10.2.0", "fixMarkup will be removed entirely in v11.0"); + deprecated2("10.2.0", "Please see https://github.com/highlightjs/highlight.js/issues/2534"); + return fixMarkup(arg); + } + function deprecateHighlightBlock(el) { + deprecated2("10.7.0", "highlightBlock will be removed entirely in v12.0"); + deprecated2("10.7.0", "Please use highlightElement now."); + return highlightElement(el); + } + Object.assign(hljs5, { + highlight: highlight2, + highlightAuto, + highlightAll, + fixMarkup: deprecateFixMarkup, + highlightElement, + // TODO: Remove with v12 API + highlightBlock: deprecateHighlightBlock, + configure, + initHighlighting, + initHighlightingOnLoad, + registerLanguage, + unregisterLanguage, + listLanguages, + getLanguage, + registerAliases, + requireLanguage, + autoDetection, + inherit: inherit$1, + addPlugin, + // plugins for frameworks + vuePlugin: BuildVuePlugin(hljs5).VuePlugin + }); + hljs5.debugMode = function() { + SAFE_MODE = false; + }; + hljs5.safeMode = function() { + SAFE_MODE = true; + }; + hljs5.versionString = version5; + for (const key in MODES2) { + if (typeof MODES2[key] === "object") { + deepFreezeEs6(MODES2[key]); + } + } + Object.assign(hljs5, MODES2); + hljs5.addPlugin(brPlugin); + hljs5.addPlugin(mergeHTMLPlugin); + hljs5.addPlugin(tabReplacePlugin); + return hljs5; + }; + var highlight = HLJS({}); + module.exports = highlight; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/1c.js +var require_c = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/1c.js"(exports, module) { + init_process_shim(); + function _1c(hljs5) { + var UNDERSCORE_IDENT_RE = "[A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_][A-Za-z\u0410-\u042F\u0430-\u044F\u0451\u0401_0-9]+"; + var v7_keywords = "\u0434\u0430\u043B\u0435\u0435 "; + var v8_keywords = "\u0432\u043E\u0437\u0432\u0440\u0430\u0442 \u0432\u044B\u0437\u0432\u0430\u0442\u044C\u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u0434\u043B\u044F \u0435\u0441\u043B\u0438 \u0438 \u0438\u0437 \u0438\u043B\u0438 \u0438\u043D\u0430\u0447\u0435 \u0438\u043D\u0430\u0447\u0435\u0435\u0441\u043B\u0438 \u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435 \u043A\u0430\u0436\u0434\u043E\u0433\u043E \u043A\u043E\u043D\u0435\u0446\u0435\u0441\u043B\u0438 \u043A\u043E\u043D\u0435\u0446\u043F\u043E\u043F\u044B\u0442\u043A\u0438 \u043A\u043E\u043D\u0435\u0446\u0446\u0438\u043A\u043B\u0430 \u043D\u0435 \u043D\u043E\u0432\u044B\u0439 \u043F\u0435\u0440\u0435\u0439\u0442\u0438 \u043F\u0435\u0440\u0435\u043C \u043F\u043E \u043F\u043E\u043A\u0430 \u043F\u043E\u043F\u044B\u0442\u043A\u0430 \u043F\u0440\u0435\u0440\u0432\u0430\u0442\u044C \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C \u0442\u043E\u0433\u0434\u0430 \u0446\u0438\u043A\u043B \u044D\u043A\u0441\u043F\u043E\u0440\u0442 "; + var KEYWORD = v7_keywords + v8_keywords; + var v7_meta_keywords = "\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C\u0438\u0437\u0444\u0430\u0439\u043B\u0430 "; + var v8_meta_keywords = "\u0432\u0435\u0431\u043A\u043B\u0438\u0435\u043D\u0442 \u0432\u043C\u0435\u0441\u0442\u043E \u0432\u043D\u0435\u0448\u043D\u0435\u0435\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u043A\u043B\u0438\u0435\u043D\u0442 \u043A\u043E\u043D\u0435\u0446\u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u043C\u043E\u0431\u0438\u043B\u044C\u043D\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u043B\u0438\u0435\u043D\u0442 \u043C\u043E\u0431\u0438\u043B\u044C\u043D\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0441\u0435\u0440\u0432\u0435\u0440 \u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0435 \u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0435\u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435 \u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0435\u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435\u0431\u0435\u0437\u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435 \u043D\u0430\u0441\u0435\u0440\u0432\u0435\u0440\u0435\u0431\u0435\u0437\u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u043E\u0431\u043B\u0430\u0441\u0442\u044C \u043F\u0435\u0440\u0435\u0434 \u043F\u043E\u0441\u043B\u0435 \u0441\u0435\u0440\u0432\u0435\u0440 \u0442\u043E\u043B\u0441\u0442\u044B\u0439\u043A\u043B\u0438\u0435\u043D\u0442\u043E\u0431\u044B\u0447\u043D\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0442\u043E\u043B\u0441\u0442\u044B\u0439\u043A\u043B\u0438\u0435\u043D\u0442\u0443\u043F\u0440\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0442\u043E\u043D\u043A\u0438\u0439\u043A\u043B\u0438\u0435\u043D\u0442 "; + var METAKEYWORD = v7_meta_keywords + v8_meta_keywords; + var v7_system_constants = "\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u0441\u0442\u0440\u0430\u043D\u0438\u0446 \u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u0441\u0442\u0440\u043E\u043A \u0441\u0438\u043C\u0432\u043E\u043B\u0442\u0430\u0431\u0443\u043B\u044F\u0446\u0438\u0438 "; + var v7_global_context_methods = "ansitooem oemtoansi \u0432\u0432\u0435\u0441\u0442\u0438\u0432\u0438\u0434\u0441\u0443\u0431\u043A\u043E\u043D\u0442\u043E \u0432\u0432\u0435\u0441\u0442\u0438\u043F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u0435 \u0432\u0432\u0435\u0441\u0442\u0438\u043F\u0435\u0440\u0438\u043E\u0434 \u0432\u0432\u0435\u0441\u0442\u0438\u043F\u043B\u0430\u043D\u0441\u0447\u0435\u0442\u043E\u0432 \u0432\u044B\u0431\u0440\u0430\u043D\u043D\u044B\u0439\u043F\u043B\u0430\u043D\u0441\u0447\u0435\u0442\u043E\u0432 \u0434\u0430\u0442\u0430\u0433\u043E\u0434 \u0434\u0430\u0442\u0430\u043C\u0435\u0441\u044F\u0446 \u0434\u0430\u0442\u0430\u0447\u0438\u0441\u043B\u043E \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0441\u0442\u0440\u043E\u043A\u0443 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0437\u0441\u0442\u0440\u043E\u043A\u0438 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0438\u0431 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043A\u043E\u0434\u0441\u0438\u043C\u0432 \u043A\u043E\u043D\u0433\u043E\u0434\u0430 \u043A\u043E\u043D\u0435\u0446\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0431\u0438 \u043A\u043E\u043D\u0435\u0446\u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u043D\u043D\u043E\u0433\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0431\u0438 \u043A\u043E\u043D\u0435\u0446\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430 \u043A\u043E\u043D\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043A\u043E\u043D\u043C\u0435\u0441\u044F\u0446\u0430 \u043A\u043E\u043D\u043D\u0435\u0434\u0435\u043B\u0438 \u043B\u043E\u0433 \u043B\u043E\u043310 \u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0435\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E\u0441\u0443\u0431\u043A\u043E\u043D\u0442\u043E \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435\u043D\u0430\u0431\u043E\u0440\u0430\u043F\u0440\u0430\u0432 \u043D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C\u0432\u0438\u0434 \u043D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C\u0441\u0447\u0435\u0442 \u043D\u0430\u0439\u0442\u0438\u0441\u0441\u044B\u043B\u043A\u0438 \u043D\u0430\u0447\u0430\u043B\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0431\u0438 \u043D\u0430\u0447\u0430\u043B\u043E\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430 \u043D\u0430\u0447\u0433\u043E\u0434\u0430 \u043D\u0430\u0447\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043D\u0430\u0447\u043C\u0435\u0441\u044F\u0446\u0430 \u043D\u0430\u0447\u043D\u0435\u0434\u0435\u043B\u0438 \u043D\u043E\u043C\u0435\u0440\u0434\u043D\u044F\u0433\u043E\u0434\u0430 \u043D\u043E\u043C\u0435\u0440\u0434\u043D\u044F\u043D\u0435\u0434\u0435\u043B\u0438 \u043D\u043E\u043C\u0435\u0440\u043D\u0435\u0434\u0435\u043B\u0438\u0433\u043E\u0434\u0430 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0430\u0441\u0447\u0435\u0442\u043E\u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439\u043F\u043B\u0430\u043D\u0441\u0447\u0435\u0442\u043E\u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439\u044F\u0437\u044B\u043A \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u043E\u043A\u043D\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439 \u043F\u0435\u0440\u0438\u043E\u0434\u0441\u0442\u0440 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u0430\u0442\u0443\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u043E\u0442\u0431\u043E\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u043E\u0437\u0438\u0446\u0438\u044E\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0443\u0441\u0442\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0442\u0430 \u043F\u0440\u0435\u0444\u0438\u043A\u0441\u0430\u0432\u0442\u043E\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u0438 \u043F\u0440\u043E\u043F\u0438\u0441\u044C \u043F\u0443\u0441\u0442\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0440\u0430\u0437\u043C \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u0442\u044C\u043F\u043E\u0437\u0438\u0446\u0438\u044E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u043D\u0430 \u0440\u0430\u0441\u0441\u0447\u0438\u0442\u0430\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u043F\u043E \u0441\u0438\u043C\u0432 \u0441\u043E\u0437\u0434\u0430\u0442\u044C\u043E\u0431\u044A\u0435\u043A\u0442 \u0441\u0442\u0430\u0442\u0443\u0441\u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430 \u0441\u0442\u0440\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E\u0441\u0442\u0440\u043E\u043A \u0441\u0444\u043E\u0440\u043C\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u043F\u043E\u0437\u0438\u0446\u0438\u044E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0441\u0447\u0435\u0442\u043F\u043E\u043A\u043E\u0434\u0443 \u0442\u0435\u043A\u0443\u0449\u0435\u0435\u0432\u0440\u0435\u043C\u044F \u0442\u0438\u043F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0441\u0442\u0440 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0442\u0430\u043D\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0442\u0430\u043F\u043E \u0444\u0438\u043A\u0441\u0448\u0430\u0431\u043B\u043E\u043D \u0448\u0430\u0431\u043B\u043E\u043D "; + var v8_global_context_methods = "acos asin atan base64\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 base64\u0441\u0442\u0440\u043E\u043A\u0430 cos exp log log10 pow sin sqrt tan xml\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 xml\u0441\u0442\u0440\u043E\u043A\u0430 xml\u0442\u0438\u043F xml\u0442\u0438\u043F\u0437\u043D\u0447 \u0430\u043A\u0442\u0438\u0432\u043D\u043E\u0435\u043E\u043A\u043D\u043E \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C\u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0431\u0443\u043B\u0435\u0432\u043E \u0432\u0432\u0435\u0441\u0442\u0438\u0434\u0430\u0442\u0443 \u0432\u0432\u0435\u0441\u0442\u0438\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432\u0432\u0435\u0441\u0442\u0438\u0441\u0442\u0440\u043E\u043A\u0443 \u0432\u0432\u0435\u0441\u0442\u0438\u0447\u0438\u0441\u043B\u043E \u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E\u0441\u0442\u044C\u0447\u0442\u0435\u043D\u0438\u044Fxml \u0432\u043E\u043F\u0440\u043E\u0441 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432\u0440\u0435\u0433 \u0432\u044B\u0433\u0440\u0443\u0437\u0438\u0442\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0443\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F \u0432\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443\u043F\u0440\u0430\u0432\u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u0432\u044B\u0447\u0438\u0441\u043B\u0438\u0442\u044C \u0433\u043E\u0434 \u0434\u0430\u043D\u043D\u044B\u0435\u0444\u043E\u0440\u043C\u044B\u0432\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0434\u0430\u0442\u0430 \u0434\u0435\u043D\u044C \u0434\u0435\u043D\u044C\u0433\u043E\u0434\u0430 \u0434\u0435\u043D\u044C\u043D\u0435\u0434\u0435\u043B\u0438 \u0434\u043E\u0431\u0430\u0432\u0438\u0442\u044C\u043C\u0435\u0441\u044F\u0446 \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0434\u043B\u044F\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0440\u0430\u0431\u043E\u0442\u0443\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0437\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044C\u0440\u0430\u0431\u043E\u0442\u0443\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C\u0432\u043D\u0435\u0448\u043D\u044E\u044E\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0443 \u0437\u0430\u043A\u0440\u044B\u0442\u044C\u0441\u043F\u0440\u0430\u0432\u043A\u0443 \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044Cjson \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044Cxml \u0437\u0430\u043F\u0438\u0441\u0430\u0442\u044C\u0434\u0430\u0442\u0443json \u0437\u0430\u043F\u0438\u0441\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u043F\u043E\u043B\u043D\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0441\u0432\u043E\u0439\u0441\u0442\u0432 \u0437\u0430\u043F\u0440\u043E\u0441\u0438\u0442\u044C\u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u044C\u0441\u0438\u0441\u0442\u0435\u043C\u0443 \u0437\u0430\u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0434\u0430\u043D\u043D\u044B\u0435\u0444\u043E\u0440\u043C\u044B \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0441\u0442\u0440\u043E\u043A\u0443\u0432\u043D\u0443\u0442\u0440 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0432\u0444\u0430\u0439\u043B \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0437\u0441\u0442\u0440\u043E\u043A\u0438\u0432\u043D\u0443\u0442\u0440 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0437\u0444\u0430\u0439\u043B\u0430 \u0438\u0437xml\u0442\u0438\u043F\u0430 \u0438\u043C\u043F\u043E\u0440\u0442\u043C\u043E\u0434\u0435\u043B\u0438xdto \u0438\u043C\u044F\u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 \u0438\u043C\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0438\u043D\u0438\u0446\u0438\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0435\u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F\u043E\u0431\u043E\u0448\u0438\u0431\u043A\u0435 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0438\u043C\u043E\u0431\u0438\u043B\u044C\u043D\u043E\u0433\u043E\u0443\u0441\u0442\u0440\u043E\u0439\u0441\u0442\u0432\u0430 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445\u0444\u0430\u0439\u043B\u043E\u0432 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0441\u0442\u0440\u043E\u043A\u0443 \u043A\u043E\u0434\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043A\u043E\u0434\u0441\u0438\u043C\u0432\u043E\u043B\u0430 \u043A\u043E\u043C\u0430\u043D\u0434\u0430\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u043A\u043E\u043D\u0435\u0446\u0433\u043E\u0434\u0430 \u043A\u043E\u043D\u0435\u0446\u0434\u043D\u044F \u043A\u043E\u043D\u0435\u0446\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043A\u043E\u043D\u0435\u0446\u043C\u0435\u0441\u044F\u0446\u0430 \u043A\u043E\u043D\u0435\u0446\u043C\u0438\u043D\u0443\u0442\u044B \u043A\u043E\u043D\u0435\u0446\u043D\u0435\u0434\u0435\u043B\u0438 \u043A\u043E\u043D\u0435\u0446\u0447\u0430\u0441\u0430 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0430\u0434\u0438\u043D\u0430\u043C\u0438\u0447\u0435\u0441\u043A\u0438 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0430 \u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0444\u043E\u0440\u043C\u044B \u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0444\u0430\u0439\u043B \u043A\u0440\u0430\u0442\u043A\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043E\u0448\u0438\u0431\u043A\u0438 \u043B\u0435\u0432 \u043C\u0430\u043A\u0441 \u043C\u0435\u0441\u0442\u043D\u043E\u0435\u0432\u0440\u0435\u043C\u044F \u043C\u0435\u0441\u044F\u0446 \u043C\u0438\u043D \u043C\u0438\u043D\u0443\u0442\u0430 \u043C\u043E\u043D\u043E\u043F\u043E\u043B\u044C\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u043D\u0430\u0439\u0442\u0438 \u043D\u0430\u0439\u0442\u0438\u043D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u0441\u0438\u043C\u0432\u043E\u043B\u044Bxml \u043D\u0430\u0439\u0442\u0438\u043E\u043A\u043D\u043E\u043F\u043E\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0441\u0441\u044B\u043B\u043A\u0435 \u043D\u0430\u0439\u0442\u0438\u043F\u043E\u043C\u0435\u0447\u0435\u043D\u043D\u044B\u0435\u043D\u0430\u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u043D\u0430\u0439\u0442\u0438\u043F\u043E\u0441\u0441\u044B\u043B\u043A\u0430\u043C \u043D\u0430\u0439\u0442\u0438\u0444\u0430\u0439\u043B\u044B \u043D\u0430\u0447\u0430\u043B\u043E\u0433\u043E\u0434\u0430 \u043D\u0430\u0447\u0430\u043B\u043E\u0434\u043D\u044F \u043D\u0430\u0447\u0430\u043B\u043E\u043A\u0432\u0430\u0440\u0442\u0430\u043B\u0430 \u043D\u0430\u0447\u0430\u043B\u043E\u043C\u0435\u0441\u044F\u0446\u0430 \u043D\u0430\u0447\u0430\u043B\u043E\u043C\u0438\u043D\u0443\u0442\u044B \u043D\u0430\u0447\u0430\u043B\u043E\u043D\u0435\u0434\u0435\u043B\u0438 \u043D\u0430\u0447\u0430\u043B\u043E\u0447\u0430\u0441\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u0437\u0430\u043F\u0440\u043E\u0441\u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043D\u0430\u0447\u0430\u0442\u044C\u0437\u0430\u043F\u0443\u0441\u043A\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043D\u0430\u0447\u0430\u0442\u044C\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u0435\u0440\u0435\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0432\u043D\u0435\u0448\u043D\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044B \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u0438\u0441\u043A\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u043F\u043E\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u0437\u0444\u0430\u0439\u043B\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0430 \u043D\u0430\u0447\u0430\u0442\u044C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044E \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u0444\u0430\u0439\u043B\u043E\u0432 \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0443\u0432\u043D\u0435\u0448\u043D\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044B \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0443\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u043D\u0430\u0447\u0430\u0442\u044C\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0443\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u043D\u0435\u0434\u0435\u043B\u044F\u0433\u043E\u0434\u0430 \u043D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u043E\u0441\u0442\u044C\u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F \u043D\u043E\u043C\u0435\u0440\u0441\u0435\u0430\u043D\u0441\u0430\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043D\u043E\u043C\u0435\u0440\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043D\u0440\u0435\u0433 \u043D\u0441\u0442\u0440 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u044E\u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C\u044B\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043F\u0440\u0435\u0440\u044B\u0432\u0430\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u043E\u043A\u0440 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u043E\u0448\u0438\u0431\u043A\u0438 \u043E\u043F\u043E\u0432\u0435\u0441\u0442\u0438\u0442\u044C \u043E\u043F\u043E\u0432\u0435\u0441\u0442\u0438\u0442\u044C\u043E\u0431\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0438 \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0437\u0430\u043F\u0440\u043E\u0441\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u043E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0438\u043D\u0434\u0435\u043A\u0441\u0441\u043F\u0440\u0430\u0432\u043A\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0441\u043E\u0434\u0435\u0440\u0436\u0430\u043D\u0438\u0435\u0441\u043F\u0440\u0430\u0432\u043A\u0438 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0441\u043F\u0440\u0430\u0432\u043A\u0443 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0444\u043E\u0440\u043C\u0443 \u043E\u0442\u043A\u0440\u044B\u0442\u044C\u0444\u043E\u0440\u043C\u0443\u043C\u043E\u0434\u0430\u043B\u044C\u043D\u043E \u043E\u0442\u043C\u0435\u043D\u0438\u0442\u044C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044E \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043E\u0447\u0438\u0441\u0442\u0438\u0442\u044C\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u043F\u0435\u0440\u0435\u0439\u0442\u0438\u043F\u043E\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0441\u0441\u044B\u043B\u043A\u0435 \u043F\u0435\u0440\u0435\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0432\u043D\u0435\u0448\u043D\u044E\u044E\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0443 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u0437\u0430\u043F\u0440\u043E\u0441\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u0447\u0438\u043A\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u043F\u043E\u0434\u0440\u043E\u0431\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043E\u0448\u0438\u0431\u043A\u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0434\u0430\u0442\u044B \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0441\u0442\u0440\u043E\u043A\u0438 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u0432\u043E\u0434\u0447\u0438\u0441\u043B\u0430 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0432\u043E\u043F\u0440\u043E\u0441 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E\u043E\u0431\u043E\u0448\u0438\u0431\u043A\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u043D\u0430\u043A\u0430\u0440\u0442\u0435 \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u044C\u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435 \u043F\u043E\u043B\u043D\u043E\u0435\u0438\u043C\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044Ccom\u043E\u0431\u044A\u0435\u043A\u0442 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044Cxml\u0442\u0438\u043F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0430\u0434\u0440\u0435\u0441\u043F\u043E\u043C\u0435\u0441\u0442\u043E\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u044E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0443\u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F\u0441\u043F\u044F\u0449\u0435\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0441\u044B\u043F\u0430\u043D\u0438\u044F\u043F\u0430\u0441\u0441\u0438\u0432\u043D\u043E\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0432\u044B\u0431\u043E\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0439\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u043A\u043E\u0434\u044B\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u0447\u0430\u0441\u043E\u0432\u044B\u0435\u043F\u043E\u044F\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u043E\u0442\u0431\u043E\u0440\u0430\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0437\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u043C\u044F\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0444\u0430\u0439\u043B\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u043C\u044F\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044E\u044D\u043A\u0440\u0430\u043D\u043E\u0432\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043A\u0440\u0430\u0442\u043A\u0438\u0439\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u043A\u0435\u0442\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u0441\u043A\u0443\u0432\u0441\u0435\u0444\u0430\u0439\u043B\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u0441\u043A\u0443\u0432\u0441\u0435\u0444\u0430\u0439\u043B\u044B\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0430\u0441\u043A\u0443\u0432\u0441\u0435\u0444\u0430\u0439\u043B\u044B\u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0435\u0441\u0442\u043E\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0430\u0434\u0440\u0435\u0441\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u0443\u044E\u0434\u043B\u0438\u043D\u0443\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u0443\u044E\u0441\u0441\u044B\u043B\u043A\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u0443\u044E\u0441\u0441\u044B\u043B\u043A\u0443\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u0449\u0438\u0439\u043C\u0430\u043A\u0435\u0442 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0431\u0449\u0443\u044E\u0444\u043E\u0440\u043C\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u043A\u043D\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u043F\u0435\u0440\u0430\u0442\u0438\u0432\u043D\u0443\u044E\u043E\u0442\u043C\u0435\u0442\u043A\u0443\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0433\u043E\u0440\u0435\u0436\u0438\u043C\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u044B\u0445\u043E\u043F\u0446\u0438\u0439\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u043E\u043B\u043D\u043E\u0435\u0438\u043C\u044F\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u043E\u043D\u043D\u044B\u0445\u0441\u0441\u044B\u043B\u043E\u043A \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443\u0441\u043B\u043E\u0436\u043D\u043E\u0441\u0442\u0438\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u043F\u0443\u0442\u0438 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u043F\u0443\u0442\u0438\u043A\u043B\u0438\u0435\u043D\u0442\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u0435\u043B\u044C\u043F\u0443\u0442\u0438\u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u0435\u0430\u043D\u0441\u044B\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043A\u043E\u0440\u043E\u0441\u0442\u044C\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435\u043E\u0431\u044A\u0435\u043A\u0442\u0430\u0438\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u043E\u0441\u0442\u0430\u0432\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430odata \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0443\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0441\u0435\u0430\u043D\u0441\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u043E\u0440\u043C\u0443 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u0443\u044E\u043E\u043F\u0446\u0438\u044E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u0443\u044E\u043E\u043F\u0446\u0438\u044E\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0438\u043E\u0441 \u043F\u043E\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0432\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0435\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043F\u043E\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u043F\u043E\u043C\u0435\u0441\u0442\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u043F\u0440\u0430\u0432 \u043F\u0440\u0430\u0432\u043E\u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043A\u043E\u0434\u0430\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0435\u0440\u0438\u043E\u0434\u0430 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0430\u0432\u0430 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0447\u0430\u0441\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u044F\u0441\u0430 \u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u043A\u0440\u0430\u0442\u0438\u0442\u044C\u0440\u0430\u0431\u043E\u0442\u0443\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u043F\u0440\u0438\u0432\u0438\u043B\u0435\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u043F\u0440\u043E\u0434\u043E\u043B\u0436\u0438\u0442\u044C\u0432\u044B\u0437\u043E\u0432 \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044Cjson \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044Cxml \u043F\u0440\u043E\u0447\u0438\u0442\u0430\u0442\u044C\u0434\u0430\u0442\u0443json \u043F\u0443\u0441\u0442\u0430\u044F\u0441\u0442\u0440\u043E\u043A\u0430 \u0440\u0430\u0431\u043E\u0447\u0438\u0439\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0440\u0430\u0437\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0434\u043B\u044F\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u044C\u0444\u0430\u0439\u043B \u0440\u0430\u0437\u043E\u0440\u0432\u0430\u0442\u044C\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\u0441\u0432\u043D\u0435\u0448\u043D\u0438\u043C\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u043E\u043C\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0441\u0442\u0440\u043E\u043A\u0443 \u0440\u043E\u043B\u044C\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u0430 \u0441\u0435\u043A\u0443\u043D\u0434\u0430 \u0441\u0438\u0433\u043D\u0430\u043B \u0441\u0438\u043C\u0432\u043E\u043B \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0441\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u043B\u0435\u0442\u043D\u0435\u0433\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0441\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u044C\u0431\u0443\u0444\u0435\u0440\u044B\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043E\u0437\u0434\u0430\u0442\u044C\u043A\u0430\u0442\u0430\u043B\u043E\u0433 \u0441\u043E\u0437\u0434\u0430\u0442\u044C\u0444\u0430\u0431\u0440\u0438\u043A\u0443xdto \u0441\u043E\u043A\u0440\u043B \u0441\u043E\u043A\u0440\u043B\u043F \u0441\u043E\u043A\u0440\u043F \u0441\u043E\u043E\u0431\u0449\u0438\u0442\u044C \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0441\u0440\u0435\u0434 \u0441\u0442\u0440\u0434\u043B\u0438\u043D\u0430 \u0441\u0442\u0440\u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0435\u0442\u0441\u044F\u043D\u0430 \u0441\u0442\u0440\u0437\u0430\u043C\u0435\u043D\u0438\u0442\u044C \u0441\u0442\u0440\u043D\u0430\u0439\u0442\u0438 \u0441\u0442\u0440\u043D\u0430\u0447\u0438\u043D\u0430\u0435\u0442\u0441\u044F\u0441 \u0441\u0442\u0440\u043E\u043A\u0430 \u0441\u0442\u0440\u043E\u043A\u0430\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0441\u0442\u0440\u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C\u0441\u0442\u0440\u043E\u043A\u0443 \u0441\u0442\u0440\u0440\u0430\u0437\u0434\u0435\u043B\u0438\u0442\u044C \u0441\u0442\u0440\u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u044C \u0441\u0442\u0440\u0441\u0440\u0430\u0432\u043D\u0438\u0442\u044C \u0441\u0442\u0440\u0447\u0438\u0441\u043B\u043E\u0432\u0445\u043E\u0436\u0434\u0435\u043D\u0438\u0439 \u0441\u0442\u0440\u0447\u0438\u0441\u043B\u043E\u0441\u0442\u0440\u043E\u043A \u0441\u0442\u0440\u0448\u0430\u0431\u043B\u043E\u043D \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0434\u0430\u0442\u0430 \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0434\u0430\u0442\u0430\u0441\u0435\u0430\u043D\u0441\u0430 \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0430\u043B\u044C\u043D\u0430\u044F\u0434\u0430\u0442\u0430 \u0442\u0435\u043A\u0443\u0449\u0430\u044F\u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0430\u043B\u044C\u043D\u0430\u044F\u0434\u0430\u0442\u0430\u0432\u043C\u0438\u043B\u043B\u0438\u0441\u0435\u043A\u0443\u043D\u0434\u0430\u0445 \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E\u0448\u0440\u0438\u0444\u0442\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u043A\u043E\u0434\u043B\u043E\u043A\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438 \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u044F\u0437\u044B\u043A \u0442\u0435\u043A\u0443\u0449\u0438\u0439\u044F\u0437\u044B\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0442\u0438\u043F \u0442\u0438\u043F\u0437\u043D\u0447 \u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u044F\u0430\u043A\u0442\u0438\u0432\u043D\u0430 \u0442\u0440\u0435\u0433 \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u0434\u0430\u043D\u043D\u044B\u0435\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u0438\u0437\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u043E\u0431\u044A\u0435\u043A\u0442\u044B \u0443\u0434\u0430\u043B\u0438\u0442\u044C\u0444\u0430\u0439\u043B\u044B \u0443\u043D\u0438\u0432\u0435\u0440\u0441\u0430\u043B\u044C\u043D\u043E\u0435\u0432\u0440\u0435\u043C\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C\u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0443\u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u043D\u0435\u0448\u043D\u044E\u044E\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u0443 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u0438\u044F\u0441\u043F\u044F\u0449\u0435\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u0437\u0430\u0441\u044B\u043F\u0430\u043D\u0438\u044F\u043F\u0430\u0441\u0441\u0438\u0432\u043D\u043E\u0433\u043E\u0441\u0435\u0430\u043D\u0441\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0432\u0440\u0435\u043C\u044F\u043E\u0436\u0438\u0434\u0430\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u0441\u0438\u0441\u0442\u0435\u043C\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043A\u0440\u0430\u0442\u043A\u0438\u0439\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u0443\u044E\u0434\u043B\u0438\u043D\u0443\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043C\u043E\u043D\u043E\u043F\u043E\u043B\u044C\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0433\u043E\u0440\u0435\u0436\u0438\u043C\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0444\u0443\u043D\u043A\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u044B\u0445\u043E\u043F\u0446\u0438\u0439\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u0440\u0438\u0432\u0438\u043B\u0435\u0433\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0443\u0441\u043B\u043E\u0436\u043D\u043E\u0441\u0442\u0438\u043F\u0430\u0440\u043E\u043B\u0435\u0439\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0435\u0439 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0435\u0439 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0442\u044B\u0441\u0444\u0430\u0439\u043B\u0430\u043C\u0438 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435\u0441\u0432\u043D\u0435\u0448\u043D\u0438\u043C\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u043E\u043C\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435\u043E\u0431\u044A\u0435\u043A\u0442\u0430\u0438\u0444\u043E\u0440\u043C\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0441\u043E\u0441\u0442\u0430\u0432\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430odata \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u044C\u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0441\u0435\u0430\u043D\u0441\u0430 \u0444\u043E\u0440\u043C\u0430\u0442 \u0446\u0435\u043B \u0447\u0430\u0441 \u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441 \u0447\u0430\u0441\u043E\u0432\u043E\u0439\u043F\u043E\u044F\u0441\u0441\u0435\u0430\u043D\u0441\u0430 \u0447\u0438\u0441\u043B\u043E \u0447\u0438\u0441\u043B\u043E\u043F\u0440\u043E\u043F\u0438\u0441\u044C\u044E \u044D\u0442\u043E\u0430\u0434\u0440\u0435\u0441\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E\u0433\u043E\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 "; + var v8_global_context_property = "ws\u0441\u0441\u044B\u043B\u043A\u0438 \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u043A\u0430\u0440\u0442\u0438\u043D\u043E\u043A \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u043C\u0430\u043A\u0435\u0442\u043E\u0432\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u0441\u0442\u0438\u043B\u0435\u0439 \u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B \u0432\u043D\u0435\u0448\u043D\u0438\u0435\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u043D\u0435\u0448\u043D\u0438\u0435\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u0432\u043D\u0435\u0448\u043D\u0438\u0435\u043E\u0442\u0447\u0435\u0442\u044B \u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0435\u043F\u043E\u043A\u0443\u043F\u043A\u0438 \u0433\u043B\u0430\u0432\u043D\u044B\u0439\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441 \u0433\u043B\u0430\u0432\u043D\u044B\u0439\u0441\u0442\u0438\u043B\u044C \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u044B \u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0435\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u0436\u0443\u0440\u043D\u0430\u043B\u044B\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0437\u0430\u0434\u0430\u0447\u0438 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F\u043E\u0431\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0431\u043E\u0447\u0435\u0439\u0434\u0430\u0442\u044B \u0438\u0441\u0442\u043E\u0440\u0438\u044F\u0440\u0430\u0431\u043E\u0442\u044B\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043A\u043E\u043D\u0441\u0442\u0430\u043D\u0442\u044B \u043A\u0440\u0438\u0442\u0435\u0440\u0438\u0438\u043E\u0442\u0431\u043E\u0440\u0430 \u043C\u0435\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0435 \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u043A\u043B\u0430\u043C\u044B \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0430\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0445\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439 \u043E\u0442\u0447\u0435\u0442\u044B \u043F\u0430\u043D\u0435\u043B\u044C\u0437\u0430\u0434\u0430\u0447\u043E\u0441 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0441\u0435\u0430\u043D\u0441\u0430 \u043F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u044F \u043F\u043B\u0430\u043D\u044B\u0432\u0438\u0434\u043E\u0432\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043F\u043B\u0430\u043D\u044B\u0432\u0438\u0434\u043E\u0432\u0445\u0430\u0440\u0430\u043A\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043A \u043F\u043B\u0430\u043D\u044B\u043E\u0431\u043C\u0435\u043D\u0430 \u043F\u043B\u0430\u043D\u044B\u0441\u0447\u0435\u0442\u043E\u0432 \u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439\u043F\u043E\u0438\u0441\u043A \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u0438\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439\u0431\u0430\u0437\u044B \u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0438 \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445\u043F\u043E\u043A\u0443\u043F\u043E\u043A \u0440\u0430\u0431\u043E\u0447\u0430\u044F\u0434\u0430\u0442\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u0431\u0443\u0445\u0433\u0430\u043B\u0442\u0435\u0440\u0438\u0438 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0440\u0435\u0433\u0438\u0441\u0442\u0440\u044B\u0441\u0432\u0435\u0434\u0435\u043D\u0438\u0439 \u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u044B\u0435\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0442\u043E\u0440xdto \u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0438 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u0433\u0435\u043E\u043F\u043E\u0437\u0438\u0446\u0438\u043E\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043C\u0443\u043B\u044C\u0442\u0438\u043C\u0435\u0434\u0438\u0430 \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0440\u0435\u043A\u043B\u0430\u043C\u044B \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u043F\u043E\u0447\u0442\u044B \u0441\u0440\u0435\u0434\u0441\u0442\u0432\u0430\u0442\u0435\u043B\u0435\u0444\u043E\u043D\u0438\u0438 \u0444\u0430\u0431\u0440\u0438\u043A\u0430xdto \u0444\u0430\u0439\u043B\u043E\u0432\u044B\u0435\u043F\u043E\u0442\u043E\u043A\u0438 \u0444\u043E\u043D\u043E\u0432\u044B\u0435\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0432\u043E\u0442\u0447\u0435\u0442\u043E\u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u0434\u0430\u043D\u043D\u044B\u0445\u0444\u043E\u0440\u043C \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043E\u0431\u0449\u0438\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u0434\u0438\u043D\u0430\u043C\u0438\u0447\u0435\u0441\u043A\u0438\u0445\u0441\u043F\u0438\u0441\u043A\u043E\u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043E\u0442\u0447\u0435\u0442\u043E\u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A "; + var BUILTIN = v7_system_constants + v7_global_context_methods + v8_global_context_methods + v8_global_context_property; + var v8_system_sets_of_values = "web\u0446\u0432\u0435\u0442\u0430 windows\u0446\u0432\u0435\u0442\u0430 windows\u0448\u0440\u0438\u0444\u0442\u044B \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0430\u043A\u0430\u0440\u0442\u0438\u043D\u043E\u043A \u0440\u0430\u043C\u043A\u0438\u0441\u0442\u0438\u043B\u044F \u0441\u0438\u043C\u0432\u043E\u043B\u044B \u0446\u0432\u0435\u0442\u0430\u0441\u0442\u0438\u043B\u044F \u0448\u0440\u0438\u0444\u0442\u044B\u0441\u0442\u0438\u043B\u044F "; + var v8_system_enums_interface = "\u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435\u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445\u0444\u043E\u0440\u043C\u044B\u0432\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445 \u0430\u0432\u0442\u043E\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u044F\u0432\u0444\u043E\u0440\u043C\u0435 \u0430\u0432\u0442\u043E\u0440\u0430\u0437\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u0435\u0441\u0435\u0440\u0438\u0439 \u0430\u043D\u0438\u043C\u0430\u0446\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0432\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0438\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u0432\u044B\u0441\u043E\u0442\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u0430\u044F\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0430\u0444\u043E\u0440\u043C\u044B \u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0432\u0438\u0434\u0433\u0440\u0443\u043F\u043F\u044B\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0434\u0435\u043A\u043E\u0440\u0430\u0446\u0438\u0438\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u0438\u0434\u043A\u043D\u043E\u043F\u043A\u0438\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u043F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0430\u0442\u0435\u043B\u044F \u0432\u0438\u0434\u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435 \u0432\u0438\u0434\u043F\u043E\u043B\u044F\u0444\u043E\u0440\u043C\u044B \u0432\u0438\u0434\u0444\u043B\u0430\u0436\u043A\u0430 \u0432\u043B\u0438\u044F\u043D\u0438\u0435\u0440\u0430\u0437\u043C\u0435\u0440\u0430\u043D\u0430\u043F\u0443\u0437\u044B\u0440\u0435\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0433\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0433\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0435\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430 \u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0430\u043A\u043E\u043B\u043E\u043D\u043E\u043A \u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0430\u043F\u043E\u0434\u0447\u0438\u043D\u0435\u043D\u043D\u044B\u0445\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0444\u043E\u0440\u043C\u044B \u0433\u0440\u0443\u043F\u043F\u044B\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435\u043F\u0435\u0440\u0435\u0442\u0430\u0441\u043A\u0438\u0432\u0430\u043D\u0438\u044F \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0439\u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F\u043F\u0435\u0440\u0435\u0442\u0430\u0441\u043A\u0438\u0432\u0430\u043D\u0438\u044F \u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u043C\u0435\u0436\u0434\u0443\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043C\u0438\u0444\u043E\u0440\u043C\u044B \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0432\u044B\u0432\u043E\u0434\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u043B\u043E\u0441\u044B\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C\u043E\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0442\u043E\u0447\u043A\u0438\u0431\u0438\u0440\u0436\u0435\u0432\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0438\u0441\u0442\u043E\u0440\u0438\u044F\u0432\u044B\u0431\u043E\u0440\u0430\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u043E\u0441\u0438\u0442\u043E\u0447\u0435\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0440\u0430\u0437\u043C\u0435\u0440\u0430\u043F\u0443\u0437\u044B\u0440\u044C\u043A\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u0433\u0440\u0443\u043F\u043F\u044B\u043A\u043E\u043C\u0430\u043D\u0434 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C\u0441\u0435\u0440\u0438\u0439 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0434\u0435\u0440\u0435\u0432\u0430 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0435\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0441\u043F\u0438\u0441\u043A\u0430 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u0434\u0435\u043D\u0434\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u043C\u0435\u0442\u043E\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u043C\u0435\u0442\u043E\u043A\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0432\u043B\u0435\u0433\u0435\u043D\u0434\u0435\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u044B\u043A\u043D\u043E\u043F\u043E\u043A \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0448\u043A\u0430\u043B\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0438\u0437\u043C\u0435\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043A\u043D\u043E\u043F\u043A\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043A\u043D\u043E\u043F\u043A\u0438\u0432\u044B\u0431\u043E\u0440\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043E\u0431\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u0439\u0444\u043E\u0440\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043E\u0431\u044B\u0447\u043D\u043E\u0439\u0433\u0440\u0443\u043F\u043F\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043E\u0442\u0440\u0438\u0446\u0430\u0442\u0435\u043B\u044C\u043D\u044B\u0445\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u043F\u0443\u0437\u044B\u0440\u044C\u043A\u043E\u0432\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u0430\u043D\u0435\u043B\u0438\u043F\u043E\u0438\u0441\u043A\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0434\u0441\u043A\u0430\u0437\u043A\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u044F\u043F\u0440\u0438\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0438 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0440\u0430\u0437\u043C\u0435\u0442\u043A\u0438\u043F\u043E\u043B\u043E\u0441\u044B\u0440\u0435\u0433\u0443\u043B\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0444\u043E\u0440\u043C\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043E\u0431\u044B\u0447\u043D\u043E\u0439\u0433\u0440\u0443\u043F\u043F\u044B \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0444\u0438\u0433\u0443\u0440\u044B\u043A\u043D\u043E\u043F\u043A\u0438 \u043F\u0430\u043B\u0438\u0442\u0440\u0430\u0446\u0432\u0435\u0442\u043E\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435\u043E\u0431\u044B\u0447\u043D\u043E\u0439\u0433\u0440\u0443\u043F\u043F\u044B \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0434\u0435\u043D\u0434\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u043A\u0430\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0438\u0441\u043A\u0432\u0442\u0430\u0431\u043B\u0438\u0446\u0435\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438\u043A\u043D\u043E\u043F\u043A\u0438\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u043E\u043C\u0430\u043D\u0434\u043D\u043E\u0439\u043F\u0430\u043D\u0435\u043B\u0438\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043A\u043E\u043C\u0430\u043D\u0434\u043D\u043E\u0439\u043F\u0430\u043D\u0435\u043B\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0444\u043E\u0440\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043E\u043F\u043E\u0440\u043D\u043E\u0439\u0442\u043E\u0447\u043A\u0438\u043E\u0442\u0440\u0438\u0441\u043E\u0432\u043A\u0438 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u0434\u043F\u0438\u0441\u0435\u0439\u0448\u043A\u0430\u043B\u044B\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0438\u0437\u043C\u0435\u0440\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044F\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0441\u0442\u0440\u043E\u043A\u0438\u043F\u043E\u0438\u0441\u043A\u0430 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u043B\u0438\u043D\u0438\u0438 \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u043E\u0438\u0441\u043A\u043E\u043C \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0448\u043A\u0430\u043B\u044B\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u043F\u043E\u0440\u044F\u0434\u043E\u043A\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0442\u043E\u0447\u0435\u043A\u0433\u043E\u0440\u0438\u0437\u043E\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0439\u0433\u0438\u0441\u0442\u043E\u0433\u0440\u0430\u043C\u043C\u044B \u043F\u043E\u0440\u044F\u0434\u043E\u043A\u0441\u0435\u0440\u0438\u0439\u0432\u043B\u0435\u0433\u0435\u043D\u0434\u0435\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0430\u0437\u043C\u0435\u0440\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0448\u043A\u0430\u043B\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0430\u0441\u0442\u044F\u0433\u0438\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u0432\u0435\u0440\u0442\u0438\u043A\u0430\u043B\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u0440\u0435\u0436\u0438\u043C\u0430\u0432\u0442\u043E\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0432\u0432\u043E\u0434\u0430\u0441\u0442\u0440\u043E\u043A\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0431\u043E\u0440\u0430\u043D\u0435\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u043D\u043E\u0433\u043E \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0434\u0430\u0442\u044B \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0441\u0442\u0440\u043E\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0440\u0435\u0436\u0438\u043C\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0440\u0435\u0436\u0438\u043C\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0440\u0430\u0437\u043C\u0435\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0441\u0432\u044F\u0437\u0430\u043D\u043D\u043E\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0434\u0438\u0430\u043B\u043E\u0433\u0430\u043F\u0435\u0447\u0430\u0442\u0438 \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0440\u0435\u0436\u0438\u043C\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E\u043E\u043A\u043D\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u043E\u043A\u043D\u0430\u0444\u043E\u0440\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0441\u0435\u0440\u0438\u0438 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u0440\u0438\u0441\u043E\u0432\u043A\u0438\u0441\u0435\u0442\u043A\u0438\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u043B\u0443\u043F\u0440\u043E\u0437\u0440\u0430\u0447\u043D\u043E\u0441\u0442\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u043F\u0440\u043E\u0431\u0435\u043B\u043E\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u043D\u0430\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u0435 \u0440\u0435\u0436\u0438\u043C\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u043A\u043E\u043B\u043E\u043D\u043A\u0438 \u0440\u0435\u0436\u0438\u043C\u0441\u0433\u043B\u0430\u0436\u0438\u0432\u0430\u043D\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0440\u0435\u0436\u0438\u043C\u0441\u0433\u043B\u0430\u0436\u0438\u0432\u0430\u043D\u0438\u044F\u0438\u043D\u0434\u0438\u043A\u0430\u0442\u043E\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u0441\u043F\u0438\u0441\u043A\u0430\u0437\u0430\u0434\u0430\u0447 \u0441\u043A\u0432\u043E\u0437\u043D\u043E\u0435\u0432\u044B\u0440\u0430\u0432\u043D\u0438\u0432\u0430\u043D\u0438\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445\u0444\u043E\u0440\u043C\u044B\u0432\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430\u0445 \u0441\u043F\u043E\u0441\u043E\u0431\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u0442\u0435\u043A\u0441\u0442\u0430\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0448\u043A\u0430\u043B\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0441\u043F\u043E\u0441\u043E\u0431\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0438\u0432\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u0430\u044F\u0433\u0440\u0443\u043F\u043F\u0430\u043A\u043E\u043C\u0430\u043D\u0434 \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0435\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u0435 \u0441\u0442\u0430\u0442\u0443\u0441\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0441\u0442\u0438\u043B\u044C\u0441\u0442\u0440\u0435\u043B\u043A\u0438 \u0442\u0438\u043F\u0430\u043F\u043F\u0440\u043E\u043A\u0441\u0438\u043C\u0430\u0446\u0438\u0438\u043B\u0438\u043D\u0438\u0438\u0442\u0440\u0435\u043D\u0434\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0435\u0434\u0438\u043D\u0438\u0446\u044B\u0448\u043A\u0430\u043B\u044B\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0442\u0438\u043F\u0438\u043C\u043F\u043E\u0440\u0442\u0430\u0441\u0435\u0440\u0438\u0439\u0441\u043B\u043E\u044F\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u043C\u0430\u0440\u043A\u0435\u0440\u0430\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043C\u0430\u0440\u043A\u0435\u0440\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u043E\u0440\u0433\u0430\u043D\u0438\u0437\u0430\u0446\u0438\u0438\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0441\u0435\u0440\u0438\u0438\u0441\u043B\u043E\u044F\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0442\u043E\u0447\u0435\u0447\u043D\u043E\u0433\u043E\u043E\u0431\u044A\u0435\u043A\u0442\u0430\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0448\u043A\u0430\u043B\u044B\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043B\u0435\u0433\u0435\u043D\u0434\u044B\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043F\u043E\u0438\u0441\u043A\u0430\u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u043F\u0440\u043E\u0435\u043A\u0446\u0438\u0438\u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u043E\u0432\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u0440\u0430\u043C\u043A\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0441\u0432\u044F\u0437\u0438\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u0433\u0430\u043D\u0442\u0430 \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u043F\u043E\u0441\u0435\u0440\u0438\u044F\u043C\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0442\u043E\u0447\u0435\u043A\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439\u043B\u0438\u043D\u0438\u0438 \u0442\u0438\u043F\u0441\u0442\u043E\u0440\u043E\u043D\u044B\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0442\u0438\u043F\u0444\u043E\u0440\u043C\u044B\u043E\u0442\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u0448\u043A\u0430\u043B\u044B\u0440\u0430\u0434\u0430\u0440\u043D\u043E\u0439\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0444\u0430\u043A\u0442\u043E\u0440\u043B\u0438\u043D\u0438\u0438\u0442\u0440\u0435\u043D\u0434\u0430\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B \u0444\u0438\u0433\u0443\u0440\u0430\u043A\u043D\u043E\u043F\u043A\u0438 \u0444\u0438\u0433\u0443\u0440\u044B\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u043E\u0439\u0441\u0445\u0435\u043C\u044B \u0444\u0438\u043A\u0441\u0430\u0446\u0438\u044F\u0432\u0442\u0430\u0431\u043B\u0438\u0446\u0435 \u0444\u043E\u0440\u043C\u0430\u0442\u0434\u043D\u044F\u0448\u043A\u0430\u043B\u044B\u0432\u0440\u0435\u043C\u0435\u043D\u0438 \u0444\u043E\u0440\u043C\u0430\u0442\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0448\u0438\u0440\u0438\u043D\u0430\u043F\u043E\u0434\u0447\u0438\u043D\u0435\u043D\u043D\u044B\u0445\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0444\u043E\u0440\u043C\u044B "; + var v8_system_enums_objects_properties = "\u0432\u0438\u0434\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u044F\u0431\u0443\u0445\u0433\u0430\u043B\u0442\u0435\u0440\u0438\u0438 \u0432\u0438\u0434\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u044F\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0432\u0438\u0434\u0441\u0447\u0435\u0442\u0430 \u0432\u0438\u0434\u0442\u043E\u0447\u043A\u0438\u043C\u0430\u0440\u0448\u0440\u0443\u0442\u0430\u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0430\u0433\u0440\u0435\u0433\u0430\u0442\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0435\u0436\u0438\u043C\u0430\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u0440\u0435\u0437\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u0430\u0433\u0440\u0435\u0433\u0430\u0442\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0430\u0432\u0442\u043E\u0432\u0440\u0435\u043C\u044F \u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0438\u0441\u0438\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0440\u0435\u0436\u0438\u043C\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 "; + var v8_system_enums_exchange_plans = "\u0430\u0432\u0442\u043E\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u044F\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439\u043D\u043E\u043C\u0435\u0440\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043E\u0442\u043F\u0440\u0430\u0432\u043A\u0430\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445 "; + var v8_system_enums_tabular_document = "\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u043E\u0440\u0438\u0435\u043D\u0442\u0430\u0446\u0438\u044F\u0441\u0442\u0440\u0430\u043D\u0438\u0446\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0438\u0442\u043E\u0433\u043E\u0432\u043A\u043E\u043B\u043E\u043D\u043E\u043A\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0438\u0442\u043E\u0433\u043E\u0432\u0441\u0442\u0440\u043E\u043A\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430\u043E\u0442\u043D\u043E\u0441\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0441\u043F\u043E\u0441\u043E\u0431\u0447\u0442\u0435\u043D\u0438\u044F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0434\u0432\u0443\u0441\u0442\u043E\u0440\u043E\u043D\u043D\u0435\u0439\u043F\u0435\u0447\u0430\u0442\u0438 \u0442\u0438\u043F\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043A\u0443\u0440\u0441\u043E\u0440\u043E\u0432\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u0440\u0438\u0441\u0443\u043D\u043A\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043B\u0438\u043D\u0438\u0438\u044F\u0447\u0435\u0439\u043A\u0438\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u0435\u0440\u0435\u0445\u043E\u0434\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u0432\u044B\u0434\u0435\u043B\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043B\u0438\u043D\u0438\u0439\u0441\u0432\u043E\u0434\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0442\u0435\u043A\u0441\u0442\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0440\u0438\u0441\u0443\u043D\u043A\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0441\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0443\u0437\u043E\u0440\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u0444\u0430\u0439\u043B\u0430\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u043E\u0447\u043D\u043E\u0441\u0442\u044C\u043F\u0435\u0447\u0430\u0442\u0438 \u0447\u0435\u0440\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u044F\u0441\u0442\u0440\u0430\u043D\u0438\u0446 "; + var v8_system_enums_sheduler = "\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u0432\u0440\u0435\u043C\u0435\u043D\u0438\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0449\u0438\u043A\u0430 "; + var v8_system_enums_formatted_document = "\u0442\u0438\u043F\u0444\u0430\u0439\u043B\u0430\u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0433\u043E\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 "; + var v8_system_enums_query = "\u043E\u0431\u0445\u043E\u0434\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u0437\u0430\u043F\u0438\u0441\u0438\u0437\u0430\u043F\u0440\u043E\u0441\u0430 "; + var v8_system_enums_report_builder = "\u0432\u0438\u0434\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044F\u043E\u0442\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u044F\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044F\u043E\u0442\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0438\u0442\u043E\u0433\u043E\u0432 "; + var v8_system_enums_files = "\u0434\u043E\u0441\u0442\u0443\u043F\u043A\u0444\u0430\u0439\u043B\u0443 \u0440\u0435\u0436\u0438\u043C\u0434\u0438\u0430\u043B\u043E\u0433\u0430\u0432\u044B\u0431\u043E\u0440\u0430\u0444\u0430\u0439\u043B\u0430 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u0444\u0430\u0439\u043B\u0430 "; + var v8_system_enums_query_builder = "\u0442\u0438\u043F\u0438\u0437\u043C\u0435\u0440\u0435\u043D\u0438\u044F\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044F\u0437\u0430\u043F\u0440\u043E\u0441\u0430 "; + var v8_system_enums_data_analysis = "\u0432\u0438\u0434\u0434\u0430\u043D\u043D\u044B\u0445\u0430\u043D\u0430\u043B\u0438\u0437\u0430 \u043C\u0435\u0442\u043E\u0434\u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u0438 \u0442\u0438\u043F\u0435\u0434\u0438\u043D\u0438\u0446\u044B\u0438\u043D\u0442\u0435\u0440\u0432\u0430\u043B\u0430\u0432\u0440\u0435\u043C\u0435\u043D\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0447\u0438\u0441\u043B\u043E\u0432\u044B\u0445\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0438\u0441\u043A\u0430\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u0434\u0435\u0440\u0435\u0432\u043E\u0440\u0435\u0448\u0435\u043D\u0438\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0438\u0437\u0430\u0446\u0438\u044F \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043E\u0431\u0449\u0430\u044F\u0441\u0442\u0430\u0442\u0438\u0441\u0442\u0438\u043A\u0430 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0438\u0441\u043A\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0438\u0441\u043A\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439 \u0442\u0438\u043F\u043A\u043E\u043B\u043E\u043D\u043A\u0438\u043C\u043E\u0434\u0435\u043B\u0438\u043F\u0440\u043E\u0433\u043D\u043E\u0437\u0430 \u0442\u0438\u043F\u043C\u0435\u0440\u044B\u0440\u0430\u0441\u0441\u0442\u043E\u044F\u043D\u0438\u044F\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043E\u0442\u0441\u0435\u0447\u0435\u043D\u0438\u044F\u043F\u0440\u0430\u0432\u0438\u043B\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0438 \u0442\u0438\u043F\u043F\u043E\u043B\u044F\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u0438\u0437\u0430\u0446\u0438\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0443\u043F\u043E\u0440\u044F\u0434\u043E\u0447\u0438\u0432\u0430\u043D\u0438\u044F\u043F\u0440\u0430\u0432\u0438\u043B\u0430\u0441\u0441\u043E\u0446\u0438\u0430\u0446\u0438\u0438\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0443\u043F\u043E\u0440\u044F\u0434\u043E\u0447\u0438\u0432\u0430\u043D\u0438\u044F\u0448\u0430\u0431\u043B\u043E\u043D\u043E\u0432\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0443\u043F\u0440\u043E\u0449\u0435\u043D\u0438\u044F\u0434\u0435\u0440\u0435\u0432\u0430\u0440\u0435\u0448\u0435\u043D\u0438\u0439 "; + var v8_system_enums_xml_json_xs_dom_xdto_ws = "ws\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430 \u0432\u0430\u0440\u0438\u0430\u043D\u0442xpathxs \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0437\u0430\u043F\u0438\u0441\u0438\u0434\u0430\u0442\u044Bjson \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043F\u0440\u043E\u0441\u0442\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u0432\u0438\u0434\u0433\u0440\u0443\u043F\u043F\u044B\u043C\u043E\u0434\u0435\u043B\u0438xs \u0432\u0438\u0434\u0444\u0430\u0441\u0435\u0442\u0430xdto \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044Fdom \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043D\u043E\u0441\u0442\u044C\u043F\u0440\u043E\u0441\u0442\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043D\u043E\u0441\u0442\u044C\u0441\u043E\u0441\u0442\u0430\u0432\u043D\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043D\u043D\u043E\u0441\u0442\u044C\u0441\u0445\u0435\u043C\u044Bxs \u0437\u0430\u043F\u0440\u0435\u0449\u0435\u043D\u043D\u044B\u0435\u043F\u043E\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438xs \u0438\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F\u0433\u0440\u0443\u043F\u043F\u043F\u043E\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438xs \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xs \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F\u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u043E\u0441\u0442\u0438xs \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F\u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0438\u043C\u0435\u043Dxs \u043C\u0435\u0442\u043E\u0434\u043D\u0430\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u043D\u0438\u044Fxs \u043C\u043E\u0434\u0435\u043B\u044C\u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0433\u043Exs \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0442\u0438\u043F\u0430xml \u043D\u0435\u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0435\u043F\u043E\u0434\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0438xs \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043F\u0440\u043E\u0431\u0435\u043B\u044C\u043D\u044B\u0445\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432xs \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0433\u043Exs \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u043E\u0442\u0431\u043E\u0440\u0430\u0443\u0437\u043B\u043E\u0432dom \u043F\u0435\u0440\u0435\u043D\u043E\u0441\u0441\u0442\u0440\u043E\u043Ajson \u043F\u043E\u0437\u0438\u0446\u0438\u044F\u0432\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0435dom \u043F\u0440\u043E\u0431\u0435\u043B\u044C\u043D\u044B\u0435\u0441\u0438\u043C\u0432\u043E\u043B\u044Bxml \u0442\u0438\u043F\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xml \u0442\u0438\u043F\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fjson \u0442\u0438\u043F\u043A\u0430\u043D\u043E\u043D\u0438\u0447\u0435\u0441\u043A\u043E\u0433\u043Exml \u0442\u0438\u043F\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044Bxs \u0442\u0438\u043F\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438xml \u0442\u0438\u043F\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430domxpath \u0442\u0438\u043F\u0443\u0437\u043B\u0430dom \u0442\u0438\u043F\u0443\u0437\u043B\u0430xml \u0444\u043E\u0440\u043C\u0430xml \u0444\u043E\u0440\u043C\u0430\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044Fxs \u0444\u043E\u0440\u043C\u0430\u0442\u0434\u0430\u0442\u044Bjson \u044D\u043A\u0440\u0430\u043D\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432json "; + var v8_system_enums_data_composition_system = "\u0432\u0438\u0434\u0441\u0440\u0430\u0432\u043D\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0432\u043B\u043E\u0436\u0435\u043D\u043D\u044B\u0445\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0438\u0442\u043E\u0433\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u0435\u0439\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u0441\u0443\u0440\u0441\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0431\u0443\u0445\u0433\u0430\u043B\u0442\u0435\u0440\u0441\u043A\u043E\u0433\u043E\u043E\u0441\u0442\u0430\u0442\u043A\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0432\u044B\u0432\u043E\u0434\u0430\u0442\u0435\u043A\u0441\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0433\u0440\u0443\u043F\u043F\u044B\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432\u043E\u0442\u0431\u043E\u0440\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0430\u043F\u043E\u043B\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043C\u0430\u043A\u0435\u0442\u0430\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043C\u0430\u043A\u0435\u0442\u0430\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043E\u0441\u0442\u0430\u0442\u043A\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0440\u0430\u0437\u043C\u0435\u0449\u0435\u043D\u0438\u044F\u0442\u0435\u043A\u0441\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u0441\u0432\u044F\u0437\u0438\u043D\u0430\u0431\u043E\u0440\u043E\u0432\u0434\u0430\u043D\u043D\u044B\u0445\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u043B\u0435\u0433\u0435\u043D\u0434\u044B\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u044B\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u043E\u0442\u0431\u043E\u0440\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043F\u043E\u0441\u043E\u0431\u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0430\u0432\u0442\u043E\u043F\u043E\u0437\u0438\u0446\u0438\u044F\u0440\u0435\u0441\u0443\u0440\u0441\u043E\u0432\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0433\u0440\u0443\u043F\u043F\u0438\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0440\u0435\u0441\u0443\u0440\u0441\u043E\u0432\u0432\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0435\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0444\u0438\u043A\u0441\u0430\u0446\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0443\u0441\u043B\u043E\u0432\u043D\u043E\u0433\u043E\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 "; + var v8_system_enums_email = "\u0432\u0430\u0436\u043D\u043E\u0441\u0442\u044C\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u0442\u0435\u043A\u0441\u0442\u0430\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0441\u043F\u043E\u0441\u043E\u0431\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0432\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0441\u043F\u043E\u0441\u043E\u0431\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u043D\u0435ascii\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0442\u0435\u043A\u0441\u0442\u0430\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043F\u0440\u043E\u0442\u043E\u043A\u043E\u043B\u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u044B \u0441\u0442\u0430\u0442\u0443\u0441\u0440\u0430\u0437\u0431\u043E\u0440\u0430\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0433\u043E\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F "; + var v8_system_enums_logbook = "\u0440\u0435\u0436\u0438\u043C\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u0438\u0437\u0430\u043F\u0438\u0441\u0438\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0441\u0442\u0430\u0442\u0443\u0441\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u0438\u0437\u0430\u043F\u0438\u0441\u0438\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 "; + var v8_system_enums_cryptography = "\u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0432\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0440\u0435\u0436\u0438\u043C\u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0432\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0440\u0435\u0436\u0438\u043C\u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u0430\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0442\u0438\u043F\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0432\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 "; + var v8_system_enums_zip = "\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0430\u0438\u043C\u0435\u043D\u0444\u0430\u0439\u043B\u043E\u0432\u0432zip\u0444\u0430\u0439\u043B\u0435 \u043C\u0435\u0442\u043E\u0434\u0441\u0436\u0430\u0442\u0438\u044Fzip \u043C\u0435\u0442\u043E\u0434\u0448\u0438\u0444\u0440\u043E\u0432\u0430\u043D\u0438\u044Fzip \u0440\u0435\u0436\u0438\u043C\u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043F\u0443\u0442\u0435\u0439\u0444\u0430\u0439\u043B\u043E\u0432zip \u0440\u0435\u0436\u0438\u043C\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438\u043F\u043E\u0434\u043A\u0430\u0442\u0430\u043B\u043E\u0433\u043E\u0432zip \u0440\u0435\u0436\u0438\u043C\u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F\u043F\u0443\u0442\u0435\u0439zip \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0441\u0436\u0430\u0442\u0438\u044Fzip "; + var v8_system_enums_other = "\u0437\u0432\u0443\u043A\u043E\u0432\u043E\u0435\u043E\u043F\u043E\u0432\u0435\u0449\u0435\u043D\u0438\u0435 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0435\u0440\u0435\u0445\u043E\u0434\u0430\u043A\u0441\u0442\u0440\u043E\u043A\u0435 \u043F\u043E\u0437\u0438\u0446\u0438\u044F\u0432\u043F\u043E\u0442\u043E\u043A\u0435 \u043F\u043E\u0440\u044F\u0434\u043E\u043A\u0431\u0430\u0439\u0442\u043E\u0432 \u0440\u0435\u0436\u0438\u043C\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0435\u0436\u0438\u043C\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u043E\u0439\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0435\u0440\u0432\u0438\u0441\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u044B\u0445\u043F\u043E\u043A\u0443\u043F\u043E\u043A \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u0444\u043E\u043D\u043E\u0432\u043E\u0433\u043E\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0442\u0438\u043F\u043F\u043E\u0434\u043F\u0438\u0441\u0447\u0438\u043A\u0430\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0445\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439 \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0437\u0430\u0449\u0438\u0449\u0435\u043D\u043D\u043E\u0433\u043E\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044Fftp "; + var v8_system_enums_request_schema = "\u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u043E\u0440\u044F\u0434\u043A\u0430\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u0434\u043E\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F\u043F\u0435\u0440\u0438\u043E\u0434\u0430\u043C\u0438\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u043A\u043E\u043D\u0442\u0440\u043E\u043B\u044C\u043D\u043E\u0439\u0442\u043E\u0447\u043A\u0438\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u043E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E\u0439\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u0442\u0438\u043F\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F\u0441\u0445\u0435\u043C\u044B\u0437\u0430\u043F\u0440\u043E\u0441\u0430 "; + var v8_system_enums_properties_of_metadata_objects = "http\u043C\u0435\u0442\u043E\u0434 \u0430\u0432\u0442\u043E\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0430\u0432\u0442\u043E\u043F\u0440\u0435\u0444\u0438\u043A\u0441\u043D\u043E\u043C\u0435\u0440\u0430\u0437\u0430\u0434\u0430\u0447\u0438 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0432\u0441\u0442\u0440\u043E\u0435\u043D\u043D\u043E\u0433\u043E\u044F\u0437\u044B\u043A\u0430 \u0432\u0438\u0434\u0438\u0435\u0440\u0430\u0440\u0445\u0438\u0438 \u0432\u0438\u0434\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u043D\u0430\u043A\u043E\u043F\u043B\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0437\u0430\u043F\u0438\u0441\u044C\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u0439\u043F\u0440\u0438\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0438 \u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439 \u0438\u043D\u0434\u0435\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0431\u0430\u0437\u044B\u043F\u043B\u0430\u043D\u0430\u0432\u0438\u0434\u043E\u0432\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0431\u044B\u0441\u0442\u0440\u043E\u0433\u043E\u0432\u044B\u0431\u043E\u0440\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u0434\u0447\u0438\u043D\u0435\u043D\u0438\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0430\u0437\u0434\u0435\u043B\u044F\u0435\u043C\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u043F\u0435\u0440\u0430\u0442\u0438\u0432\u043D\u043E\u0435\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0432\u0438\u0434\u0430\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0432\u0438\u0434\u0430\u0445\u0430\u0440\u0430\u043A\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043A\u0438 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0437\u0430\u0434\u0430\u0447\u0438 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u043B\u0430\u043D\u0430\u043E\u0431\u043C\u0435\u043D\u0430 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0435\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u0447\u0435\u0442\u0430 \u043F\u0435\u0440\u0435\u043C\u0435\u0449\u0435\u043D\u0438\u0435\u0433\u0440\u0430\u043D\u0438\u0446\u044B\u043F\u0440\u0438\u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0438 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u043D\u043E\u043C\u0435\u0440\u0430\u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u043D\u043E\u043C\u0435\u0440\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u043F\u0435\u0440\u0438\u043E\u0434\u0438\u0447\u043D\u043E\u0441\u0442\u044C\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0441\u0432\u0435\u0434\u0435\u043D\u0438\u0439 \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0432\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043C\u044B\u0445\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439\u043F\u043E\u0438\u0441\u043A\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u043A\u0435 \u043F\u0440\u0438\u043D\u0430\u0434\u043B\u0435\u0436\u043D\u043E\u0441\u0442\u044C\u043E\u0431\u044A\u0435\u043A\u0442\u0430 \u043F\u0440\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u0435 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0430\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u0438\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u043E\u0431\u0449\u0435\u0433\u043E\u0440\u0435\u043A\u0432\u0438\u0437\u0438\u0442\u0430 \u0440\u0435\u0436\u0438\u043C\u0430\u0432\u0442\u043E\u043D\u0443\u043C\u0435\u0440\u0430\u0446\u0438\u0438\u043E\u0431\u044A\u0435\u043A\u0442\u043E\u0432 \u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0438\u0441\u0438\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430 \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u043C\u043E\u0434\u0430\u043B\u044C\u043D\u043E\u0441\u0442\u0438 \u0440\u0435\u0436\u0438\u043C\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0438\u043D\u0445\u0440\u043E\u043D\u043D\u044B\u0445\u0432\u044B\u0437\u043E\u0432\u043E\u0432\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439\u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u044B\u0438\u0432\u043D\u0435\u0448\u043D\u0438\u0445\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442 \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E\u0433\u043E\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445\u0432\u044B\u0431\u043E\u0440\u0430\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u043A\u0435 \u0440\u0435\u0436\u0438\u043C\u0441\u043E\u0432\u043C\u0435\u0441\u0442\u0438\u043C\u043E\u0441\u0442\u0438 \u0440\u0435\u0436\u0438\u043C\u0441\u043E\u0432\u043C\u0435\u0441\u0442\u0438\u043C\u043E\u0441\u0442\u0438\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u0440\u0435\u0436\u0438\u043C\u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u043E\u0439\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E \u0441\u0435\u0440\u0438\u0438\u043A\u043E\u0434\u043E\u0432\u043F\u043B\u0430\u043D\u0430\u0432\u0438\u0434\u043E\u0432\u0445\u0430\u0440\u0430\u043A\u0442\u0435\u0440\u0438\u0441\u0442\u0438\u043A \u0441\u0435\u0440\u0438\u0438\u043A\u043E\u0434\u043E\u0432\u043F\u043B\u0430\u043D\u0430\u0441\u0447\u0435\u0442\u043E\u0432 \u0441\u0435\u0440\u0438\u0438\u043A\u043E\u0434\u043E\u0432\u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u0441\u043E\u0437\u0434\u0430\u043D\u0438\u0435\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435 \u0441\u043F\u043E\u0441\u043E\u0431\u0432\u044B\u0431\u043E\u0440\u0430 \u0441\u043F\u043E\u0441\u043E\u0431\u043F\u043E\u0438\u0441\u043A\u0430\u0441\u0442\u0440\u043E\u043A\u0438\u043F\u0440\u0438\u0432\u0432\u043E\u0434\u0435\u043F\u043E\u0441\u0442\u0440\u043E\u043A\u0435 \u0441\u043F\u043E\u0441\u043E\u0431\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0442\u0438\u043F\u0434\u0430\u043D\u043D\u044B\u0445\u0442\u0430\u0431\u043B\u0438\u0446\u044B\u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0438\u043F\u043A\u043E\u0434\u0430\u043F\u043B\u0430\u043D\u0430\u0432\u0438\u0434\u043E\u0432\u0440\u0430\u0441\u0447\u0435\u0442\u0430 \u0442\u0438\u043F\u043A\u043E\u0434\u0430\u0441\u043F\u0440\u0430\u0432\u043E\u0447\u043D\u0438\u043A\u0430 \u0442\u0438\u043F\u043C\u0430\u043A\u0435\u0442\u0430 \u0442\u0438\u043F\u043D\u043E\u043C\u0435\u0440\u0430\u0431\u0438\u0437\u043D\u0435\u0441\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u0442\u0438\u043F\u043D\u043E\u043C\u0435\u0440\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430 \u0442\u0438\u043F\u043D\u043E\u043C\u0435\u0440\u0430\u0437\u0430\u0434\u0430\u0447\u0438 \u0442\u0438\u043F\u0444\u043E\u0440\u043C\u044B \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u0434\u0432\u0438\u0436\u0435\u043D\u0438\u0439 "; + var v8_system_enums_differents = "\u0432\u0430\u0436\u043D\u043E\u0441\u0442\u044C\u043F\u0440\u043E\u0431\u043B\u0435\u043C\u044B\u043F\u0440\u0438\u043C\u0435\u043D\u0435\u043D\u0438\u044F\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043C\u0430\u0441\u0448\u0442\u0430\u0431\u0430\u0444\u043E\u0440\u043C\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0433\u043E\u0448\u0440\u0438\u0444\u0442\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430 \u0432\u0430\u0440\u0438\u0430\u043D\u0442\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0439\u0434\u0430\u0442\u044B\u043D\u0430\u0447\u0430\u043B\u0430 \u0432\u0438\u0434\u0433\u0440\u0430\u043D\u0438\u0446\u044B \u0432\u0438\u0434\u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0438 \u0432\u0438\u0434\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0432\u0438\u0434\u0440\u0430\u043C\u043A\u0438 \u0432\u0438\u0434\u0441\u0440\u0430\u0432\u043D\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u0446\u0432\u0435\u0442\u0430 \u0432\u0438\u0434\u0447\u0438\u0441\u043B\u043E\u0432\u043E\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0432\u0438\u0434\u0448\u0440\u0438\u0444\u0442\u0430 \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u0430\u044F\u0434\u043B\u0438\u043D\u0430 \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439\u0437\u043D\u0430\u043A \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435byteordermark \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043C\u0435\u0442\u0430\u0434\u0430\u043D\u043D\u044B\u0445\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0439\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438 \u043A\u043B\u0430\u0432\u0438\u0448\u0430 \u043A\u043E\u0434\u0432\u043E\u0437\u0432\u0440\u0430\u0442\u0430\u0434\u0438\u0430\u043B\u043E\u0433\u0430 \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0430xbase \u043A\u043E\u0434\u0438\u0440\u043E\u0432\u043A\u0430\u0442\u0435\u043A\u0441\u0442\u0430 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u043E\u0438\u0441\u043A\u0430 \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0438 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0435\u0434\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u0438\u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043F\u0430\u043D\u0435\u043B\u0438\u0440\u0430\u0437\u0434\u0435\u043B\u043E\u0432 \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0430\u0437\u0430\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u0434\u0438\u0430\u043B\u043E\u0433\u0430\u0432\u043E\u043F\u0440\u043E\u0441 \u0440\u0435\u0436\u0438\u043C\u0437\u0430\u043F\u0443\u0441\u043A\u0430\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u043A\u0440\u0443\u0433\u043B\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043E\u0442\u043A\u0440\u044B\u0442\u0438\u044F\u0444\u043E\u0440\u043C\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F \u0440\u0435\u0436\u0438\u043C\u043F\u043E\u043B\u043D\u043E\u0442\u0435\u043A\u0441\u0442\u043E\u0432\u043E\u0433\u043E\u043F\u043E\u0438\u0441\u043A\u0430 \u0441\u043A\u043E\u0440\u043E\u0441\u0442\u044C\u043A\u043B\u0438\u0435\u043D\u0442\u0441\u043A\u043E\u0433\u043E\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E\u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u043F\u043E\u0441\u043E\u0431\u0432\u044B\u0431\u043E\u0440\u0430\u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u0430windows \u0441\u043F\u043E\u0441\u043E\u0431\u043A\u043E\u0434\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0442\u0440\u043E\u043A\u0438 \u0441\u0442\u0430\u0442\u0443\u0441\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0442\u0438\u043F\u0432\u043D\u0435\u0448\u043D\u0435\u0439\u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u044B \u0442\u0438\u043F\u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u044B \u0442\u0438\u043F\u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F\u043A\u043B\u0430\u0432\u0438\u0448\u0438enter \u0442\u0438\u043F\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u0438\u043E\u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0438\u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438\u0431\u0430\u0437\u044B\u0434\u0430\u043D\u043D\u044B\u0445 \u0443\u0440\u043E\u0432\u0435\u043D\u044C\u0438\u0437\u043E\u043B\u044F\u0446\u0438\u0438\u0442\u0440\u0430\u043D\u0437\u0430\u043A\u0446\u0438\u0439 \u0445\u0435\u0448\u0444\u0443\u043D\u043A\u0446\u0438\u044F \u0447\u0430\u0441\u0442\u0438\u0434\u0430\u0442\u044B"; + var CLASS = v8_system_sets_of_values + v8_system_enums_interface + v8_system_enums_objects_properties + v8_system_enums_exchange_plans + v8_system_enums_tabular_document + v8_system_enums_sheduler + v8_system_enums_formatted_document + v8_system_enums_query + v8_system_enums_report_builder + v8_system_enums_files + v8_system_enums_query_builder + v8_system_enums_data_analysis + v8_system_enums_xml_json_xs_dom_xdto_ws + v8_system_enums_data_composition_system + v8_system_enums_email + v8_system_enums_logbook + v8_system_enums_cryptography + v8_system_enums_zip + v8_system_enums_other + v8_system_enums_request_schema + v8_system_enums_properties_of_metadata_objects + v8_system_enums_differents; + var v8_shared_object = "com\u043E\u0431\u044A\u0435\u043A\u0442 ftp\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 http\u0437\u0430\u043F\u0440\u043E\u0441 http\u0441\u0435\u0440\u0432\u0438\u0441\u043E\u0442\u0432\u0435\u0442 http\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 ws\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F ws\u043F\u0440\u043E\u043A\u0441\u0438 xbase \u0430\u043D\u0430\u043B\u0438\u0437\u0434\u0430\u043D\u043D\u044B\u0445 \u0430\u043D\u043D\u043E\u0442\u0430\u0446\u0438\u044Fxs \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u0431\u0443\u0444\u0435\u0440\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0435xs \u0432\u044B\u0440\u0430\u0436\u0435\u043D\u0438\u0435\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0433\u0435\u043D\u0435\u0440\u0430\u0442\u043E\u0440\u0441\u043B\u0443\u0447\u0430\u0439\u043D\u044B\u0445\u0447\u0438\u0441\u0435\u043B \u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0430\u044F\u0441\u0445\u0435\u043C\u0430 \u0433\u0435\u043E\u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0438\u0435\u043A\u043E\u043E\u0440\u0434\u0438\u043D\u0430\u0442\u044B \u0433\u0440\u0430\u0444\u0438\u0447\u0435\u0441\u043A\u0430\u044F\u0441\u0445\u0435\u043C\u0430 \u0433\u0440\u0443\u043F\u043F\u0430\u043C\u043E\u0434\u0435\u043B\u0438xs \u0434\u0430\u043D\u043D\u044B\u0435\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0435\u0434\u0430\u043D\u043D\u044B\u0435 \u0434\u0435\u043D\u0434\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0430 \u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0430 \u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0430\u0433\u0430\u043D\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0432\u044B\u0431\u043E\u0440\u0430\u0444\u0430\u0439\u043B\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0432\u044B\u0431\u043E\u0440\u0430\u0446\u0432\u0435\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0432\u044B\u0431\u043E\u0440\u0430\u0448\u0440\u0438\u0444\u0442\u0430 \u0434\u0438\u0430\u043B\u043E\u0433\u0440\u0430\u0441\u043F\u0438\u0441\u0430\u043D\u0438\u044F\u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u043E\u0433\u043E\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0434\u0438\u0430\u043B\u043E\u0433\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u043E\u0433\u043E\u043F\u0435\u0440\u0438\u043E\u0434\u0430 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442dom \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442html \u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u044Fxs \u0434\u043E\u0441\u0442\u0430\u0432\u043B\u044F\u0435\u043C\u043E\u0435\u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u0437\u0430\u043F\u0438\u0441\u044Cdom \u0437\u0430\u043F\u0438\u0441\u044Cfastinfoset \u0437\u0430\u043F\u0438\u0441\u044Chtml \u0437\u0430\u043F\u0438\u0441\u044Cjson \u0437\u0430\u043F\u0438\u0441\u044Cxml \u0437\u0430\u043F\u0438\u0441\u044Czip\u0444\u0430\u0439\u043B\u0430 \u0437\u0430\u043F\u0438\u0441\u044C\u0434\u0430\u043D\u043D\u044B\u0445 \u0437\u0430\u043F\u0438\u0441\u044C\u0442\u0435\u043A\u0441\u0442\u0430 \u0437\u0430\u043F\u0438\u0441\u044C\u0443\u0437\u043B\u043E\u0432dom \u0437\u0430\u043F\u0440\u043E\u0441 \u0437\u0430\u0449\u0438\u0449\u0435\u043D\u043D\u043E\u0435\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435openssl \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F\u043F\u043E\u043B\u0435\u0439\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430 \u0438\u043C\u043F\u043E\u0440\u0442xs \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u0430 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0435\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u043E\u0447\u0442\u043E\u0432\u044B\u0439\u043F\u0440\u043E\u0444\u0438\u043B\u044C \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u043F\u0440\u043E\u043A\u0441\u0438 \u0438\u043D\u0442\u0435\u0440\u043D\u0435\u0442\u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F\u0434\u043B\u044F\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044Fxs \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xs \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u0438\u0441\u0442\u043E\u0447\u043D\u0438\u043A\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B\u0445\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0438\u0442\u0435\u0440\u0430\u0442\u043E\u0440\u0443\u0437\u043B\u043E\u0432dom \u043A\u0430\u0440\u0442\u0438\u043D\u043A\u0430 \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0434\u0430\u0442\u044B \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0434\u0432\u043E\u0438\u0447\u043D\u044B\u0445\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0441\u0442\u0440\u043E\u043A\u0438 \u043A\u0432\u0430\u043B\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B\u0447\u0438\u0441\u043B\u0430 \u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u0449\u0438\u043A\u043C\u0430\u043A\u0435\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u0449\u0438\u043A\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043D\u0441\u0442\u0440\u0443\u043A\u0442\u043E\u0440\u043C\u0430\u043A\u0435\u0442\u0430\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043D\u0441\u0442\u0440\u0443\u043A\u0442\u043E\u0440\u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043A\u043E\u043D\u0441\u0442\u0440\u0443\u043A\u0442\u043E\u0440\u0444\u043E\u0440\u043C\u0430\u0442\u043D\u043E\u0439\u0441\u0442\u0440\u043E\u043A\u0438 \u043B\u0438\u043D\u0438\u044F \u043C\u0430\u043A\u0435\u0442\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043C\u0430\u043A\u0435\u0442\u043E\u0431\u043B\u0430\u0441\u0442\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043C\u0430\u043A\u0435\u0442\u043E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u0438\u044F\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043C\u0430\u0441\u043A\u0430xs \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u043D\u0430\u0431\u043E\u0440\u0441\u0445\u0435\u043Cxml \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438\u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0446\u0438\u0438json \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u043A\u0430\u0440\u0442\u0438\u043D\u043E\u043A \u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0430\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u0431\u0445\u043E\u0434\u0434\u0435\u0440\u0435\u0432\u0430dom \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0435\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u0430xs \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0435\u043D\u043E\u0442\u0430\u0446\u0438\u0438xs \u043E\u0431\u044A\u044F\u0432\u043B\u0435\u043D\u0438\u0435\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430xs \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u0434\u043E\u0441\u0442\u0443\u043F\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F\u0441\u043E\u0431\u044B\u0442\u0438\u044F\u043E\u0442\u043A\u0430\u0437\u0432\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u0436\u0443\u0440\u043D\u0430\u043B\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0430\u0446\u0438\u0438 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u043E\u0431\u0440\u0430\u0431\u043E\u0442\u043A\u0438\u0440\u0430\u0441\u0448\u0438\u0444\u0440\u043E\u0432\u043A\u0438\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u043F\u0435\u0440\u0435\u0434\u0430\u0432\u0430\u0435\u043C\u043E\u0433\u043E\u0444\u0430\u0439\u043B\u0430 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0442\u0438\u043F\u043E\u0432 \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u044B\u0430\u0442\u0440\u0438\u0431\u0443\u0442\u043E\u0432xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0433\u0440\u0443\u043F\u043F\u044B\u043C\u043E\u0434\u0435\u043B\u0438xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F\u0438\u0434\u0435\u043D\u0442\u0438\u0447\u043D\u043E\u0441\u0442\u0438xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u043F\u0440\u043E\u0441\u0442\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0441\u043E\u0441\u0442\u0430\u0432\u043D\u043E\u0433\u043E\u0442\u0438\u043F\u0430xs \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435\u0442\u0438\u043F\u0430\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430dom \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044Fxpathxs \u043E\u0442\u0431\u043E\u0440\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u0430\u043A\u0435\u0442\u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u0435\u043C\u044B\u0445\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0432\u044B\u0431\u043E\u0440\u0430 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0437\u0430\u043F\u0438\u0441\u0438json \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0437\u0430\u043F\u0438\u0441\u0438xml \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B\u0447\u0442\u0435\u043D\u0438\u044Fxml \u043F\u0435\u0440\u0435\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435xs \u043F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0449\u0438\u043A \u043F\u043E\u043B\u0435\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u043B\u0435\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044Cdom \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u0437\u0430\u043F\u0440\u043E\u0441\u0430 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u043E\u0442\u0447\u0435\u0442\u0430 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u043E\u0442\u0447\u0435\u0442\u0430\u0430\u043D\u0430\u043B\u0438\u0437\u0430\u0434\u0430\u043D\u043D\u044B\u0445 \u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u0435\u043B\u044C\u0441\u0445\u0435\u043Cxml \u043F\u043E\u0442\u043E\u043A \u043F\u043E\u0442\u043E\u043A\u0432\u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u043E\u0447\u0442\u0430 \u043F\u043E\u0447\u0442\u043E\u0432\u043E\u0435\u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043F\u0440\u0435\u043E\u0431\u0440\u0430\u0437\u043E\u0432\u0430\u043D\u0438\u0435xsl \u043F\u0440\u0435\u043E\u0431\u0440\u0430\u0437\u043E\u0432\u0430\u043D\u0438\u0435\u043A\u043A\u0430\u043D\u043E\u043D\u0438\u0447\u0435\u0441\u043A\u043E\u043C\u0443xml \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u0432\u044B\u0432\u043E\u0434\u0430\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445\u0432\u043A\u043E\u043B\u043B\u0435\u043A\u0446\u0438\u044E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u0432\u044B\u0432\u043E\u0434\u0430\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445\u0432\u0442\u0430\u0431\u043B\u0438\u0447\u043D\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0440\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0440\u0430\u0437\u044B\u043C\u0435\u043D\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043F\u0440\u043E\u0441\u0442\u0440\u0430\u043D\u0441\u0442\u0432\u0438\u043C\u0435\u043Ddom \u0440\u0430\u043C\u043A\u0430 \u0440\u0430\u0441\u043F\u0438\u0441\u0430\u043D\u0438\u0435\u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u043E\u0433\u043E\u0437\u0430\u0434\u0430\u043D\u0438\u044F \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u043D\u043E\u0435\u0438\u043C\u044Fxml \u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0447\u0442\u0435\u043D\u0438\u044F\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0432\u043E\u0434\u043D\u0430\u044F\u0434\u0438\u0430\u0433\u0440\u0430\u043C\u043C\u0430 \u0441\u0432\u044F\u0437\u044C\u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0430\u0432\u044B\u0431\u043E\u0440\u0430 \u0441\u0432\u044F\u0437\u044C\u043F\u043E\u0442\u0438\u043F\u0443 \u0441\u0432\u044F\u0437\u044C\u043F\u043E\u0442\u0438\u043F\u0443\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0435\u0440\u0438\u0430\u043B\u0438\u0437\u0430\u0442\u043E\u0440xdto \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043A\u043B\u0438\u0435\u043D\u0442\u0430windows \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043A\u043B\u0438\u0435\u043D\u0442\u0430\u0444\u0430\u0439\u043B \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043A\u0440\u0438\u043F\u0442\u043E\u0433\u0440\u0430\u0444\u0438\u0438 \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u044B\u0443\u0434\u043E\u0441\u0442\u043E\u0432\u0435\u0440\u044F\u044E\u0449\u0438\u0445\u0446\u0435\u043D\u0442\u0440\u043E\u0432windows \u0441\u0435\u0440\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u044B\u0443\u0434\u043E\u0441\u0442\u043E\u0432\u0435\u0440\u044F\u044E\u0449\u0438\u0445\u0446\u0435\u043D\u0442\u0440\u043E\u0432\u0444\u0430\u0439\u043B \u0441\u0436\u0430\u0442\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u0430\u044F\u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044E \u0441\u043E\u0447\u0435\u0442\u0430\u043D\u0438\u0435\u043A\u043B\u0430\u0432\u0438\u0448 \u0441\u0440\u0430\u0432\u043D\u0435\u043D\u0438\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u0430\u044F\u0434\u0430\u0442\u0430\u043D\u0430\u0447\u0430\u043B\u0430 \u0441\u0442\u0430\u043D\u0434\u0430\u0440\u0442\u043D\u044B\u0439\u043F\u0435\u0440\u0438\u043E\u0434 \u0441\u0445\u0435\u043C\u0430xml \u0441\u0445\u0435\u043C\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 \u0442\u0430\u0431\u043B\u0438\u0447\u043D\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0442\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0442\u0435\u0441\u0442\u0438\u0440\u0443\u0435\u043C\u043E\u0435\u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u0442\u0438\u043F\u0434\u0430\u043D\u043D\u044B\u0445xml \u0443\u043D\u0438\u043A\u0430\u043B\u044C\u043D\u044B\u0439\u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440 \u0444\u0430\u0431\u0440\u0438\u043A\u0430xdto \u0444\u0430\u0439\u043B \u0444\u0430\u0439\u043B\u043E\u0432\u044B\u0439\u043F\u043E\u0442\u043E\u043A \u0444\u0430\u0441\u0435\u0442\u0434\u043B\u0438\u043D\u044Bxs \u0444\u0430\u0441\u0435\u0442\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430\u0440\u0430\u0437\u0440\u044F\u0434\u043E\u0432\u0434\u0440\u043E\u0431\u043D\u043E\u0439\u0447\u0430\u0441\u0442\u0438xs \u0444\u0430\u0441\u0435\u0442\u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0432\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0438\u0441\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0439\u0434\u043B\u0438\u043D\u044Bxs \u0444\u0430\u0441\u0435\u0442\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0432\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E\u0438\u0441\u043A\u043B\u044E\u0447\u0430\u044E\u0449\u0435\u0433\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0439\u0434\u043B\u0438\u043D\u044Bxs \u0444\u0430\u0441\u0435\u0442\u043E\u0431\u0440\u0430\u0437\u0446\u0430xs \u0444\u0430\u0441\u0435\u0442\u043E\u0431\u0449\u0435\u0433\u043E\u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430\u0440\u0430\u0437\u0440\u044F\u0434\u043E\u0432xs \u0444\u0430\u0441\u0435\u0442\u043F\u0435\u0440\u0435\u0447\u0438\u0441\u043B\u0435\u043D\u0438\u044Fxs \u0444\u0430\u0441\u0435\u0442\u043F\u0440\u043E\u0431\u0435\u043B\u044C\u043D\u044B\u0445\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432xs \u0444\u0438\u043B\u044C\u0442\u0440\u0443\u0437\u043B\u043E\u0432dom \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u0430\u044F\u0441\u0442\u0440\u043E\u043A\u0430 \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442 \u0444\u0440\u0430\u0433\u043C\u0435\u043D\u0442xs \u0445\u0435\u0448\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u0446\u0432\u0435\u0442 \u0447\u0442\u0435\u043D\u0438\u0435fastinfoset \u0447\u0442\u0435\u043D\u0438\u0435html \u0447\u0442\u0435\u043D\u0438\u0435json \u0447\u0442\u0435\u043D\u0438\u0435xml \u0447\u0442\u0435\u043D\u0438\u0435zip\u0444\u0430\u0439\u043B\u0430 \u0447\u0442\u0435\u043D\u0438\u0435\u0434\u0430\u043D\u043D\u044B\u0445 \u0447\u0442\u0435\u043D\u0438\u0435\u0442\u0435\u043A\u0441\u0442\u0430 \u0447\u0442\u0435\u043D\u0438\u0435\u0443\u0437\u043B\u043E\u0432dom \u0448\u0440\u0438\u0444\u0442 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0440\u0435\u0437\u0443\u043B\u044C\u0442\u0430\u0442\u0430\u043A\u043E\u043C\u043F\u043E\u043D\u043E\u0432\u043A\u0438\u0434\u0430\u043D\u043D\u044B\u0445 "; + var v8_universal_collection = "comsafearray \u0434\u0435\u0440\u0435\u0432\u043E\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u043C\u0430\u0441\u0441\u0438\u0432 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u0441\u043F\u0438\u0441\u043E\u043A\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430 \u0442\u0430\u0431\u043B\u0438\u0446\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0439 \u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u0430\u044F\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430 \u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435\u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0435 \u0444\u0438\u043A\u0441\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439\u043C\u0430\u0441\u0441\u0438\u0432 "; + var TYPE = v8_shared_object + v8_universal_collection; + var LITERAL = "null \u0438\u0441\u0442\u0438\u043D\u0430 \u043B\u043E\u0436\u044C \u043D\u0435\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u043E"; + var NUMBERS = hljs5.inherit(hljs5.NUMBER_MODE); + var STRINGS = { + className: "string", + begin: '"|\\|', + end: '"|$', + contains: [{ begin: '""' }] + }; + var DATE = { + begin: "'", + end: "'", + excludeBegin: true, + excludeEnd: true, + contains: [ + { + className: "number", + begin: "\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}" + } + ] + }; + var COMMENTS = hljs5.inherit(hljs5.C_LINE_COMMENT_MODE); + var META = { + className: "meta", + begin: "#|&", + end: "$", + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + "meta-keyword": KEYWORD + METAKEYWORD + }, + contains: [ + COMMENTS + ] + }; + var SYMBOL = { + className: "symbol", + begin: "~", + end: ";|:", + excludeEnd: true + }; + var FUNCTION = { + className: "function", + variants: [ + { begin: "\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u0430|\u0444\u0443\u043D\u043A\u0446\u0438\u044F", end: "\\)", keywords: "\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u0430 \u0444\u0443\u043D\u043A\u0446\u0438\u044F" }, + { begin: "\u043A\u043E\u043D\u0435\u0446\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u044B|\u043A\u043E\u043D\u0435\u0446\u0444\u0443\u043D\u043A\u0446\u0438\u0438", keywords: "\u043A\u043E\u043D\u0435\u0446\u043F\u0440\u043E\u0446\u0435\u0434\u0443\u0440\u044B \u043A\u043E\u043D\u0435\u0446\u0444\u0443\u043D\u043A\u0446\u0438\u0438" } + ], + contains: [ + { + begin: "\\(", + end: "\\)", + endsParent: true, + contains: [ + { + className: "params", + begin: UNDERSCORE_IDENT_RE, + end: ",", + excludeEnd: true, + endsWithParent: true, + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + keyword: "\u0437\u043D\u0430\u0447", + literal: LITERAL + }, + contains: [ + NUMBERS, + STRINGS, + DATE + ] + }, + COMMENTS + ] + }, + hljs5.inherit(hljs5.TITLE_MODE, { begin: UNDERSCORE_IDENT_RE }) + ] + }; + return { + name: "1C:Enterprise", + case_insensitive: true, + keywords: { + $pattern: UNDERSCORE_IDENT_RE, + keyword: KEYWORD, + built_in: BUILTIN, + class: CLASS, + type: TYPE, + literal: LITERAL + }, + contains: [ + META, + FUNCTION, + COMMENTS, + SYMBOL, + NUMBERS, + STRINGS, + DATE + ] + }; + } + module.exports = _1c; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/abnf.js +var require_abnf = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/abnf.js"(exports, module) { + init_process_shim(); + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function abnf(hljs5) { + const regexes = { + ruleDeclaration: /^[a-zA-Z][a-zA-Z0-9-]*/, + unexpectedChars: /[!@#$^&',?+~`|:]/ + }; + const keywords = [ + "ALPHA", + "BIT", + "CHAR", + "CR", + "CRLF", + "CTL", + "DIGIT", + "DQUOTE", + "HEXDIG", + "HTAB", + "LF", + "LWSP", + "OCTET", + "SP", + "VCHAR", + "WSP" + ]; + const commentMode = hljs5.COMMENT(/;/, /$/); + const terminalBinaryMode = { + className: "symbol", + begin: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+){0,1}/ + }; + const terminalDecimalMode = { + className: "symbol", + begin: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+){0,1}/ + }; + const terminalHexadecimalMode = { + className: "symbol", + begin: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+){0,1}/ + }; + const caseSensitivityIndicatorMode = { + className: "symbol", + begin: /%[si]/ + }; + const ruleDeclarationMode = { + className: "attribute", + begin: concat(regexes.ruleDeclaration, /(?=\s*=)/) + }; + return { + name: "Augmented Backus-Naur Form", + illegal: regexes.unexpectedChars, + keywords, + contains: [ + ruleDeclarationMode, + commentMode, + terminalBinaryMode, + terminalDecimalMode, + terminalHexadecimalMode, + caseSensitivityIndicatorMode, + hljs5.QUOTE_STRING_MODE, + hljs5.NUMBER_MODE + ] + }; + } + module.exports = abnf; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/accesslog.js +var require_accesslog = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/accesslog.js"(exports, module) { + init_process_shim(); + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function either(...args) { + const joined = "(" + args.map((x2) => source(x2)).join("|") + ")"; + return joined; + } + function accesslog(_hljs) { + const HTTP_VERBS = [ + "GET", + "POST", + "HEAD", + "PUT", + "DELETE", + "CONNECT", + "OPTIONS", + "PATCH", + "TRACE" + ]; + return { + name: "Apache Access Log", + contains: [ + // IP + { + className: "number", + begin: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/, + relevance: 5 + }, + // Other numbers + { + className: "number", + begin: /\b\d+\b/, + relevance: 0 + }, + // Requests + { + className: "string", + begin: concat(/"/, either(...HTTP_VERBS)), + end: /"/, + keywords: HTTP_VERBS, + illegal: /\n/, + relevance: 5, + contains: [ + { + begin: /HTTP\/[12]\.\d'/, + relevance: 5 + } + ] + }, + // Dates + { + className: "string", + // dates must have a certain length, this prevents matching + // simple array accesses a[123] and [] and other common patterns + // found in other languages + begin: /\[\d[^\]\n]{8,}\]/, + illegal: /\n/, + relevance: 1 + }, + { + className: "string", + begin: /\[/, + end: /\]/, + illegal: /\n/, + relevance: 0 + }, + // User agent / relevance boost + { + className: "string", + begin: /"Mozilla\/\d\.\d \(/, + end: /"/, + illegal: /\n/, + relevance: 3 + }, + // Strings + { + className: "string", + begin: /"/, + end: /"/, + illegal: /\n/, + relevance: 0 + } + ] + }; + } + module.exports = accesslog; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/actionscript.js +var require_actionscript = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/actionscript.js"(exports, module) { + init_process_shim(); + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function actionscript(hljs5) { + const IDENT_RE3 = /[a-zA-Z_$][a-zA-Z0-9_$]*/; + const IDENT_FUNC_RETURN_TYPE_RE = /([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)/; + const AS3_REST_ARG_MODE = { + className: "rest_arg", + begin: /[.]{3}/, + end: IDENT_RE3, + relevance: 10 + }; + return { + name: "ActionScript", + aliases: ["as"], + keywords: { + keyword: "as break case catch class const continue default delete do dynamic each else extends final finally for function get if implements import in include instanceof interface internal is namespace native new override package private protected public return set static super switch this throw try typeof use var void while with", + literal: "true false null undefined" + }, + contains: [ + hljs5.APOS_STRING_MODE, + hljs5.QUOTE_STRING_MODE, + hljs5.C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + hljs5.C_NUMBER_MODE, + { + className: "class", + beginKeywords: "package", + end: /\{/, + contains: [hljs5.TITLE_MODE] + }, + { + className: "class", + beginKeywords: "class interface", + end: /\{/, + excludeEnd: true, + contains: [ + { beginKeywords: "extends implements" }, + hljs5.TITLE_MODE + ] + }, + { + className: "meta", + beginKeywords: "import include", + end: /;/, + keywords: { "meta-keyword": "import include" } + }, + { + className: "function", + beginKeywords: "function", + end: /[{;]/, + excludeEnd: true, + illegal: /\S/, + contains: [ + hljs5.TITLE_MODE, + { + className: "params", + begin: /\(/, + end: /\)/, + contains: [ + hljs5.APOS_STRING_MODE, + hljs5.QUOTE_STRING_MODE, + hljs5.C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + AS3_REST_ARG_MODE + ] + }, + { begin: concat(/:\s*/, IDENT_FUNC_RETURN_TYPE_RE) } + ] + }, + hljs5.METHOD_GUARD + ], + illegal: /#/ + }; + } + module.exports = actionscript; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/ada.js +var require_ada = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/ada.js"(exports, module) { + init_process_shim(); + function ada(hljs5) { + const INTEGER_RE = "\\d(_|\\d)*"; + const EXPONENT_RE = "[eE][-+]?" + INTEGER_RE; + const DECIMAL_LITERAL_RE = INTEGER_RE + "(\\." + INTEGER_RE + ")?(" + EXPONENT_RE + ")?"; + const BASED_INTEGER_RE = "\\w+"; + const BASED_LITERAL_RE = INTEGER_RE + "#" + BASED_INTEGER_RE + "(\\." + BASED_INTEGER_RE + ")?#(" + EXPONENT_RE + ")?"; + const NUMBER_RE = "\\b(" + BASED_LITERAL_RE + "|" + DECIMAL_LITERAL_RE + ")"; + const ID_REGEX = "[A-Za-z](_?[A-Za-z0-9.])*"; + const BAD_CHARS = `[]\\{\\}%#'"`; + const COMMENTS = hljs5.COMMENT("--", "$"); + const VAR_DECLS = { + // TODO: These spaces are not required by the Ada syntax + // however, I have yet to see handwritten Ada code where + // someone does not put spaces around : + begin: "\\s+:\\s+", + end: "\\s*(:=|;|\\)|=>|$)", + // endsWithParent: true, + // returnBegin: true, + illegal: BAD_CHARS, + contains: [ + { + // workaround to avoid highlighting + // named loops and declare blocks + beginKeywords: "loop for declare others", + endsParent: true + }, + { + // properly highlight all modifiers + className: "keyword", + beginKeywords: "not null constant access function procedure in out aliased exception" + }, + { + className: "type", + begin: ID_REGEX, + endsParent: true, + relevance: 0 + } + ] + }; + return { + name: "Ada", + case_insensitive: true, + keywords: { + keyword: "abort else new return abs elsif not reverse abstract end accept entry select access exception of separate aliased exit or some all others subtype and for out synchronized array function overriding at tagged generic package task begin goto pragma terminate body private then if procedure type case in protected constant interface is raise use declare range delay limited record when delta loop rem while digits renames with do mod requeue xor", + literal: "True False" + }, + contains: [ + COMMENTS, + // strings "foobar" + { + className: "string", + begin: /"/, + end: /"/, + contains: [{ + begin: /""/, + relevance: 0 + }] + }, + // characters '' + { + // character literals always contain one char + className: "string", + begin: /'.'/ + }, + { + // number literals + className: "number", + begin: NUMBER_RE, + relevance: 0 + }, + { + // Attributes + className: "symbol", + begin: "'" + ID_REGEX + }, + { + // package definition, maybe inside generic + className: "title", + begin: "(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?", + end: "(is|$)", + keywords: "package body", + excludeBegin: true, + excludeEnd: true, + illegal: BAD_CHARS + }, + { + // function/procedure declaration/definition + // maybe inside generic + begin: "(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+", + end: "(\\bis|\\bwith|\\brenames|\\)\\s*;)", + keywords: "overriding function procedure with is renames return", + // we need to re-match the 'function' keyword, so that + // the title mode below matches only exactly once + returnBegin: true, + contains: [ + COMMENTS, + { + // name of the function/procedure + className: "title", + begin: "(\\bwith\\s+)?\\b(function|procedure)\\s+", + end: "(\\(|\\s+|$)", + excludeBegin: true, + excludeEnd: true, + illegal: BAD_CHARS + }, + // 'self' + // // parameter types + VAR_DECLS, + { + // return type + className: "type", + begin: "\\breturn\\s+", + end: "(\\s+|;|$)", + keywords: "return", + excludeBegin: true, + excludeEnd: true, + // we are done with functions + endsParent: true, + illegal: BAD_CHARS + } + ] + }, + { + // new type declarations + // maybe inside generic + className: "type", + begin: "\\b(sub)?type\\s+", + end: "\\s+", + keywords: "type", + excludeBegin: true, + illegal: BAD_CHARS + }, + // see comment above the definition + VAR_DECLS + // no markup + // relevance boosters for small snippets + // {begin: '\\s*=>\\s*'}, + // {begin: '\\s*:=\\s*'}, + // {begin: '\\s+:=\\s+'}, + ] + }; + } + module.exports = ada; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/angelscript.js +var require_angelscript = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/angelscript.js"(exports, module) { + init_process_shim(); + function angelscript(hljs5) { + var builtInTypeMode = { + className: "built_in", + begin: "\\b(void|bool|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|string|ref|array|double|float|auto|dictionary)" + }; + var objectHandleMode = { + className: "symbol", + begin: "[a-zA-Z0-9_]+@" + }; + var genericMode = { + className: "keyword", + begin: "<", + end: ">", + contains: [builtInTypeMode, objectHandleMode] + }; + builtInTypeMode.contains = [genericMode]; + objectHandleMode.contains = [genericMode]; + return { + name: "AngelScript", + aliases: ["asc"], + keywords: "for in|0 break continue while do|0 return if else case switch namespace is cast or and xor not get|0 in inout|10 out override set|0 private public const default|0 final shared external mixin|10 enum typedef funcdef this super import from interface abstract|0 try catch protected explicit property", + // avoid close detection with C# and JS + illegal: "(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\\s*[^\\(])", + contains: [ + { + // 'strings' + className: "string", + begin: "'", + end: "'", + illegal: "\\n", + contains: [hljs5.BACKSLASH_ESCAPE], + relevance: 0 + }, + // """heredoc strings""" + { + className: "string", + begin: '"""', + end: '"""' + }, + { + // "strings" + className: "string", + begin: '"', + end: '"', + illegal: "\\n", + contains: [hljs5.BACKSLASH_ESCAPE], + relevance: 0 + }, + hljs5.C_LINE_COMMENT_MODE, + // single-line comments + hljs5.C_BLOCK_COMMENT_MODE, + // comment blocks + { + // metadata + className: "string", + begin: "^\\s*\\[", + end: "\\]" + }, + { + // interface or namespace declaration + beginKeywords: "interface namespace", + end: /\{/, + illegal: "[;.\\-]", + contains: [ + { + // interface or namespace name + className: "symbol", + begin: "[a-zA-Z0-9_]+" + } + ] + }, + { + // class declaration + beginKeywords: "class", + end: /\{/, + illegal: "[;.\\-]", + contains: [ + { + // class name + className: "symbol", + begin: "[a-zA-Z0-9_]+", + contains: [ + { + begin: "[:,]\\s*", + contains: [ + { + className: "symbol", + begin: "[a-zA-Z0-9_]+" + } + ] + } + ] + } + ] + }, + builtInTypeMode, + // built-in types + objectHandleMode, + // object handles + { + // literals + className: "literal", + begin: "\\b(null|true|false)" + }, + { + // numbers + className: "number", + relevance: 0, + begin: "(-?)(\\b0[xXbBoOdD][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)" + } + ] + }; + } + module.exports = angelscript; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/apache.js +var require_apache = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/apache.js"(exports, module) { + init_process_shim(); + function apache(hljs5) { + const NUMBER_REF = { + className: "number", + begin: /[$%]\d+/ + }; + const NUMBER = { + className: "number", + begin: /\d+/ + }; + const IP_ADDRESS = { + className: "number", + begin: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?/ + }; + const PORT_NUMBER = { + className: "number", + begin: /:\d{1,5}/ + }; + return { + name: "Apache config", + aliases: ["apacheconf"], + case_insensitive: true, + contains: [ + hljs5.HASH_COMMENT_MODE, + { + className: "section", + begin: /<\/?/, + end: />/, + contains: [ + IP_ADDRESS, + PORT_NUMBER, + // low relevance prevents us from claming XML/HTML where this rule would + // match strings inside of XML tags + hljs5.inherit(hljs5.QUOTE_STRING_MODE, { relevance: 0 }) + ] + }, + { + className: "attribute", + begin: /\w+/, + relevance: 0, + // keywords aren’t needed for highlighting per se, they only boost relevance + // for a very generally defined mode (starts with a word, ends with line-end + keywords: { + nomarkup: "order deny allow setenv rewriterule rewriteengine rewritecond documentroot sethandler errordocument loadmodule options header listen serverroot servername" + }, + starts: { + end: /$/, + relevance: 0, + keywords: { literal: "on off all deny allow" }, + contains: [ + { + className: "meta", + begin: /\s\[/, + end: /\]$/ + }, + { + className: "variable", + begin: /[\$%]\{/, + end: /\}/, + contains: [ + "self", + NUMBER_REF + ] + }, + IP_ADDRESS, + NUMBER, + hljs5.QUOTE_STRING_MODE + ] + } + } + ], + illegal: /\S/ + }; + } + module.exports = apache; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/applescript.js +var require_applescript = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/applescript.js"(exports, module) { + init_process_shim(); + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function either(...args) { + const joined = "(" + args.map((x2) => source(x2)).join("|") + ")"; + return joined; + } + function applescript(hljs5) { + const STRING = hljs5.inherit( + hljs5.QUOTE_STRING_MODE, + { + illegal: null + } + ); + const PARAMS = { + className: "params", + begin: /\(/, + end: /\)/, + contains: [ + "self", + hljs5.C_NUMBER_MODE, + STRING + ] + }; + const COMMENT_MODE_1 = hljs5.COMMENT(/--/, /$/); + const COMMENT_MODE_2 = hljs5.COMMENT( + /\(\*/, + /\*\)/, + { + contains: [ + "self", + // allow nesting + COMMENT_MODE_1 + ] + } + ); + const COMMENTS = [ + COMMENT_MODE_1, + COMMENT_MODE_2, + hljs5.HASH_COMMENT_MODE + ]; + const KEYWORD_PATTERNS = [ + /apart from/, + /aside from/, + /instead of/, + /out of/, + /greater than/, + /isn't|(doesn't|does not) (equal|come before|come after|contain)/, + /(greater|less) than( or equal)?/, + /(starts?|ends|begins?) with/, + /contained by/, + /comes (before|after)/, + /a (ref|reference)/, + /POSIX (file|path)/, + /(date|time) string/, + /quoted form/ + ]; + const BUILT_IN_PATTERNS = [ + /clipboard info/, + /the clipboard/, + /info for/, + /list (disks|folder)/, + /mount volume/, + /path to/, + /(close|open for) access/, + /(get|set) eof/, + /current date/, + /do shell script/, + /get volume settings/, + /random number/, + /set volume/, + /system attribute/, + /system info/, + /time to GMT/, + /(load|run|store) script/, + /scripting components/, + /ASCII (character|number)/, + /localized string/, + /choose (application|color|file|file name|folder|from list|remote application|URL)/, + /display (alert|dialog)/ + ]; + return { + name: "AppleScript", + aliases: ["osascript"], + keywords: { + keyword: "about above after against and around as at back before beginning behind below beneath beside between but by considering contain contains continue copy div does eighth else end equal equals error every exit fifth first for fourth from front get given global if ignoring in into is it its last local me middle mod my ninth not of on onto or over prop property put ref reference repeat returning script second set seventh since sixth some tell tenth that the|0 then third through thru timeout times to transaction try until where while whose with without", + literal: "AppleScript false linefeed return pi quote result space tab true", + built_in: "alias application boolean class constant date file integer list number real record string text activate beep count delay launch log offset read round run say summarize write character characters contents day frontmost id item length month name paragraph paragraphs rest reverse running time version weekday word words year" + }, + contains: [ + STRING, + hljs5.C_NUMBER_MODE, + { + className: "built_in", + begin: concat( + /\b/, + either(...BUILT_IN_PATTERNS), + /\b/ + ) + }, + { + className: "built_in", + begin: /^\s*return\b/ + }, + { + className: "literal", + begin: /\b(text item delimiters|current application|missing value)\b/ + }, + { + className: "keyword", + begin: concat( + /\b/, + either(...KEYWORD_PATTERNS), + /\b/ + ) + }, + { + beginKeywords: "on", + illegal: /[${=;\n]/, + contains: [ + hljs5.UNDERSCORE_TITLE_MODE, + PARAMS + ] + }, + ...COMMENTS + ], + illegal: /\/\/|->|=>|\[\[/ + }; + } + module.exports = applescript; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/arcade.js +var require_arcade = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/arcade.js"(exports, module) { + init_process_shim(); + function arcade(hljs5) { + const IDENT_RE3 = "[A-Za-z_][0-9A-Za-z_]*"; + const KEYWORDS3 = { + keyword: "if for while var new function do return void else break", + literal: "BackSlash DoubleQuote false ForwardSlash Infinity NaN NewLine null PI SingleQuote Tab TextFormatting true undefined", + built_in: "Abs Acos Angle Attachments Area AreaGeodetic Asin Atan Atan2 Average Bearing Boolean Buffer BufferGeodetic Ceil Centroid Clip Console Constrain Contains Cos Count Crosses Cut Date DateAdd DateDiff Day Decode DefaultValue Dictionary Difference Disjoint Distance DistanceGeodetic Distinct DomainCode DomainName Equals Exp Extent Feature FeatureSet FeatureSetByAssociation FeatureSetById FeatureSetByPortalItem FeatureSetByRelationshipName FeatureSetByTitle FeatureSetByUrl Filter First Floor Geometry GroupBy Guid HasKey Hour IIf IndexOf Intersection Intersects IsEmpty IsNan IsSelfIntersecting Length LengthGeodetic Log Max Mean Millisecond Min Minute Month MultiPartToSinglePart Multipoint NextSequenceValue Now Number OrderBy Overlaps Point Polygon Polyline Portal Pow Random Relate Reverse RingIsClockWise Round Second SetGeometry Sin Sort Sqrt Stdev Sum SymmetricDifference Tan Text Timestamp Today ToLocal Top Touches ToUTC TrackCurrentTime TrackGeometryWindow TrackIndex TrackStartTime TrackWindow TypeOf Union UrlEncode Variance Weekday When Within Year " + }; + const SYMBOL = { + className: "symbol", + begin: "\\$[datastore|feature|layer|map|measure|sourcefeature|sourcelayer|targetfeature|targetlayer|value|view]+" + }; + const NUMBER = { + className: "number", + variants: [ + { + begin: "\\b(0[bB][01]+)" + }, + { + begin: "\\b(0[oO][0-7]+)" + }, + { + begin: hljs5.C_NUMBER_RE + } + ], + relevance: 0 + }; + const SUBST = { + className: "subst", + begin: "\\$\\{", + end: "\\}", + keywords: KEYWORDS3, + contains: [] + // defined later + }; + const TEMPLATE_STRING = { + className: "string", + begin: "`", + end: "`", + contains: [ + hljs5.BACKSLASH_ESCAPE, + SUBST + ] + }; + SUBST.contains = [ + hljs5.APOS_STRING_MODE, + hljs5.QUOTE_STRING_MODE, + TEMPLATE_STRING, + NUMBER, + hljs5.REGEXP_MODE + ]; + const PARAMS_CONTAINS = SUBST.contains.concat([ + hljs5.C_BLOCK_COMMENT_MODE, + hljs5.C_LINE_COMMENT_MODE + ]); + return { + name: "ArcGIS Arcade", + keywords: KEYWORDS3, + contains: [ + hljs5.APOS_STRING_MODE, + hljs5.QUOTE_STRING_MODE, + TEMPLATE_STRING, + hljs5.C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + SYMBOL, + NUMBER, + { + // object attr container + begin: /[{,]\s*/, + relevance: 0, + contains: [{ + begin: IDENT_RE3 + "\\s*:", + returnBegin: true, + relevance: 0, + contains: [{ + className: "attr", + begin: IDENT_RE3, + relevance: 0 + }] + }] + }, + { + // "value" container + begin: "(" + hljs5.RE_STARTERS_RE + "|\\b(return)\\b)\\s*", + keywords: "return", + contains: [ + hljs5.C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + hljs5.REGEXP_MODE, + { + className: "function", + begin: "(\\(.*?\\)|" + IDENT_RE3 + ")\\s*=>", + returnBegin: true, + end: "\\s*=>", + contains: [{ + className: "params", + variants: [ + { + begin: IDENT_RE3 + }, + { + begin: /\(\s*\)/ + }, + { + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + keywords: KEYWORDS3, + contains: PARAMS_CONTAINS + } + ] + }] + } + ], + relevance: 0 + }, + { + className: "function", + beginKeywords: "function", + end: /\{/, + excludeEnd: true, + contains: [ + hljs5.inherit(hljs5.TITLE_MODE, { + begin: IDENT_RE3 + }), + { + className: "params", + begin: /\(/, + end: /\)/, + excludeBegin: true, + excludeEnd: true, + contains: PARAMS_CONTAINS + } + ], + illegal: /\[|%/ + }, + { + begin: /\$[(.]/ + } + ], + illegal: /#(?!!)/ + }; + } + module.exports = arcade; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/arduino.js +var require_arduino = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/arduino.js"(exports, module) { + init_process_shim(); + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function lookahead(re2) { + return concat("(?=", re2, ")"); + } + function optional(re2) { + return concat("(", re2, ")?"); + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function cPlusPlus(hljs5) { + const C_LINE_COMMENT_MODE = hljs5.COMMENT("//", "$", { + contains: [ + { + begin: /\\\n/ + } + ] + }); + const DECLTYPE_AUTO_RE = "decltype\\(auto\\)"; + const NAMESPACE_RE = "[a-zA-Z_]\\w*::"; + const TEMPLATE_ARGUMENT_RE = "<[^<>]+>"; + const FUNCTION_TYPE_RE = "(" + DECLTYPE_AUTO_RE + "|" + optional(NAMESPACE_RE) + "[a-zA-Z_]\\w*" + optional(TEMPLATE_ARGUMENT_RE) + ")"; + const CPP_PRIMITIVE_TYPES = { + className: "keyword", + begin: "\\b[a-z\\d_]*_t\\b" + }; + const CHARACTER_ESCAPES = "\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"; + const STRINGS = { + className: "string", + variants: [ + { + begin: '(u8?|U|L)?"', + end: '"', + illegal: "\\n", + contains: [hljs5.BACKSLASH_ESCAPE] + }, + { + begin: "(u8?|U|L)?'(" + CHARACTER_ESCAPES + "|.)", + end: "'", + illegal: "." + }, + hljs5.END_SAME_AS_BEGIN({ + begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/, + end: /\)([^()\\ ]{0,16})"/ + }) + ] + }; + const NUMBERS = { + className: "number", + variants: [ + { + begin: "\\b(0b[01']+)" + }, + { + begin: "(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)" + }, + { + begin: "(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)" + } + ], + relevance: 0 + }; + const PREPROCESSOR = { + className: "meta", + begin: /#\s*[a-z]+\b/, + end: /$/, + keywords: { + "meta-keyword": "if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include" + }, + contains: [ + { + begin: /\\\n/, + relevance: 0 + }, + hljs5.inherit(STRINGS, { + className: "meta-string" + }), + { + className: "meta-string", + begin: /<.*?>/ + }, + C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE + ] + }; + const TITLE_MODE = { + className: "title", + begin: optional(NAMESPACE_RE) + hljs5.IDENT_RE, + relevance: 0 + }; + const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs5.IDENT_RE + "\\s*\\("; + const COMMON_CPP_HINTS = [ + "asin", + "atan2", + "atan", + "calloc", + "ceil", + "cosh", + "cos", + "exit", + "exp", + "fabs", + "floor", + "fmod", + "fprintf", + "fputs", + "free", + "frexp", + "auto_ptr", + "deque", + "list", + "queue", + "stack", + "vector", + "map", + "set", + "pair", + "bitset", + "multiset", + "multimap", + "unordered_set", + "fscanf", + "future", + "isalnum", + "isalpha", + "iscntrl", + "isdigit", + "isgraph", + "islower", + "isprint", + "ispunct", + "isspace", + "isupper", + "isxdigit", + "tolower", + "toupper", + "labs", + "ldexp", + "log10", + "log", + "malloc", + "realloc", + "memchr", + "memcmp", + "memcpy", + "memset", + "modf", + "pow", + "printf", + "putchar", + "puts", + "scanf", + "sinh", + "sin", + "snprintf", + "sprintf", + "sqrt", + "sscanf", + "strcat", + "strchr", + "strcmp", + "strcpy", + "strcspn", + "strlen", + "strncat", + "strncmp", + "strncpy", + "strpbrk", + "strrchr", + "strspn", + "strstr", + "tanh", + "tan", + "unordered_map", + "unordered_multiset", + "unordered_multimap", + "priority_queue", + "make_pair", + "array", + "shared_ptr", + "abort", + "terminate", + "abs", + "acos", + "vfprintf", + "vprintf", + "vsprintf", + "endl", + "initializer_list", + "unique_ptr", + "complex", + "imaginary", + "std", + "string", + "wstring", + "cin", + "cout", + "cerr", + "clog", + "stdin", + "stdout", + "stderr", + "stringstream", + "istringstream", + "ostringstream" + ]; + const CPP_KEYWORDS = { + keyword: "int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace unsigned long volatile static protected bool template mutable if public friend do goto auto void enum else break extern using asm case typeid wchar_t short reinterpret_cast|10 default double register explicit signed typename try this switch continue inline delete alignas alignof constexpr consteval constinit decltype concept co_await co_return co_yield requires noexcept static_assert thread_local restrict final override atomic_bool atomic_char atomic_schar atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong atomic_ullong new throw return and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq", + built_in: "_Bool _Complex _Imaginary", + _relevance_hints: COMMON_CPP_HINTS, + literal: "true false nullptr NULL" + }; + const FUNCTION_DISPATCH = { + className: "function.dispatch", + relevance: 0, + keywords: CPP_KEYWORDS, + begin: concat( + /\b/, + /(?!decltype)/, + /(?!if)/, + /(?!for)/, + /(?!while)/, + hljs5.IDENT_RE, + lookahead(/\s*\(/) + ) + }; + const EXPRESSION_CONTAINS = [ + FUNCTION_DISPATCH, + PREPROCESSOR, + CPP_PRIMITIVE_TYPES, + C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + NUMBERS, + STRINGS + ]; + const EXPRESSION_CONTEXT = { + // This mode covers expression context where we can't expect a function + // definition and shouldn't highlight anything that looks like one: + // `return some()`, `else if()`, `(x*sum(1, 2))` + variants: [ + { + begin: /=/, + end: /;/ + }, + { + begin: /\(/, + end: /\)/ + }, + { + beginKeywords: "new throw return else", + end: /;/ + } + ], + keywords: CPP_KEYWORDS, + contains: EXPRESSION_CONTAINS.concat([ + { + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + contains: EXPRESSION_CONTAINS.concat(["self"]), + relevance: 0 + } + ]), + relevance: 0 + }; + const FUNCTION_DECLARATION = { + className: "function", + begin: "(" + FUNCTION_TYPE_RE + "[\\*&\\s]+)+" + FUNCTION_TITLE, + returnBegin: true, + end: /[{;=]/, + excludeEnd: true, + keywords: CPP_KEYWORDS, + illegal: /[^\w\s\*&:<>.]/, + contains: [ + { + // to prevent it from being confused as the function title + begin: DECLTYPE_AUTO_RE, + keywords: CPP_KEYWORDS, + relevance: 0 + }, + { + begin: FUNCTION_TITLE, + returnBegin: true, + contains: [TITLE_MODE], + relevance: 0 + }, + // needed because we do not have look-behind on the below rule + // to prevent it from grabbing the final : in a :: pair + { + begin: /::/, + relevance: 0 + }, + // initializers + { + begin: /:/, + endsWithParent: true, + contains: [ + STRINGS, + NUMBERS + ] + }, + { + className: "params", + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + relevance: 0, + contains: [ + C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + STRINGS, + NUMBERS, + CPP_PRIMITIVE_TYPES, + // Count matching parentheses. + { + begin: /\(/, + end: /\)/, + keywords: CPP_KEYWORDS, + relevance: 0, + contains: [ + "self", + C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + STRINGS, + NUMBERS, + CPP_PRIMITIVE_TYPES + ] + } + ] + }, + CPP_PRIMITIVE_TYPES, + C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE, + PREPROCESSOR + ] + }; + return { + name: "C++", + aliases: [ + "cc", + "c++", + "h++", + "hpp", + "hh", + "hxx", + "cxx" + ], + keywords: CPP_KEYWORDS, + illegal: " rooms (9);` + begin: "\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<", + end: ">", + keywords: CPP_KEYWORDS, + contains: [ + "self", + CPP_PRIMITIVE_TYPES + ] + }, + { + begin: hljs5.IDENT_RE + "::", + keywords: CPP_KEYWORDS + }, + { + className: "class", + beginKeywords: "enum class struct union", + end: /[{;:<>=]/, + contains: [ + { + beginKeywords: "final class struct" + }, + hljs5.TITLE_MODE + ] + } + ] + ), + exports: { + preprocessor: PREPROCESSOR, + strings: STRINGS, + keywords: CPP_KEYWORDS + } + }; + } + function arduino(hljs5) { + const ARDUINO_KW = { + keyword: "boolean byte word String", + built_in: "KeyboardController MouseController SoftwareSerial EthernetServer EthernetClient LiquidCrystal RobotControl GSMVoiceCall EthernetUDP EsploraTFT HttpClient RobotMotor WiFiClient GSMScanner FileSystem Scheduler GSMServer YunClient YunServer IPAddress GSMClient GSMModem Keyboard Ethernet Console GSMBand Esplora Stepper Process WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage Client Server GSMPIN FileIO Bridge Serial EEPROM Stream Mouse Audio Servo File Task GPRS WiFi Wire TFT GSM SPI SD ", + _: "setup loop runShellCommandAsynchronously analogWriteResolution retrieveCallingNumber printFirmwareVersion analogReadResolution sendDigitalPortPair noListenOnLocalhost readJoystickButton setFirmwareVersion readJoystickSwitch scrollDisplayRight getVoiceCallStatus scrollDisplayLeft writeMicroseconds delayMicroseconds beginTransmission getSignalStrength runAsynchronously getAsynchronously listenOnLocalhost getCurrentCarrier readAccelerometer messageAvailable sendDigitalPorts lineFollowConfig countryNameWrite runShellCommand readStringUntil rewindDirectory readTemperature setClockDivider readLightSensor endTransmission analogReference detachInterrupt countryNameRead attachInterrupt encryptionType readBytesUntil robotNameWrite readMicrophone robotNameRead cityNameWrite userNameWrite readJoystickY readJoystickX mouseReleased openNextFile scanNetworks noInterrupts digitalWrite beginSpeaker mousePressed isActionDone mouseDragged displayLogos noAutoscroll addParameter remoteNumber getModifiers keyboardRead userNameRead waitContinue processInput parseCommand printVersion readNetworks writeMessage blinkVersion cityNameRead readMessage setDataMode parsePacket isListening setBitOrder beginPacket isDirectory motorsWrite drawCompass digitalRead clearScreen serialEvent rightToLeft setTextSize leftToRight requestFrom keyReleased compassRead analogWrite interrupts WiFiServer disconnect playMelody parseFloat autoscroll getPINUsed setPINUsed setTimeout sendAnalog readSlider analogRead beginWrite createChar motorsStop keyPressed tempoWrite readButton subnetMask debugPrint macAddress writeGreen randomSeed attachGPRS readString sendString remotePort releaseAll mouseMoved background getXChange getYChange answerCall getResult voiceCall endPacket constrain getSocket writeJSON getButton available connected findUntil readBytes exitValue readGreen writeBlue startLoop IPAddress isPressed sendSysex pauseMode gatewayIP setCursor getOemKey tuneWrite noDisplay loadImage switchPIN onRequest onReceive changePIN playFile noBuffer parseInt overflow checkPIN knobRead beginTFT bitClear updateIR bitWrite position writeRGB highByte writeRed setSpeed readBlue noStroke remoteIP transfer shutdown hangCall beginSMS endWrite attached maintain noCursor checkReg checkPUK shiftOut isValid shiftIn pulseIn connect println localIP pinMode getIMEI display noBlink process getBand running beginSD drawBMP lowByte setBand release bitRead prepare pointTo readRed setMode noFill remove listen stroke detach attach noTone exists buffer height bitSet circle config cursor random IRread setDNS endSMS getKey micros millis begin print write ready flush width isPIN blink clear press mkdir rmdir close point yield image BSSID click delay read text move peek beep rect line open seek fill size turn stop home find step tone sqrt RSSI SSID end bit tan cos sin pow map abs max min get run put", + literal: "DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL DEFAULT OUTPUT INPUT HIGH LOW" + }; + const ARDUINO = cPlusPlus(hljs5); + const kws = ( + /** @type {Record} */ + ARDUINO.keywords + ); + kws.keyword += " " + ARDUINO_KW.keyword; + kws.literal += " " + ARDUINO_KW.literal; + kws.built_in += " " + ARDUINO_KW.built_in; + kws._ += " " + ARDUINO_KW._; + ARDUINO.name = "Arduino"; + ARDUINO.aliases = ["ino"]; + ARDUINO.supersetOf = "cpp"; + return ARDUINO; + } + module.exports = arduino; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/armasm.js +var require_armasm = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/armasm.js"(exports, module) { + init_process_shim(); + function armasm(hljs5) { + const COMMENT = { + variants: [ + hljs5.COMMENT("^[ \\t]*(?=#)", "$", { + relevance: 0, + excludeBegin: true + }), + hljs5.COMMENT("[;@]", "$", { + relevance: 0 + }), + hljs5.C_LINE_COMMENT_MODE, + hljs5.C_BLOCK_COMMENT_MODE + ] + }; + return { + name: "ARM Assembly", + case_insensitive: true, + aliases: ["arm"], + keywords: { + $pattern: "\\.?" + hljs5.IDENT_RE, + meta: ( + // GNU preprocs + ".2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND " + ), + built_in: "r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 pc lr sp ip sl sb fp a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 s16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 d16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 {PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @" + }, + contains: [ + { + className: "keyword", + begin: "\\b(adc|(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|wfe|wfi|yield)(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?[sptrx]?(?=\\s)" + // followed by space + }, + COMMENT, + hljs5.QUOTE_STRING_MODE, + { + className: "string", + begin: "'", + end: "[^\\\\]'", + relevance: 0 + }, + { + className: "title", + begin: "\\|", + end: "\\|", + illegal: "\\n", + relevance: 0 + }, + { + className: "number", + variants: [ + { + // hex + begin: "[#$=]?0x[0-9a-f]+" + }, + { + // bin + begin: "[#$=]?0b[01]+" + }, + { + // literal + begin: "[#$=]\\d+" + }, + { + // bare number + begin: "\\b\\d+" + } + ], + relevance: 0 + }, + { + className: "symbol", + variants: [ + { + // GNU ARM syntax + begin: "^[ \\t]*[a-z_\\.\\$][a-z0-9_\\.\\$]+:" + }, + { + // ARM syntax + begin: "^[a-z_\\.\\$][a-z0-9_\\.\\$]+" + }, + { + // label reference + begin: "[=#]\\w+" + } + ], + relevance: 0 + } + ] + }; + } + module.exports = armasm; + } +}); + +// ../pi-mono/node_modules/highlight.js/lib/languages/xml.js +var require_xml = __commonJS({ + "../pi-mono/node_modules/highlight.js/lib/languages/xml.js"(exports, module) { + init_process_shim(); + function source(re2) { + if (!re2) return null; + if (typeof re2 === "string") return re2; + return re2.source; + } + function lookahead(re2) { + return concat("(?=", re2, ")"); + } + function optional(re2) { + return concat("(", re2, ")?"); + } + function concat(...args) { + const joined = args.map((x2) => source(x2)).join(""); + return joined; + } + function either(...args) { + const joined = "(" + args.map((x2) => source(x2)).join("|") + ")"; + return joined; + } + function xml2(hljs5) { + const TAG_NAME_RE = concat(/[A-Z_]/, optional(/[A-Z0-9_.-]*:/), /[A-Z0-9_.-]*/); + const XML_IDENT_RE = /[A-Za-z0-9._:-]+/; + const XML_ENTITIES = { + className: "symbol", + begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/ + }; + const XML_META_KEYWORDS = { + begin: /\s/, + contains: [ + { + className: "meta-keyword", + begin: /#?[a-z_][a-z1-9_-]+/, + illegal: /\n/ + } + ] + }; + const XML_META_PAR_KEYWORDS = hljs5.inherit(XML_META_KEYWORDS, { + begin: /\(/, + end: /\)/ + }); + const APOS_META_STRING_MODE = hljs5.inherit(hljs5.APOS_STRING_MODE, { + className: "meta-string" + }); + const QUOTE_META_STRING_MODE = hljs5.inherit(hljs5.QUOTE_STRING_MODE, { + className: "meta-string" + }); + const TAG_INTERNALS = { + endsWithParent: true, + illegal: /`]+/ + } + ] + } + ] + } + ] + }; + return { + name: "HTML, XML", + aliases: [ + "html", + "xhtml", + "rss", + "atom", + "xjb", + "xsd", + "xsl", + "plist", + "wsf", + "svg" + ], + case_insensitive: true, + contains: [ + { + className: "meta", + begin: //, + relevance: 10, + contains: [ + XML_META_KEYWORDS, + QUOTE_META_STRING_MODE, + APOS_META_STRING_MODE, + XML_META_PAR_KEYWORDS, + { + begin: /\[/, + end: /\]/, + contains: [ + { + className: "meta", + begin: //, + contains: [ + XML_META_KEYWORDS, + XML_META_PAR_KEYWORDS, + QUOTE_META_STRING_MODE, + APOS_META_STRING_MODE + ] + } + ] + } + ] + }, + hljs5.COMMENT( + //, + { + relevance: 10 + } + ), + { + begin: //, + relevance: 10 + }, + XML_ENTITIES, + { + className: "meta", + begin: /<\?xml/, + end: /\?>/, + relevance: 10 + }, + { + className: "tag", + /* + The lookahead pattern (?=...) ensures that 'begin' only matches + ')/, + end: />/, + keywords: { + name: "style" + }, + contains: [TAG_INTERNALS], + starts: { + end: /<\/style>/, + returnEnd: true, + subLanguage: [ + "css", + "xml" + ] + } + }, + { + className: "tag", + // See the comment in the + + + +
+ + + diff --git a/icons.js b/icons.js new file mode 100644 index 0000000..4e69ab5 --- /dev/null +++ b/icons.js @@ -0,0 +1,26038 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __decorateClass = (decorators, target, key, kind) => { + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + for (var i6 = decorators.length - 1, decorator; i6 >= 0; i6--) + if (decorator = decorators[i6]) + result = (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) __defProp(target, key, result); + return result; +}; + +// node_modules/@lit/reactive-element/css-tag.js +var t = globalThis; +var e = t.ShadowRoot && (void 0 === t.ShadyCSS || t.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype; +var s = Symbol(); +var o = /* @__PURE__ */ new WeakMap(); +var n = class { + constructor(t6, e8, o8) { + if (this._$cssResult$ = true, o8 !== s) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead."); + this.cssText = t6, this.t = e8; + } + get styleSheet() { + let t6 = this.o; + const s5 = this.t; + if (e && void 0 === t6) { + const e8 = void 0 !== s5 && 1 === s5.length; + e8 && (t6 = o.get(s5)), void 0 === t6 && ((this.o = t6 = new CSSStyleSheet()).replaceSync(this.cssText), e8 && o.set(s5, t6)); + } + return t6; + } + toString() { + return this.cssText; + } +}; +var r = (t6) => new n("string" == typeof t6 ? t6 : t6 + "", void 0, s); +var S = (s5, o8) => { + if (e) s5.adoptedStyleSheets = o8.map((t6) => t6 instanceof CSSStyleSheet ? t6 : t6.styleSheet); + else for (const e8 of o8) { + const o9 = document.createElement("style"), n7 = t.litNonce; + void 0 !== n7 && o9.setAttribute("nonce", n7), o9.textContent = e8.cssText, s5.appendChild(o9); + } +}; +var c = e ? (t6) => t6 : (t6) => t6 instanceof CSSStyleSheet ? ((t7) => { + let e8 = ""; + for (const s5 of t7.cssRules) e8 += s5.cssText; + return r(e8); +})(t6) : t6; + +// node_modules/@lit/reactive-element/reactive-element.js +var { is: i2, defineProperty: e2, getOwnPropertyDescriptor: h, getOwnPropertyNames: r2, getOwnPropertySymbols: o2, getPrototypeOf: n2 } = Object; +var a = globalThis; +var c2 = a.trustedTypes; +var l = c2 ? c2.emptyScript : ""; +var p = a.reactiveElementPolyfillSupport; +var d = (t6, s5) => t6; +var u = { toAttribute(t6, s5) { + switch (s5) { + case Boolean: + t6 = t6 ? l : null; + break; + case Object: + case Array: + t6 = null == t6 ? t6 : JSON.stringify(t6); + } + return t6; +}, fromAttribute(t6, s5) { + let i6 = t6; + switch (s5) { + case Boolean: + i6 = null !== t6; + break; + case Number: + i6 = null === t6 ? null : Number(t6); + break; + case Object: + case Array: + try { + i6 = JSON.parse(t6); + } catch (t7) { + i6 = null; + } + } + return i6; +} }; +var f = (t6, s5) => !i2(t6, s5); +var b = { attribute: true, type: String, converter: u, reflect: false, useDefault: false, hasChanged: f }; +Symbol.metadata ??= Symbol("metadata"), a.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap(); +var y = class extends HTMLElement { + static addInitializer(t6) { + this._$Ei(), (this.l ??= []).push(t6); + } + static get observedAttributes() { + return this.finalize(), this._$Eh && [...this._$Eh.keys()]; + } + static createProperty(t6, s5 = b) { + if (s5.state && (s5.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t6) && ((s5 = Object.create(s5)).wrapped = true), this.elementProperties.set(t6, s5), !s5.noAccessor) { + const i6 = Symbol(), h4 = this.getPropertyDescriptor(t6, i6, s5); + void 0 !== h4 && e2(this.prototype, t6, h4); + } + } + static getPropertyDescriptor(t6, s5, i6) { + const { get: e8, set: r6 } = h(this.prototype, t6) ?? { get() { + return this[s5]; + }, set(t7) { + this[s5] = t7; + } }; + return { get: e8, set(s6) { + const h4 = e8?.call(this); + r6?.call(this, s6), this.requestUpdate(t6, h4, i6); + }, configurable: true, enumerable: true }; + } + static getPropertyOptions(t6) { + return this.elementProperties.get(t6) ?? b; + } + static _$Ei() { + if (this.hasOwnProperty(d("elementProperties"))) return; + const t6 = n2(this); + t6.finalize(), void 0 !== t6.l && (this.l = [...t6.l]), this.elementProperties = new Map(t6.elementProperties); + } + static finalize() { + if (this.hasOwnProperty(d("finalized"))) return; + if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d("properties"))) { + const t7 = this.properties, s5 = [...r2(t7), ...o2(t7)]; + for (const i6 of s5) this.createProperty(i6, t7[i6]); + } + const t6 = this[Symbol.metadata]; + if (null !== t6) { + const s5 = litPropertyMetadata.get(t6); + if (void 0 !== s5) for (const [t7, i6] of s5) this.elementProperties.set(t7, i6); + } + this._$Eh = /* @__PURE__ */ new Map(); + for (const [t7, s5] of this.elementProperties) { + const i6 = this._$Eu(t7, s5); + void 0 !== i6 && this._$Eh.set(i6, t7); + } + this.elementStyles = this.finalizeStyles(this.styles); + } + static finalizeStyles(s5) { + const i6 = []; + if (Array.isArray(s5)) { + const e8 = new Set(s5.flat(1 / 0).reverse()); + for (const s6 of e8) i6.unshift(c(s6)); + } else void 0 !== s5 && i6.push(c(s5)); + return i6; + } + static _$Eu(t6, s5) { + const i6 = s5.attribute; + return false === i6 ? void 0 : "string" == typeof i6 ? i6 : "string" == typeof t6 ? t6.toLowerCase() : void 0; + } + constructor() { + super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev(); + } + _$Ev() { + this._$ES = new Promise((t6) => this.enableUpdating = t6), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach((t6) => t6(this)); + } + addController(t6) { + (this._$EO ??= /* @__PURE__ */ new Set()).add(t6), void 0 !== this.renderRoot && this.isConnected && t6.hostConnected?.(); + } + removeController(t6) { + this._$EO?.delete(t6); + } + _$E_() { + const t6 = /* @__PURE__ */ new Map(), s5 = this.constructor.elementProperties; + for (const i6 of s5.keys()) this.hasOwnProperty(i6) && (t6.set(i6, this[i6]), delete this[i6]); + t6.size > 0 && (this._$Ep = t6); + } + createRenderRoot() { + const t6 = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions); + return S(t6, this.constructor.elementStyles), t6; + } + connectedCallback() { + this.renderRoot ??= this.createRenderRoot(), this.enableUpdating(true), this._$EO?.forEach((t6) => t6.hostConnected?.()); + } + enableUpdating(t6) { + } + disconnectedCallback() { + this._$EO?.forEach((t6) => t6.hostDisconnected?.()); + } + attributeChangedCallback(t6, s5, i6) { + this._$AK(t6, i6); + } + _$ET(t6, s5) { + const i6 = this.constructor.elementProperties.get(t6), e8 = this.constructor._$Eu(t6, i6); + if (void 0 !== e8 && true === i6.reflect) { + const h4 = (void 0 !== i6.converter?.toAttribute ? i6.converter : u).toAttribute(s5, i6.type); + this._$Em = t6, null == h4 ? this.removeAttribute(e8) : this.setAttribute(e8, h4), this._$Em = null; + } + } + _$AK(t6, s5) { + const i6 = this.constructor, e8 = i6._$Eh.get(t6); + if (void 0 !== e8 && this._$Em !== e8) { + const t7 = i6.getPropertyOptions(e8), h4 = "function" == typeof t7.converter ? { fromAttribute: t7.converter } : void 0 !== t7.converter?.fromAttribute ? t7.converter : u; + this._$Em = e8; + const r6 = h4.fromAttribute(s5, t7.type); + this[e8] = r6 ?? this._$Ej?.get(e8) ?? r6, this._$Em = null; + } + } + requestUpdate(t6, s5, i6, e8 = false, h4) { + if (void 0 !== t6) { + const r6 = this.constructor; + if (false === e8 && (h4 = this[t6]), i6 ??= r6.getPropertyOptions(t6), !((i6.hasChanged ?? f)(h4, s5) || i6.useDefault && i6.reflect && h4 === this._$Ej?.get(t6) && !this.hasAttribute(r6._$Eu(t6, i6)))) return; + this.C(t6, s5, i6); + } + false === this.isUpdatePending && (this._$ES = this._$EP()); + } + C(t6, s5, { useDefault: i6, reflect: e8, wrapped: h4 }, r6) { + i6 && !(this._$Ej ??= /* @__PURE__ */ new Map()).has(t6) && (this._$Ej.set(t6, r6 ?? s5 ?? this[t6]), true !== h4 || void 0 !== r6) || (this._$AL.has(t6) || (this.hasUpdated || i6 || (s5 = void 0), this._$AL.set(t6, s5)), true === e8 && this._$Em !== t6 && (this._$Eq ??= /* @__PURE__ */ new Set()).add(t6)); + } + async _$EP() { + this.isUpdatePending = true; + try { + await this._$ES; + } catch (t7) { + Promise.reject(t7); + } + const t6 = this.scheduleUpdate(); + return null != t6 && await t6, !this.isUpdatePending; + } + scheduleUpdate() { + return this.performUpdate(); + } + performUpdate() { + if (!this.isUpdatePending) return; + if (!this.hasUpdated) { + if (this.renderRoot ??= this.createRenderRoot(), this._$Ep) { + for (const [t8, s6] of this._$Ep) this[t8] = s6; + this._$Ep = void 0; + } + const t7 = this.constructor.elementProperties; + if (t7.size > 0) for (const [s6, i6] of t7) { + const { wrapped: t8 } = i6, e8 = this[s6]; + true !== t8 || this._$AL.has(s6) || void 0 === e8 || this.C(s6, void 0, i6, e8); + } + } + let t6 = false; + const s5 = this._$AL; + try { + t6 = this.shouldUpdate(s5), t6 ? (this.willUpdate(s5), this._$EO?.forEach((t7) => t7.hostUpdate?.()), this.update(s5)) : this._$EM(); + } catch (s6) { + throw t6 = false, this._$EM(), s6; + } + t6 && this._$AE(s5); + } + willUpdate(t6) { + } + _$AE(t6) { + this._$EO?.forEach((t7) => t7.hostUpdated?.()), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t6)), this.updated(t6); + } + _$EM() { + this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = false; + } + get updateComplete() { + return this.getUpdateComplete(); + } + getUpdateComplete() { + return this._$ES; + } + shouldUpdate(t6) { + return true; + } + update(t6) { + this._$Eq &&= this._$Eq.forEach((t7) => this._$ET(t7, this[t7])), this._$EM(); + } + updated(t6) { + } + firstUpdated(t6) { + } +}; +y.elementStyles = [], y.shadowRootOptions = { mode: "open" }, y[d("elementProperties")] = /* @__PURE__ */ new Map(), y[d("finalized")] = /* @__PURE__ */ new Map(), p?.({ ReactiveElement: y }), (a.reactiveElementVersions ??= []).push("2.1.2"); + +// node_modules/lit-html/lit-html.js +var t2 = globalThis; +var i3 = (t6) => t6; +var s2 = t2.trustedTypes; +var e3 = s2 ? s2.createPolicy("lit-html", { createHTML: (t6) => t6 }) : void 0; +var h2 = "$lit$"; +var o3 = `lit$${Math.random().toFixed(9).slice(2)}$`; +var n3 = "?" + o3; +var r3 = `<${n3}>`; +var l2 = document; +var c3 = () => l2.createComment(""); +var a2 = (t6) => null === t6 || "object" != typeof t6 && "function" != typeof t6; +var u2 = Array.isArray; +var d2 = (t6) => u2(t6) || "function" == typeof t6?.[Symbol.iterator]; +var f2 = "[ \n\f\r]"; +var v = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g; +var _ = /-->/g; +var m = />/g; +var p2 = RegExp(`>|${f2}(?:([^\\s"'>=/]+)(${f2}*=${f2}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`, "g"); +var g = /'/g; +var $ = /"/g; +var y2 = /^(?:script|style|textarea|title)$/i; +var x = (t6) => (i6, ...s5) => ({ _$litType$: t6, strings: i6, values: s5 }); +var b2 = x(1); +var w = x(2); +var T = x(3); +var E = Symbol.for("lit-noChange"); +var A = Symbol.for("lit-nothing"); +var C = /* @__PURE__ */ new WeakMap(); +var P = l2.createTreeWalker(l2, 129); +function V(t6, i6) { + if (!u2(t6) || !t6.hasOwnProperty("raw")) throw Error("invalid template strings array"); + return void 0 !== e3 ? e3.createHTML(i6) : i6; +} +var N = (t6, i6) => { + const s5 = t6.length - 1, e8 = []; + let n7, l3 = 2 === i6 ? "" : 3 === i6 ? "" : "", c5 = v; + for (let i7 = 0; i7 < s5; i7++) { + const s6 = t6[i7]; + let a3, u3, d3 = -1, f4 = 0; + for (; f4 < s6.length && (c5.lastIndex = f4, u3 = c5.exec(s6), null !== u3); ) f4 = c5.lastIndex, c5 === v ? "!--" === u3[1] ? c5 = _ : void 0 !== u3[1] ? c5 = m : void 0 !== u3[2] ? (y2.test(u3[2]) && (n7 = RegExp("" === u3[0] ? (c5 = n7 ?? v, d3 = -1) : void 0 === u3[1] ? d3 = -2 : (d3 = c5.lastIndex - u3[2].length, a3 = u3[1], c5 = void 0 === u3[3] ? p2 : '"' === u3[3] ? $ : g) : c5 === $ || c5 === g ? c5 = p2 : c5 === _ || c5 === m ? c5 = v : (c5 = p2, n7 = void 0); + const x2 = c5 === p2 && t6[i7 + 1].startsWith("/>") ? " " : ""; + l3 += c5 === v ? s6 + r3 : d3 >= 0 ? (e8.push(a3), s6.slice(0, d3) + h2 + s6.slice(d3) + o3 + x2) : s6 + o3 + (-2 === d3 ? i7 : x2); + } + return [V(t6, l3 + (t6[s5] || "") + (2 === i6 ? "" : 3 === i6 ? "" : "")), e8]; +}; +var S2 = class _S { + constructor({ strings: t6, _$litType$: i6 }, e8) { + let r6; + this.parts = []; + let l3 = 0, a3 = 0; + const u3 = t6.length - 1, d3 = this.parts, [f4, v2] = N(t6, i6); + if (this.el = _S.createElement(f4, e8), P.currentNode = this.el.content, 2 === i6 || 3 === i6) { + const t7 = this.el.content.firstChild; + t7.replaceWith(...t7.childNodes); + } + for (; null !== (r6 = P.nextNode()) && d3.length < u3; ) { + if (1 === r6.nodeType) { + if (r6.hasAttributes()) for (const t7 of r6.getAttributeNames()) if (t7.endsWith(h2)) { + const i7 = v2[a3++], s5 = r6.getAttribute(t7).split(o3), e9 = /([.?@])?(.*)/.exec(i7); + d3.push({ type: 1, index: l3, name: e9[2], strings: s5, ctor: "." === e9[1] ? I : "?" === e9[1] ? L : "@" === e9[1] ? z : H }), r6.removeAttribute(t7); + } else t7.startsWith(o3) && (d3.push({ type: 6, index: l3 }), r6.removeAttribute(t7)); + if (y2.test(r6.tagName)) { + const t7 = r6.textContent.split(o3), i7 = t7.length - 1; + if (i7 > 0) { + r6.textContent = s2 ? s2.emptyScript : ""; + for (let s5 = 0; s5 < i7; s5++) r6.append(t7[s5], c3()), P.nextNode(), d3.push({ type: 2, index: ++l3 }); + r6.append(t7[i7], c3()); + } + } + } else if (8 === r6.nodeType) if (r6.data === n3) d3.push({ type: 2, index: l3 }); + else { + let t7 = -1; + for (; -1 !== (t7 = r6.data.indexOf(o3, t7 + 1)); ) d3.push({ type: 7, index: l3 }), t7 += o3.length - 1; + } + l3++; + } + } + static createElement(t6, i6) { + const s5 = l2.createElement("template"); + return s5.innerHTML = t6, s5; + } +}; +function M(t6, i6, s5 = t6, e8) { + if (i6 === E) return i6; + let h4 = void 0 !== e8 ? s5._$Co?.[e8] : s5._$Cl; + const o8 = a2(i6) ? void 0 : i6._$litDirective$; + return h4?.constructor !== o8 && (h4?._$AO?.(false), void 0 === o8 ? h4 = void 0 : (h4 = new o8(t6), h4._$AT(t6, s5, e8)), void 0 !== e8 ? (s5._$Co ??= [])[e8] = h4 : s5._$Cl = h4), void 0 !== h4 && (i6 = M(t6, h4._$AS(t6, i6.values), h4, e8)), i6; +} +var R = class { + constructor(t6, i6) { + this._$AV = [], this._$AN = void 0, this._$AD = t6, this._$AM = i6; + } + get parentNode() { + return this._$AM.parentNode; + } + get _$AU() { + return this._$AM._$AU; + } + u(t6) { + const { el: { content: i6 }, parts: s5 } = this._$AD, e8 = (t6?.creationScope ?? l2).importNode(i6, true); + P.currentNode = e8; + let h4 = P.nextNode(), o8 = 0, n7 = 0, r6 = s5[0]; + for (; void 0 !== r6; ) { + if (o8 === r6.index) { + let i7; + 2 === r6.type ? i7 = new k(h4, h4.nextSibling, this, t6) : 1 === r6.type ? i7 = new r6.ctor(h4, r6.name, r6.strings, this, t6) : 6 === r6.type && (i7 = new Z(h4, this, t6)), this._$AV.push(i7), r6 = s5[++n7]; + } + o8 !== r6?.index && (h4 = P.nextNode(), o8++); + } + return P.currentNode = l2, e8; + } + p(t6) { + let i6 = 0; + for (const s5 of this._$AV) void 0 !== s5 && (void 0 !== s5.strings ? (s5._$AI(t6, s5, i6), i6 += s5.strings.length - 2) : s5._$AI(t6[i6])), i6++; + } +}; +var k = class _k { + get _$AU() { + return this._$AM?._$AU ?? this._$Cv; + } + constructor(t6, i6, s5, e8) { + this.type = 2, this._$AH = A, this._$AN = void 0, this._$AA = t6, this._$AB = i6, this._$AM = s5, this.options = e8, this._$Cv = e8?.isConnected ?? true; + } + get parentNode() { + let t6 = this._$AA.parentNode; + const i6 = this._$AM; + return void 0 !== i6 && 11 === t6?.nodeType && (t6 = i6.parentNode), t6; + } + get startNode() { + return this._$AA; + } + get endNode() { + return this._$AB; + } + _$AI(t6, i6 = this) { + t6 = M(this, t6, i6), a2(t6) ? t6 === A || null == t6 || "" === t6 ? (this._$AH !== A && this._$AR(), this._$AH = A) : t6 !== this._$AH && t6 !== E && this._(t6) : void 0 !== t6._$litType$ ? this.$(t6) : void 0 !== t6.nodeType ? this.T(t6) : d2(t6) ? this.k(t6) : this._(t6); + } + O(t6) { + return this._$AA.parentNode.insertBefore(t6, this._$AB); + } + T(t6) { + this._$AH !== t6 && (this._$AR(), this._$AH = this.O(t6)); + } + _(t6) { + this._$AH !== A && a2(this._$AH) ? this._$AA.nextSibling.data = t6 : this.T(l2.createTextNode(t6)), this._$AH = t6; + } + $(t6) { + const { values: i6, _$litType$: s5 } = t6, e8 = "number" == typeof s5 ? this._$AC(t6) : (void 0 === s5.el && (s5.el = S2.createElement(V(s5.h, s5.h[0]), this.options)), s5); + if (this._$AH?._$AD === e8) this._$AH.p(i6); + else { + const t7 = new R(e8, this), s6 = t7.u(this.options); + t7.p(i6), this.T(s6), this._$AH = t7; + } + } + _$AC(t6) { + let i6 = C.get(t6.strings); + return void 0 === i6 && C.set(t6.strings, i6 = new S2(t6)), i6; + } + k(t6) { + u2(this._$AH) || (this._$AH = [], this._$AR()); + const i6 = this._$AH; + let s5, e8 = 0; + for (const h4 of t6) e8 === i6.length ? i6.push(s5 = new _k(this.O(c3()), this.O(c3()), this, this.options)) : s5 = i6[e8], s5._$AI(h4), e8++; + e8 < i6.length && (this._$AR(s5 && s5._$AB.nextSibling, e8), i6.length = e8); + } + _$AR(t6 = this._$AA.nextSibling, s5) { + for (this._$AP?.(false, true, s5); t6 !== this._$AB; ) { + const s6 = i3(t6).nextSibling; + i3(t6).remove(), t6 = s6; + } + } + setConnected(t6) { + void 0 === this._$AM && (this._$Cv = t6, this._$AP?.(t6)); + } +}; +var H = class { + get tagName() { + return this.element.tagName; + } + get _$AU() { + return this._$AM._$AU; + } + constructor(t6, i6, s5, e8, h4) { + this.type = 1, this._$AH = A, this._$AN = void 0, this.element = t6, this.name = i6, this._$AM = e8, this.options = h4, s5.length > 2 || "" !== s5[0] || "" !== s5[1] ? (this._$AH = Array(s5.length - 1).fill(new String()), this.strings = s5) : this._$AH = A; + } + _$AI(t6, i6 = this, s5, e8) { + const h4 = this.strings; + let o8 = false; + if (void 0 === h4) t6 = M(this, t6, i6, 0), o8 = !a2(t6) || t6 !== this._$AH && t6 !== E, o8 && (this._$AH = t6); + else { + const e9 = t6; + let n7, r6; + for (t6 = h4[0], n7 = 0; n7 < h4.length - 1; n7++) r6 = M(this, e9[s5 + n7], i6, n7), r6 === E && (r6 = this._$AH[n7]), o8 ||= !a2(r6) || r6 !== this._$AH[n7], r6 === A ? t6 = A : t6 !== A && (t6 += (r6 ?? "") + h4[n7 + 1]), this._$AH[n7] = r6; + } + o8 && !e8 && this.j(t6); + } + j(t6) { + t6 === A ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t6 ?? ""); + } +}; +var I = class extends H { + constructor() { + super(...arguments), this.type = 3; + } + j(t6) { + this.element[this.name] = t6 === A ? void 0 : t6; + } +}; +var L = class extends H { + constructor() { + super(...arguments), this.type = 4; + } + j(t6) { + this.element.toggleAttribute(this.name, !!t6 && t6 !== A); + } +}; +var z = class extends H { + constructor(t6, i6, s5, e8, h4) { + super(t6, i6, s5, e8, h4), this.type = 5; + } + _$AI(t6, i6 = this) { + if ((t6 = M(this, t6, i6, 0) ?? A) === E) return; + const s5 = this._$AH, e8 = t6 === A && s5 !== A || t6.capture !== s5.capture || t6.once !== s5.once || t6.passive !== s5.passive, h4 = t6 !== A && (s5 === A || e8); + e8 && this.element.removeEventListener(this.name, this, s5), h4 && this.element.addEventListener(this.name, this, t6), this._$AH = t6; + } + handleEvent(t6) { + "function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t6) : this._$AH.handleEvent(t6); + } +}; +var Z = class { + constructor(t6, i6, s5) { + this.element = t6, this.type = 6, this._$AN = void 0, this._$AM = i6, this.options = s5; + } + get _$AU() { + return this._$AM._$AU; + } + _$AI(t6) { + M(this, t6); + } +}; +var j = { M: h2, P: o3, A: n3, C: 1, L: N, R, D: d2, V: M, I: k, H, N: L, U: z, B: I, F: Z }; +var B = t2.litHtmlPolyfillSupport; +B?.(S2, k), (t2.litHtmlVersions ??= []).push("3.3.2"); +var D = (t6, i6, s5) => { + const e8 = s5?.renderBefore ?? i6; + let h4 = e8._$litPart$; + if (void 0 === h4) { + const t7 = s5?.renderBefore ?? null; + e8._$litPart$ = h4 = new k(i6.insertBefore(c3(), t7), t7, void 0, s5 ?? {}); + } + return h4._$AI(t6), h4; +}; + +// node_modules/lit-element/lit-element.js +var s3 = globalThis; +var i4 = class extends y { + constructor() { + super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0; + } + createRenderRoot() { + const t6 = super.createRenderRoot(); + return this.renderOptions.renderBefore ??= t6.firstChild, t6; + } + update(t6) { + const r6 = this.render(); + this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t6), this._$Do = D(r6, this.renderRoot, this.renderOptions); + } + connectedCallback() { + super.connectedCallback(), this._$Do?.setConnected(true); + } + disconnectedCallback() { + super.disconnectedCallback(), this._$Do?.setConnected(false); + } + render() { + return E; + } +}; +i4._$litElement$ = true, i4["finalized"] = true, s3.litElementHydrateSupport?.({ LitElement: i4 }); +var o4 = s3.litElementPolyfillSupport; +o4?.({ LitElement: i4 }); +(s3.litElementVersions ??= []).push("4.2.2"); + +// node_modules/lit-html/directive-helpers.js +var { I: t3 } = j; +var r4 = (o8) => void 0 === o8.strings; + +// node_modules/lit-html/directive.js +var t4 = { ATTRIBUTE: 1, CHILD: 2, PROPERTY: 3, BOOLEAN_ATTRIBUTE: 4, EVENT: 5, ELEMENT: 6 }; +var e4 = (t6) => (...e8) => ({ _$litDirective$: t6, values: e8 }); +var i5 = class { + constructor(t6) { + } + get _$AU() { + return this._$AM._$AU; + } + _$AT(t6, e8, i6) { + this._$Ct = t6, this._$AM = e8, this._$Ci = i6; + } + _$AS(t6, e8) { + return this.update(t6, e8); + } + update(t6, e8) { + return this.render(...e8); + } +}; + +// node_modules/lit-html/async-directive.js +var s4 = (i6, t6) => { + const e8 = i6._$AN; + if (void 0 === e8) return false; + for (const i7 of e8) i7._$AO?.(t6, false), s4(i7, t6); + return true; +}; +var o5 = (i6) => { + let t6, e8; + do { + if (void 0 === (t6 = i6._$AM)) break; + e8 = t6._$AN, e8.delete(i6), i6 = t6; + } while (0 === e8?.size); +}; +var r5 = (i6) => { + for (let t6; t6 = i6._$AM; i6 = t6) { + let e8 = t6._$AN; + if (void 0 === e8) t6._$AN = e8 = /* @__PURE__ */ new Set(); + else if (e8.has(i6)) break; + e8.add(i6), c4(t6); + } +}; +function h3(i6) { + void 0 !== this._$AN ? (o5(this), this._$AM = i6, r5(this)) : this._$AM = i6; +} +function n4(i6, t6 = false, e8 = 0) { + const r6 = this._$AH, h4 = this._$AN; + if (void 0 !== h4 && 0 !== h4.size) if (t6) if (Array.isArray(r6)) for (let i7 = e8; i7 < r6.length; i7++) s4(r6[i7], false), o5(r6[i7]); + else null != r6 && (s4(r6, false), o5(r6)); + else s4(this, i6); +} +var c4 = (i6) => { + i6.type == t4.CHILD && (i6._$AP ??= n4, i6._$AQ ??= h3); +}; +var f3 = class extends i5 { + constructor() { + super(...arguments), this._$AN = void 0; + } + _$AT(i6, t6, e8) { + super._$AT(i6, t6, e8), r5(this), this.isConnected = i6._$AU; + } + _$AO(i6, t6 = true) { + i6 !== this.isConnected && (this.isConnected = i6, i6 ? this.reconnected?.() : this.disconnected?.()), t6 && (s4(this, i6), o5(this)); + } + setValue(t6) { + if (r4(this._$Ct)) this._$Ct._$AI(t6, this); + else { + const i6 = [...this._$Ct._$AH]; + i6[this._$Ci] = t6, this._$Ct._$AI(i6, this, 0); + } + } + disconnected() { + } + reconnected() { + } +}; + +// node_modules/lit-html/directives/ref.js +var o6 = /* @__PURE__ */ new WeakMap(); +var n5 = e4(class extends f3 { + render(i6) { + return A; + } + update(i6, [s5]) { + const e8 = s5 !== this.G; + return e8 && void 0 !== this.G && this.rt(void 0), (e8 || this.lt !== this.ct) && (this.G = s5, this.ht = i6.options?.host, this.rt(this.ct = i6.element)), A; + } + rt(t6) { + if (this.isConnected || (t6 = void 0), "function" == typeof this.G) { + const i6 = this.ht ?? globalThis; + let s5 = o6.get(i6); + void 0 === s5 && (s5 = /* @__PURE__ */ new WeakMap(), o6.set(i6, s5)), void 0 !== s5.get(this.G) && this.G.call(this.ht, void 0), s5.set(this.G, t6), void 0 !== t6 && this.G.call(this.ht, t6); + } else this.G.value = t6; + } + get lt() { + return "function" == typeof this.G ? o6.get(this.ht ?? globalThis)?.get(this.G) : this.G?.value; + } + disconnected() { + this.lt === this.ct && this.rt(void 0); + } + reconnected() { + this.rt(this.ct); + } +}); + +// ../mini-lit/dist/mini.js +function fc(renderFn) { + return (props) => renderFn(props || {}); +} + +// node_modules/lit-html/directives/unsafe-html.js +var e6 = class extends i5 { + constructor(i6) { + if (super(i6), this.it = A, i6.type !== t4.CHILD) throw Error(this.constructor.directiveName + "() can only be used in child bindings"); + } + render(r6) { + if (r6 === A || null == r6) return this._t = void 0, this.it = r6; + if (r6 === E) return r6; + if ("string" != typeof r6) throw Error(this.constructor.directiveName + "() called with a non-string value"); + if (r6 === this.it) return this._t; + this.it = r6; + const s5 = [r6]; + return s5.raw = s5, this._t = { _$litType$: this.constructor.resultType, strings: s5, values: [] }; + } +}; +e6.directiveName = "unsafeHTML", e6.resultType = 1; +var o7 = e4(e6); + +// ../mini-lit/node_modules/lucide/dist/esm/defaultAttributes.js +var defaultAttributes = { + xmlns: "http://www.w3.org/2000/svg", + width: 24, + height: 24, + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + "stroke-width": 2, + "stroke-linecap": "round", + "stroke-linejoin": "round" +}; + +// ../mini-lit/node_modules/lucide/dist/esm/createElement.js +var createSVGElement = ([tag, attrs, children]) => { + const element = document.createElementNS("http://www.w3.org/2000/svg", tag); + Object.keys(attrs).forEach((name) => { + element.setAttribute(name, String(attrs[name])); + }); + if (children?.length) { + children.forEach((child) => { + const childElement = createSVGElement(child); + element.appendChild(childElement); + }); + } + return element; +}; +var createElement = (iconNode, customAttrs = {}) => { + const tag = "svg"; + const attrs = { + ...defaultAttributes, + ...customAttrs + }; + return createSVGElement([tag, attrs, iconNode]); +}; + +// ../mini-lit/dist/icons.js +var sizeClasses = { + xs: "w-3 h-3", + sm: "w-4 h-4", + md: "w-5 h-5", + lg: "w-6 h-6", + xl: "w-8 h-8" +}; +function icon(lucideIcon, size = "md", className) { + return b2`${o7(iconDOM(lucideIcon, size, className).outerHTML)}`; +} +function iconDOM(lucideIcon, size = "md", className) { + const element = createElement(lucideIcon, { + class: sizeClasses[size] + (className ? " " + className : "") + }); + return element; +} + +// ../mini-lit/dist/Button.js +var Button = fc(({ variant = "default", size = "md", disabled = false, type = "button", loading = false, onClick, title, className = "", children }) => { + const sizeClasses2 = { + sm: "h-8 rounded-md px-3 text-xs", + md: "h-9 rounded-md px-4 text-sm", + lg: "h-10 rounded-md px-8 text-sm", + icon: "size-8 rounded-md" + }; + const variantClasses = { + default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", + destructive: "bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90", + outline: "border border-input bg-background text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground", + secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", + ghost: "text-foreground hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline" + }; + const baseClasses = "inline-flex items-center justify-center whitespace-nowrap text-sm font-medium transition-all cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"; + const gapClass = size === "icon" ? "" : "gap-2"; + const paddingAdjustClass = size === "icon" ? "" : "has-[>svg]:px-2.5"; + const variantClass = variantClasses[variant] || variantClasses.default; + const handleClick = (e8) => { + if (disabled || loading) { + e8.preventDefault(); + e8.stopPropagation(); + return; + } + onClick?.(e8); + }; + return b2` + + `; +}); + +// node_modules/lucide/dist/esm/icons/arrow-left.js +var ArrowLeft = [ + ["path", { d: "m12 19-7-7 7-7" }], + ["path", { d: "M19 12H5" }] +]; + +// node_modules/lucide/dist/esm/icons/download.js +var Download = [ + ["path", { d: "M12 15V3" }], + ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }], + ["path", { d: "m7 10 5 5 5-5" }] +]; + +// node_modules/@lit/reactive-element/decorators/custom-element.js +var t5 = (t6) => (e8, o8) => { + void 0 !== o8 ? o8.addInitializer(() => { + customElements.define(t6, e8); + }) : customElements.define(t6, e8); +}; + +// node_modules/three/build/three.core.js +var REVISION = "180"; +var CullFaceNone = 0; +var CullFaceBack = 1; +var CullFaceFront = 2; +var PCFShadowMap = 1; +var PCFSoftShadowMap = 2; +var VSMShadowMap = 3; +var FrontSide = 0; +var BackSide = 1; +var DoubleSide = 2; +var NoBlending = 0; +var NormalBlending = 1; +var AdditiveBlending = 2; +var SubtractiveBlending = 3; +var MultiplyBlending = 4; +var CustomBlending = 5; +var AddEquation = 100; +var SubtractEquation = 101; +var ReverseSubtractEquation = 102; +var MinEquation = 103; +var MaxEquation = 104; +var ZeroFactor = 200; +var OneFactor = 201; +var SrcColorFactor = 202; +var OneMinusSrcColorFactor = 203; +var SrcAlphaFactor = 204; +var OneMinusSrcAlphaFactor = 205; +var DstAlphaFactor = 206; +var OneMinusDstAlphaFactor = 207; +var DstColorFactor = 208; +var OneMinusDstColorFactor = 209; +var SrcAlphaSaturateFactor = 210; +var ConstantColorFactor = 211; +var OneMinusConstantColorFactor = 212; +var ConstantAlphaFactor = 213; +var OneMinusConstantAlphaFactor = 214; +var NeverDepth = 0; +var AlwaysDepth = 1; +var LessDepth = 2; +var LessEqualDepth = 3; +var EqualDepth = 4; +var GreaterEqualDepth = 5; +var GreaterDepth = 6; +var NotEqualDepth = 7; +var MultiplyOperation = 0; +var MixOperation = 1; +var AddOperation = 2; +var NoToneMapping = 0; +var LinearToneMapping = 1; +var ReinhardToneMapping = 2; +var CineonToneMapping = 3; +var ACESFilmicToneMapping = 4; +var CustomToneMapping = 5; +var AgXToneMapping = 6; +var NeutralToneMapping = 7; +var UVMapping = 300; +var CubeReflectionMapping = 301; +var CubeRefractionMapping = 302; +var EquirectangularReflectionMapping = 303; +var EquirectangularRefractionMapping = 304; +var CubeUVReflectionMapping = 306; +var RepeatWrapping = 1e3; +var ClampToEdgeWrapping = 1001; +var MirroredRepeatWrapping = 1002; +var NearestFilter = 1003; +var NearestMipmapNearestFilter = 1004; +var NearestMipmapLinearFilter = 1005; +var LinearFilter = 1006; +var LinearMipmapNearestFilter = 1007; +var LinearMipmapLinearFilter = 1008; +var UnsignedByteType = 1009; +var ByteType = 1010; +var ShortType = 1011; +var UnsignedShortType = 1012; +var IntType = 1013; +var UnsignedIntType = 1014; +var FloatType = 1015; +var HalfFloatType = 1016; +var UnsignedShort4444Type = 1017; +var UnsignedShort5551Type = 1018; +var UnsignedInt248Type = 1020; +var UnsignedInt5999Type = 35902; +var UnsignedInt101111Type = 35899; +var AlphaFormat = 1021; +var RGBFormat = 1022; +var RGBAFormat = 1023; +var DepthFormat = 1026; +var DepthStencilFormat = 1027; +var RedFormat = 1028; +var RedIntegerFormat = 1029; +var RGFormat = 1030; +var RGIntegerFormat = 1031; +var RGBAIntegerFormat = 1033; +var RGB_S3TC_DXT1_Format = 33776; +var RGBA_S3TC_DXT1_Format = 33777; +var RGBA_S3TC_DXT3_Format = 33778; +var RGBA_S3TC_DXT5_Format = 33779; +var RGB_PVRTC_4BPPV1_Format = 35840; +var RGB_PVRTC_2BPPV1_Format = 35841; +var RGBA_PVRTC_4BPPV1_Format = 35842; +var RGBA_PVRTC_2BPPV1_Format = 35843; +var RGB_ETC1_Format = 36196; +var RGB_ETC2_Format = 37492; +var RGBA_ETC2_EAC_Format = 37496; +var RGBA_ASTC_4x4_Format = 37808; +var RGBA_ASTC_5x4_Format = 37809; +var RGBA_ASTC_5x5_Format = 37810; +var RGBA_ASTC_6x5_Format = 37811; +var RGBA_ASTC_6x6_Format = 37812; +var RGBA_ASTC_8x5_Format = 37813; +var RGBA_ASTC_8x6_Format = 37814; +var RGBA_ASTC_8x8_Format = 37815; +var RGBA_ASTC_10x5_Format = 37816; +var RGBA_ASTC_10x6_Format = 37817; +var RGBA_ASTC_10x8_Format = 37818; +var RGBA_ASTC_10x10_Format = 37819; +var RGBA_ASTC_12x10_Format = 37820; +var RGBA_ASTC_12x12_Format = 37821; +var RGBA_BPTC_Format = 36492; +var RGB_BPTC_SIGNED_Format = 36494; +var RGB_BPTC_UNSIGNED_Format = 36495; +var RED_RGTC1_Format = 36283; +var SIGNED_RED_RGTC1_Format = 36284; +var RED_GREEN_RGTC2_Format = 36285; +var SIGNED_RED_GREEN_RGTC2_Format = 36286; +var InterpolateDiscrete = 2300; +var InterpolateLinear = 2301; +var InterpolateSmooth = 2302; +var ZeroCurvatureEnding = 2400; +var ZeroSlopeEnding = 2401; +var WrapAroundEnding = 2402; +var BasicDepthPacking = 3200; +var RGBADepthPacking = 3201; +var TangentSpaceNormalMap = 0; +var ObjectSpaceNormalMap = 1; +var NoColorSpace = ""; +var SRGBColorSpace = "srgb"; +var LinearSRGBColorSpace = "srgb-linear"; +var LinearTransfer = "linear"; +var SRGBTransfer = "srgb"; +var KeepStencilOp = 7680; +var AlwaysStencilFunc = 519; +var NeverCompare = 512; +var LessCompare = 513; +var EqualCompare = 514; +var LessEqualCompare = 515; +var GreaterCompare = 516; +var NotEqualCompare = 517; +var GreaterEqualCompare = 518; +var AlwaysCompare = 519; +var StaticDrawUsage = 35044; +var GLSL3 = "300 es"; +var WebGLCoordinateSystem = 2e3; +var WebGPUCoordinateSystem = 2001; +var EventDispatcher = class { + /** + * Adds the given event listener to the given event type. + * + * @param {string} type - The type of event to listen to. + * @param {Function} listener - The function that gets called when the event is fired. + */ + addEventListener(type, listener) { + if (this._listeners === void 0) this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === void 0) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + /** + * Returns `true` if the given event listener has been added to the given event type. + * + * @param {string} type - The type of event. + * @param {Function} listener - The listener to check. + * @return {boolean} Whether the given event listener has been added to the given event type. + */ + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === void 0) return false; + return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1; + } + /** + * Removes the given event listener from the given event type. + * + * @param {string} type - The type of event. + * @param {Function} listener - The listener to remove. + */ + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === void 0) return; + const listenerArray = listeners[type]; + if (listenerArray !== void 0) { + const index = listenerArray.indexOf(listener); + if (index !== -1) { + listenerArray.splice(index, 1); + } + } + } + /** + * Dispatches an event object. + * + * @param {Object} event - The event that gets fired. + */ + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === void 0) return; + const listenerArray = listeners[event.type]; + if (listenerArray !== void 0) { + event.target = this; + const array = listenerArray.slice(0); + for (let i6 = 0, l3 = array.length; i6 < l3; i6++) { + array[i6].call(this, event); + } + event.target = null; + } + } +}; +var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; +var DEG2RAD = Math.PI / 180; +var RAD2DEG = 180 / Math.PI; +function generateUUID() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d22 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d22 & 63 | 128] + _lut[d22 >> 8 & 255] + "-" + _lut[d22 >> 16 & 255] + _lut[d22 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; + return uuid.toLowerCase(); +} +function clamp(value, min, max) { + return Math.max(min, Math.min(max, value)); +} +function euclideanModulo(n7, m2) { + return (n7 % m2 + m2) % m2; +} +function lerp(x2, y3, t6) { + return (1 - t6) * x2 + t6 * y3; +} +function denormalize(value, array) { + switch (array.constructor) { + case Float32Array: + return value; + case Uint32Array: + return value / 4294967295; + case Uint16Array: + return value / 65535; + case Uint8Array: + return value / 255; + case Int32Array: + return Math.max(value / 2147483647, -1); + case Int16Array: + return Math.max(value / 32767, -1); + case Int8Array: + return Math.max(value / 127, -1); + default: + throw new Error("Invalid component type."); + } +} +function normalize(value, array) { + switch (array.constructor) { + case Float32Array: + return value; + case Uint32Array: + return Math.round(value * 4294967295); + case Uint16Array: + return Math.round(value * 65535); + case Uint8Array: + return Math.round(value * 255); + case Int32Array: + return Math.round(value * 2147483647); + case Int16Array: + return Math.round(value * 32767); + case Int8Array: + return Math.round(value * 127); + default: + throw new Error("Invalid component type."); + } +} +var Vector2 = class _Vector2 { + /** + * Constructs a new 2D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + */ + constructor(x2 = 0, y3 = 0) { + _Vector2.prototype.isVector2 = true; + this.x = x2; + this.y = y3; + } + /** + * Alias for {@link Vector2#x}. + * + * @type {number} + */ + get width() { + return this.x; + } + set width(value) { + this.x = value; + } + /** + * Alias for {@link Vector2#y}. + * + * @type {number} + */ + get height() { + return this.y; + } + set height(value) { + this.y = value; + } + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @return {Vector2} A reference to this vector. + */ + set(x2, y3) { + this.x = x2; + this.y = y3; + return this; + } + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector2} A reference to this vector. + */ + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector2} A reference to this vector. + */ + setX(x2) { + this.x = x2; + return this; + } + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector2} A reference to this vector. + */ + setY(y3) { + this.y = y3; + return this; + } + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y. + * @param {number} value - The value to set. + * @return {Vector2} A reference to this vector. + */ + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y. + * @return {number} A vector component value. + */ + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index); + } + } + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector2} A clone of this instance. + */ + clone() { + return new this.constructor(this.x, this.y); + } + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector2} v - The vector to copy. + * @return {Vector2} A reference to this vector. + */ + copy(v2) { + this.x = v2.x; + this.y = v2.y; + return this; + } + /** + * Adds the given vector to this instance. + * + * @param {Vector2} v - The vector to add. + * @return {Vector2} A reference to this vector. + */ + add(v2) { + this.x += v2.x; + this.y += v2.y; + return this; + } + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector2} A reference to this vector. + */ + addScalar(s5) { + this.x += s5; + this.y += s5; + return this; + } + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector2} a - The first vector. + * @param {Vector2} b - The second vector. + * @return {Vector2} A reference to this vector. + */ + addVectors(a3, b3) { + this.x = a3.x + b3.x; + this.y = a3.y + b3.y; + return this; + } + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector2} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector2} A reference to this vector. + */ + addScaledVector(v2, s5) { + this.x += v2.x * s5; + this.y += v2.y * s5; + return this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector2} v - The vector to subtract. + * @return {Vector2} A reference to this vector. + */ + sub(v2) { + this.x -= v2.x; + this.y -= v2.y; + return this; + } + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector2} A reference to this vector. + */ + subScalar(s5) { + this.x -= s5; + this.y -= s5; + return this; + } + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector2} a - The first vector. + * @param {Vector2} b - The second vector. + * @return {Vector2} A reference to this vector. + */ + subVectors(a3, b3) { + this.x = a3.x - b3.x; + this.y = a3.y - b3.y; + return this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector2} v - The vector to multiply. + * @return {Vector2} A reference to this vector. + */ + multiply(v2) { + this.x *= v2.x; + this.y *= v2.y; + return this; + } + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector2} A reference to this vector. + */ + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + /** + * Divides this instance by the given vector. + * + * @param {Vector2} v - The vector to divide. + * @return {Vector2} A reference to this vector. + */ + divide(v2) { + this.x /= v2.x; + this.y /= v2.y; + return this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector2} A reference to this vector. + */ + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + /** + * Multiplies this vector (with an implicit 1 as the 3rd component) by + * the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to apply. + * @return {Vector2} A reference to this vector. + */ + applyMatrix3(m2) { + const x2 = this.x, y3 = this.y; + const e8 = m2.elements; + this.x = e8[0] * x2 + e8[3] * y3 + e8[6]; + this.y = e8[1] * x2 + e8[4] * y3 + e8[7]; + return this; + } + /** + * If this vector's x or y value is greater than the given vector's x or y + * value, replace that value with the corresponding min value. + * + * @param {Vector2} v - The vector. + * @return {Vector2} A reference to this vector. + */ + min(v2) { + this.x = Math.min(this.x, v2.x); + this.y = Math.min(this.y, v2.y); + return this; + } + /** + * If this vector's x or y value is less than the given vector's x or y + * value, replace that value with the corresponding max value. + * + * @param {Vector2} v - The vector. + * @return {Vector2} A reference to this vector. + */ + max(v2) { + this.x = Math.max(this.x, v2.x); + this.y = Math.max(this.y, v2.y); + return this; + } + /** + * If this vector's x or y value is greater than the max vector's x or y + * value, it is replaced by the corresponding value. + * If this vector's x or y value is less than the min vector's x or y value, + * it is replaced by the corresponding value. + * + * @param {Vector2} min - The minimum x and y values. + * @param {Vector2} max - The maximum x and y values in the desired range. + * @return {Vector2} A reference to this vector. + */ + clamp(min, max) { + this.x = clamp(this.x, min.x, max.x); + this.y = clamp(this.y, min.y, max.y); + return this; + } + /** + * If this vector's x or y values are greater than the max value, they are + * replaced by the max value. + * If this vector's x or y values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector2} A reference to this vector. + */ + clampScalar(minVal, maxVal) { + this.x = clamp(this.x, minVal, maxVal); + this.y = clamp(this.y, minVal, maxVal); + return this; + } + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector2} A reference to this vector. + */ + clampLength(min, max) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max)); + } + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector2} A reference to this vector. + */ + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector2} A reference to this vector. + */ + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector2} A reference to this vector. + */ + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector2} A reference to this vector. + */ + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + /** + * Inverts this vector - i.e. sets x = -x and y = -y. + * + * @return {Vector2} A reference to this vector. + */ + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector2} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v2) { + return this.x * v2.x + this.y * v2.y; + } + /** + * Calculates the cross product of the given vector with this instance. + * + * @param {Vector2} v - The vector to compute the cross product with. + * @return {number} The result of the cross product. + */ + cross(v2) { + return this.x * v2.y - this.y * v2.x; + } + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + return this.x * this.x + this.y * this.y; + } + /** + * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y). + * + * @return {number} The length of this vector. + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector2} A reference to this vector. + */ + normalize() { + return this.divideScalar(this.length() || 1); + } + /** + * Computes the angle in radians of this vector with respect to the positive x-axis. + * + * @return {number} The angle in radians. + */ + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + /** + * Returns the angle between the given vector and this instance in radians. + * + * @param {Vector2} v - The vector to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo(v2) { + const denominator = Math.sqrt(this.lengthSq() * v2.lengthSq()); + if (denominator === 0) return Math.PI / 2; + const theta = this.dot(v2) / denominator; + return Math.acos(clamp(theta, -1, 1)); + } + /** + * Computes the distance from the given vector to this instance. + * + * @param {Vector2} v - The vector to compute the distance to. + * @return {number} The distance. + */ + distanceTo(v2) { + return Math.sqrt(this.distanceToSquared(v2)); + } + /** + * Computes the squared distance from the given vector to this instance. + * If you are just comparing the distance with another distance, you should compare + * the distance squared instead as it is slightly more efficient to calculate. + * + * @param {Vector2} v - The vector to compute the squared distance to. + * @return {number} The squared distance. + */ + distanceToSquared(v2) { + const dx = this.x - v2.x, dy = this.y - v2.y; + return dx * dx + dy * dy; + } + /** + * Computes the Manhattan distance from the given vector to this instance. + * + * @param {Vector2} v - The vector to compute the Manhattan distance to. + * @return {number} The Manhattan distance. + */ + manhattanDistanceTo(v2) { + return Math.abs(this.x - v2.x) + Math.abs(this.y - v2.y); + } + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector2} A reference to this vector. + */ + setLength(length) { + return this.normalize().multiplyScalar(length); + } + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector2} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector2} A reference to this vector. + */ + lerp(v2, alpha) { + this.x += (v2.x - this.x) * alpha; + this.y += (v2.y - this.y) * alpha; + return this; + } + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector2} v1 - The first vector. + * @param {Vector2} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector2} A reference to this vector. + */ + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector2} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals(v2) { + return v2.x === this.x && v2.y === this.y; + } + /** + * Sets this vector's x value to be `array[ offset ]` and y + * value to be `array[ offset + 1 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector2} A reference to this vector. + */ + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector2} A reference to this vector. + */ + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + return this; + } + /** + * Rotates this vector around the given center by the given angle. + * + * @param {Vector2} center - The point around which to rotate. + * @param {number} angle - The angle to rotate, in radians. + * @return {Vector2} A reference to this vector. + */ + rotateAround(center, angle) { + const c5 = Math.cos(angle), s5 = Math.sin(angle); + const x2 = this.x - center.x; + const y3 = this.y - center.y; + this.x = x2 * c5 - y3 * s5 + center.x; + this.y = x2 * s5 + y3 * c5 + center.y; + return this; + } + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector2} A reference to this vector. + */ + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } +}; +var Quaternion = class { + /** + * Constructs a new quaternion. + * + * @param {number} [x=0] - The x value of this quaternion. + * @param {number} [y=0] - The y value of this quaternion. + * @param {number} [z=0] - The z value of this quaternion. + * @param {number} [w=1] - The w value of this quaternion. + */ + constructor(x2 = 0, y3 = 0, z2 = 0, w2 = 1) { + this.isQuaternion = true; + this._x = x2; + this._y = y3; + this._z = z2; + this._w = w2; + } + /** + * Interpolates between two quaternions via SLERP. This implementation assumes the + * quaternion data are managed in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @param {number} t - The interpolation factor in the range `[0,1]`. + * @see {@link Quaternion#slerp} + */ + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t6) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t6 === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t6 === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s5 = 1 - t6; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s5 = Math.sin(s5 * len) / sin; + t6 = Math.sin(t6 * len) / sin; + } + const tDir = t6 * dir; + x0 = x0 * s5 + x1 * tDir; + y0 = y0 * s5 + y1 * tDir; + z0 = z0 * s5 + z1 * tDir; + w0 = w0 * s5 + w1 * tDir; + if (s5 === 1 - t6) { + const f4 = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f4; + y0 *= f4; + z0 *= f4; + w0 *= f4; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + /** + * Multiplies two quaternions. This implementation assumes the quaternion data are managed + * in flat arrays. + * + * @param {Array} dst - The destination array. + * @param {number} dstOffset - An offset into the destination array. + * @param {Array} src0 - The source array of the first quaternion. + * @param {number} srcOffset0 - An offset into the first source array. + * @param {Array} src1 - The source array of the second quaternion. + * @param {number} srcOffset1 - An offset into the second source array. + * @return {Array} The destination array. + * @see {@link Quaternion#multiplyQuaternions}. + */ + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + /** + * The x value of this quaternion. + * + * @type {number} + * @default 0 + */ + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._onChangeCallback(); + } + /** + * The y value of this quaternion. + * + * @type {number} + * @default 0 + */ + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._onChangeCallback(); + } + /** + * The z value of this quaternion. + * + * @type {number} + * @default 0 + */ + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._onChangeCallback(); + } + /** + * The w value of this quaternion. + * + * @type {number} + * @default 1 + */ + get w() { + return this._w; + } + set w(value) { + this._w = value; + this._onChangeCallback(); + } + /** + * Sets the quaternion components. + * + * @param {number} x - The x value of this quaternion. + * @param {number} y - The y value of this quaternion. + * @param {number} z - The z value of this quaternion. + * @param {number} w - The w value of this quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + set(x2, y3, z2, w2) { + this._x = x2; + this._y = y3; + this._z = z2; + this._w = w2; + this._onChangeCallback(); + return this; + } + /** + * Returns a new quaternion with copied values from this instance. + * + * @return {Quaternion} A clone of this instance. + */ + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + /** + * Copies the values of the given quaternion to this instance. + * + * @param {Quaternion} quaternion - The quaternion to copy. + * @return {Quaternion} A reference to this quaternion. + */ + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion from the rotation specified by the given + * Euler angles. + * + * @param {Euler} euler - The Euler angles. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Quaternion} A reference to this quaternion. + */ + setFromEuler(euler, update = true) { + const x2 = euler._x, y3 = euler._y, z2 = euler._z, order = euler._order; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x2 / 2); + const c22 = cos(y3 / 2); + const c32 = cos(z2 / 2); + const s1 = sin(x2 / 2); + const s22 = sin(y3 / 2); + const s32 = sin(z2 / 2); + switch (order) { + case "XYZ": + this._x = s1 * c22 * c32 + c1 * s22 * s32; + this._y = c1 * s22 * c32 - s1 * c22 * s32; + this._z = c1 * c22 * s32 + s1 * s22 * c32; + this._w = c1 * c22 * c32 - s1 * s22 * s32; + break; + case "YXZ": + this._x = s1 * c22 * c32 + c1 * s22 * s32; + this._y = c1 * s22 * c32 - s1 * c22 * s32; + this._z = c1 * c22 * s32 - s1 * s22 * c32; + this._w = c1 * c22 * c32 + s1 * s22 * s32; + break; + case "ZXY": + this._x = s1 * c22 * c32 - c1 * s22 * s32; + this._y = c1 * s22 * c32 + s1 * c22 * s32; + this._z = c1 * c22 * s32 + s1 * s22 * c32; + this._w = c1 * c22 * c32 - s1 * s22 * s32; + break; + case "ZYX": + this._x = s1 * c22 * c32 - c1 * s22 * s32; + this._y = c1 * s22 * c32 + s1 * c22 * s32; + this._z = c1 * c22 * s32 - s1 * s22 * c32; + this._w = c1 * c22 * c32 + s1 * s22 * s32; + break; + case "YZX": + this._x = s1 * c22 * c32 + c1 * s22 * s32; + this._y = c1 * s22 * c32 + s1 * c22 * s32; + this._z = c1 * c22 * s32 - s1 * s22 * c32; + this._w = c1 * c22 * c32 - s1 * s22 * s32; + break; + case "XZY": + this._x = s1 * c22 * c32 - c1 * s22 * s32; + this._y = c1 * s22 * c32 - s1 * c22 * s32; + this._z = c1 * c22 * s32 + s1 * s22 * c32; + this._w = c1 * c22 * c32 + s1 * s22 * s32; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion from the given axis and angle. + * + * @param {Vector3} axis - The normalized axis. + * @param {number} angle - The angle in radians. + * @return {Quaternion} A reference to this quaternion. + */ + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s5 = Math.sin(halfAngle); + this._x = axis.x * s5; + this._y = axis.y * s5; + this._z = axis.z * s5; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion from the given rotation matrix. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). + * @return {Quaternion} A reference to this quaternion. + */ + setFromRotationMatrix(m2) { + const te = m2.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s5 = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s5; + this._x = (m32 - m23) * s5; + this._y = (m13 - m31) * s5; + this._z = (m21 - m12) * s5; + } else if (m11 > m22 && m11 > m33) { + const s5 = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s5; + this._x = 0.25 * s5; + this._y = (m12 + m21) / s5; + this._z = (m13 + m31) / s5; + } else if (m22 > m33) { + const s5 = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s5; + this._x = (m12 + m21) / s5; + this._y = 0.25 * s5; + this._z = (m23 + m32) / s5; + } else { + const s5 = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s5; + this._x = (m13 + m31) / s5; + this._y = (m23 + m32) / s5; + this._z = 0.25 * s5; + } + this._onChangeCallback(); + return this; + } + /** + * Sets this quaternion to the rotation required to rotate the direction vector + * `vFrom` to the direction vector `vTo`. + * + * @param {Vector3} vFrom - The first (normalized) direction vector. + * @param {Vector3} vTo - The second (normalized) direction vector. + * @return {Quaternion} A reference to this quaternion. + */ + setFromUnitVectors(vFrom, vTo) { + let r6 = vFrom.dot(vTo) + 1; + if (r6 < 1e-8) { + r6 = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r6; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r6; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r6; + } + return this.normalize(); + } + /** + * Returns the angle between this quaternion and the given one in radians. + * + * @param {Quaternion} q - The quaternion to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1))); + } + /** + * Rotates this quaternion by a given angular step to the given quaternion. + * The method ensures that the final quaternion will not overshoot `q`. + * + * @param {Quaternion} q - The target quaternion. + * @param {number} step - The angular step in radians. + * @return {Quaternion} A reference to this quaternion. + */ + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) return this; + const t6 = Math.min(1, step / angle); + this.slerp(q, t6); + return this; + } + /** + * Sets this quaternion to the identity quaternion; that is, to the + * quaternion that represents "no rotation". + * + * @return {Quaternion} A reference to this quaternion. + */ + identity() { + return this.set(0, 0, 0, 1); + } + /** + * Inverts this quaternion via {@link Quaternion#conjugate}. The + * quaternion is assumed to have unit length. + * + * @return {Quaternion} A reference to this quaternion. + */ + invert() { + return this.conjugate(); + } + /** + * Returns the rotational conjugate of this quaternion. The conjugate of a + * quaternion represents the same rotation in the opposite direction about + * the rotational axis. + * + * @return {Quaternion} A reference to this quaternion. + */ + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + /** + * Calculates the dot product of this quaternion and the given one. + * + * @param {Quaternion} v - The quaternion to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v2) { + return this._x * v2._x + this._y * v2._y + this._z * v2._z + this._w * v2._w; + } + /** + * Computes the squared Euclidean length (straight-line length) of this quaternion, + * considered as a 4 dimensional vector. This can be useful if you are comparing the + * lengths of two quaternions, as this is a slightly more efficient calculation than + * {@link Quaternion#length}. + * + * @return {number} The squared Euclidean length. + */ + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + /** + * Computes the Euclidean length (straight-line length) of this quaternion, + * considered as a 4 dimensional vector. + * + * @return {number} The Euclidean length. + */ + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + /** + * Normalizes this quaternion - that is, calculated the quaternion that performs + * the same rotation as this one, but has a length equal to `1`. + * + * @return {Quaternion} A reference to this quaternion. + */ + normalize() { + let l3 = this.length(); + if (l3 === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l3 = 1 / l3; + this._x = this._x * l3; + this._y = this._y * l3; + this._z = this._z * l3; + this._w = this._w * l3; + } + this._onChangeCallback(); + return this; + } + /** + * Multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiply(q) { + return this.multiplyQuaternions(this, q); + } + /** + * Pre-multiplies this quaternion by the given one. + * + * @param {Quaternion} q - The quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + premultiply(q) { + return this.multiplyQuaternions(q, this); + } + /** + * Multiplies the given quaternions and stores the result in this instance. + * + * @param {Quaternion} a - The first quaternion. + * @param {Quaternion} b - The second quaternion. + * @return {Quaternion} A reference to this quaternion. + */ + multiplyQuaternions(a3, b3) { + const qax = a3._x, qay = a3._y, qaz = a3._z, qaw = a3._w; + const qbx = b3._x, qby = b3._y, qbz = b3._z, qbw = b3._w; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + /** + * Performs a spherical linear interpolation between quaternions. + * + * @param {Quaternion} qb - The target quaternion. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {Quaternion} A reference to this quaternion. + */ + slerp(qb, t6) { + if (t6 === 0) return this; + if (t6 === 1) return this.copy(qb); + const x2 = this._x, y3 = this._y, z2 = this._z, w2 = this._w; + let cosHalfTheta = w2 * qb._w + x2 * qb._x + y3 * qb._y + z2 * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w2; + this._x = x2; + this._y = y3; + this._z = z2; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s5 = 1 - t6; + this._w = s5 * w2 + t6 * this._w; + this._x = s5 * x2 + t6 * this._x; + this._y = s5 * y3 + t6 * this._y; + this._z = s5 * z2 + t6 * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t6) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t6 * halfTheta) / sinHalfTheta; + this._w = w2 * ratioA + this._w * ratioB; + this._x = x2 * ratioA + this._x * ratioB; + this._y = y3 * ratioA + this._y * ratioB; + this._z = z2 * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + /** + * Performs a spherical linear interpolation between the given quaternions + * and stores the result in this quaternion. + * + * @param {Quaternion} qa - The source quaternion. + * @param {Quaternion} qb - The target quaternion. + * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. + * @return {Quaternion} A reference to this quaternion. + */ + slerpQuaternions(qa, qb, t6) { + return this.copy(qa).slerp(qb, t6); + } + /** + * Sets this quaternion to a uniformly random, normalized quaternion. + * + * @return {Quaternion} A reference to this quaternion. + */ + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r22 = Math.sqrt(x0); + return this.set( + r1 * Math.sin(theta1), + r1 * Math.cos(theta1), + r22 * Math.sin(theta2), + r22 * Math.cos(theta2) + ); + } + /** + * Returns `true` if this quaternion is equal with the given one. + * + * @param {Quaternion} quaternion - The quaternion to test for equality. + * @return {boolean} Whether this quaternion is equal with the given one. + */ + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + /** + * Sets this quaternion's components from the given array. + * + * @param {Array} array - An array holding the quaternion component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Quaternion} A reference to this quaternion. + */ + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + /** + * Writes the components of this quaternion to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the quaternion components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The quaternion components. + */ + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + /** + * Sets the components of this quaternion from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data. + * @param {number} index - The index into the attribute. + * @return {Quaternion} A reference to this quaternion. + */ + fromBufferAttribute(attribute, index) { + this._x = attribute.getX(index); + this._y = attribute.getY(index); + this._z = attribute.getZ(index); + this._w = attribute.getW(index); + this._onChangeCallback(); + return this; + } + /** + * This methods defines the serialization result of this class. Returns the + * numerical elements of this quaternion in an array of format `[x, y, z, w]`. + * + * @return {Array} The serialized quaternion. + */ + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } +}; +var Vector3 = class _Vector3 { + /** + * Constructs a new 3D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + * @param {number} [z=0] - The z value of this vector. + */ + constructor(x2 = 0, y3 = 0, z2 = 0) { + _Vector3.prototype.isVector3 = true; + this.x = x2; + this.y = y3; + this.z = z2; + } + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @param {number} z - The value of the z component. + * @return {Vector3} A reference to this vector. + */ + set(x2, y3, z2) { + if (z2 === void 0) z2 = this.z; + this.x = x2; + this.y = y3; + this.z = z2; + return this; + } + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector3} A reference to this vector. + */ + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector3} A reference to this vector. + */ + setX(x2) { + this.x = x2; + return this; + } + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector3} A reference to this vector. + */ + setY(y3) { + this.y = y3; + return this; + } + /** + * Sets the vector's z component to the given value + * + * @param {number} z - The value to set. + * @return {Vector3} A reference to this vector. + */ + setZ(z2) { + this.z = z2; + return this; + } + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. + * @param {number} value - The value to set. + * @return {Vector3} A reference to this vector. + */ + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. + * @return {number} A vector component value. + */ + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index); + } + } + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector3} A clone of this instance. + */ + clone() { + return new this.constructor(this.x, this.y, this.z); + } + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector3} v - The vector to copy. + * @return {Vector3} A reference to this vector. + */ + copy(v2) { + this.x = v2.x; + this.y = v2.y; + this.z = v2.z; + return this; + } + /** + * Adds the given vector to this instance. + * + * @param {Vector3} v - The vector to add. + * @return {Vector3} A reference to this vector. + */ + add(v2) { + this.x += v2.x; + this.y += v2.y; + this.z += v2.z; + return this; + } + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector3} A reference to this vector. + */ + addScalar(s5) { + this.x += s5; + this.y += s5; + this.z += s5; + return this; + } + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + addVectors(a3, b3) { + this.x = a3.x + b3.x; + this.y = a3.y + b3.y; + this.z = a3.z + b3.z; + return this; + } + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector3|Vector4} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector3} A reference to this vector. + */ + addScaledVector(v2, s5) { + this.x += v2.x * s5; + this.y += v2.y * s5; + this.z += v2.z * s5; + return this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector3} v - The vector to subtract. + * @return {Vector3} A reference to this vector. + */ + sub(v2) { + this.x -= v2.x; + this.y -= v2.y; + this.z -= v2.z; + return this; + } + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector3} A reference to this vector. + */ + subScalar(s5) { + this.x -= s5; + this.y -= s5; + this.z -= s5; + return this; + } + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + subVectors(a3, b3) { + this.x = a3.x - b3.x; + this.y = a3.y - b3.y; + this.z = a3.z - b3.z; + return this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector3} v - The vector to multiply. + * @return {Vector3} A reference to this vector. + */ + multiply(v2) { + this.x *= v2.x; + this.y *= v2.y; + this.z *= v2.z; + return this; + } + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector3} A reference to this vector. + */ + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + /** + * Multiplies the given vectors and stores the result in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + multiplyVectors(a3, b3) { + this.x = a3.x * b3.x; + this.y = a3.y * b3.y; + this.z = a3.z * b3.z; + return this; + } + /** + * Applies the given Euler rotation to this vector. + * + * @param {Euler} euler - The Euler angles. + * @return {Vector3} A reference to this vector. + */ + applyEuler(euler) { + return this.applyQuaternion(_quaternion$4.setFromEuler(euler)); + } + /** + * Applies a rotation specified by an axis and an angle to this vector. + * + * @param {Vector3} axis - A normalized vector representing the rotation axis. + * @param {number} angle - The angle in radians. + * @return {Vector3} A reference to this vector. + */ + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle)); + } + /** + * Multiplies this vector with the given 3x3 matrix. + * + * @param {Matrix3} m - The 3x3 matrix. + * @return {Vector3} A reference to this vector. + */ + applyMatrix3(m2) { + const x2 = this.x, y3 = this.y, z2 = this.z; + const e8 = m2.elements; + this.x = e8[0] * x2 + e8[3] * y3 + e8[6] * z2; + this.y = e8[1] * x2 + e8[4] * y3 + e8[7] * z2; + this.z = e8[2] * x2 + e8[5] * y3 + e8[8] * z2; + return this; + } + /** + * Multiplies this vector by the given normal matrix and normalizes + * the result. + * + * @param {Matrix3} m - The normal matrix. + * @return {Vector3} A reference to this vector. + */ + applyNormalMatrix(m2) { + return this.applyMatrix3(m2).normalize(); + } + /** + * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and + * divides by perspective. + * + * @param {Matrix4} m - The matrix to apply. + * @return {Vector3} A reference to this vector. + */ + applyMatrix4(m2) { + const x2 = this.x, y3 = this.y, z2 = this.z; + const e8 = m2.elements; + const w2 = 1 / (e8[3] * x2 + e8[7] * y3 + e8[11] * z2 + e8[15]); + this.x = (e8[0] * x2 + e8[4] * y3 + e8[8] * z2 + e8[12]) * w2; + this.y = (e8[1] * x2 + e8[5] * y3 + e8[9] * z2 + e8[13]) * w2; + this.z = (e8[2] * x2 + e8[6] * y3 + e8[10] * z2 + e8[14]) * w2; + return this; + } + /** + * Applies the given Quaternion to this vector. + * + * @param {Quaternion} q - The Quaternion. + * @return {Vector3} A reference to this vector. + */ + applyQuaternion(q) { + const vx = this.x, vy = this.y, vz = this.z; + const qx = q.x, qy = q.y, qz = q.z, qw = q.w; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + /** + * Projects this vector from world space into the camera's normalized + * device coordinate (NDC) space. + * + * @param {Camera} camera - The camera. + * @return {Vector3} A reference to this vector. + */ + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + /** + * Unprojects this vector from the camera's normalized device coordinate (NDC) + * space into world space. + * + * @param {Camera} camera - The camera. + * @return {Vector3} A reference to this vector. + */ + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + /** + * Transforms the direction of this vector by a matrix (the upper left 3 x 3 + * subset of the given 4x4 matrix and then normalizes the result. + * + * @param {Matrix4} m - The matrix. + * @return {Vector3} A reference to this vector. + */ + transformDirection(m2) { + const x2 = this.x, y3 = this.y, z2 = this.z; + const e8 = m2.elements; + this.x = e8[0] * x2 + e8[4] * y3 + e8[8] * z2; + this.y = e8[1] * x2 + e8[5] * y3 + e8[9] * z2; + this.z = e8[2] * x2 + e8[6] * y3 + e8[10] * z2; + return this.normalize(); + } + /** + * Divides this instance by the given vector. + * + * @param {Vector3} v - The vector to divide. + * @return {Vector3} A reference to this vector. + */ + divide(v2) { + this.x /= v2.x; + this.y /= v2.y; + this.z /= v2.z; + return this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector3} A reference to this vector. + */ + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + /** + * If this vector's x, y or z value is greater than the given vector's x, y or z + * value, replace that value with the corresponding min value. + * + * @param {Vector3} v - The vector. + * @return {Vector3} A reference to this vector. + */ + min(v2) { + this.x = Math.min(this.x, v2.x); + this.y = Math.min(this.y, v2.y); + this.z = Math.min(this.z, v2.z); + return this; + } + /** + * If this vector's x, y or z value is less than the given vector's x, y or z + * value, replace that value with the corresponding max value. + * + * @param {Vector3} v - The vector. + * @return {Vector3} A reference to this vector. + */ + max(v2) { + this.x = Math.max(this.x, v2.x); + this.y = Math.max(this.y, v2.y); + this.z = Math.max(this.z, v2.z); + return this; + } + /** + * If this vector's x, y or z value is greater than the max vector's x, y or z + * value, it is replaced by the corresponding value. + * If this vector's x, y or z value is less than the min vector's x, y or z value, + * it is replaced by the corresponding value. + * + * @param {Vector3} min - The minimum x, y and z values. + * @param {Vector3} max - The maximum x, y and z values in the desired range. + * @return {Vector3} A reference to this vector. + */ + clamp(min, max) { + this.x = clamp(this.x, min.x, max.x); + this.y = clamp(this.y, min.y, max.y); + this.z = clamp(this.z, min.z, max.z); + return this; + } + /** + * If this vector's x, y or z values are greater than the max value, they are + * replaced by the max value. + * If this vector's x, y or z values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector3} A reference to this vector. + */ + clampScalar(minVal, maxVal) { + this.x = clamp(this.x, minVal, maxVal); + this.y = clamp(this.y, minVal, maxVal); + this.z = clamp(this.z, minVal, maxVal); + return this; + } + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector3} A reference to this vector. + */ + clampLength(min, max) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max)); + } + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector3} A reference to this vector. + */ + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector3} A reference to this vector. + */ + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector3} A reference to this vector. + */ + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector3} A reference to this vector. + */ + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + /** + * Inverts this vector - i.e. sets x = -x, y = -y and z = -z. + * + * @return {Vector3} A reference to this vector. + */ + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector3} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v2) { + return this.x * v2.x + this.y * v2.y + this.z * v2.z; + } + // TODO lengthSquared? + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + /** + * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z). + * + * @return {number} The length of this vector. + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector3} A reference to this vector. + */ + normalize() { + return this.divideScalar(this.length() || 1); + } + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector3} A reference to this vector. + */ + setLength(length) { + return this.normalize().multiplyScalar(length); + } + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector3} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector3} A reference to this vector. + */ + lerp(v2, alpha) { + this.x += (v2.x - this.x) * alpha; + this.y += (v2.y - this.y) * alpha; + this.z += (v2.z - this.z) * alpha; + return this; + } + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector3} v1 - The first vector. + * @param {Vector3} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector3} A reference to this vector. + */ + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + return this; + } + /** + * Calculates the cross product of the given vector with this instance. + * + * @param {Vector3} v - The vector to compute the cross product with. + * @return {Vector3} The result of the cross product. + */ + cross(v2) { + return this.crossVectors(this, v2); + } + /** + * Calculates the cross product of the given vectors and stores the result + * in this instance. + * + * @param {Vector3} a - The first vector. + * @param {Vector3} b - The second vector. + * @return {Vector3} A reference to this vector. + */ + crossVectors(a3, b3) { + const ax = a3.x, ay = a3.y, az = a3.z; + const bx = b3.x, by = b3.y, bz = b3.z; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + /** + * Projects this vector onto the given one. + * + * @param {Vector3} v - The vector to project to. + * @return {Vector3} A reference to this vector. + */ + projectOnVector(v2) { + const denominator = v2.lengthSq(); + if (denominator === 0) return this.set(0, 0, 0); + const scalar = v2.dot(this) / denominator; + return this.copy(v2).multiplyScalar(scalar); + } + /** + * Projects this vector onto a plane by subtracting this + * vector projected onto the plane's normal from this vector. + * + * @param {Vector3} planeNormal - The plane normal. + * @return {Vector3} A reference to this vector. + */ + projectOnPlane(planeNormal) { + _vector$c.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c); + } + /** + * Reflects this vector off a plane orthogonal to the given normal vector. + * + * @param {Vector3} normal - The (normalized) normal vector. + * @return {Vector3} A reference to this vector. + */ + reflect(normal) { + return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + /** + * Returns the angle between the given vector and this instance in radians. + * + * @param {Vector3} v - The vector to compute the angle with. + * @return {number} The angle in radians. + */ + angleTo(v2) { + const denominator = Math.sqrt(this.lengthSq() * v2.lengthSq()); + if (denominator === 0) return Math.PI / 2; + const theta = this.dot(v2) / denominator; + return Math.acos(clamp(theta, -1, 1)); + } + /** + * Computes the distance from the given vector to this instance. + * + * @param {Vector3} v - The vector to compute the distance to. + * @return {number} The distance. + */ + distanceTo(v2) { + return Math.sqrt(this.distanceToSquared(v2)); + } + /** + * Computes the squared distance from the given vector to this instance. + * If you are just comparing the distance with another distance, you should compare + * the distance squared instead as it is slightly more efficient to calculate. + * + * @param {Vector3} v - The vector to compute the squared distance to. + * @return {number} The squared distance. + */ + distanceToSquared(v2) { + const dx = this.x - v2.x, dy = this.y - v2.y, dz = this.z - v2.z; + return dx * dx + dy * dy + dz * dz; + } + /** + * Computes the Manhattan distance from the given vector to this instance. + * + * @param {Vector3} v - The vector to compute the Manhattan distance to. + * @return {number} The Manhattan distance. + */ + manhattanDistanceTo(v2) { + return Math.abs(this.x - v2.x) + Math.abs(this.y - v2.y) + Math.abs(this.z - v2.z); + } + /** + * Sets the vector components from the given spherical coordinates. + * + * @param {Spherical} s - The spherical coordinates. + * @return {Vector3} A reference to this vector. + */ + setFromSpherical(s5) { + return this.setFromSphericalCoords(s5.radius, s5.phi, s5.theta); + } + /** + * Sets the vector components from the given spherical coordinates. + * + * @param {number} radius - The radius. + * @param {number} phi - The phi angle in radians. + * @param {number} theta - The theta angle in radians. + * @return {Vector3} A reference to this vector. + */ + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + /** + * Sets the vector components from the given cylindrical coordinates. + * + * @param {Cylindrical} c - The cylindrical coordinates. + * @return {Vector3} A reference to this vector. + */ + setFromCylindrical(c5) { + return this.setFromCylindricalCoords(c5.radius, c5.theta, c5.y); + } + /** + * Sets the vector components from the given cylindrical coordinates. + * + * @param {number} radius - The radius. + * @param {number} theta - The theta angle in radians. + * @param {number} y - The y value. + * @return {Vector3} A reference to this vector. + */ + setFromCylindricalCoords(radius, theta, y3) { + this.x = radius * Math.sin(theta); + this.y = y3; + this.z = radius * Math.cos(theta); + return this; + } + /** + * Sets the vector components to the position elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector3} A reference to this vector. + */ + setFromMatrixPosition(m2) { + const e8 = m2.elements; + this.x = e8[12]; + this.y = e8[13]; + this.z = e8[14]; + return this; + } + /** + * Sets the vector components to the scale elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector3} A reference to this vector. + */ + setFromMatrixScale(m2) { + const sx = this.setFromMatrixColumn(m2, 0).length(); + const sy = this.setFromMatrixColumn(m2, 1).length(); + const sz = this.setFromMatrixColumn(m2, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + /** + * Sets the vector components from the specified matrix column. + * + * @param {Matrix4} m - The 4x4 matrix. + * @param {number} index - The column index. + * @return {Vector3} A reference to this vector. + */ + setFromMatrixColumn(m2, index) { + return this.fromArray(m2.elements, index * 4); + } + /** + * Sets the vector components from the specified matrix column. + * + * @param {Matrix3} m - The 3x3 matrix. + * @param {number} index - The column index. + * @return {Vector3} A reference to this vector. + */ + setFromMatrix3Column(m2, index) { + return this.fromArray(m2.elements, index * 3); + } + /** + * Sets the vector components from the given Euler angles. + * + * @param {Euler} e - The Euler angles to set. + * @return {Vector3} A reference to this vector. + */ + setFromEuler(e8) { + this.x = e8._x; + this.y = e8._y; + this.z = e8._z; + return this; + } + /** + * Sets the vector components from the RGB components of the + * given color. + * + * @param {Color} c - The color to set. + * @return {Vector3} A reference to this vector. + */ + setFromColor(c5) { + this.x = c5.r; + this.y = c5.g; + this.z = c5.b; + return this; + } + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector3} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals(v2) { + return v2.x === this.x && v2.y === this.y && v2.z === this.z; + } + /** + * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]` + * and z value to be `array[ offset + 2 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector3} A reference to this vector. + */ + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector3} A reference to this vector. + */ + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + this.z = attribute.getZ(index); + return this; + } + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector3} A reference to this vector. + */ + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + /** + * Sets this vector to a uniformly random point on a unit sphere. + * + * @return {Vector3} A reference to this vector. + */ + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u3 = Math.random() * 2 - 1; + const c5 = Math.sqrt(1 - u3 * u3); + this.x = c5 * Math.cos(theta); + this.y = u3; + this.z = c5 * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } +}; +var _vector$c = /* @__PURE__ */ new Vector3(); +var _quaternion$4 = /* @__PURE__ */ new Quaternion(); +var Matrix3 = class _Matrix3 { + /** + * Constructs a new 3x3 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + */ + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + _Matrix3.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @return {Matrix3} A reference to this matrix. + */ + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te = this.elements; + te[0] = n11; + te[1] = n21; + te[2] = n31; + te[3] = n12; + te[4] = n22; + te[5] = n32; + te[6] = n13; + te[7] = n23; + te[8] = n33; + return this; + } + /** + * Sets this matrix to the 3x3 identity matrix. + * + * @return {Matrix3} A reference to this matrix. + */ + identity() { + this.set( + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Copies the values of the given matrix to this instance. + * + * @param {Matrix3} m - The matrix to copy. + * @return {Matrix3} A reference to this matrix. + */ + copy(m2) { + const te = this.elements; + const me = m2.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + return this; + } + /** + * Extracts the basis of this matrix into the three axis vectors provided. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix3} A reference to this matrix. + */ + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + /** + * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Matrix3} A reference to this matrix. + */ + setFromMatrix4(m2) { + const me = m2.elements; + this.set( + me[0], + me[4], + me[8], + me[1], + me[5], + me[9], + me[2], + me[6], + me[10] + ); + return this; + } + /** + * Post-multiplies this matrix by the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to multiply with. + * @return {Matrix3} A reference to this matrix. + */ + multiply(m2) { + return this.multiplyMatrices(this, m2); + } + /** + * Pre-multiplies this matrix by the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix to multiply with. + * @return {Matrix3} A reference to this matrix. + */ + premultiply(m2) { + return this.multiplyMatrices(m2, this); + } + /** + * Multiples the given 3x3 matrices and stores the result + * in this matrix. + * + * @param {Matrix3} a - The first matrix. + * @param {Matrix3} b - The second matrix. + * @return {Matrix3} A reference to this matrix. + */ + multiplyMatrices(a3, b3) { + const ae = a3.elements; + const be = b3.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[3], a13 = ae[6]; + const a21 = ae[1], a22 = ae[4], a23 = ae[7]; + const a31 = ae[2], a32 = ae[5], a33 = ae[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31; + te[3] = a11 * b12 + a12 * b22 + a13 * b32; + te[6] = a11 * b13 + a12 * b23 + a13 * b33; + te[1] = a21 * b11 + a22 * b21 + a23 * b31; + te[4] = a21 * b12 + a22 * b22 + a23 * b32; + te[7] = a21 * b13 + a22 * b23 + a23 * b33; + te[2] = a31 * b11 + a32 * b21 + a33 * b31; + te[5] = a31 * b12 + a32 * b22 + a33 * b32; + te[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix3} A reference to this matrix. + */ + multiplyScalar(s5) { + const te = this.elements; + te[0] *= s5; + te[3] *= s5; + te[6] *= s5; + te[1] *= s5; + te[4] *= s5; + te[7] *= s5; + te[2] *= s5; + te[5] *= s5; + te[8] *= s5; + return this; + } + /** + * Computes and returns the determinant of this matrix. + * + * @return {number} The determinant. + */ + determinant() { + const te = this.elements; + const a3 = te[0], b3 = te[1], c5 = te[2], d3 = te[3], e8 = te[4], f4 = te[5], g2 = te[6], h4 = te[7], i6 = te[8]; + return a3 * e8 * i6 - a3 * f4 * h4 - b3 * d3 * i6 + b3 * f4 * g2 + c5 * d3 * h4 - c5 * e8 * g2; + } + /** + * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}. + * You can not invert with a determinant of zero. If you attempt this, the method produces + * a zero matrix instead. + * + * @return {Matrix3} A reference to this matrix. + */ + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n31 * n23 - n33 * n21) * detInv; + te[2] = (n32 * n21 - n31 * n22) * detInv; + te[3] = t12 * detInv; + te[4] = (n33 * n11 - n31 * n13) * detInv; + te[5] = (n31 * n12 - n32 * n11) * detInv; + te[6] = t13 * detInv; + te[7] = (n21 * n13 - n23 * n11) * detInv; + te[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + /** + * Transposes this matrix in place. + * + * @return {Matrix3} A reference to this matrix. + */ + transpose() { + let tmp; + const m2 = this.elements; + tmp = m2[1]; + m2[1] = m2[3]; + m2[3] = tmp; + tmp = m2[2]; + m2[2] = m2[6]; + m2[6] = tmp; + tmp = m2[5]; + m2[5] = m2[7]; + m2[7] = tmp; + return this; + } + /** + * Computes the normal matrix which is the inverse transpose of the upper + * left 3x3 portion of the given 4x4 matrix. + * + * @param {Matrix4} matrix4 - The 4x4 matrix. + * @return {Matrix3} A reference to this matrix. + */ + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + /** + * Transposes this matrix into the supplied array, and returns itself unchanged. + * + * @param {Array} r - An array to store the transposed matrix elements. + * @return {Matrix3} A reference to this matrix. + */ + transposeIntoArray(r6) { + const m2 = this.elements; + r6[0] = m2[0]; + r6[1] = m2[3]; + r6[2] = m2[6]; + r6[3] = m2[1]; + r6[4] = m2[4]; + r6[5] = m2[7]; + r6[6] = m2[2]; + r6[7] = m2[5]; + r6[8] = m2[8]; + return this; + } + /** + * Sets the UV transform matrix from offset, repeat, rotation, and center. + * + * @param {number} tx - Offset x. + * @param {number} ty - Offset y. + * @param {number} sx - Repeat x. + * @param {number} sy - Repeat y. + * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise. + * @param {number} cx - Center x of rotation. + * @param {number} cy - Center y of rotation + * @return {Matrix3} A reference to this matrix. + */ + setUvTransform(tx, ty, sx, sy, rotation, cx, cy) { + const c5 = Math.cos(rotation); + const s5 = Math.sin(rotation); + this.set( + sx * c5, + sx * s5, + -sx * (c5 * cx + s5 * cy) + cx + tx, + -sy * s5, + sy * c5, + -sy * (-s5 * cx + c5 * cy) + cy + ty, + 0, + 0, + 1 + ); + return this; + } + /** + * Scales this matrix with the given scalar values. + * + * @param {number} sx - The amount to scale in the X axis. + * @param {number} sy - The amount to scale in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + scale(sx, sy) { + this.premultiply(_m3.makeScale(sx, sy)); + return this; + } + /** + * Rotates this matrix by the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + rotate(theta) { + this.premultiply(_m3.makeRotation(-theta)); + return this; + } + /** + * Translates this matrix by the given scalar values. + * + * @param {number} tx - The amount to translate in the X axis. + * @param {number} ty - The amount to translate in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + translate(tx, ty) { + this.premultiply(_m3.makeTranslation(tx, ty)); + return this; + } + // for 2D Transforms + /** + * Sets this matrix as a 2D translation transform. + * + * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector. + * @param {number} y - The amount to translate in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + makeTranslation(x2, y3) { + if (x2.isVector2) { + this.set( + 1, + 0, + x2.x, + 0, + 1, + x2.y, + 0, + 0, + 1 + ); + } else { + this.set( + 1, + 0, + x2, + 0, + 1, + y3, + 0, + 0, + 1 + ); + } + return this; + } + /** + * Sets this matrix as a 2D rotational transformation. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix3} A reference to this matrix. + */ + makeRotation(theta) { + const c5 = Math.cos(theta); + const s5 = Math.sin(theta); + this.set( + c5, + -s5, + 0, + s5, + c5, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a 2D scale transform. + * + * @param {number} x - The amount to scale in the X axis. + * @param {number} y - The amount to scale in the Y axis. + * @return {Matrix3} A reference to this matrix. + */ + makeScale(x2, y3) { + this.set( + x2, + 0, + 0, + 0, + y3, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Returns `true` if this matrix is equal with the given one. + * + * @param {Matrix3} matrix - The matrix to test for equality. + * @return {boolean} Whether this matrix is equal with the given one. + */ + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i6 = 0; i6 < 9; i6++) { + if (te[i6] !== me[i6]) return false; + } + return true; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix3} A reference to this matrix. + */ + fromArray(array, offset = 0) { + for (let i6 = 0; i6 < 9; i6++) { + this.elements[i6] = array[i6 + offset]; + } + return this; + } + /** + * Writes the elements of this matrix to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The matrix elements in column-major order. + */ + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + return array; + } + /** + * Returns a matrix with copied values from this instance. + * + * @return {Matrix3} A clone of this instance. + */ + clone() { + return new this.constructor().fromArray(this.elements); + } +}; +var _m3 = /* @__PURE__ */ new Matrix3(); +function arrayNeedsUint32(array) { + for (let i6 = array.length - 1; i6 >= 0; --i6) { + if (array[i6] >= 65535) return true; + } + return false; +} +function createElementNS(name) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name); +} +function createCanvasElement() { + const canvas = createElementNS("canvas"); + canvas.style.display = "block"; + return canvas; +} +var _cache = {}; +function warnOnce(message) { + if (message in _cache) return; + _cache[message] = true; + console.warn(message); +} +function probeAsync(gl, sync, interval) { + return new Promise(function(resolve, reject) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); +} +var LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set( + 0.4123908, + 0.3575843, + 0.1804808, + 0.212639, + 0.7151687, + 0.0721923, + 0.0193308, + 0.1191948, + 0.9505322 +); +var XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set( + 3.2409699, + -1.5373832, + -0.4986108, + -0.9692436, + 1.8759675, + 0.0415551, + 0.0556301, + -0.203977, + 1.0569715 +); +function createColorManagement() { + const ColorManagement2 = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace, + /** + * Implementations of supported color spaces. + * + * Required: + * - primaries: chromaticity coordinates [ rx ry gx gy bx by ] + * - whitePoint: reference white [ x y ] + * - transfer: transfer function (pre-defined) + * - toXYZ: Matrix3 RGB to XYZ transform + * - fromXYZ: Matrix3 XYZ to RGB transform + * - luminanceCoefficients: RGB luminance coefficients + * + * Optional: + * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' } + * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace } + * + * Reference: + * - https://www.russellcottrell.com/photo/matrixCalculator.htm + */ + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) { + color.r = SRGBToLinear(color.r); + color.g = SRGBToLinear(color.g); + color.b = SRGBToLinear(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer) { + color.r = LinearToSRGB(color.r); + color.g = LinearToSRGB(color.g); + color.b = LinearToSRGB(color.b); + } + return color; + }, + workingToColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + colorSpaceToWorking: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace) return LinearTransfer; + return this.spaces[colorSpace].transfer; + }, + getToneMappingMode: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.toneMappingMode || "standard"; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + // Internal APIs + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + }, + // Deprecated + fromWorkingColorSpace: function(color, targetColorSpace) { + warnOnce("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."); + return ColorManagement2.workingToColorSpace(color, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + warnOnce("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."); + return ColorManagement2.colorSpaceToWorking(color, sourceColorSpace); + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement2.define({ + [LinearSRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + [SRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + } + }); + return ColorManagement2; +} +var ColorManagement = /* @__PURE__ */ createColorManagement(); +function SRGBToLinear(c5) { + return c5 < 0.04045 ? c5 * 0.0773993808 : Math.pow(c5 * 0.9478672986 + 0.0521327014, 2.4); +} +function LinearToSRGB(c5) { + return c5 < 31308e-7 ? c5 * 12.92 : 1.055 * Math.pow(c5, 0.41666) - 0.055; +} +var _canvas; +var ImageUtils = class { + /** + * Returns a data URI containing a representation of the given image. + * + * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object. + * @param {string} [type='image/png'] - Indicates the image format. + * @return {string} The data URI. + */ + static getDataURL(image, type = "image/png") { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas === void 0) _canvas = createElementNS("canvas"); + _canvas.width = image.width; + _canvas.height = image.height; + const context = _canvas.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas; + } + return canvas.toDataURL(type); + } + /** + * Converts the given sRGB image data to linear color space. + * + * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object. + * @return {HTMLCanvasElement|Object} The converted image. + */ + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data = imageData.data; + for (let i6 = 0; i6 < data.length; i6++) { + data[i6] = SRGBToLinear(data[i6] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data = image.data.slice(0); + for (let i6 = 0; i6 < data.length; i6++) { + if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) { + data[i6] = Math.floor(SRGBToLinear(data[i6] / 255) * 255); + } else { + data[i6] = SRGBToLinear(data[i6]); + } + } + return { + data, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } +}; +var _sourceId = 0; +var Source = class { + /** + * Constructs a new video texture. + * + * @param {any} [data=null] - The data definition of a texture. + */ + constructor(data = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId++ }); + this.uuid = generateUUID(); + this.data = data; + this.dataReady = true; + this.version = 0; + } + /** + * Returns the dimensions of the source into the given target vector. + * + * @param {(Vector2|Vector3)} target - The target object the result is written into. + * @return {(Vector2|Vector3)} The dimensions of the source. + */ + getSize(target) { + const data = this.data; + if (typeof HTMLVideoElement !== "undefined" && data instanceof HTMLVideoElement) { + target.set(data.videoWidth, data.videoHeight, 0); + } else if (data instanceof VideoFrame) { + target.set(data.displayHeight, data.displayWidth, 0); + } else if (data !== null) { + target.set(data.width, data.height, data.depth || 0); + } else { + target.set(0, 0, 0); + } + return target; + } + /** + * When the property is set to `true`, the engine allocates the memory + * for the texture (if necessary) and triggers the actual texture upload + * to the GPU next time the source is used. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + /** + * Serializes the source into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized source. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== void 0) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data = this.data; + if (data !== null) { + let url; + if (Array.isArray(data)) { + url = []; + for (let i6 = 0, l3 = data.length; i6 < l3; i6++) { + if (data[i6].isDataTexture) { + url.push(serializeImage(data[i6].image)); + } else { + url.push(serializeImage(data[i6])); + } + } + } else { + url = serializeImage(data); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } +}; +function serializeImage(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } +} +var _textureId = 0; +var _tempVec3 = /* @__PURE__ */ new Vector3(); +var Texture = class _Texture extends EventDispatcher { + /** + * Constructs a new texture. + * + * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space. + */ + constructor(image = _Texture.DEFAULT_IMAGE, mapping = _Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = _Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.source = new Source(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector2(0, 0); + this.repeat = new Vector2(1, 1); + this.center = new Vector2(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3(); + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.updateRanges = []; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false; + this.pmremVersion = 0; + } + /** + * The width of the texture in pixels. + */ + get width() { + return this.source.getSize(_tempVec3).x; + } + /** + * The height of the texture in pixels. + */ + get height() { + return this.source.getSize(_tempVec3).y; + } + /** + * The depth of the texture in pixels. + */ + get depth() { + return this.source.getSize(_tempVec3).z; + } + /** + * The image object holding the texture data. + * + * @type {?Object} + */ + get image() { + return this.source.data; + } + set image(value = null) { + this.source.data = value; + } + /** + * Updates the texture transformation matrix from the from the properties {@link Texture#offset}, + * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}. + */ + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + /** + * Adds a range of data in the data texture to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + this.updateRanges.length = 0; + } + /** + * Returns a new texture with copied values from this instance. + * + * @return {Texture} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given texture to this instance. + * + * @param {Texture} source - The texture to copy. + * @return {Texture} A reference to this instance. + */ + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.isArrayTexture = source.isArrayTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + /** + * Sets this texture's properties based on `values`. + * @param {Object} values - A container with texture parameters. + */ + setValues(values) { + for (const key in values) { + const newValue = values[key]; + if (newValue === void 0) { + console.warn(`THREE.Texture.setValues(): parameter '${key}' has value of undefined.`); + continue; + } + const currentValue = this[key]; + if (currentValue === void 0) { + console.warn(`THREE.Texture.setValues(): property '${key}' does not exist.`); + continue; + } + if (currentValue && newValue && (currentValue.isVector2 && newValue.isVector2)) { + currentValue.copy(newValue); + } else if (currentValue && newValue && (currentValue.isVector3 && newValue.isVector3)) { + currentValue.copy(newValue); + } else if (currentValue && newValue && (currentValue.isMatrix3 && newValue.isMatrix3)) { + currentValue.copy(newValue); + } else { + this[key] = newValue; + } + } + } + /** + * Serializes the texture into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized texture. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== void 0) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.7, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Texture#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + /** + * Transforms the given uv vector with the textures uv transformation matrix. + * + * @param {Vector2} uv - The uv vector. + * @return {Vector2} The transformed uv vector. + */ + transformUv(uv) { + if (this.mapping !== UVMapping) return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + /** + * Setting this property to `true` indicates the engine the texture + * must be updated in the next render. This triggers a texture upload + * to the GPU and ensures correct texture parameter configuration. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) { + this.version++; + this.source.needsUpdate = true; + } + } + /** + * Setting this property to `true` indicates the engine the PMREM + * must be regenerated. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsPMREMUpdate(value) { + if (value === true) { + this.pmremVersion++; + } + } +}; +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; +var Vector4 = class _Vector4 { + /** + * Constructs a new 4D vector. + * + * @param {number} [x=0] - The x value of this vector. + * @param {number} [y=0] - The y value of this vector. + * @param {number} [z=0] - The z value of this vector. + * @param {number} [w=1] - The w value of this vector. + */ + constructor(x2 = 0, y3 = 0, z2 = 0, w2 = 1) { + _Vector4.prototype.isVector4 = true; + this.x = x2; + this.y = y3; + this.z = z2; + this.w = w2; + } + /** + * Alias for {@link Vector4#z}. + * + * @type {number} + */ + get width() { + return this.z; + } + set width(value) { + this.z = value; + } + /** + * Alias for {@link Vector4#w}. + * + * @type {number} + */ + get height() { + return this.w; + } + set height(value) { + this.w = value; + } + /** + * Sets the vector components. + * + * @param {number} x - The value of the x component. + * @param {number} y - The value of the y component. + * @param {number} z - The value of the z component. + * @param {number} w - The value of the w component. + * @return {Vector4} A reference to this vector. + */ + set(x2, y3, z2, w2) { + this.x = x2; + this.y = y3; + this.z = z2; + this.w = w2; + return this; + } + /** + * Sets the vector components to the same value. + * + * @param {number} scalar - The value to set for all vector components. + * @return {Vector4} A reference to this vector. + */ + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + /** + * Sets the vector's x component to the given value + * + * @param {number} x - The value to set. + * @return {Vector4} A reference to this vector. + */ + setX(x2) { + this.x = x2; + return this; + } + /** + * Sets the vector's y component to the given value + * + * @param {number} y - The value to set. + * @return {Vector4} A reference to this vector. + */ + setY(y3) { + this.y = y3; + return this; + } + /** + * Sets the vector's z component to the given value + * + * @param {number} z - The value to set. + * @return {Vector4} A reference to this vector. + */ + setZ(z2) { + this.z = z2; + return this; + } + /** + * Sets the vector's w component to the given value + * + * @param {number} w - The value to set. + * @return {Vector4} A reference to this vector. + */ + setW(w2) { + this.w = w2; + return this; + } + /** + * Allows to set a vector component with an index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, + * `2` equals to z, `3` equals to w. + * @param {number} value - The value to set. + * @return {Vector4} A reference to this vector. + */ + setComponent(index, value) { + switch (index) { + case 0: + this.x = value; + break; + case 1: + this.y = value; + break; + case 2: + this.z = value; + break; + case 3: + this.w = value; + break; + default: + throw new Error("index is out of range: " + index); + } + return this; + } + /** + * Returns the value of the vector component which matches the given index. + * + * @param {number} index - The component index. `0` equals to x, `1` equals to y, + * `2` equals to z, `3` equals to w. + * @return {number} A vector component value. + */ + getComponent(index) { + switch (index) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index); + } + } + /** + * Returns a new vector with copied values from this instance. + * + * @return {Vector4} A clone of this instance. + */ + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + /** + * Copies the values of the given vector to this instance. + * + * @param {Vector3|Vector4} v - The vector to copy. + * @return {Vector4} A reference to this vector. + */ + copy(v2) { + this.x = v2.x; + this.y = v2.y; + this.z = v2.z; + this.w = v2.w !== void 0 ? v2.w : 1; + return this; + } + /** + * Adds the given vector to this instance. + * + * @param {Vector4} v - The vector to add. + * @return {Vector4} A reference to this vector. + */ + add(v2) { + this.x += v2.x; + this.y += v2.y; + this.z += v2.z; + this.w += v2.w; + return this; + } + /** + * Adds the given scalar value to all components of this instance. + * + * @param {number} s - The scalar to add. + * @return {Vector4} A reference to this vector. + */ + addScalar(s5) { + this.x += s5; + this.y += s5; + this.z += s5; + this.w += s5; + return this; + } + /** + * Adds the given vectors and stores the result in this instance. + * + * @param {Vector4} a - The first vector. + * @param {Vector4} b - The second vector. + * @return {Vector4} A reference to this vector. + */ + addVectors(a3, b3) { + this.x = a3.x + b3.x; + this.y = a3.y + b3.y; + this.z = a3.z + b3.z; + this.w = a3.w + b3.w; + return this; + } + /** + * Adds the given vector scaled by the given factor to this instance. + * + * @param {Vector4} v - The vector. + * @param {number} s - The factor that scales `v`. + * @return {Vector4} A reference to this vector. + */ + addScaledVector(v2, s5) { + this.x += v2.x * s5; + this.y += v2.y * s5; + this.z += v2.z * s5; + this.w += v2.w * s5; + return this; + } + /** + * Subtracts the given vector from this instance. + * + * @param {Vector4} v - The vector to subtract. + * @return {Vector4} A reference to this vector. + */ + sub(v2) { + this.x -= v2.x; + this.y -= v2.y; + this.z -= v2.z; + this.w -= v2.w; + return this; + } + /** + * Subtracts the given scalar value from all components of this instance. + * + * @param {number} s - The scalar to subtract. + * @return {Vector4} A reference to this vector. + */ + subScalar(s5) { + this.x -= s5; + this.y -= s5; + this.z -= s5; + this.w -= s5; + return this; + } + /** + * Subtracts the given vectors and stores the result in this instance. + * + * @param {Vector4} a - The first vector. + * @param {Vector4} b - The second vector. + * @return {Vector4} A reference to this vector. + */ + subVectors(a3, b3) { + this.x = a3.x - b3.x; + this.y = a3.y - b3.y; + this.z = a3.z - b3.z; + this.w = a3.w - b3.w; + return this; + } + /** + * Multiplies the given vector with this instance. + * + * @param {Vector4} v - The vector to multiply. + * @return {Vector4} A reference to this vector. + */ + multiply(v2) { + this.x *= v2.x; + this.y *= v2.y; + this.z *= v2.z; + this.w *= v2.w; + return this; + } + /** + * Multiplies the given scalar value with all components of this instance. + * + * @param {number} scalar - The scalar to multiply. + * @return {Vector4} A reference to this vector. + */ + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + /** + * Multiplies this vector with the given 4x4 matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + applyMatrix4(m2) { + const x2 = this.x, y3 = this.y, z2 = this.z, w2 = this.w; + const e8 = m2.elements; + this.x = e8[0] * x2 + e8[4] * y3 + e8[8] * z2 + e8[12] * w2; + this.y = e8[1] * x2 + e8[5] * y3 + e8[9] * z2 + e8[13] * w2; + this.z = e8[2] * x2 + e8[6] * y3 + e8[10] * z2 + e8[14] * w2; + this.w = e8[3] * x2 + e8[7] * y3 + e8[11] * z2 + e8[15] * w2; + return this; + } + /** + * Divides this instance by the given vector. + * + * @param {Vector4} v - The vector to divide. + * @return {Vector4} A reference to this vector. + */ + divide(v2) { + this.x /= v2.x; + this.y /= v2.y; + this.z /= v2.z; + this.w /= v2.w; + return this; + } + /** + * Divides this vector by the given scalar. + * + * @param {number} scalar - The scalar to divide. + * @return {Vector4} A reference to this vector. + */ + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + /** + * Sets the x, y and z components of this + * vector to the quaternion's axis and w to the angle. + * + * @param {Quaternion} q - The Quaternion to set. + * @return {Vector4} A reference to this vector. + */ + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s5 = Math.sqrt(1 - q.w * q.w); + if (s5 < 1e-4) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s5; + this.y = q.y / s5; + this.z = q.z / s5; + } + return this; + } + /** + * Sets the x, y and z components of this + * vector to the axis of rotation and w to the angle. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix. + * @return {Vector4} A reference to this vector. + */ + setAxisAngleFromRotationMatrix(m2) { + let angle, x2, y3, z2; + const epsilon = 0.01, epsilon2 = 0.1, te = m2.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x2 = 0; + y3 = 0.707106781; + z2 = 0.707106781; + } else { + x2 = Math.sqrt(xx); + y3 = xy / x2; + z2 = xz / x2; + } + } else if (yy > zz) { + if (yy < epsilon) { + x2 = 0.707106781; + y3 = 0; + z2 = 0.707106781; + } else { + y3 = Math.sqrt(yy); + x2 = xy / y3; + z2 = yz / y3; + } + } else { + if (zz < epsilon) { + x2 = 0.707106781; + y3 = 0.707106781; + z2 = 0; + } else { + z2 = Math.sqrt(zz); + x2 = xz / z2; + y3 = yz / z2; + } + } + this.set(x2, y3, z2, angle); + return this; + } + let s5 = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s5) < 1e-3) s5 = 1; + this.x = (m32 - m23) / s5; + this.y = (m13 - m31) / s5; + this.z = (m21 - m12) / s5; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + /** + * Sets the vector components to the position elements of the + * given transformation matrix. + * + * @param {Matrix4} m - The 4x4 matrix. + * @return {Vector4} A reference to this vector. + */ + setFromMatrixPosition(m2) { + const e8 = m2.elements; + this.x = e8[12]; + this.y = e8[13]; + this.z = e8[14]; + this.w = e8[15]; + return this; + } + /** + * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w + * value, replace that value with the corresponding min value. + * + * @param {Vector4} v - The vector. + * @return {Vector4} A reference to this vector. + */ + min(v2) { + this.x = Math.min(this.x, v2.x); + this.y = Math.min(this.y, v2.y); + this.z = Math.min(this.z, v2.z); + this.w = Math.min(this.w, v2.w); + return this; + } + /** + * If this vector's x, y, z or w value is less than the given vector's x, y, z or w + * value, replace that value with the corresponding max value. + * + * @param {Vector4} v - The vector. + * @return {Vector4} A reference to this vector. + */ + max(v2) { + this.x = Math.max(this.x, v2.x); + this.y = Math.max(this.y, v2.y); + this.z = Math.max(this.z, v2.z); + this.w = Math.max(this.w, v2.w); + return this; + } + /** + * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w + * value, it is replaced by the corresponding value. + * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value, + * it is replaced by the corresponding value. + * + * @param {Vector4} min - The minimum x, y and z values. + * @param {Vector4} max - The maximum x, y and z values in the desired range. + * @return {Vector4} A reference to this vector. + */ + clamp(min, max) { + this.x = clamp(this.x, min.x, max.x); + this.y = clamp(this.y, min.y, max.y); + this.z = clamp(this.z, min.z, max.z); + this.w = clamp(this.w, min.w, max.w); + return this; + } + /** + * If this vector's x, y, z or w values are greater than the max value, they are + * replaced by the max value. + * If this vector's x, y, z or w values are less than the min value, they are + * replaced by the min value. + * + * @param {number} minVal - The minimum value the components will be clamped to. + * @param {number} maxVal - The maximum value the components will be clamped to. + * @return {Vector4} A reference to this vector. + */ + clampScalar(minVal, maxVal) { + this.x = clamp(this.x, minVal, maxVal); + this.y = clamp(this.y, minVal, maxVal); + this.z = clamp(this.z, minVal, maxVal); + this.w = clamp(this.w, minVal, maxVal); + return this; + } + /** + * If this vector's length is greater than the max value, it is replaced by + * the max value. + * If this vector's length is less than the min value, it is replaced by the + * min value. + * + * @param {number} min - The minimum value the vector length will be clamped to. + * @param {number} max - The maximum value the vector length will be clamped to. + * @return {Vector4} A reference to this vector. + */ + clampLength(min, max) { + const length = this.length(); + return this.divideScalar(length || 1).multiplyScalar(clamp(length, min, max)); + } + /** + * The components of this vector are rounded down to the nearest integer value. + * + * @return {Vector4} A reference to this vector. + */ + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + /** + * The components of this vector are rounded up to the nearest integer value. + * + * @return {Vector4} A reference to this vector. + */ + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + /** + * The components of this vector are rounded to the nearest integer value + * + * @return {Vector4} A reference to this vector. + */ + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + /** + * The components of this vector are rounded towards zero (up if negative, + * down if positive) to an integer value. + * + * @return {Vector4} A reference to this vector. + */ + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + /** + * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w. + * + * @return {Vector4} A reference to this vector. + */ + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + /** + * Calculates the dot product of the given vector with this instance. + * + * @param {Vector4} v - The vector to compute the dot product with. + * @return {number} The result of the dot product. + */ + dot(v2) { + return this.x * v2.x + this.y * v2.y + this.z * v2.z + this.w * v2.w; + } + /** + * Computes the square of the Euclidean length (straight-line length) from + * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should + * compare the length squared instead as it is slightly more efficient to calculate. + * + * @return {number} The square length of this vector. + */ + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + /** + * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w). + * + * @return {number} The length of this vector. + */ + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + /** + * Computes the Manhattan length of this vector. + * + * @return {number} The length of this vector. + */ + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + /** + * Converts this vector to a unit vector - that is, sets it equal to a vector + * with the same direction as this one, but with a vector length of `1`. + * + * @return {Vector4} A reference to this vector. + */ + normalize() { + return this.divideScalar(this.length() || 1); + } + /** + * Sets this vector to a vector with the same direction as this one, but + * with the specified length. + * + * @param {number} length - The new length of this vector. + * @return {Vector4} A reference to this vector. + */ + setLength(length) { + return this.normalize().multiplyScalar(length); + } + /** + * Linearly interpolates between the given vector and this instance, where + * alpha is the percent distance along the line - alpha = 0 will be this + * vector, and alpha = 1 will be the given one. + * + * @param {Vector4} v - The vector to interpolate towards. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector4} A reference to this vector. + */ + lerp(v2, alpha) { + this.x += (v2.x - this.x) * alpha; + this.y += (v2.y - this.y) * alpha; + this.z += (v2.z - this.z) * alpha; + this.w += (v2.w - this.w) * alpha; + return this; + } + /** + * Linearly interpolates between the given vectors, where alpha is the percent + * distance along the line - alpha = 0 will be first vector, and alpha = 1 will + * be the second one. The result is stored in this instance. + * + * @param {Vector4} v1 - The first vector. + * @param {Vector4} v2 - The second vector. + * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. + * @return {Vector4} A reference to this vector. + */ + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + /** + * Returns `true` if this vector is equal with the given one. + * + * @param {Vector4} v - The vector to test for equality. + * @return {boolean} Whether this vector is equal with the given one. + */ + equals(v2) { + return v2.x === this.x && v2.y === this.y && v2.z === this.z && v2.w === this.w; + } + /** + * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`, + * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`. + * + * @param {Array} array - An array holding the vector component values. + * @param {number} [offset=0] - The offset into the array. + * @return {Vector4} A reference to this vector. + */ + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + /** + * Writes the components of this vector to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the vector components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The vector components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + /** + * Sets the components of this vector from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding vector data. + * @param {number} index - The index into the attribute. + * @return {Vector4} A reference to this vector. + */ + fromBufferAttribute(attribute, index) { + this.x = attribute.getX(index); + this.y = attribute.getY(index); + this.z = attribute.getZ(index); + this.w = attribute.getW(index); + return this; + } + /** + * Sets each component of this vector to a pseudo-random value between `0` and + * `1`, excluding `1`. + * + * @return {Vector4} A reference to this vector. + */ + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } +}; +var RenderTarget = class extends EventDispatcher { + /** + * Render target options. + * + * @typedef {Object} RenderTarget~Options + * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not. + * @property {number} [magFilter=LinearFilter] - The mag filter. + * @property {number} [minFilter=LinearFilter] - The min filter. + * @property {number} [format=RGBAFormat] - The texture format. + * @property {number} [type=UnsignedByteType] - The texture type. + * @property {?string} [internalFormat=null] - The texture's internal format. + * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode. + * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode. + * @property {number} [anisotropy=1] - The texture's anisotropy value. + * @property {string} [colorSpace=NoColorSpace] - The texture's color space. + * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not. + * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not. + * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not. + * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not. + * @property {?Texture} [depthTexture=null] - Reference to a depth texture. + * @property {number} [samples=0] - The MSAA samples count. + * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`. + * @property {number} [depth=1] - The texture depth. + * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering. + */ + /** + * Constructs a new render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, options = {}) { + super(); + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1, + depth: 1, + multiview: false + }, options); + this.isRenderTarget = true; + this.width = width; + this.height = height; + this.depth = options.depth; + this.scissor = new Vector4(0, 0, width, height); + this.scissorTest = false; + this.viewport = new Vector4(0, 0, width, height); + const image = { width, height, depth: options.depth }; + const texture = new Texture(image); + this.textures = []; + const count = options.count; + for (let i6 = 0; i6 < count; i6++) { + this.textures[i6] = texture.clone(); + this.textures[i6].isRenderTargetTexture = true; + this.textures[i6].renderTarget = this; + } + this._setTextureOptions(options); + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + this.multiview = options.multiview; + } + _setTextureOptions(options = {}) { + const values = { + minFilter: LinearFilter, + generateMipmaps: false, + flipY: false, + internalFormat: null + }; + if (options.mapping !== void 0) values.mapping = options.mapping; + if (options.wrapS !== void 0) values.wrapS = options.wrapS; + if (options.wrapT !== void 0) values.wrapT = options.wrapT; + if (options.wrapR !== void 0) values.wrapR = options.wrapR; + if (options.magFilter !== void 0) values.magFilter = options.magFilter; + if (options.minFilter !== void 0) values.minFilter = options.minFilter; + if (options.format !== void 0) values.format = options.format; + if (options.type !== void 0) values.type = options.type; + if (options.anisotropy !== void 0) values.anisotropy = options.anisotropy; + if (options.colorSpace !== void 0) values.colorSpace = options.colorSpace; + if (options.flipY !== void 0) values.flipY = options.flipY; + if (options.generateMipmaps !== void 0) values.generateMipmaps = options.generateMipmaps; + if (options.internalFormat !== void 0) values.internalFormat = options.internalFormat; + for (let i6 = 0; i6 < this.textures.length; i6++) { + const texture = this.textures[i6]; + texture.setValues(values); + } + } + /** + * The texture representing the default color attachment. + * + * @type {Texture} + */ + get texture() { + return this.textures[0]; + } + set texture(value) { + this.textures[0] = value; + } + set depthTexture(current) { + if (this._depthTexture !== null) this._depthTexture.renderTarget = null; + if (current !== null) current.renderTarget = this; + this._depthTexture = current; + } + /** + * Instead of saving the depth in a renderbuffer, a texture + * can be used instead which is useful for further processing + * e.g. in context of post-processing. + * + * @type {?DepthTexture} + * @default null + */ + get depthTexture() { + return this._depthTexture; + } + /** + * Sets the size of this render target. + * + * @param {number} width - The width. + * @param {number} height - The height. + * @param {number} [depth=1] - The depth. + */ + setSize(width, height, depth = 1) { + if (this.width !== width || this.height !== height || this.depth !== depth) { + this.width = width; + this.height = height; + this.depth = depth; + for (let i6 = 0, il = this.textures.length; i6 < il; i6++) { + this.textures[i6].image.width = width; + this.textures[i6].image.height = height; + this.textures[i6].image.depth = depth; + this.textures[i6].isArrayTexture = this.textures[i6].image.depth > 1; + } + this.dispose(); + } + this.viewport.set(0, 0, width, height); + this.scissor.set(0, 0, width, height); + } + /** + * Returns a new render target with copied values from this instance. + * + * @return {RenderTarget} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the settings of the given render target. This is a structural copy so + * no resources are shared between render targets after the copy. That includes + * all MRT textures and the depth texture. + * + * @param {RenderTarget} source - The render target to copy. + * @return {RenderTarget} A reference to this instance. + */ + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i6 = 0, il = source.textures.length; i6 < il; i6++) { + this.textures[i6] = source.textures[i6].clone(); + this.textures[i6].isRenderTargetTexture = true; + this.textures[i6].renderTarget = this; + const image = Object.assign({}, source.textures[i6].image); + this.textures[i6].source = new Source(image); + } + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires RenderTarget#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +}; +var WebGLRenderTarget = class extends RenderTarget { + /** + * Constructs a new 3D render target. + * + * @param {number} [width=1] - The width of the render target. + * @param {number} [height=1] - The height of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(width = 1, height = 1, options = {}) { + super(width, height, options); + this.isWebGLRenderTarget = true; + } +}; +var DataArrayTexture = class extends Texture { + /** + * Constructs a new data array texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor(data = null, width = 1, height = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data, width, height, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = /* @__PURE__ */ new Set(); + } + /** + * Describes that a specific layer of the texture needs to be updated. + * Normally when {@link Texture#needsUpdate} is set to `true`, the + * entire data texture array is sent to the GPU. Marking specific + * layers will only transmit subsets of all mipmaps associated with a + * specific depth in the array which is often much more performant. + * + * @param {number} layerIndex - The layer index that should be updated. + */ + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + /** + * Resets the layer updates registry. + */ + clearLayerUpdates() { + this.layerUpdates.clear(); + } +}; +var Data3DTexture = class extends Texture { + /** + * Constructs a new data array texture. + * + * @param {?TypedArray} [data=null] - The buffer data. + * @param {number} [width=1] - The width of the texture. + * @param {number} [height=1] - The height of the texture. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor(data = null, width = 1, height = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data, width, height, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +}; +var Box3 = class { + /** + * Constructs a new bounding box. + * + * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box. + * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box. + */ + constructor(min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + /** + * Sets the lower and upper boundaries of this box. + * Please note that this method only copies the values from the given objects. + * + * @param {Vector3} min - The lower boundary of the box. + * @param {Vector3} max - The upper boundary of the box. + * @return {Box3} A reference to this bounding box. + */ + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} array - An array holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromArray(array) { + this.makeEmpty(); + for (let i6 = 0, il = array.length; i6 < il; i6 += 3) { + this.expandByPoint(_vector$b.fromArray(array, i6)); + } + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given buffer attribute. + * + * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data. + * @return {Box3} A reference to this bounding box. + */ + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i6 = 0, il = attribute.count; i6 < il; i6++) { + this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i6)); + } + return this; + } + /** + * Sets the upper and lower bounds of this box so it encloses the position data + * in the given array. + * + * @param {Array} points - An array holding 3D position data as instances of {@link Vector3}. + * @return {Box3} A reference to this bounding box. + */ + setFromPoints(points) { + this.makeEmpty(); + for (let i6 = 0, il = points.length; i6 < il; i6++) { + this.expandByPoint(points[i6]); + } + return this; + } + /** + * Centers this box on the given center vector and sets this box's width, height and + * depth to the given size values. + * + * @param {Vector3} center - The center of the box. + * @param {Vector3} size - The x, y and z dimensions of the box. + * @return {Box3} A reference to this bounding box. + */ + setFromCenterAndSize(center, size) { + const halfSize = _vector$b.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + /** + * Computes the world-axis-aligned bounding box for the given 3D object + * (including its children), accounting for the object's, and children's, + * world transforms. The function may result in a larger box than strictly necessary. + * + * @param {Object3D} object - The 3D object to compute the bounding box for. + * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest + * world-axis-aligned bounding box at the expense of more computation. + * @return {Box3} A reference to this bounding box. + */ + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + /** + * Returns a new box with copied values from this instance. + * + * @return {Box3} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given box to this instance. + * + * @param {Box3} box - The box to copy. + * @return {Box3} A reference to this bounding box. + */ + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + /** + * Makes this box empty which means in encloses a zero space in 3D. + * + * @return {Box3} A reference to this bounding box. + */ + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + /** + * Returns true if this box includes zero points within its bounds. + * Note that a box with equal lower and upper bounds still includes one + * point, the one both bounds share. + * + * @return {boolean} Whether this box is empty or not. + */ + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + /** + * Returns the center point of this box. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The center point. + */ + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + /** + * Returns the dimensions of this box. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The size. + */ + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + /** + * Expands the boundaries of this box to include the given point. + * + * @param {Vector3} point - The point that should be included by the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + /** + * Expands this box equilaterally by the given vector. The width of this + * box will be expanded by the x component of the vector in both + * directions. The height of this box will be expanded by the y component of + * the vector in both directions. The depth of this box will be + * expanded by the z component of the vector in both directions. + * + * @param {Vector3} vector - The vector that should expand the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + /** + * Expands each dimension of the box by the given scalar. If negative, the + * dimensions of the box will be contracted. + * + * @param {number} scalar - The scalar value that should expand the bounding box. + * @return {Box3} A reference to this bounding box. + */ + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + /** + * Expands the boundaries of this box to include the given 3D object and + * its children, accounting for the object's, and children's, world + * transforms. The function may result in a larger box than strictly + * necessary (unless the precise parameter is set to true). + * + * @param {Object3D} object - The 3D object that should expand the bounding box. + * @param {boolean} precise - If set to `true`, the method expands the bounding box + * as little as necessary at the expense of more computation. + * @return {Box3} A reference to this bounding box. + */ + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== void 0) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== void 0 && object.isInstancedMesh !== true) { + for (let i6 = 0, l3 = positionAttribute.count; i6 < l3; i6++) { + if (object.isMesh === true) { + object.getVertexPosition(i6, _vector$b); + } else { + _vector$b.fromBufferAttribute(positionAttribute, i6); + } + _vector$b.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b); + } + } else { + if (object.boundingBox !== void 0) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$4.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$4.copy(geometry.boundingBox); + } + _box$4.applyMatrix4(object.matrixWorld); + this.union(_box$4); + } + } + const children = object.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + this.expandByObject(children[i6], precise); + } + return this; + } + /** + * Returns `true` if the given point lies within or on the boundaries of this box. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the bounding box contains the given point or not. + */ + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + /** + * Returns `true` if this bounding box includes the entirety of the given bounding box. + * If this box and the given one are identical, this function also returns `true`. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the bounding box contains the given bounding box or not. + */ + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + /** + * Returns a point as a proportion of this box's width, height and depth. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} A point as a proportion of this box's width, height and depth. + */ + getParameter(point, target) { + return target.set( + (point.x - this.min.x) / (this.max.x - this.min.x), + (point.y - this.min.y) / (this.max.y - this.min.y), + (point.z - this.min.z) / (this.max.z - this.min.z) + ); + } + /** + * Returns `true` if the given bounding box intersects with this bounding box. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with this bounding box. + */ + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + /** + * Returns `true` if the given bounding sphere intersects with this bounding box. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the given bounding sphere intersects with this bounding box. + */ + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b); + return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + /** + * Returns `true` if the given plane intersects with this bounding box. + * + * @param {Plane} plane - The plane to test. + * @return {boolean} Whether the given plane intersects with this bounding box. + */ + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + /** + * Returns `true` if the given triangle intersects with this bounding box. + * + * @param {Triangle} triangle - The triangle to test. + * @return {boolean} Whether the given triangle intersects with this bounding box. + */ + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center); + _extents.subVectors(this.max, _center); + _v0$2.subVectors(triangle.a, _center); + _v1$7.subVectors(triangle.b, _center); + _v2$4.subVectors(triangle.c, _center); + _f0.subVectors(_v1$7, _v0$2); + _f1.subVectors(_v2$4, _v1$7); + _f2.subVectors(_v0$2, _v2$4); + let axes = [ + 0, + -_f0.z, + _f0.y, + 0, + -_f1.z, + _f1.y, + 0, + -_f2.z, + _f2.y, + _f0.z, + 0, + -_f0.x, + _f1.z, + 0, + -_f1.x, + _f2.z, + 0, + -_f2.x, + -_f0.y, + _f0.x, + 0, + -_f1.y, + _f1.x, + 0, + -_f2.y, + _f2.x, + 0 + ]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + _triangleNormal.crossVectors(_f0, _f1); + axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; + return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents); + } + /** + * Clamps the given point within the bounds of this box. + * + * @param {Vector3} point - The point to clamp. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The clamped point. + */ + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + /** + * Returns the euclidean distance from any edge of this box to the specified point. If + * the given point lies inside of this box, the distance will be `0`. + * + * @param {Vector3} point - The point to compute the distance to. + * @return {number} The euclidean distance. + */ + distanceToPoint(point) { + return this.clampPoint(point, _vector$b).distanceTo(point); + } + /** + * Returns a bounding sphere that encloses this bounding box. + * + * @param {Sphere} target - The target sphere that is used to store the method's result. + * @return {Sphere} The bounding sphere that encloses this bounding box. + */ + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b).length() * 0.5; + } + return target; + } + /** + * Computes the intersection of this bounding box and the given one, setting the upper + * bound of this box to the lesser of the two boxes' upper bounds and the + * lower bound of this box to the greater of the two boxes' lower bounds. If + * there's no overlap, makes this box empty. + * + * @param {Box3} box - The bounding box to intersect with. + * @return {Box3} A reference to this bounding box. + */ + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) this.makeEmpty(); + return this; + } + /** + * Computes the union of this box and another and the given one, setting the upper + * bound of this box to the greater of the two boxes' upper bounds and the + * lower bound of this box to the lesser of the two boxes' lower bounds. + * + * @param {Box3} box - The bounding box that will be unioned with this instance. + * @return {Box3} A reference to this bounding box. + */ + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + /** + * Transforms this bounding box by the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Box3} A reference to this bounding box. + */ + applyMatrix4(matrix) { + if (this.isEmpty()) return this; + _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points); + return this; + } + /** + * Adds the given offset to both the upper and lower bounds of this bounding box, + * effectively moving it in 3D space. + * + * @param {Vector3} offset - The offset that should be used to translate the bounding box. + * @return {Box3} A reference to this bounding box. + */ + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + /** + * Returns `true` if this bounding box is equal with the given one. + * + * @param {Box3} box - The box to test for equality. + * @return {boolean} Whether this bounding box is equal with the given one. + */ + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + /** + * Returns a serialized structure of the bounding box. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + return { + min: this.min.toArray(), + max: this.max.toArray() + }; + } + /** + * Returns a serialized structure of the bounding box. + * + * @param {Object} json - The serialized json to set the box from. + * @return {Box3} A reference to this bounding box. + */ + fromJSON(json) { + this.min.fromArray(json.min); + this.max.fromArray(json.max); + return this; + } +}; +var _points = [ + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3(), + /* @__PURE__ */ new Vector3() +]; +var _vector$b = /* @__PURE__ */ new Vector3(); +var _box$4 = /* @__PURE__ */ new Box3(); +var _v0$2 = /* @__PURE__ */ new Vector3(); +var _v1$7 = /* @__PURE__ */ new Vector3(); +var _v2$4 = /* @__PURE__ */ new Vector3(); +var _f0 = /* @__PURE__ */ new Vector3(); +var _f1 = /* @__PURE__ */ new Vector3(); +var _f2 = /* @__PURE__ */ new Vector3(); +var _center = /* @__PURE__ */ new Vector3(); +var _extents = /* @__PURE__ */ new Vector3(); +var _triangleNormal = /* @__PURE__ */ new Vector3(); +var _testAxis = /* @__PURE__ */ new Vector3(); +function satForAxes(axes, v0, v1, v2, extents) { + for (let i6 = 0, j2 = axes.length - 3; i6 <= j2; i6 += 3) { + _testAxis.fromArray(axes, i6); + const r6 = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); + const p0 = v0.dot(_testAxis); + const p1 = v1.dot(_testAxis); + const p22 = v2.dot(_testAxis); + if (Math.max(-Math.max(p0, p1, p22), Math.min(p0, p1, p22)) > r6) { + return false; + } + } + return true; +} +var _box$3 = /* @__PURE__ */ new Box3(); +var _v1$6 = /* @__PURE__ */ new Vector3(); +var _v2$3 = /* @__PURE__ */ new Vector3(); +var Sphere = class { + /** + * Constructs a new sphere. + * + * @param {Vector3} [center=(0,0,0)] - The center of the sphere + * @param {number} [radius=-1] - The radius of the sphere. + */ + constructor(center = new Vector3(), radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + /** + * Sets the sphere's components by copying the given values. + * + * @param {Vector3} center - The center. + * @param {number} radius - The radius. + * @return {Sphere} A reference to this sphere. + */ + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + /** + * Computes the minimum bounding sphere for list of points. + * If the optional center point is given, it is used as the sphere's + * center. Otherwise, the center of the axis-aligned bounding box + * encompassing the points is calculated. + * + * @param {Array} points - A list of points in 3D space. + * @param {Vector3} [optionalCenter] - The center of the sphere. + * @return {Sphere} A reference to this sphere. + */ + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== void 0) { + center.copy(optionalCenter); + } else { + _box$3.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i6 = 0, il = points.length; i6 < il; i6++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i6])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + /** + * Copies the values of the given sphere to this instance. + * + * @param {Sphere} sphere - The sphere to copy. + * @return {Sphere} A reference to this sphere. + */ + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + /** + * Returns `true` if the sphere is empty (the radius set to a negative number). + * + * Spheres with a radius of `0` contain only their center point and are not + * considered to be empty. + * + * @return {boolean} Whether this sphere is empty or not. + */ + isEmpty() { + return this.radius < 0; + } + /** + * Makes this sphere empty which means in encloses a zero space in 3D. + * + * @return {Sphere} A reference to this sphere. + */ + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + /** + * Returns `true` if this sphere contains the given point inclusive of + * the surface of the sphere. + * + * @param {Vector3} point - The point to check. + * @return {boolean} Whether this sphere contains the given point or not. + */ + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + /** + * Returns the closest distance from the boundary of the sphere to the + * given point. If the sphere contains the point, the distance will + * be negative. + * + * @param {Vector3} point - The point to compute the distance to. + * @return {number} The distance to the point. + */ + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + /** + * Returns `true` if this sphere intersects with the given one. + * + * @param {Sphere} sphere - The sphere to test. + * @return {boolean} Whether this sphere intersects with the given one or not. + */ + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + /** + * Returns `true` if this sphere intersects with the given box. + * + * @param {Box3} box - The box to test. + * @return {boolean} Whether this sphere intersects with the given box or not. + */ + intersectsBox(box) { + return box.intersectsSphere(this); + } + /** + * Returns `true` if this sphere intersects with the given plane. + * + * @param {Plane} plane - The plane to test. + * @return {boolean} Whether this sphere intersects with the given plane or not. + */ + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + /** + * Clamps a point within the sphere. If the point is outside the sphere, it + * will clamp it to the closest point on the edge of the sphere. Points + * already inside the sphere will not be affected. + * + * @param {Vector3} point - The plane to clamp. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The clamped point. + */ + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + /** + * Returns a bounding box that encloses this sphere. + * + * @param {Box3} target - The target box that is used to store the method's result. + * @return {Box3} The bounding box that encloses this sphere. + */ + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + /** + * Transforms this sphere with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix - The transformation matrix. + * @return {Sphere} A reference to this sphere. + */ + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + /** + * Translates the sphere's center by the given offset. + * + * @param {Vector3} offset - The offset. + * @return {Sphere} A reference to this sphere. + */ + translate(offset) { + this.center.add(offset); + return this; + } + /** + * Expands the boundaries of this sphere to include the given point. + * + * @param {Vector3} point - The point to include. + * @return {Sphere} A reference to this sphere. + */ + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$6.subVectors(point, this.center); + const lengthSq = _v1$6.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length = Math.sqrt(lengthSq); + const delta = (length - this.radius) * 0.5; + this.center.addScaledVector(_v1$6, delta / length); + this.radius += delta; + } + return this; + } + /** + * Expands this sphere to enclose both the original sphere and the given sphere. + * + * @param {Sphere} sphere - The sphere to include. + * @return {Sphere} A reference to this sphere. + */ + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3)); + this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3)); + } + return this; + } + /** + * Returns `true` if this sphere is equal with the given one. + * + * @param {Sphere} sphere - The sphere to test for equality. + * @return {boolean} Whether this bounding sphere is equal with the given one. + */ + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + /** + * Returns a new sphere with copied values from this instance. + * + * @return {Sphere} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Returns a serialized structure of the bounding sphere. + * + * @return {Object} Serialized structure with fields representing the object state. + */ + toJSON() { + return { + radius: this.radius, + center: this.center.toArray() + }; + } + /** + * Returns a serialized structure of the bounding sphere. + * + * @param {Object} json - The serialized json to set the sphere from. + * @return {Box3} A reference to this bounding sphere. + */ + fromJSON(json) { + this.radius = json.radius; + this.center.fromArray(json.center); + return this; + } +}; +var _vector$a = /* @__PURE__ */ new Vector3(); +var _segCenter = /* @__PURE__ */ new Vector3(); +var _segDir = /* @__PURE__ */ new Vector3(); +var _diff = /* @__PURE__ */ new Vector3(); +var _edge1 = /* @__PURE__ */ new Vector3(); +var _edge2 = /* @__PURE__ */ new Vector3(); +var _normal$1 = /* @__PURE__ */ new Vector3(); +var Ray = class { + /** + * Constructs a new ray. + * + * @param {Vector3} [origin=(0,0,0)] - The origin of the ray. + * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray. + */ + constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + /** + * Sets the ray's components by copying the given values. + * + * @param {Vector3} origin - The origin. + * @param {Vector3} direction - The direction. + * @return {Ray} A reference to this ray. + */ + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + /** + * Copies the values of the given ray to this instance. + * + * @param {Ray} ray - The ray to copy. + * @return {Ray} A reference to this ray. + */ + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + /** + * Returns a vector that is located at a given distance along this ray. + * + * @param {number} t - The distance along the ray to retrieve a position for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} A position on the ray. + */ + at(t6, target) { + return target.copy(this.origin).addScaledVector(this.direction, t6); + } + /** + * Adjusts the direction of the ray to point at the given vector in world space. + * + * @param {Vector3} v - The target position. + * @return {Ray} A reference to this ray. + */ + lookAt(v2) { + this.direction.copy(v2).sub(this.origin).normalize(); + return this; + } + /** + * Shift the origin of this ray along its direction by the given distance. + * + * @param {number} t - The distance along the ray to interpolate. + * @return {Ray} A reference to this ray. + */ + recast(t6) { + this.origin.copy(this.at(t6, _vector$a)); + return this; + } + /** + * Returns the point along this ray that is closest to the given point. + * + * @param {Vector3} point - A point in 3D space to get the closet location on the ray for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on this ray. + */ + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + /** + * Returns the distance of the closest approach between this ray and the given point. + * + * @param {Vector3} point - A point in 3D space to compute the distance to. + * @return {number} The distance. + */ + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + /** + * Returns the squared distance of the closest approach between this ray and the given point. + * + * @param {Vector3} point - A point in 3D space to compute the distance to. + * @return {number} The squared distance. + */ + distanceSqToPoint(point) { + const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a.distanceToSquared(point); + } + /** + * Returns the squared distance between this ray and the given line segment. + * + * @param {Vector3} v0 - The start point of the line segment. + * @param {Vector3} v1 - The end point of the line segment. + * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment. + * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray. + * @return {number} The squared distance. + */ + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter.copy(v0).add(v1).multiplyScalar(0.5); + _segDir.copy(v1).sub(v0).normalize(); + _diff.copy(this.origin).sub(_segCenter); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir); + const b0 = _diff.dot(this.direction); + const b1 = -_diff.dot(_segDir); + const c5 = _diff.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c5; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c5; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c5; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c5; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c5; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c5; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c5; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1); + } + return sqrDist; + } + /** + * Intersects this ray with the given sphere, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Sphere} sphere - The sphere to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectSphere(sphere, target) { + _vector$a.subVectors(sphere.center, this.origin); + const tca = _vector$a.dot(this.direction); + const d22 = _vector$a.dot(_vector$a) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d22 > radius2) return null; + const thc = Math.sqrt(radius2 - d22); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) return null; + if (t0 < 0) return this.at(t1, target); + return this.at(t0, target); + } + /** + * Returns `true` if this ray intersects with the given sphere. + * + * @param {Sphere} sphere - The sphere to intersect. + * @return {boolean} Whether this ray intersects with the given sphere or not. + */ + intersectsSphere(sphere) { + if (sphere.radius < 0) return false; + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + /** + * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray + * does not intersect with the plane. + * + * @param {Plane} plane - The plane to compute the distance to. + * @return {?number} Whether this ray intersects with the given sphere or not. + */ + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t6 = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t6 >= 0 ? t6 : null; + } + /** + * Intersects this ray with the given plane, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Plane} plane - The plane to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectPlane(plane, target) { + const t6 = this.distanceToPlane(plane); + if (t6 === null) { + return null; + } + return this.at(t6, target); + } + /** + * Returns `true` if this ray intersects with the given plane. + * + * @param {Plane} plane - The plane to intersect. + * @return {boolean} Whether this ray intersects with the given plane or not. + */ + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + /** + * Intersects this ray with the given bounding box, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Box3} box - The box to intersect. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) return null; + if (tymin > tmin || isNaN(tmin)) tmin = tymin; + if (tymax < tmax || isNaN(tmax)) tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) return null; + if (tzmin > tmin || tmin !== tmin) tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) tmax = tzmax; + if (tmax < 0) return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + /** + * Returns `true` if this ray intersects with the given box. + * + * @param {Box3} box - The box to intersect. + * @return {boolean} Whether this ray intersects with the given box or not. + */ + intersectsBox(box) { + return this.intersectBox(box, _vector$a) !== null; + } + /** + * Intersects this ray with the given triangle, returning the intersection + * point or `null` if there is no intersection. + * + * @param {Vector3} a - The first vertex of the triangle. + * @param {Vector3} b - The second vertex of the triangle. + * @param {Vector3} c - The third vertex of the triangle. + * @param {boolean} backfaceCulling - Whether to use backface culling or not. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectTriangle(a3, b3, c5, backfaceCulling, target) { + _edge1.subVectors(b3, a3); + _edge2.subVectors(c5, a3); + _normal$1.crossVectors(_edge1, _edge2); + let DdN = this.direction.dot(_normal$1); + let sign; + if (DdN > 0) { + if (backfaceCulling) return null; + sign = 1; + } else if (DdN < 0) { + sign = -1; + DdN = -DdN; + } else { + return null; + } + _diff.subVectors(this.origin, a3); + const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign * _diff.dot(_normal$1); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + /** + * Transforms this ray with the given 4x4 transformation matrix. + * + * @param {Matrix4} matrix4 - The transformation matrix. + * @return {Ray} A reference to this ray. + */ + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + /** + * Returns `true` if this ray is equal with the given one. + * + * @param {Ray} ray - The ray to test for equality. + * @return {boolean} Whether this ray is equal with the given one. + */ + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + /** + * Returns a new ray with copied values from this instance. + * + * @return {Ray} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } +}; +var Matrix4 = class _Matrix4 { + /** + * Constructs a new 4x4 matrix. The arguments are supposed to be + * in row-major order. If no arguments are provided, the constructor + * initializes the matrix as an identity matrix. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n14] - 1-4 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n24] - 2-4 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @param {number} [n34] - 3-4 matrix element. + * @param {number} [n41] - 4-1 matrix element. + * @param {number} [n42] - 4-2 matrix element. + * @param {number} [n43] - 4-3 matrix element. + * @param {number} [n44] - 4-4 matrix element. + */ + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + _Matrix4.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== void 0) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + /** + * Sets the elements of the matrix.The arguments are supposed to be + * in row-major order. + * + * @param {number} [n11] - 1-1 matrix element. + * @param {number} [n12] - 1-2 matrix element. + * @param {number} [n13] - 1-3 matrix element. + * @param {number} [n14] - 1-4 matrix element. + * @param {number} [n21] - 2-1 matrix element. + * @param {number} [n22] - 2-2 matrix element. + * @param {number} [n23] - 2-3 matrix element. + * @param {number} [n24] - 2-4 matrix element. + * @param {number} [n31] - 3-1 matrix element. + * @param {number} [n32] - 3-2 matrix element. + * @param {number} [n33] - 3-3 matrix element. + * @param {number} [n34] - 3-4 matrix element. + * @param {number} [n41] - 4-1 matrix element. + * @param {number} [n42] - 4-2 matrix element. + * @param {number} [n43] - 4-3 matrix element. + * @param {number} [n44] - 4-4 matrix element. + * @return {Matrix4} A reference to this matrix. + */ + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te = this.elements; + te[0] = n11; + te[4] = n12; + te[8] = n13; + te[12] = n14; + te[1] = n21; + te[5] = n22; + te[9] = n23; + te[13] = n24; + te[2] = n31; + te[6] = n32; + te[10] = n33; + te[14] = n34; + te[3] = n41; + te[7] = n42; + te[11] = n43; + te[15] = n44; + return this; + } + /** + * Sets this matrix to the 4x4 identity matrix. + * + * @return {Matrix4} A reference to this matrix. + */ + identity() { + this.set( + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Returns a matrix with copied values from this instance. + * + * @return {Matrix4} A clone of this instance. + */ + clone() { + return new _Matrix4().fromArray(this.elements); + } + /** + * Copies the values of the given matrix to this instance. + * + * @param {Matrix4} m - The matrix to copy. + * @return {Matrix4} A reference to this matrix. + */ + copy(m2) { + const te = this.elements; + const me = m2.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + te[9] = me[9]; + te[10] = me[10]; + te[11] = me[11]; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + te[15] = me[15]; + return this; + } + /** + * Copies the translation component of the given matrix + * into this matrix's translation component. + * + * @param {Matrix4} m - The matrix to copy the translation component. + * @return {Matrix4} A reference to this matrix. + */ + copyPosition(m2) { + const te = this.elements, me = m2.elements; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + return this; + } + /** + * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix. + * + * @param {Matrix3} m - The 3x3 matrix. + * @return {Matrix4} A reference to this matrix. + */ + setFromMatrix3(m2) { + const me = m2.elements; + this.set( + me[0], + me[3], + me[6], + 0, + me[1], + me[4], + me[7], + 0, + me[2], + me[5], + me[8], + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Extracts the basis of this matrix into the three axis vectors provided. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix4} A reference to this matrix. + */ + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + /** + * Sets the given basis vectors to this matrix. + * + * @param {Vector3} xAxis - The basis's x axis. + * @param {Vector3} yAxis - The basis's y axis. + * @param {Vector3} zAxis - The basis's z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeBasis(xAxis, yAxis, zAxis) { + this.set( + xAxis.x, + yAxis.x, + zAxis.x, + 0, + xAxis.y, + yAxis.y, + zAxis.y, + 0, + xAxis.z, + yAxis.z, + zAxis.z, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Extracts the rotation component of the given matrix + * into this matrix's rotation component. + * + * Note: This method does not support reflection matrices. + * + * @param {Matrix4} m - The matrix. + * @return {Matrix4} A reference to this matrix. + */ + extractRotation(m2) { + const te = this.elements; + const me = m2.elements; + const scaleX = 1 / _v1$5.setFromMatrixColumn(m2, 0).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn(m2, 1).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn(m2, 2).length(); + te[0] = me[0] * scaleX; + te[1] = me[1] * scaleX; + te[2] = me[2] * scaleX; + te[3] = 0; + te[4] = me[4] * scaleY; + te[5] = me[5] * scaleY; + te[6] = me[6] * scaleY; + te[7] = 0; + te[8] = me[8] * scaleZ; + te[9] = me[9] * scaleZ; + te[10] = me[10] * scaleZ; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + /** + * Sets the rotation component (the upper left 3x3 matrix) of this matrix to + * the rotation specified by the given Euler angles. The rest of + * the matrix is set to the identity. Depending on the {@link Euler#order}, + * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix} + * for a complete list. + * + * @param {Euler} euler - The Euler angles. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationFromEuler(euler) { + const te = this.elements; + const x2 = euler.x, y3 = euler.y, z2 = euler.z; + const a3 = Math.cos(x2), b3 = Math.sin(x2); + const c5 = Math.cos(y3), d3 = Math.sin(y3); + const e8 = Math.cos(z2), f4 = Math.sin(z2); + if (euler.order === "XYZ") { + const ae = a3 * e8, af = a3 * f4, be = b3 * e8, bf = b3 * f4; + te[0] = c5 * e8; + te[4] = -c5 * f4; + te[8] = d3; + te[1] = af + be * d3; + te[5] = ae - bf * d3; + te[9] = -b3 * c5; + te[2] = bf - ae * d3; + te[6] = be + af * d3; + te[10] = a3 * c5; + } else if (euler.order === "YXZ") { + const ce = c5 * e8, cf = c5 * f4, de = d3 * e8, df = d3 * f4; + te[0] = ce + df * b3; + te[4] = de * b3 - cf; + te[8] = a3 * d3; + te[1] = a3 * f4; + te[5] = a3 * e8; + te[9] = -b3; + te[2] = cf * b3 - de; + te[6] = df + ce * b3; + te[10] = a3 * c5; + } else if (euler.order === "ZXY") { + const ce = c5 * e8, cf = c5 * f4, de = d3 * e8, df = d3 * f4; + te[0] = ce - df * b3; + te[4] = -a3 * f4; + te[8] = de + cf * b3; + te[1] = cf + de * b3; + te[5] = a3 * e8; + te[9] = df - ce * b3; + te[2] = -a3 * d3; + te[6] = b3; + te[10] = a3 * c5; + } else if (euler.order === "ZYX") { + const ae = a3 * e8, af = a3 * f4, be = b3 * e8, bf = b3 * f4; + te[0] = c5 * e8; + te[4] = be * d3 - af; + te[8] = ae * d3 + bf; + te[1] = c5 * f4; + te[5] = bf * d3 + ae; + te[9] = af * d3 - be; + te[2] = -d3; + te[6] = b3 * c5; + te[10] = a3 * c5; + } else if (euler.order === "YZX") { + const ac = a3 * c5, ad = a3 * d3, bc = b3 * c5, bd = b3 * d3; + te[0] = c5 * e8; + te[4] = bd - ac * f4; + te[8] = bc * f4 + ad; + te[1] = f4; + te[5] = a3 * e8; + te[9] = -b3 * e8; + te[2] = -d3 * e8; + te[6] = ad * f4 + bc; + te[10] = ac - bd * f4; + } else if (euler.order === "XZY") { + const ac = a3 * c5, ad = a3 * d3, bc = b3 * c5, bd = b3 * d3; + te[0] = c5 * e8; + te[4] = -f4; + te[8] = d3 * e8; + te[1] = ac * f4 + bd; + te[5] = a3 * e8; + te[9] = ad * f4 - bc; + te[2] = bc * f4 - ad; + te[6] = b3 * e8; + te[10] = bd * f4 + ac; + } + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + /** + * Sets the rotation component of this matrix to the rotation specified by + * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion} + * The rest of the matrix is set to the identity. + * + * @param {Quaternion} q - The Quaternion. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationFromQuaternion(q) { + return this.compose(_zero, q, _one); + } + /** + * Sets the rotation component of the transformation matrix, looking from `eye` towards + * `target`, and oriented by the up-direction. + * + * @param {Vector3} eye - The eye vector. + * @param {Vector3} target - The target vector. + * @param {Vector3} up - The up vector. + * @return {Matrix4} A reference to this matrix. + */ + lookAt(eye, target, up) { + const te = this.elements; + _z.subVectors(eye, target); + if (_z.lengthSq() === 0) { + _z.z = 1; + } + _z.normalize(); + _x.crossVectors(up, _z); + if (_x.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z.x += 1e-4; + } else { + _z.z += 1e-4; + } + _z.normalize(); + _x.crossVectors(up, _z); + } + _x.normalize(); + _y.crossVectors(_z, _x); + te[0] = _x.x; + te[4] = _y.x; + te[8] = _z.x; + te[1] = _x.y; + te[5] = _y.y; + te[9] = _z.y; + te[2] = _x.z; + te[6] = _y.z; + te[10] = _z.z; + return this; + } + /** + * Post-multiplies this matrix by the given 4x4 matrix. + * + * @param {Matrix4} m - The matrix to multiply with. + * @return {Matrix4} A reference to this matrix. + */ + multiply(m2) { + return this.multiplyMatrices(this, m2); + } + /** + * Pre-multiplies this matrix by the given 4x4 matrix. + * + * @param {Matrix4} m - The matrix to multiply with. + * @return {Matrix4} A reference to this matrix. + */ + premultiply(m2) { + return this.multiplyMatrices(m2, this); + } + /** + * Multiples the given 4x4 matrices and stores the result + * in this matrix. + * + * @param {Matrix4} a - The first matrix. + * @param {Matrix4} b - The second matrix. + * @return {Matrix4} A reference to this matrix. + */ + multiplyMatrices(a3, b3) { + const ae = a3.elements; + const be = b3.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; + const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; + const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; + const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + /** + * Multiplies every component of the matrix by the given scalar. + * + * @param {number} s - The scalar. + * @return {Matrix4} A reference to this matrix. + */ + multiplyScalar(s5) { + const te = this.elements; + te[0] *= s5; + te[4] *= s5; + te[8] *= s5; + te[12] *= s5; + te[1] *= s5; + te[5] *= s5; + te[9] *= s5; + te[13] *= s5; + te[2] *= s5; + te[6] *= s5; + te[10] *= s5; + te[14] *= s5; + te[3] *= s5; + te[7] *= s5; + te[11] *= s5; + te[15] *= s5; + return this; + } + /** + * Computes and returns the determinant of this matrix. + * + * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}. + * + * @return {number} The determinant. + */ + determinant() { + const te = this.elements; + const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; + const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; + const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; + const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + /** + * Transposes this matrix in place. + * + * @return {Matrix4} A reference to this matrix. + */ + transpose() { + const te = this.elements; + let tmp; + tmp = te[1]; + te[1] = te[4]; + te[4] = tmp; + tmp = te[2]; + te[2] = te[8]; + te[8] = tmp; + tmp = te[6]; + te[6] = te[9]; + te[9] = tmp; + tmp = te[3]; + te[3] = te[12]; + te[12] = tmp; + tmp = te[7]; + te[7] = te[13]; + te[13] = tmp; + tmp = te[11]; + te[11] = te[14]; + te[14] = tmp; + return this; + } + /** + * Sets the position component for this matrix from the given vector, + * without affecting the rest of the matrix. + * + * @param {number|Vector3} x - The x component of the vector or alternatively the vector object. + * @param {number} y - The y component of the vector. + * @param {number} z - The z component of the vector. + * @return {Matrix4} A reference to this matrix. + */ + setPosition(x2, y3, z2) { + const te = this.elements; + if (x2.isVector3) { + te[12] = x2.x; + te[13] = x2.y; + te[14] = x2.z; + } else { + te[12] = x2; + te[13] = y3; + te[14] = z2; + } + return this; + } + /** + * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}. + * You can not invert with a determinant of zero. If you attempt this, the method produces + * a zero matrix instead. + * + * @return {Matrix4} A reference to this matrix. + */ + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te[4] = t12 * detInv; + te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te[8] = t13 * detInv; + te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te[12] = t14 * detInv; + te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + /** + * Multiplies the columns of this matrix by the given vector. + * + * @param {Vector3} v - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + scale(v2) { + const te = this.elements; + const x2 = v2.x, y3 = v2.y, z2 = v2.z; + te[0] *= x2; + te[4] *= y3; + te[8] *= z2; + te[1] *= x2; + te[5] *= y3; + te[9] *= z2; + te[2] *= x2; + te[6] *= y3; + te[10] *= z2; + te[3] *= x2; + te[7] *= y3; + te[11] *= z2; + return this; + } + /** + * Gets the maximum scale value of the three axes. + * + * @return {number} The maximum scale. + */ + getMaxScaleOnAxis() { + const te = this.elements; + const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; + const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; + const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + /** + * Sets this matrix as a translation transform from the given vector. + * + * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector. + * @param {number} y - The amount to translate in the Y axis. + * @param {number} z - The amount to translate in the z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeTranslation(x2, y3, z2) { + if (x2.isVector3) { + this.set( + 1, + 0, + 0, + x2.x, + 0, + 1, + 0, + x2.y, + 0, + 0, + 1, + x2.z, + 0, + 0, + 0, + 1 + ); + } else { + this.set( + 1, + 0, + 0, + x2, + 0, + 1, + 0, + y3, + 0, + 0, + 1, + z2, + 0, + 0, + 0, + 1 + ); + } + return this; + } + /** + * Sets this matrix as a rotational transformation around the X axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationX(theta) { + const c5 = Math.cos(theta), s5 = Math.sin(theta); + this.set( + 1, + 0, + 0, + 0, + 0, + c5, + -s5, + 0, + 0, + s5, + c5, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a rotational transformation around the Y axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationY(theta) { + const c5 = Math.cos(theta), s5 = Math.sin(theta); + this.set( + c5, + 0, + s5, + 0, + 0, + 1, + 0, + 0, + -s5, + 0, + c5, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a rotational transformation around the Z axis by + * the given angle. + * + * @param {number} theta - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationZ(theta) { + const c5 = Math.cos(theta), s5 = Math.sin(theta); + this.set( + c5, + -s5, + 0, + 0, + s5, + c5, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a rotational transformation around the given axis by + * the given angle. + * + * This is a somewhat controversial but mathematically sound alternative to + * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}. + * + * @param {Vector3} axis - The normalized rotation axis. + * @param {number} angle - The rotation in radians. + * @return {Matrix4} A reference to this matrix. + */ + makeRotationAxis(axis, angle) { + const c5 = Math.cos(angle); + const s5 = Math.sin(angle); + const t6 = 1 - c5; + const x2 = axis.x, y3 = axis.y, z2 = axis.z; + const tx = t6 * x2, ty = t6 * y3; + this.set( + tx * x2 + c5, + tx * y3 - s5 * z2, + tx * z2 + s5 * y3, + 0, + tx * y3 + s5 * z2, + ty * y3 + c5, + ty * z2 - s5 * x2, + 0, + tx * z2 - s5 * y3, + ty * z2 + s5 * x2, + t6 * z2 * z2 + c5, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a scale transformation. + * + * @param {number} x - The amount to scale in the X axis. + * @param {number} y - The amount to scale in the Y axis. + * @param {number} z - The amount to scale in the Z axis. + * @return {Matrix4} A reference to this matrix. + */ + makeScale(x2, y3, z2) { + this.set( + x2, + 0, + 0, + 0, + 0, + y3, + 0, + 0, + 0, + 0, + z2, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix as a shear transformation. + * + * @param {number} xy - The amount to shear X by Y. + * @param {number} xz - The amount to shear X by Z. + * @param {number} yx - The amount to shear Y by X. + * @param {number} yz - The amount to shear Y by Z. + * @param {number} zx - The amount to shear Z by X. + * @param {number} zy - The amount to shear Z by Y. + * @return {Matrix4} A reference to this matrix. + */ + makeShear(xy, xz, yx, yz, zx, zy) { + this.set( + 1, + yx, + zx, + 0, + xy, + 1, + zy, + 0, + xz, + yz, + 1, + 0, + 0, + 0, + 0, + 1 + ); + return this; + } + /** + * Sets this matrix to the transformation composed of the given position, + * rotation (Quaternion) and scale. + * + * @param {Vector3} position - The position vector. + * @param {Quaternion} quaternion - The rotation as a Quaternion. + * @param {Vector3} scale - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + compose(position, quaternion, scale) { + const te = this.elements; + const x2 = quaternion._x, y3 = quaternion._y, z2 = quaternion._z, w2 = quaternion._w; + const x22 = x2 + x2, y22 = y3 + y3, z22 = z2 + z2; + const xx = x2 * x22, xy = x2 * y22, xz = x2 * z22; + const yy = y3 * y22, yz = y3 * z22, zz = z2 * z22; + const wx = w2 * x22, wy = w2 * y22, wz = w2 * z22; + const sx = scale.x, sy = scale.y, sz = scale.z; + te[0] = (1 - (yy + zz)) * sx; + te[1] = (xy + wz) * sx; + te[2] = (xz - wy) * sx; + te[3] = 0; + te[4] = (xy - wz) * sy; + te[5] = (1 - (xx + zz)) * sy; + te[6] = (yz + wx) * sy; + te[7] = 0; + te[8] = (xz + wy) * sz; + te[9] = (yz - wx) * sz; + te[10] = (1 - (xx + yy)) * sz; + te[11] = 0; + te[12] = position.x; + te[13] = position.y; + te[14] = position.z; + te[15] = 1; + return this; + } + /** + * Decomposes this matrix into its position, rotation and scale components + * and provides the result in the given objects. + * + * Note: Not all matrices are decomposable in this way. For example, if an + * object has a non-uniformly scaled parent, then the object's world matrix + * may not be decomposable, and this method may not be appropriate. + * + * @param {Vector3} position - The position vector. + * @param {Quaternion} quaternion - The rotation as a Quaternion. + * @param {Vector3} scale - The scale vector. + * @return {Matrix4} A reference to this matrix. + */ + decompose(position, quaternion, scale) { + const te = this.elements; + let sx = _v1$5.set(te[0], te[1], te[2]).length(); + const sy = _v1$5.set(te[4], te[5], te[6]).length(); + const sz = _v1$5.set(te[8], te[9], te[10]).length(); + const det = this.determinant(); + if (det < 0) sx = -sx; + position.x = te[12]; + position.y = te[13]; + position.z = te[14]; + _m1$2.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$2.elements[0] *= invSX; + _m1$2.elements[1] *= invSX; + _m1$2.elements[2] *= invSX; + _m1$2.elements[4] *= invSY; + _m1$2.elements[5] *= invSY; + _m1$2.elements[6] *= invSY; + _m1$2.elements[8] *= invSZ; + _m1$2.elements[9] *= invSZ; + _m1$2.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$2); + scale.x = sx; + scale.y = sy; + scale.z = sz; + return this; + } + /** + * Creates a perspective projection matrix. This is used internally by + * {@link PerspectiveCamera#updateProjectionMatrix}. + + * @param {number} left - Left boundary of the viewing frustum at the near plane. + * @param {number} right - Right boundary of the viewing frustum at the near plane. + * @param {number} top - Top boundary of the viewing frustum at the near plane. + * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. + * @param {number} near - The distance from the camera to the near plane. + * @param {number} far - The distance from the camera to the far plane. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Matrix4} A reference to this matrix. + */ + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) { + const te = this.elements; + const x2 = 2 * near / (right - left); + const y3 = 2 * near / (top - bottom); + const a3 = (right + left) / (right - left); + const b3 = (top + bottom) / (top - bottom); + let c5, d3; + if (reversedDepth) { + c5 = near / (far - near); + d3 = far * near / (far - near); + } else { + if (coordinateSystem === WebGLCoordinateSystem) { + c5 = -(far + near) / (far - near); + d3 = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c5 = -far / (far - near); + d3 = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + } + te[0] = x2; + te[4] = 0; + te[8] = a3; + te[12] = 0; + te[1] = 0; + te[5] = y3; + te[9] = b3; + te[13] = 0; + te[2] = 0; + te[6] = 0; + te[10] = c5; + te[14] = d3; + te[3] = 0; + te[7] = 0; + te[11] = -1; + te[15] = 0; + return this; + } + /** + * Creates a orthographic projection matrix. This is used internally by + * {@link OrthographicCamera#updateProjectionMatrix}. + + * @param {number} left - Left boundary of the viewing frustum at the near plane. + * @param {number} right - Right boundary of the viewing frustum at the near plane. + * @param {number} top - Top boundary of the viewing frustum at the near plane. + * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. + * @param {number} near - The distance from the camera to the near plane. + * @param {number} far - The distance from the camera to the far plane. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Matrix4} A reference to this matrix. + */ + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) { + const te = this.elements; + const x2 = 2 / (right - left); + const y3 = 2 / (top - bottom); + const a3 = -(right + left) / (right - left); + const b3 = -(top + bottom) / (top - bottom); + let c5, d3; + if (reversedDepth) { + c5 = 1 / (far - near); + d3 = far / (far - near); + } else { + if (coordinateSystem === WebGLCoordinateSystem) { + c5 = -2 / (far - near); + d3 = -(far + near) / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c5 = -1 / (far - near); + d3 = -near / (far - near); + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + } + te[0] = x2; + te[4] = 0; + te[8] = 0; + te[12] = a3; + te[1] = 0; + te[5] = y3; + te[9] = 0; + te[13] = b3; + te[2] = 0; + te[6] = 0; + te[10] = c5; + te[14] = d3; + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[15] = 1; + return this; + } + /** + * Returns `true` if this matrix is equal with the given one. + * + * @param {Matrix4} matrix - The matrix to test for equality. + * @return {boolean} Whether this matrix is equal with the given one. + */ + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i6 = 0; i6 < 16; i6++) { + if (te[i6] !== me[i6]) return false; + } + return true; + } + /** + * Sets the elements of the matrix from the given array. + * + * @param {Array} array - The matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Matrix4} A reference to this matrix. + */ + fromArray(array, offset = 0) { + for (let i6 = 0; i6 < 16; i6++) { + this.elements[i6] = array[i6 + offset]; + } + return this; + } + /** + * Writes the elements of this matrix to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the matrix elements in column-major order. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The matrix elements in column-major order. + */ + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + array[offset + 9] = te[9]; + array[offset + 10] = te[10]; + array[offset + 11] = te[11]; + array[offset + 12] = te[12]; + array[offset + 13] = te[13]; + array[offset + 14] = te[14]; + array[offset + 15] = te[15]; + return array; + } +}; +var _v1$5 = /* @__PURE__ */ new Vector3(); +var _m1$2 = /* @__PURE__ */ new Matrix4(); +var _zero = /* @__PURE__ */ new Vector3(0, 0, 0); +var _one = /* @__PURE__ */ new Vector3(1, 1, 1); +var _x = /* @__PURE__ */ new Vector3(); +var _y = /* @__PURE__ */ new Vector3(); +var _z = /* @__PURE__ */ new Vector3(); +var _matrix$2 = /* @__PURE__ */ new Matrix4(); +var _quaternion$3 = /* @__PURE__ */ new Quaternion(); +var Euler = class _Euler { + /** + * Constructs a new euler instance. + * + * @param {number} [x=0] - The angle of the x axis in radians. + * @param {number} [y=0] - The angle of the y axis in radians. + * @param {number} [z=0] - The angle of the z axis in radians. + * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied. + */ + constructor(x2 = 0, y3 = 0, z2 = 0, order = _Euler.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x2; + this._y = y3; + this._z = z2; + this._order = order; + } + /** + * The angle of the x axis in radians. + * + * @type {number} + * @default 0 + */ + get x() { + return this._x; + } + set x(value) { + this._x = value; + this._onChangeCallback(); + } + /** + * The angle of the y axis in radians. + * + * @type {number} + * @default 0 + */ + get y() { + return this._y; + } + set y(value) { + this._y = value; + this._onChangeCallback(); + } + /** + * The angle of the z axis in radians. + * + * @type {number} + * @default 0 + */ + get z() { + return this._z; + } + set z(value) { + this._z = value; + this._onChangeCallback(); + } + /** + * A string representing the order that the rotations are applied. + * + * @type {string} + * @default 'XYZ' + */ + get order() { + return this._order; + } + set order(value) { + this._order = value; + this._onChangeCallback(); + } + /** + * Sets the Euler components. + * + * @param {number} x - The angle of the x axis in radians. + * @param {number} y - The angle of the y axis in radians. + * @param {number} z - The angle of the z axis in radians. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + set(x2, y3, z2, order = this._order) { + this._x = x2; + this._y = y3; + this._z = z2; + this._order = order; + this._onChangeCallback(); + return this; + } + /** + * Returns a new Euler instance with copied values from this instance. + * + * @return {Euler} A clone of this instance. + */ + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + /** + * Copies the values of the given Euler instance to this instance. + * + * @param {Euler} euler - The Euler instance to copy. + * @return {Euler} A reference to this Euler instance. + */ + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + /** + * Sets the angles of this Euler instance from a pure rotation matrix. + * + * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). + * @param {string} [order] - A string representing the order that the rotations are applied. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Euler} A reference to this Euler instance. + */ + setFromRotationMatrix(m2, order = this._order, update = true) { + const te = m2.elements; + const m11 = te[0], m12 = te[4], m13 = te[8]; + const m21 = te[1], m22 = te[5], m23 = te[9]; + const m31 = te[2], m32 = te[6], m33 = te[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) this._onChangeCallback(); + return this; + } + /** + * Sets the angles of this Euler instance from a normalized quaternion. + * + * @param {Quaternion} q - A normalized Quaternion. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. + * @return {Euler} A reference to this Euler instance. + */ + setFromQuaternion(q, order, update) { + _matrix$2.makeRotationFromQuaternion(q); + return this.setFromRotationMatrix(_matrix$2, order, update); + } + /** + * Sets the angles of this Euler instance from the given vector. + * + * @param {Vector3} v - The vector. + * @param {string} [order] - A string representing the order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + setFromVector3(v2, order = this._order) { + return this.set(v2.x, v2.y, v2.z, order); + } + /** + * Resets the euler angle with a new order by creating a quaternion from this + * euler angle and then setting this euler angle with the quaternion and the + * new order. + * + * Warning: This discards revolution information. + * + * @param {string} [newOrder] - A string representing the new order that the rotations are applied. + * @return {Euler} A reference to this Euler instance. + */ + reorder(newOrder) { + _quaternion$3.setFromEuler(this); + return this.setFromQuaternion(_quaternion$3, newOrder); + } + /** + * Returns `true` if this Euler instance is equal with the given one. + * + * @param {Euler} euler - The Euler instance to test for equality. + * @return {boolean} Whether this Euler instance is equal with the given one. + */ + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + /** + * Sets this Euler instance's components to values from the given array. The first three + * entries of the array are assign to the x,y and z components. An optional fourth entry + * defines the Euler order. + * + * @param {Array} array - An array holding the Euler component values. + * @return {Euler} A reference to this Euler instance. + */ + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== void 0) this._order = array[3]; + this._onChangeCallback(); + return this; + } + /** + * Writes the components of this Euler instance to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the Euler components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The Euler components. + */ + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } +}; +Euler.DEFAULT_ORDER = "XYZ"; +var Layers = class { + /** + * Constructs a new layers instance, with membership + * initially set to layer `0`. + */ + constructor() { + this.mask = 1 | 0; + } + /** + * Sets membership to the given layer, and remove membership all other layers. + * + * @param {number} layer - The layer to set. + */ + set(layer) { + this.mask = (1 << layer | 0) >>> 0; + } + /** + * Adds membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + enable(layer) { + this.mask |= 1 << layer | 0; + } + /** + * Adds membership to all layers. + */ + enableAll() { + this.mask = 4294967295 | 0; + } + /** + * Toggles the membership of the given layer. + * + * @param {number} layer - The layer to toggle. + */ + toggle(layer) { + this.mask ^= 1 << layer | 0; + } + /** + * Removes membership of the given layer. + * + * @param {number} layer - The layer to enable. + */ + disable(layer) { + this.mask &= ~(1 << layer | 0); + } + /** + * Removes the membership from all layers. + */ + disableAll() { + this.mask = 0; + } + /** + * Returns `true` if this and the given layers object have at least one + * layer in common. + * + * @param {Layers} layers - The layers to test. + * @return {boolean } Whether this and the given layers object have at least one layer in common or not. + */ + test(layers) { + return (this.mask & layers.mask) !== 0; + } + /** + * Returns `true` if the given layer is enabled. + * + * @param {number} layer - The layer to test. + * @return {boolean } Whether the given layer is enabled or not. + */ + isEnabled(layer) { + return (this.mask & (1 << layer | 0)) !== 0; + } +}; +var _object3DId = 0; +var _v1$4 = /* @__PURE__ */ new Vector3(); +var _q1 = /* @__PURE__ */ new Quaternion(); +var _m1$1 = /* @__PURE__ */ new Matrix4(); +var _target = /* @__PURE__ */ new Vector3(); +var _position$3 = /* @__PURE__ */ new Vector3(); +var _scale$2 = /* @__PURE__ */ new Vector3(); +var _quaternion$2 = /* @__PURE__ */ new Quaternion(); +var _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0); +var _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0); +var _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1); +var _addedEvent = { type: "added" }; +var _removedEvent = { type: "removed" }; +var _childaddedEvent = { type: "childadded", child: null }; +var _childremovedEvent = { type: "childremoved", child: null }; +var Object3D = class _Object3D extends EventDispatcher { + /** + * Constructs a new 3D object. + */ + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = _Object3D.DEFAULT_UP.clone(); + const position = new Vector3(); + const rotation = new Euler(); + const quaternion = new Quaternion(); + const scale = new Vector3(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation, false); + } + function onQuaternionChange() { + rotation.setFromQuaternion(quaternion, void 0, false); + } + rotation._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + /** + * Represents the object's local position. + * + * @name Object3D#position + * @type {Vector3} + * @default (0,0,0) + */ + position: { + configurable: true, + enumerable: true, + value: position + }, + /** + * Represents the object's local rotation as Euler angles, in radians. + * + * @name Object3D#rotation + * @type {Euler} + * @default (0,0,0) + */ + rotation: { + configurable: true, + enumerable: true, + value: rotation + }, + /** + * Represents the object's local rotation as Quaternions. + * + * @name Object3D#quaternion + * @type {Quaternion} + */ + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + /** + * Represents the object's local scale. + * + * @name Object3D#scale + * @type {Vector3} + * @default (1,1,1) + */ + scale: { + configurable: true, + enumerable: true, + value: scale + }, + /** + * Represents the object's model-view matrix. + * + * @name Object3D#modelViewMatrix + * @type {Matrix4} + */ + modelViewMatrix: { + value: new Matrix4() + }, + /** + * Represents the object's normal matrix. + * + * @name Object3D#normalMatrix + * @type {Matrix3} + */ + normalMatrix: { + value: new Matrix3() + } + }); + this.matrix = new Matrix4(); + this.matrixWorld = new Matrix4(); + this.matrixAutoUpdate = _Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = _Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers(); + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.customDepthMaterial = void 0; + this.customDistanceMaterial = void 0; + this.userData = {}; + } + /** + * A callback that is executed immediately before a 3D object is rendered to a shadow map. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {Camera} shadowCamera - The shadow camera. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} depthMaterial - The depth material. + * @param {Object} group - The geometry group data. + */ + onBeforeShadow() { + } + /** + * A callback that is executed immediately after a 3D object is rendered to a shadow map. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {Camera} shadowCamera - The shadow camera. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} depthMaterial - The depth material. + * @param {Object} group - The geometry group data. + */ + onAfterShadow() { + } + /** + * A callback that is executed immediately before a 3D object is rendered. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} material - The 3D object's material. + * @param {Object} group - The geometry group data. + */ + onBeforeRender() { + } + /** + * A callback that is executed immediately after a 3D object is rendered. + * + * @param {Renderer|WebGLRenderer} renderer - The renderer. + * @param {Object3D} object - The 3D object. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Material} material - The 3D object's material. + * @param {Object} group - The geometry group data. + */ + onAfterRender() { + } + /** + * Applies the given transformation matrix to the object and updates the object's position, + * rotation and scale. + * + * @param {Matrix4} matrix - The transformation matrix. + */ + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + /** + * Applies a rotation represented by given the quaternion to the 3D object. + * + * @param {Quaternion} q - The quaternion. + * @return {Object3D} A reference to this instance. + */ + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + /** + * Sets the given rotation represented as an axis/angle couple to the 3D object. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + */ + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + /** + * Sets the given rotation represented as Euler angles to the 3D object. + * + * @param {Euler} euler - The Euler angles. + */ + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + /** + * Sets the given rotation represented as rotation matrix to the 3D object. + * + * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be + * a pure rotation matrix (i.e, unscaled). + */ + setRotationFromMatrix(m2) { + this.quaternion.setFromRotationMatrix(m2); + } + /** + * Sets the given rotation represented as a Quaternion to the 3D object. + * + * @param {Quaternion} q - The Quaternion + */ + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + /** + * Rotates the 3D object along an axis in local space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateOnAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q1); + return this; + } + /** + * Rotates the 3D object along an axis in world space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateOnWorldAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q1); + return this; + } + /** + * Rotates the 3D object around its X axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateX(angle) { + return this.rotateOnAxis(_xAxis, angle); + } + /** + * Rotates the 3D object around its Y axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateY(angle) { + return this.rotateOnAxis(_yAxis, angle); + } + /** + * Rotates the 3D object around its Z axis in local space. + * + * @param {number} angle - The angle in radians. + * @return {Object3D} A reference to this instance. + */ + rotateZ(angle) { + return this.rotateOnAxis(_zAxis, angle); + } + /** + * Translate the 3D object by a distance along the given axis in local space. + * + * @param {Vector3} axis - The (normalized) axis vector. + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateOnAxis(axis, distance) { + _v1$4.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$4.multiplyScalar(distance)); + return this; + } + /** + * Translate the 3D object by a distance along its X-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateX(distance) { + return this.translateOnAxis(_xAxis, distance); + } + /** + * Translate the 3D object by a distance along its Y-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateY(distance) { + return this.translateOnAxis(_yAxis, distance); + } + /** + * Translate the 3D object by a distance along its Z-axis in local space. + * + * @param {number} distance - The distance in world units. + * @return {Object3D} A reference to this instance. + */ + translateZ(distance) { + return this.translateOnAxis(_zAxis, distance); + } + /** + * Converts the given vector from this 3D object's local space to world space. + * + * @param {Vector3} vector - The vector to convert. + * @return {Vector3} The converted vector. + */ + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + /** + * Converts the given vector from this 3D object's word space to local space. + * + * @param {Vector3} vector - The vector to convert. + * @return {Vector3} The converted vector. + */ + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); + } + /** + * Rotates the object to face a point in world space. + * + * This method does not support objects having non-uniformly-scaled parent(s). + * + * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space + * @param {number} [y] - The y coordinate in world space. + * @param {number} [z] - The z coordinate in world space. + */ + lookAt(x2, y3, z2) { + if (x2.isVector3) { + _target.copy(x2); + } else { + _target.set(x2, y3, z2); + } + const parent = this.parent; + this.updateWorldMatrix(true, false); + _position$3.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$1.lookAt(_position$3, _target, this.up); + } else { + _m1$1.lookAt(_target, _position$3, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$1); + if (parent) { + _m1$1.extractRotation(parent.matrixWorld); + _q1.setFromRotationMatrix(_m1$1); + this.quaternion.premultiply(_q1.invert()); + } + } + /** + * Adds the given 3D object as a child to this 3D object. An arbitrary number of + * objects may be added. Any current parent on an object passed in here will be + * removed, since an object can have at most one parent. + * + * @fires Object3D#added + * @fires Object3D#childadded + * @param {Object3D} object - The 3D object to add. + * @return {Object3D} A reference to this instance. + */ + add(object) { + if (arguments.length > 1) { + for (let i6 = 0; i6 < arguments.length; i6++) { + this.add(arguments[i6]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + /** + * Removes the given 3D object as child from this 3D object. + * An arbitrary number of objects may be removed. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @param {Object3D} object - The 3D object to remove. + * @return {Object3D} A reference to this instance. + */ + remove(object) { + if (arguments.length > 1) { + for (let i6 = 0; i6 < arguments.length; i6++) { + this.remove(arguments[i6]); + } + return this; + } + const index = this.children.indexOf(object); + if (index !== -1) { + object.parent = null; + this.children.splice(index, 1); + object.dispatchEvent(_removedEvent); + _childremovedEvent.child = object; + this.dispatchEvent(_childremovedEvent); + _childremovedEvent.child = null; + } + return this; + } + /** + * Removes this 3D object from its current parent. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @return {Object3D} A reference to this instance. + */ + removeFromParent() { + const parent = this.parent; + if (parent !== null) { + parent.remove(this); + } + return this; + } + /** + * Removes all child objects. + * + * @fires Object3D#removed + * @fires Object3D#childremoved + * @return {Object3D} A reference to this instance. + */ + clear() { + return this.remove(...this.children); + } + /** + * Adds the given 3D object as a child of this 3D object, while maintaining the object's world + * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s). + * + * @fires Object3D#added + * @fires Object3D#childadded + * @param {Object3D} object - The 3D object to attach. + * @return {Object3D} A reference to this instance. + */ + attach(object) { + this.updateWorldMatrix(true, false); + _m1$1.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$1.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$1); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + return this; + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching ID. + * + * @param {number} id - The id. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching name. + * + * @param {string} name - The name. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectByName(name) { + return this.getObjectByProperty("name", name); + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns the first with a matching property value. + * + * @param {string} name - The name of the property. + * @param {any} value - The value. + * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. + */ + getObjectByProperty(name, value) { + if (this[name] === value) return this; + for (let i6 = 0, l3 = this.children.length; i6 < l3; i6++) { + const child = this.children[i6]; + const object = child.getObjectByProperty(name, value); + if (object !== void 0) { + return object; + } + } + return void 0; + } + /** + * Searches through the 3D object and its children, starting with the 3D object + * itself, and returns all 3D objects with a matching property value. + * + * @param {string} name - The name of the property. + * @param {any} value - The value. + * @param {Array} result - The method stores the result in this array. + * @return {Array} The found 3D objects. + */ + getObjectsByProperty(name, value, result = []) { + if (this[name] === value) result.push(this); + const children = this.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + children[i6].getObjectsByProperty(name, value, result); + } + return result; + } + /** + * Returns a vector representing the position of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's position in world space. + */ + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + /** + * Returns a Quaternion representing the position of the 3D object in world space. + * + * @param {Quaternion} target - The target Quaternion the result is stored to. + * @return {Quaternion} The 3D object's rotation in world space. + */ + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, target, _scale$2); + return target; + } + /** + * Returns a vector representing the scale of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's scale in world space. + */ + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, _quaternion$2, target); + return target; + } + /** + * Returns a vector representing the ("look") direction of the 3D object in world space. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's direction in world space. + */ + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e8 = this.matrixWorld.elements; + return target.set(e8[8], e8[9], e8[10]).normalize(); + } + /** + * Abstract method to get intersections between a casted ray and this + * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points} + * implement this method in order to use raycasting. + * + * @abstract + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - An array holding the result of the method. + */ + raycast() { + } + /** + * Executes the callback on this 3D object and all descendants. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverse(callback) { + callback(this); + const children = this.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + children[i6].traverse(callback); + } + } + /** + * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects. + * Descendants of invisible 3D objects are not traversed. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverseVisible(callback) { + if (this.visible === false) return; + callback(this); + const children = this.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + children[i6].traverseVisible(callback); + } + } + /** + * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors. + * + * Note: Modifying the scene graph inside the callback is discouraged. + * + * @param {Function} callback - A callback function that allows to process the current 3D object. + */ + traverseAncestors(callback) { + const parent = this.parent; + if (parent !== null) { + callback(parent); + parent.traverseAncestors(callback); + } + } + /** + * Updates the transformation matrix in local space by computing it from the current + * position, rotation and scale values. + */ + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + /** + * Updates the transformation matrix in world space of this 3D objects and its descendants. + * + * To ensure correct results, this method also recomputes the 3D object's transformation matrix in + * local space. The computation of the local and world matrix can be controlled with the + * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both + * `true` by default. Set these flags to `false` if you need more control over the update matrix process. + * + * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even + * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`. + */ + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + const child = children[i6]; + child.updateMatrixWorld(force); + } + } + /** + * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the + * update of ancestor and descendant nodes. + * + * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not. + * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not. + */ + updateWorldMatrix(updateParents, updateChildren) { + const parent = this.parent; + if (updateParents === true && parent !== null) { + parent.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + const child = children[i6]; + child.updateWorldMatrix(false, true); + } + } + } + /** + * Serializes the 3D object into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized 3D object. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.7, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") object.name = this.name; + if (this.castShadow === true) object.castShadow = true; + if (this.receiveShadow === true) object.receiveShadow = true; + if (this.visible === false) object.visible = false; + if (this.frustumCulled === false) object.frustumCulled = false; + if (this.renderOrder !== 0) object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.geometryInfo = this._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox ? info.boundingBox.toJSON() : void 0, + boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : void 0 + })); + object.instanceInfo = this._instanceInfo.map((info) => ({ ...info })); + object.availableInstanceIds = this._availableInstanceIds.slice(); + object.availableGeometryIds = this._availableGeometryIds.slice(); + object.nextIndexStart = this._nextIndexStart; + object.nextVertexStart = this._nextVertexStart; + object.geometryCount = this._geometryCount; + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.matricesTexture = this._matricesTexture.toJSON(meta); + object.indirectTexture = this._indirectTexture.toJSON(meta); + if (this._colorsTexture !== null) { + object.colorsTexture = this._colorsTexture.toJSON(meta); + } + if (this.boundingSphere !== null) { + object.boundingSphere = this.boundingSphere.toJSON(); + } + if (this.boundingBox !== null) { + object.boundingBox = this.boundingBox.toJSON(); + } + } + function serialize(library, element) { + if (library[element.uuid] === void 0) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== void 0 && parameters.shapes !== void 0) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i6 = 0, l3 = shapes.length; i6 < l3; i6++) { + const shape = shapes[i6]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== void 0) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== void 0) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i6 = 0, l3 = this.material.length; i6 < l3; i6++) { + uuids.push(serialize(meta.materials, this.material[i6])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i6 = 0; i6 < this.children.length; i6++) { + object.children.push(this.children[i6].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i6 = 0; i6 < this.animations.length; i6++) { + const animation = this.animations[i6]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) output.geometries = geometries; + if (materials.length > 0) output.materials = materials; + if (textures.length > 0) output.textures = textures; + if (images.length > 0) output.images = images; + if (shapes.length > 0) output.shapes = shapes; + if (skeletons.length > 0) output.skeletons = skeletons; + if (animations.length > 0) output.animations = animations; + if (nodes.length > 0) output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values = []; + for (const key in cache) { + const data = cache[key]; + delete data.metadata; + values.push(data); + } + return values; + } + } + /** + * Returns a new 3D object with copied values from this instance. + * + * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned. + * @return {Object3D} A clone of this instance. + */ + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + /** + * Copies the values of the given 3D object to this instance. + * + * @param {Object3D} source - The 3D object to copy. + * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned. + * @return {Object3D} A reference to this instance. + */ + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i6 = 0; i6 < source.children.length; i6++) { + const child = source.children[i6]; + this.add(child.clone()); + } + } + return this; + } +}; +Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; +var _v0$1 = /* @__PURE__ */ new Vector3(); +var _v1$3 = /* @__PURE__ */ new Vector3(); +var _v2$2 = /* @__PURE__ */ new Vector3(); +var _v3$2 = /* @__PURE__ */ new Vector3(); +var _vab = /* @__PURE__ */ new Vector3(); +var _vac = /* @__PURE__ */ new Vector3(); +var _vbc = /* @__PURE__ */ new Vector3(); +var _vap = /* @__PURE__ */ new Vector3(); +var _vbp = /* @__PURE__ */ new Vector3(); +var _vcp = /* @__PURE__ */ new Vector3(); +var _v40 = /* @__PURE__ */ new Vector4(); +var _v41 = /* @__PURE__ */ new Vector4(); +var _v42 = /* @__PURE__ */ new Vector4(); +var Triangle = class _Triangle { + /** + * Constructs a new triangle. + * + * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle. + * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle. + * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle. + */ + constructor(a3 = new Vector3(), b3 = new Vector3(), c5 = new Vector3()) { + this.a = a3; + this.b = b3; + this.c = c5; + } + /** + * Computes the normal vector of a triangle. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's normal. + */ + static getNormal(a3, b3, c5, target) { + target.subVectors(c5, b3); + _v0$1.subVectors(a3, b3); + target.cross(_v0$1); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + /** + * Computes a barycentric coordinates from the given vector. + * Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The barycentric coordinates for the given point + */ + static getBarycoord(point, a3, b3, c5, target) { + _v0$1.subVectors(c5, a3); + _v1$3.subVectors(b3, a3); + _v2$2.subVectors(point, a3); + const dot00 = _v0$1.dot(_v0$1); + const dot01 = _v0$1.dot(_v1$3); + const dot02 = _v0$1.dot(_v2$2); + const dot11 = _v1$3.dot(_v1$3); + const dot12 = _v1$3.dot(_v2$2); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u3 = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v2 = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u3 - v2, v2, u3); + } + /** + * Returns `true` if the given point, when projected onto the plane of the + * triangle, lies within the triangle. + * + * @param {Vector3} point - The point in 3D space to test. + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @return {boolean} Whether the given point, when projected onto the plane of the + * triangle, lies within the triangle or not. + */ + static containsPoint(point, a3, b3, c5) { + if (this.getBarycoord(point, a3, b3, c5, _v3$2) === null) { + return false; + } + return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1; + } + /** + * Computes the value barycentrically interpolated for the given point on the + * triangle. Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - Position of interpolated point. + * @param {Vector3} p1 - The first corner of the triangle. + * @param {Vector3} p2 - The second corner of the triangle. + * @param {Vector3} p3 - The third corner of the triangle. + * @param {Vector3} v1 - Value to interpolate of first vertex. + * @param {Vector3} v2 - Value to interpolate of second vertex. + * @param {Vector3} v3 - Value to interpolate of third vertex. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The interpolated value. + */ + static getInterpolation(point, p1, p22, p3, v1, v2, v3, target) { + if (this.getBarycoord(point, p1, p22, p3, _v3$2) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) target.z = 0; + if ("w" in target) target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$2.x); + target.addScaledVector(v2, _v3$2.y); + target.addScaledVector(v3, _v3$2.z); + return target; + } + /** + * Computes the value barycentrically interpolated for the given attribute and indices. + * + * @param {BufferAttribute} attr - The attribute to interpolate. + * @param {number} i1 - Index of first vertex. + * @param {number} i2 - Index of second vertex. + * @param {number} i3 - Index of third vertex. + * @param {Vector3} barycoord - The barycoordinate value to use to interpolate. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The interpolated attribute value. + */ + static getInterpolatedAttribute(attr, i1, i22, i32, barycoord, target) { + _v40.setScalar(0); + _v41.setScalar(0); + _v42.setScalar(0); + _v40.fromBufferAttribute(attr, i1); + _v41.fromBufferAttribute(attr, i22); + _v42.fromBufferAttribute(attr, i32); + target.setScalar(0); + target.addScaledVector(_v40, barycoord.x); + target.addScaledVector(_v41, barycoord.y); + target.addScaledVector(_v42, barycoord.z); + return target; + } + /** + * Returns `true` if the triangle is oriented towards the given direction. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @param {Vector3} direction - The (normalized) direction vector. + * @return {boolean} Whether the triangle is oriented towards the given direction or not. + */ + static isFrontFacing(a3, b3, c5, direction) { + _v0$1.subVectors(c5, b3); + _v1$3.subVectors(a3, b3); + return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false; + } + /** + * Sets the triangle's vertices by copying the given values. + * + * @param {Vector3} a - The first corner of the triangle. + * @param {Vector3} b - The second corner of the triangle. + * @param {Vector3} c - The third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + set(a3, b3, c5) { + this.a.copy(a3); + this.b.copy(b3); + this.c.copy(c5); + return this; + } + /** + * Sets the triangle's vertices by copying the given array values. + * + * @param {Array} points - An array with 3D points. + * @param {number} i0 - The array index representing the first corner of the triangle. + * @param {number} i1 - The array index representing the second corner of the triangle. + * @param {number} i2 - The array index representing the third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + setFromPointsAndIndices(points, i0, i1, i22) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i22]); + return this; + } + /** + * Sets the triangle's vertices by copying the given attribute values. + * + * @param {BufferAttribute} attribute - A buffer attribute with 3D points data. + * @param {number} i0 - The attribute index representing the first corner of the triangle. + * @param {number} i1 - The attribute index representing the second corner of the triangle. + * @param {number} i2 - The attribute index representing the third corner of the triangle. + * @return {Triangle} A reference to this triangle. + */ + setFromAttributeAndIndices(attribute, i0, i1, i22) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i22); + return this; + } + /** + * Returns a new triangle with copied values from this instance. + * + * @return {Triangle} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given triangle to this instance. + * + * @param {Triangle} triangle - The triangle to copy. + * @return {Triangle} A reference to this triangle. + */ + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + /** + * Computes the area of the triangle. + * + * @return {number} The triangle's area. + */ + getArea() { + _v0$1.subVectors(this.c, this.b); + _v1$3.subVectors(this.a, this.b); + return _v0$1.cross(_v1$3).length() * 0.5; + } + /** + * Computes the midpoint of the triangle. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's midpoint. + */ + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + /** + * Computes the normal of the triangle. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The triangle's normal. + */ + getNormal(target) { + return _Triangle.getNormal(this.a, this.b, this.c, target); + } + /** + * Computes a plane the triangle lies within. + * + * @param {Plane} target - The target vector that is used to store the method's result. + * @return {Plane} The plane the triangle lies within. + */ + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + /** + * Computes a barycentric coordinates from the given vector. + * Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - A point in 3D space. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The barycentric coordinates for the given point + */ + getBarycoord(point, target) { + return _Triangle.getBarycoord(point, this.a, this.b, this.c, target); + } + /** + * Computes the value barycentrically interpolated for the given point on the + * triangle. Returns `null` if the triangle is degenerate. + * + * @param {Vector3} point - Position of interpolated point. + * @param {Vector3} v1 - Value to interpolate of first vertex. + * @param {Vector3} v2 - Value to interpolate of second vertex. + * @param {Vector3} v3 - Value to interpolate of third vertex. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The interpolated value. + */ + getInterpolation(point, v1, v2, v3, target) { + return _Triangle.getInterpolation(point, this.a, this.b, this.c, v1, v2, v3, target); + } + /** + * Returns `true` if the given point, when projected onto the plane of the + * triangle, lies within the triangle. + * + * @param {Vector3} point - The point in 3D space to test. + * @return {boolean} Whether the given point, when projected onto the plane of the + * triangle, lies within the triangle or not. + */ + containsPoint(point) { + return _Triangle.containsPoint(point, this.a, this.b, this.c); + } + /** + * Returns `true` if the triangle is oriented towards the given direction. + * + * @param {Vector3} direction - The (normalized) direction vector. + * @return {boolean} Whether the triangle is oriented towards the given direction or not. + */ + isFrontFacing(direction) { + return _Triangle.isFrontFacing(this.a, this.b, this.c, direction); + } + /** + * Returns `true` if this triangle intersects with the given box. + * + * @param {Box3} box - The box to intersect. + * @return {boolean} Whether this triangle intersects with the given box or not. + */ + intersectsBox(box) { + return box.intersectsTriangle(this); + } + /** + * Returns the closest point on the triangle to the given point. + * + * @param {Vector3} p - The point to compute the closest point for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The closest point on the triangle. + */ + closestPointToPoint(p3, target) { + const a3 = this.a, b3 = this.b, c5 = this.c; + let v2, w2; + _vab.subVectors(b3, a3); + _vac.subVectors(c5, a3); + _vap.subVectors(p3, a3); + const d1 = _vab.dot(_vap); + const d22 = _vac.dot(_vap); + if (d1 <= 0 && d22 <= 0) { + return target.copy(a3); + } + _vbp.subVectors(p3, b3); + const d3 = _vab.dot(_vbp); + const d4 = _vac.dot(_vbp); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b3); + } + const vc = d1 * d4 - d3 * d22; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v2 = d1 / (d1 - d3); + return target.copy(a3).addScaledVector(_vab, v2); + } + _vcp.subVectors(p3, c5); + const d5 = _vab.dot(_vcp); + const d6 = _vac.dot(_vcp); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c5); + } + const vb = d5 * d22 - d1 * d6; + if (vb <= 0 && d22 >= 0 && d6 <= 0) { + w2 = d22 / (d22 - d6); + return target.copy(a3).addScaledVector(_vac, w2); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc.subVectors(c5, b3); + w2 = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b3).addScaledVector(_vbc, w2); + } + const denom = 1 / (va + vb + vc); + v2 = vb * denom; + w2 = vc * denom; + return target.copy(a3).addScaledVector(_vab, v2).addScaledVector(_vac, w2); + } + /** + * Returns `true` if this triangle is equal with the given one. + * + * @param {Triangle} triangle - The triangle to test for equality. + * @return {boolean} Whether this triangle is equal with the given one. + */ + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } +}; +var _colorKeywords = { + "aliceblue": 15792383, + "antiquewhite": 16444375, + "aqua": 65535, + "aquamarine": 8388564, + "azure": 15794175, + "beige": 16119260, + "bisque": 16770244, + "black": 0, + "blanchedalmond": 16772045, + "blue": 255, + "blueviolet": 9055202, + "brown": 10824234, + "burlywood": 14596231, + "cadetblue": 6266528, + "chartreuse": 8388352, + "chocolate": 13789470, + "coral": 16744272, + "cornflowerblue": 6591981, + "cornsilk": 16775388, + "crimson": 14423100, + "cyan": 65535, + "darkblue": 139, + "darkcyan": 35723, + "darkgoldenrod": 12092939, + "darkgray": 11119017, + "darkgreen": 25600, + "darkgrey": 11119017, + "darkkhaki": 12433259, + "darkmagenta": 9109643, + "darkolivegreen": 5597999, + "darkorange": 16747520, + "darkorchid": 10040012, + "darkred": 9109504, + "darksalmon": 15308410, + "darkseagreen": 9419919, + "darkslateblue": 4734347, + "darkslategray": 3100495, + "darkslategrey": 3100495, + "darkturquoise": 52945, + "darkviolet": 9699539, + "deeppink": 16716947, + "deepskyblue": 49151, + "dimgray": 6908265, + "dimgrey": 6908265, + "dodgerblue": 2003199, + "firebrick": 11674146, + "floralwhite": 16775920, + "forestgreen": 2263842, + "fuchsia": 16711935, + "gainsboro": 14474460, + "ghostwhite": 16316671, + "gold": 16766720, + "goldenrod": 14329120, + "gray": 8421504, + "green": 32768, + "greenyellow": 11403055, + "grey": 8421504, + "honeydew": 15794160, + "hotpink": 16738740, + "indianred": 13458524, + "indigo": 4915330, + "ivory": 16777200, + "khaki": 15787660, + "lavender": 15132410, + "lavenderblush": 16773365, + "lawngreen": 8190976, + "lemonchiffon": 16775885, + "lightblue": 11393254, + "lightcoral": 15761536, + "lightcyan": 14745599, + "lightgoldenrodyellow": 16448210, + "lightgray": 13882323, + "lightgreen": 9498256, + "lightgrey": 13882323, + "lightpink": 16758465, + "lightsalmon": 16752762, + "lightseagreen": 2142890, + "lightskyblue": 8900346, + "lightslategray": 7833753, + "lightslategrey": 7833753, + "lightsteelblue": 11584734, + "lightyellow": 16777184, + "lime": 65280, + "limegreen": 3329330, + "linen": 16445670, + "magenta": 16711935, + "maroon": 8388608, + "mediumaquamarine": 6737322, + "mediumblue": 205, + "mediumorchid": 12211667, + "mediumpurple": 9662683, + "mediumseagreen": 3978097, + "mediumslateblue": 8087790, + "mediumspringgreen": 64154, + "mediumturquoise": 4772300, + "mediumvioletred": 13047173, + "midnightblue": 1644912, + "mintcream": 16121850, + "mistyrose": 16770273, + "moccasin": 16770229, + "navajowhite": 16768685, + "navy": 128, + "oldlace": 16643558, + "olive": 8421376, + "olivedrab": 7048739, + "orange": 16753920, + "orangered": 16729344, + "orchid": 14315734, + "palegoldenrod": 15657130, + "palegreen": 10025880, + "paleturquoise": 11529966, + "palevioletred": 14381203, + "papayawhip": 16773077, + "peachpuff": 16767673, + "peru": 13468991, + "pink": 16761035, + "plum": 14524637, + "powderblue": 11591910, + "purple": 8388736, + "rebeccapurple": 6697881, + "red": 16711680, + "rosybrown": 12357519, + "royalblue": 4286945, + "saddlebrown": 9127187, + "salmon": 16416882, + "sandybrown": 16032864, + "seagreen": 3050327, + "seashell": 16774638, + "sienna": 10506797, + "silver": 12632256, + "skyblue": 8900331, + "slateblue": 6970061, + "slategray": 7372944, + "slategrey": 7372944, + "snow": 16775930, + "springgreen": 65407, + "steelblue": 4620980, + "tan": 13808780, + "teal": 32896, + "thistle": 14204888, + "tomato": 16737095, + "turquoise": 4251856, + "violet": 15631086, + "wheat": 16113331, + "white": 16777215, + "whitesmoke": 16119285, + "yellow": 16776960, + "yellowgreen": 10145074 +}; +var _hslA = { h: 0, s: 0, l: 0 }; +var _hslB = { h: 0, s: 0, l: 0 }; +function hue2rgb(p3, q, t6) { + if (t6 < 0) t6 += 1; + if (t6 > 1) t6 -= 1; + if (t6 < 1 / 6) return p3 + (q - p3) * 6 * t6; + if (t6 < 1 / 2) return q; + if (t6 < 2 / 3) return p3 + (q - p3) * 6 * (2 / 3 - t6); + return p3; +} +var Color = class { + /** + * Constructs a new color. + * + * Note that standard method of specifying color in three.js is with a hexadecimal triplet, + * and that method is used throughout the rest of the documentation. + * + * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are + * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. + * @param {number} [g] - The green component. + * @param {number} [b] - The blue component. + */ + constructor(r6, g2, b3) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r6, g2, b3); + } + /** + * Sets the colors's components from the given values. + * + * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are + * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. + * @param {number} [g] - The green component. + * @param {number} [b] - The blue component. + * @return {Color} A reference to this color. + */ + set(r6, g2, b3) { + if (g2 === void 0 && b3 === void 0) { + const value = r6; + if (value && value.isColor) { + this.copy(value); + } else if (typeof value === "number") { + this.setHex(value); + } else if (typeof value === "string") { + this.setStyle(value); + } + } else { + this.setRGB(r6, g2, b3); + } + return this; + } + /** + * Sets the colors's components to the given scalar value. + * + * @param {number} scalar - The scalar value. + * @return {Color} A reference to this color. + */ + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + /** + * Sets this color from a hexadecimal value. + * + * @param {number} hex - The hexadecimal value. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setHex(hex, colorSpace = SRGBColorSpace) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement.colorSpaceToWorking(this, colorSpace); + return this; + } + /** + * Sets this color from RGB values. + * + * @param {number} r - Red channel value between `0.0` and `1.0`. + * @param {number} g - Green channel value between `0.0` and `1.0`. + * @param {number} b - Blue channel value between `0.0` and `1.0`. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setRGB(r6, g2, b3, colorSpace = ColorManagement.workingColorSpace) { + this.r = r6; + this.g = g2; + this.b = b3; + ColorManagement.colorSpaceToWorking(this, colorSpace); + return this; + } + /** + * Sets this color from RGB values. + * + * @param {number} h - Hue value between `0.0` and `1.0`. + * @param {number} s - Saturation value between `0.0` and `1.0`. + * @param {number} l - Lightness value between `0.0` and `1.0`. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setHSL(h4, s5, l3, colorSpace = ColorManagement.workingColorSpace) { + h4 = euclideanModulo(h4, 1); + s5 = clamp(s5, 0, 1); + l3 = clamp(l3, 0, 1); + if (s5 === 0) { + this.r = this.g = this.b = l3; + } else { + const p3 = l3 <= 0.5 ? l3 * (1 + s5) : l3 + s5 - l3 * s5; + const q = 2 * l3 - p3; + this.r = hue2rgb(q, p3, h4 + 1 / 3); + this.g = hue2rgb(q, p3, h4); + this.b = hue2rgb(q, p3, h4 - 1 / 3); + } + ColorManagement.colorSpaceToWorking(this, colorSpace); + return this; + } + /** + * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`, + * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or + * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} - + * all 140 color names are supported). + * + * @param {string} style - Color as a CSS-style string. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setStyle(style, colorSpace = SRGBColorSpace) { + function handleAlpha(string) { + if (string === void 0) return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m2; + if (m2 = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name = m2[1]; + const components = m2[2]; + switch (name) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB( + Math.min(255, parseInt(color[1], 10)) / 255, + Math.min(255, parseInt(color[2], 10)) / 255, + Math.min(255, parseInt(color[3], 10)) / 255, + colorSpace + ); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB( + Math.min(100, parseInt(color[1], 10)) / 100, + Math.min(100, parseInt(color[2], 10)) / 100, + Math.min(100, parseInt(color[3], 10)) / 100, + colorSpace + ); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL( + parseFloat(color[1]) / 360, + parseFloat(color[2]) / 100, + parseFloat(color[3]) / 100, + colorSpace + ); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m2 = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m2[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB( + parseInt(hex.charAt(0), 16) / 15, + parseInt(hex.charAt(1), 16) / 15, + parseInt(hex.charAt(2), 16) / 15, + colorSpace + ); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + /** + * Sets this color from a color name. Faster than {@link Color#setStyle} if + * you don't need the other CSS-style formats. + * + * For convenience, the list of names is exposed in `Color.NAMES` as a hash. + * ```js + * Color.NAMES.aliceblue // returns 0xF0F8FF + * ``` + * + * @param {string} style - The color name. + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {Color} A reference to this color. + */ + setColorName(style, colorSpace = SRGBColorSpace) { + const hex = _colorKeywords[style.toLowerCase()]; + if (hex !== void 0) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + /** + * Returns a new color with copied values from this instance. + * + * @return {Color} A clone of this instance. + */ + clone() { + return new this.constructor(this.r, this.g, this.b); + } + /** + * Copies the values of the given color to this instance. + * + * @param {Color} color - The color to copy. + * @return {Color} A reference to this color. + */ + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + /** + * Copies the given color into this color, and then converts this color from + * `SRGBColorSpace` to `LinearSRGBColorSpace`. + * + * @param {Color} color - The color to copy/convert. + * @return {Color} A reference to this color. + */ + copySRGBToLinear(color) { + this.r = SRGBToLinear(color.r); + this.g = SRGBToLinear(color.g); + this.b = SRGBToLinear(color.b); + return this; + } + /** + * Copies the given color into this color, and then converts this color from + * `LinearSRGBColorSpace` to `SRGBColorSpace`. + * + * @param {Color} color - The color to copy/convert. + * @return {Color} A reference to this color. + */ + copyLinearToSRGB(color) { + this.r = LinearToSRGB(color.r); + this.g = LinearToSRGB(color.g); + this.b = LinearToSRGB(color.b); + return this; + } + /** + * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`. + * + * @return {Color} A reference to this color. + */ + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + /** + * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`. + * + * @return {Color} A reference to this color. + */ + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + /** + * Returns the hexadecimal value of this color. + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {number} The hexadecimal value. + */ + getHex(colorSpace = SRGBColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + return Math.round(clamp(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp(_color.g * 255, 0, 255)) * 256 + Math.round(clamp(_color.b * 255, 0, 255)); + } + /** + * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF'). + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {string} The hexadecimal value as a string. + */ + getHexString(colorSpace = SRGBColorSpace) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + /** + * Converts the colors RGB values into the HSL format and stores them into the + * given target object. + * + * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {{h:number,s:number,l:number}} The HSL representation of this color. + */ + getHSL(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + const r6 = _color.r, g2 = _color.g, b3 = _color.b; + const max = Math.max(r6, g2, b3); + const min = Math.min(r6, g2, b3); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r6: + hue = (g2 - b3) / delta + (g2 < b3 ? 6 : 0); + break; + case g2: + hue = (b3 - r6) / delta + 2; + break; + case b3: + hue = (r6 - g2) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + /** + * Returns the RGB values of this color and stores them into the given target object. + * + * @param {Color} target - The target color that is used to store the method's result. + * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. + * @return {Color} The RGB representation of this color. + */ + getRGB(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + return target; + } + /** + * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`. + * + * @param {string} [colorSpace=SRGBColorSpace] - The color space. + * @return {string} The CSS representation of this color. + */ + getStyle(colorSpace = SRGBColorSpace) { + ColorManagement.workingToColorSpace(_color.copy(this), colorSpace); + const r6 = _color.r, g2 = _color.g, b3 = _color.b; + if (colorSpace !== SRGBColorSpace) { + return `color(${colorSpace} ${r6.toFixed(3)} ${g2.toFixed(3)} ${b3.toFixed(3)})`; + } + return `rgb(${Math.round(r6 * 255)},${Math.round(g2 * 255)},${Math.round(b3 * 255)})`; + } + /** + * Adds the given HSL values to this color's values. + * Internally, this converts the color's RGB values to HSL, adds HSL + * and then converts the color back to RGB. + * + * @param {number} h - Hue value between `0.0` and `1.0`. + * @param {number} s - Saturation value between `0.0` and `1.0`. + * @param {number} l - Lightness value between `0.0` and `1.0`. + * @return {Color} A reference to this color. + */ + offsetHSL(h4, s5, l3) { + this.getHSL(_hslA); + return this.setHSL(_hslA.h + h4, _hslA.s + s5, _hslA.l + l3); + } + /** + * Adds the RGB values of the given color to the RGB values of this color. + * + * @param {Color} color - The color to add. + * @return {Color} A reference to this color. + */ + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + /** + * Adds the RGB values of the given colors and stores the result in this instance. + * + * @param {Color} color1 - The first color. + * @param {Color} color2 - The second color. + * @return {Color} A reference to this color. + */ + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + /** + * Adds the given scalar value to the RGB values of this color. + * + * @param {number} s - The scalar to add. + * @return {Color} A reference to this color. + */ + addScalar(s5) { + this.r += s5; + this.g += s5; + this.b += s5; + return this; + } + /** + * Subtracts the RGB values of the given color from the RGB values of this color. + * + * @param {Color} color - The color to subtract. + * @return {Color} A reference to this color. + */ + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + /** + * Multiplies the RGB values of the given color with the RGB values of this color. + * + * @param {Color} color - The color to multiply. + * @return {Color} A reference to this color. + */ + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + /** + * Multiplies the given scalar value with the RGB values of this color. + * + * @param {number} s - The scalar to multiply. + * @return {Color} A reference to this color. + */ + multiplyScalar(s5) { + this.r *= s5; + this.g *= s5; + this.b *= s5; + return this; + } + /** + * Linearly interpolates this color's RGB values toward the RGB values of the + * given color. The alpha argument can be thought of as the ratio between + * the two colors, where `0.0` is this color and `1.0` is the first argument. + * + * @param {Color} color - The color to converge on. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + /** + * Linearly interpolates between the given colors and stores the result in this instance. + * The alpha argument can be thought of as the ratio between the two colors, where `0.0` + * is the first and `1.0` is the second color. + * + * @param {Color} color1 - The first color. + * @param {Color} color2 - The second color. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + /** + * Linearly interpolates this color's HSL values toward the HSL values of the + * given color. It differs from {@link Color#lerp} by not interpolating straight + * from one color to the other, but instead going through all the hues in between + * those two colors. The alpha argument can be thought of as the ratio between + * the two colors, where 0.0 is this color and 1.0 is the first argument. + * + * @param {Color} color - The color to converge on. + * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. + * @return {Color} A reference to this color. + */ + lerpHSL(color, alpha) { + this.getHSL(_hslA); + color.getHSL(_hslB); + const h4 = lerp(_hslA.h, _hslB.h, alpha); + const s5 = lerp(_hslA.s, _hslB.s, alpha); + const l3 = lerp(_hslA.l, _hslB.l, alpha); + this.setHSL(h4, s5, l3); + return this; + } + /** + * Sets the color's RGB components from the given 3D vector. + * + * @param {Vector3} v - The vector to set. + * @return {Color} A reference to this color. + */ + setFromVector3(v2) { + this.r = v2.x; + this.g = v2.y; + this.b = v2.z; + return this; + } + /** + * Transforms this color with the given 3x3 matrix. + * + * @param {Matrix3} m - The matrix. + * @return {Color} A reference to this color. + */ + applyMatrix3(m2) { + const r6 = this.r, g2 = this.g, b3 = this.b; + const e8 = m2.elements; + this.r = e8[0] * r6 + e8[3] * g2 + e8[6] * b3; + this.g = e8[1] * r6 + e8[4] * g2 + e8[7] * b3; + this.b = e8[2] * r6 + e8[5] * g2 + e8[8] * b3; + return this; + } + /** + * Returns `true` if this color is equal with the given one. + * + * @param {Color} c - The color to test for equality. + * @return {boolean} Whether this bounding color is equal with the given one. + */ + equals(c5) { + return c5.r === this.r && c5.g === this.g && c5.b === this.b; + } + /** + * Sets this color's RGB components from the given array. + * + * @param {Array} array - An array holding the RGB values. + * @param {number} [offset=0] - The offset into the array. + * @return {Color} A reference to this color. + */ + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + /** + * Writes the RGB components of this color to the given array. If no array is provided, + * the method returns a new instance. + * + * @param {Array} [array=[]] - The target array holding the color components. + * @param {number} [offset=0] - Index of the first element in the array. + * @return {Array} The color components. + */ + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + /** + * Sets the components of this color from the given buffer attribute. + * + * @param {BufferAttribute} attribute - The buffer attribute holding color data. + * @param {number} index - The index into the attribute. + * @return {Color} A reference to this color. + */ + fromBufferAttribute(attribute, index) { + this.r = attribute.getX(index); + this.g = attribute.getY(index); + this.b = attribute.getZ(index); + return this; + } + /** + * This methods defines the serialization result of this class. Returns the color + * as a hexadecimal value. + * + * @return {number} The hexadecimal value. + */ + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } +}; +var _color = /* @__PURE__ */ new Color(); +Color.NAMES = _colorKeywords; +var _materialId = 0; +var Material = class extends EventDispatcher { + /** + * Constructs a new material. + */ + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.allowOverride = true; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + /** + * Sets the alpha value to be used when running an alpha test. The material + * will not be rendered if the opacity is lower than this value. + * + * @type {number} + * @readonly + * @default 0 + */ + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value) { + if (this._alphaTest > 0 !== value > 0) { + this.version++; + } + this._alphaTest = value; + } + /** + * An optional callback that is executed immediately before the material is used to render a 3D object. + * + * This method can only be used when rendering with {@link WebGLRenderer}. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {Scene} scene - The scene. + * @param {Camera} camera - The camera that is used to render the scene. + * @param {BufferGeometry} geometry - The 3D object's geometry. + * @param {Object3D} object - The 3D object. + * @param {Object} group - The geometry group data. + */ + onBeforeRender() { + } + /** + * An optional callback that is executed immediately before the shader + * program is compiled. This function is called with the shader source code + * as a parameter. Useful for the modification of built-in materials. + * + * This method can only be used when rendering with {@link WebGLRenderer}. The + * recommended approach when customizing materials is to use `WebGPURenderer` with the new + * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}. + * + * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source. + * @param {WebGLRenderer} renderer - A reference to the renderer. + */ + onBeforeCompile() { + } + /** + * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify + * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached + * shader or recompile the shader for this material as needed. + * + * This method can only be used when rendering with {@link WebGLRenderer}. + * + * @return {string} The custom program cache key. + */ + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + /** + * This method can be used to set default values from parameter objects. + * It is a generic implementation so it can be used with different types + * of materials. + * + * @param {Object} [values] - The material values to set. + */ + setValues(values) { + if (values === void 0) return; + for (const key in values) { + const newValue = values[key]; + if (newValue === void 0) { + console.warn(`THREE.Material: parameter '${key}' has value of undefined.`); + continue; + } + const currentValue = this[key]; + if (currentValue === void 0) { + console.warn(`THREE.Material: '${key}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key] = newValue; + } + } + } + /** + * Serializes the material into JSON. + * + * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. + * @return {Object} A JSON object representing the serialized material. + * @see {@link ObjectLoader#parse} + */ + toJSON(meta) { + const isRootObject = meta === void 0 || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data = { + metadata: { + version: 4.7, + type: "Material", + generator: "Material.toJSON" + } + }; + data.uuid = this.uuid; + data.type = this.type; + if (this.name !== "") data.name = this.name; + if (this.color && this.color.isColor) data.color = this.color.getHex(); + if (this.roughness !== void 0) data.roughness = this.roughness; + if (this.metalness !== void 0) data.metalness = this.metalness; + if (this.sheen !== void 0) data.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== void 0) data.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) data.specular = this.specular.getHex(); + if (this.specularIntensity !== void 0) data.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex(); + if (this.shininess !== void 0) data.shininess = this.shininess; + if (this.clearcoat !== void 0) data.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== void 0) data.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.sheenColorMap && this.sheenColorMap.isTexture) { + data.sheenColorMap = this.sheenColorMap.toJSON(meta).uuid; + } + if (this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture) { + data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(meta).uuid; + } + if (this.dispersion !== void 0) data.dispersion = this.dispersion; + if (this.iridescence !== void 0) data.iridescence = this.iridescence; + if (this.iridescenceIOR !== void 0) data.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== void 0) data.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== void 0) data.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== void 0) data.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data.lightMap = this.lightMap.toJSON(meta).uuid; + data.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data.aoMap = this.aoMap.toJSON(meta).uuid; + data.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data.bumpMap = this.bumpMap.toJSON(meta).uuid; + data.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data.normalMap = this.normalMap.toJSON(meta).uuid; + data.normalMapType = this.normalMapType; + data.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data.displacementMap = this.displacementMap.toJSON(meta).uuid; + data.displacementScale = this.displacementScale; + data.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== void 0) data.combine = this.combine; + } + if (this.envMapRotation !== void 0) data.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== void 0) data.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== void 0) data.reflectivity = this.reflectivity; + if (this.refractionRatio !== void 0) data.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== void 0) data.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== void 0) data.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== void 0 && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== void 0) data.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== void 0) data.size = this.size; + if (this.shadowSide !== null) data.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== void 0) data.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending) data.blending = this.blending; + if (this.side !== FrontSide) data.side = this.side; + if (this.vertexColors === true) data.vertexColors = true; + if (this.opacity < 1) data.opacity = this.opacity; + if (this.transparent === true) data.transparent = true; + if (this.blendSrc !== SrcAlphaFactor) data.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor) data.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation) data.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) data.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) data.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) data.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) data.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) data.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth) data.depthFunc = this.depthFunc; + if (this.depthTest === false) data.depthTest = this.depthTest; + if (this.depthWrite === false) data.depthWrite = this.depthWrite; + if (this.colorWrite === false) data.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) data.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc) data.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) data.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) data.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp) data.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp) data.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp) data.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) data.stencilWrite = this.stencilWrite; + if (this.rotation !== void 0 && this.rotation !== 0) data.rotation = this.rotation; + if (this.polygonOffset === true) data.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== void 0 && this.linewidth !== 1) data.linewidth = this.linewidth; + if (this.dashSize !== void 0) data.dashSize = this.dashSize; + if (this.gapSize !== void 0) data.gapSize = this.gapSize; + if (this.scale !== void 0) data.scale = this.scale; + if (this.dithering === true) data.dithering = true; + if (this.alphaTest > 0) data.alphaTest = this.alphaTest; + if (this.alphaHash === true) data.alphaHash = true; + if (this.alphaToCoverage === true) data.alphaToCoverage = true; + if (this.premultipliedAlpha === true) data.premultipliedAlpha = true; + if (this.forceSinglePass === true) data.forceSinglePass = true; + if (this.wireframe === true) data.wireframe = true; + if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") data.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") data.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) data.flatShading = true; + if (this.visible === false) data.visible = false; + if (this.toneMapped === false) data.toneMapped = false; + if (this.fog === false) data.fog = false; + if (Object.keys(this.userData).length > 0) data.userData = this.userData; + function extractFromCache(cache) { + const values = []; + for (const key in cache) { + const data2 = cache[key]; + delete data2.metadata; + values.push(data2); + } + return values; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) data.textures = textures; + if (images.length > 0) data.images = images; + } + return data; + } + /** + * Returns a new material with copied values from this instance. + * + * @return {Material} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given material to this instance. + * + * @param {Material} source - The material to copy. + * @return {Material} A reference to this instance. + */ + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n7 = srcPlanes.length; + dstPlanes = new Array(n7); + for (let i6 = 0; i6 !== n7; ++i6) { + dstPlanes[i6] = srcPlanes[i6].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires Material#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + /** + * Setting this property to `true` indicates the engine the material + * needs to be recompiled. + * + * @type {boolean} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } +}; +var MeshBasicMaterial = class extends Material { + /** + * Constructs a new mesh basic material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler(); + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +}; +var _vector$9 = /* @__PURE__ */ new Vector3(); +var _vector2$1 = /* @__PURE__ */ new Vector2(); +var _id$2 = 0; +var BufferAttribute = class { + /** + * Constructs a new buffer attribute. + * + * @param {TypedArray} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$2++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== void 0 ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.gpuType = FloatType; + this.version = 0; + } + /** + * A callback function that is executed after the renderer has transferred the attribute + * array data to the GPU. + */ + onUploadCallback() { + } + /** + * Flag to indicate that this attribute has changed and should be re-sent to + * the GPU. Set this to `true` when you modify the value of the array. + * + * @type {number} + * @default false + * @param {boolean} value + */ + set needsUpdate(value) { + if (value === true) this.version++; + } + /** + * Sets the usage of this buffer attribute. + * + * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. + * @return {BufferAttribute} A reference to this buffer attribute. + */ + setUsage(value) { + this.usage = value; + return this; + } + /** + * Adds a range of data in the data array to be updated on the GPU. + * + * @param {number} start - Position at which to start update. + * @param {number} count - The number of components to update. + */ + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + /** + * Clears the update ranges. + */ + clearUpdateRanges() { + this.updateRanges.length = 0; + } + /** + * Copies the values of the given buffer attribute to this instance. + * + * @param {BufferAttribute} source - The buffer attribute to copy. + * @return {BufferAttribute} A reference to this instance. + */ + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + /** + * Copies a vector from the given buffer attribute to this one. The start + * and destination position in the attribute buffers are represented by the + * given indices. + * + * @param {number} index1 - The destination index into this buffer attribute. + * @param {BufferAttribute} attribute - The buffer attribute to copy from. + * @param {number} index2 - The source index into the given buffer attribute. + * @return {BufferAttribute} A reference to this instance. + */ + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i6 = 0, l3 = this.itemSize; i6 < l3; i6++) { + this.array[index1 + i6] = attribute.array[index2 + i6]; + } + return this; + } + /** + * Copies the given array data into this buffer attribute. + * + * @param {(TypedArray|Array)} array - The array to copy. + * @return {BufferAttribute} A reference to this instance. + */ + copyArray(array) { + this.array.set(array); + return this; + } + /** + * Applies the given 3x3 matrix to the given attribute. Works with + * item size `2` and `3`. + * + * @param {Matrix3} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyMatrix3(m2) { + if (this.itemSize === 2) { + for (let i6 = 0, l3 = this.count; i6 < l3; i6++) { + _vector2$1.fromBufferAttribute(this, i6); + _vector2$1.applyMatrix3(m2); + this.setXY(i6, _vector2$1.x, _vector2$1.y); + } + } else if (this.itemSize === 3) { + for (let i6 = 0, l3 = this.count; i6 < l3; i6++) { + _vector$9.fromBufferAttribute(this, i6); + _vector$9.applyMatrix3(m2); + this.setXYZ(i6, _vector$9.x, _vector$9.y, _vector$9.z); + } + } + return this; + } + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix4} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyMatrix4(m2) { + for (let i6 = 0, l3 = this.count; i6 < l3; i6++) { + _vector$9.fromBufferAttribute(this, i6); + _vector$9.applyMatrix4(m2); + this.setXYZ(i6, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + /** + * Applies the given 3x3 normal matrix to the given attribute. Only works with + * item size `3`. + * + * @param {Matrix3} m - The normal matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + applyNormalMatrix(m2) { + for (let i6 = 0, l3 = this.count; i6 < l3; i6++) { + _vector$9.fromBufferAttribute(this, i6); + _vector$9.applyNormalMatrix(m2); + this.setXYZ(i6, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + /** + * Applies the given 4x4 matrix to the given attribute. Only works with + * item size `3` and with direction vectors. + * + * @param {Matrix4} m - The matrix to apply. + * @return {BufferAttribute} A reference to this instance. + */ + transformDirection(m2) { + for (let i6 = 0, l3 = this.count; i6 < l3; i6++) { + _vector$9.fromBufferAttribute(this, i6); + _vector$9.transformDirection(m2); + this.setXYZ(i6, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + /** + * Sets the given array data in the buffer attribute. + * + * @param {(TypedArray|Array)} value - The array data to set. + * @param {number} [offset=0] - The offset in this buffer attribute's array. + * @return {BufferAttribute} A reference to this instance. + */ + set(value, offset = 0) { + this.array.set(value, offset); + return this; + } + /** + * Returns the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @return {number} The returned value. + */ + getComponent(index, component) { + let value = this.array[index * this.itemSize + component]; + if (this.normalized) value = denormalize(value, this.array); + return value; + } + /** + * Sets the given value to the given component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} component - The component index. + * @param {number} value - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setComponent(index, component, value) { + if (this.normalized) value = normalize(value, this.array); + this.array[index * this.itemSize + component] = value; + return this; + } + /** + * Returns the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The x component. + */ + getX(index) { + let x2 = this.array[index * this.itemSize]; + if (this.normalized) x2 = denormalize(x2, this.array); + return x2; + } + /** + * Sets the x component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setX(index, x2) { + if (this.normalized) x2 = normalize(x2, this.array); + this.array[index * this.itemSize] = x2; + return this; + } + /** + * Returns the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The y component. + */ + getY(index) { + let y3 = this.array[index * this.itemSize + 1]; + if (this.normalized) y3 = denormalize(y3, this.array); + return y3; + } + /** + * Sets the y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} y - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setY(index, y3) { + if (this.normalized) y3 = normalize(y3, this.array); + this.array[index * this.itemSize + 1] = y3; + return this; + } + /** + * Returns the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The z component. + */ + getZ(index) { + let z2 = this.array[index * this.itemSize + 2]; + if (this.normalized) z2 = denormalize(z2, this.array); + return z2; + } + /** + * Sets the z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} z - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setZ(index, z2) { + if (this.normalized) z2 = normalize(z2, this.array); + this.array[index * this.itemSize + 2] = z2; + return this; + } + /** + * Returns the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @return {number} The w component. + */ + getW(index) { + let w2 = this.array[index * this.itemSize + 3]; + if (this.normalized) w2 = denormalize(w2, this.array); + return w2; + } + /** + * Sets the w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} w - The value to set. + * @return {BufferAttribute} A reference to this instance. + */ + setW(index, w2) { + if (this.normalized) w2 = normalize(w2, this.array); + this.array[index * this.itemSize + 3] = w2; + return this; + } + /** + * Sets the x and y component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXY(index, x2, y3) { + index *= this.itemSize; + if (this.normalized) { + x2 = normalize(x2, this.array); + y3 = normalize(y3, this.array); + } + this.array[index + 0] = x2; + this.array[index + 1] = y3; + return this; + } + /** + * Sets the x, y and z component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXYZ(index, x2, y3, z2) { + index *= this.itemSize; + if (this.normalized) { + x2 = normalize(x2, this.array); + y3 = normalize(y3, this.array); + z2 = normalize(z2, this.array); + } + this.array[index + 0] = x2; + this.array[index + 1] = y3; + this.array[index + 2] = z2; + return this; + } + /** + * Sets the x, y, z and w component of the vector at the given index. + * + * @param {number} index - The index into the buffer attribute. + * @param {number} x - The value for the x component to set. + * @param {number} y - The value for the y component to set. + * @param {number} z - The value for the z component to set. + * @param {number} w - The value for the w component to set. + * @return {BufferAttribute} A reference to this instance. + */ + setXYZW(index, x2, y3, z2, w2) { + index *= this.itemSize; + if (this.normalized) { + x2 = normalize(x2, this.array); + y3 = normalize(y3, this.array); + z2 = normalize(z2, this.array); + w2 = normalize(w2, this.array); + } + this.array[index + 0] = x2; + this.array[index + 1] = y3; + this.array[index + 2] = z2; + this.array[index + 3] = w2; + return this; + } + /** + * Sets the given callback function that is executed after the Renderer has transferred + * the attribute array data to the GPU. Can be used to perform clean-up operations after + * the upload when attribute data are not needed anymore on the CPU side. + * + * @param {Function} callback - The `onUpload()` callback. + * @return {BufferAttribute} A reference to this instance. + */ + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + /** + * Returns a new buffer attribute with copied values from this instance. + * + * @return {BufferAttribute} A clone of this instance. + */ + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + /** + * Serializes the buffer attribute into JSON. + * + * @return {Object} A JSON object representing the serialized buffer attribute. + */ + toJSON() { + const data = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") data.name = this.name; + if (this.usage !== StaticDrawUsage) data.usage = this.usage; + return data; + } +}; +var Uint16BufferAttribute = class extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint16Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } +}; +var Uint32BufferAttribute = class extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Uint32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } +}; +var Float32BufferAttribute = class extends BufferAttribute { + /** + * Constructs a new buffer attribute. + * + * @param {(Array|Float32Array)} array - The array holding the attribute data. + * @param {number} itemSize - The item size. + * @param {boolean} [normalized=false] - Whether the data are normalized or not. + */ + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } +}; +var _id$1 = 0; +var _m1 = /* @__PURE__ */ new Matrix4(); +var _obj = /* @__PURE__ */ new Object3D(); +var _offset = /* @__PURE__ */ new Vector3(); +var _box$2 = /* @__PURE__ */ new Box3(); +var _boxMorphTargets = /* @__PURE__ */ new Box3(); +var _vector$8 = /* @__PURE__ */ new Vector3(); +var BufferGeometry = class _BufferGeometry extends EventDispatcher { + /** + * Constructs a new geometry. + */ + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$1++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + /** + * Returns the index of this geometry. + * + * @return {?BufferAttribute} The index. Returns `null` if no index is defined. + */ + getIndex() { + return this.index; + } + /** + * Sets the given index to this geometry. + * + * @param {Array|BufferAttribute} index - The index to set. + * @return {BufferGeometry} A reference to this instance. + */ + setIndex(index) { + if (Array.isArray(index)) { + this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1); + } else { + this.index = index; + } + return this; + } + /** + * Sets the given indirect attribute to this geometry. + * + * @param {BufferAttribute} indirect - The attribute holding indirect draw calls. + * @return {BufferGeometry} A reference to this instance. + */ + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + /** + * Returns the indirect attribute of this geometry. + * + * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined. + */ + getIndirect() { + return this.indirect; + } + /** + * Returns the buffer attribute for the given name. + * + * @param {string} name - The attribute name. + * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute. + * Returns `undefined` if not attribute has been found. + */ + getAttribute(name) { + return this.attributes[name]; + } + /** + * Sets the given attribute for the given name. + * + * @param {string} name - The attribute name. + * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set. + * @return {BufferGeometry} A reference to this instance. + */ + setAttribute(name, attribute) { + this.attributes[name] = attribute; + return this; + } + /** + * Deletes the attribute for the given name. + * + * @param {string} name - The attribute name to delete. + * @return {BufferGeometry} A reference to this instance. + */ + deleteAttribute(name) { + delete this.attributes[name]; + return this; + } + /** + * Returns `true` if this geometry has an attribute for the given name. + * + * @param {string} name - The attribute name. + * @return {boolean} Whether this geometry has an attribute for the given name or not. + */ + hasAttribute(name) { + return this.attributes[name] !== void 0; + } + /** + * Adds a group to this geometry. + * + * @param {number} start - The first element in this draw call. That is the first + * vertex for non-indexed geometry, otherwise the first triangle index. + * @param {number} count - Specifies how many vertices (or indices) are part of this group. + * @param {number} [materialIndex=0] - The material array index to use. + */ + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + /** + * Clears all groups. + */ + clearGroups() { + this.groups = []; + } + /** + * Sets the draw range for this geometry. + * + * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index. + * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render. + * For indexed BufferGeometry, `count` is the number of indices to render. + */ + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + /** + * Applies the given 4x4 transformation matrix to the geometry. + * + * @param {Matrix4} matrix - The matrix to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyMatrix4(matrix) { + const position = this.attributes.position; + if (position !== void 0) { + position.applyMatrix4(matrix); + position.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== void 0) { + const normalMatrix = new Matrix3().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== void 0) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + /** + * Applies the rotation represented by the Quaternion to the geometry. + * + * @param {Quaternion} q - The Quaternion to apply. + * @return {BufferGeometry} A reference to this instance. + */ + applyQuaternion(q) { + _m1.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1); + return this; + } + /** + * Rotates the geometry about the X axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateX(angle) { + _m1.makeRotationX(angle); + this.applyMatrix4(_m1); + return this; + } + /** + * Rotates the geometry about the Y axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateY(angle) { + _m1.makeRotationY(angle); + this.applyMatrix4(_m1); + return this; + } + /** + * Rotates the geometry about the Z axis. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#rotation} for typical + * real-time mesh rotation. + * + * @param {number} angle - The angle in radians. + * @return {BufferGeometry} A reference to this instance. + */ + rotateZ(angle) { + _m1.makeRotationZ(angle); + this.applyMatrix4(_m1); + return this; + } + /** + * Translates the geometry. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#position} for typical + * real-time mesh rotation. + * + * @param {number} x - The x offset. + * @param {number} y - The y offset. + * @param {number} z - The z offset. + * @return {BufferGeometry} A reference to this instance. + */ + translate(x2, y3, z2) { + _m1.makeTranslation(x2, y3, z2); + this.applyMatrix4(_m1); + return this; + } + /** + * Scales the geometry. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#scale} for typical + * real-time mesh rotation. + * + * @param {number} x - The x scale. + * @param {number} y - The y scale. + * @param {number} z - The z scale. + * @return {BufferGeometry} A reference to this instance. + */ + scale(x2, y3, z2) { + _m1.makeScale(x2, y3, z2); + this.applyMatrix4(_m1); + return this; + } + /** + * Rotates the geometry to face a point in 3D space. This is typically done as a one time + * operation, and not during a loop. Use {@link Object3D#lookAt} for typical + * real-time mesh rotation. + * + * @param {Vector3} vector - The target point. + * @return {BufferGeometry} A reference to this instance. + */ + lookAt(vector) { + _obj.lookAt(vector); + _obj.updateMatrix(); + this.applyMatrix4(_obj.matrix); + return this; + } + /** + * Center the geometry based on its bounding box. + * + * @return {BufferGeometry} A reference to this instance. + */ + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset).negate(); + this.translate(_offset.x, _offset.y, _offset.z); + return this; + } + /** + * Defines a geometry by creating a `position` attribute based on the given array of points. The array + * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is + * set to `0`. + * + * If the method is used with an existing `position` attribute, the vertex data are overwritten with the + * data from the array. The length of the array must match the vertex count. + * + * @param {Array|Array} points - The points. + * @return {BufferGeometry} A reference to this instance. + */ + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === void 0) { + const position = []; + for (let i6 = 0, l3 = points.length; i6 < l3; i6++) { + const point = points[i6]; + position.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute(position, 3)); + } else { + const l3 = Math.min(points.length, positionAttribute.count); + for (let i6 = 0; i6 < l3; i6++) { + const point = points[i6]; + positionAttribute.setXYZ(i6, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + /** + * Computes the bounding box of the geometry, and updates the `boundingBox` member. + * The bounding box is not computed by the engine; it must be computed by your app. + * You may need to recompute the bounding box if the geometry vertices are modified. + */ + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3(); + } + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position && position.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set( + new Vector3(-Infinity, -Infinity, -Infinity), + new Vector3(Infinity, Infinity, Infinity) + ); + return; + } + if (position !== void 0) { + this.boundingBox.setFromBufferAttribute(position); + if (morphAttributesPosition) { + for (let i6 = 0, il = morphAttributesPosition.length; i6 < il; i6++) { + const morphAttribute = morphAttributesPosition[i6]; + _box$2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(this.boundingBox.min, _box$2.min); + this.boundingBox.expandByPoint(_vector$8); + _vector$8.addVectors(this.boundingBox.max, _box$2.max); + this.boundingBox.expandByPoint(_vector$8); + } else { + this.boundingBox.expandByPoint(_box$2.min); + this.boundingBox.expandByPoint(_box$2.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + /** + * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member. + * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. + * You may need to recompute the bounding sphere if the geometry vertices are modified. + */ + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere(); + } + const position = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position && position.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector3(), Infinity); + return; + } + if (position) { + const center = this.boundingSphere.center; + _box$2.setFromBufferAttribute(position); + if (morphAttributesPosition) { + for (let i6 = 0, il = morphAttributesPosition.length; i6 < il; i6++) { + const morphAttribute = morphAttributesPosition[i6]; + _boxMorphTargets.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(_box$2.min, _boxMorphTargets.min); + _box$2.expandByPoint(_vector$8); + _vector$8.addVectors(_box$2.max, _boxMorphTargets.max); + _box$2.expandByPoint(_vector$8); + } else { + _box$2.expandByPoint(_boxMorphTargets.min); + _box$2.expandByPoint(_boxMorphTargets.max); + } + } + } + _box$2.getCenter(center); + let maxRadiusSq = 0; + for (let i6 = 0, il = position.count; i6 < il; i6++) { + _vector$8.fromBufferAttribute(position, i6); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + if (morphAttributesPosition) { + for (let i6 = 0, il = morphAttributesPosition.length; i6 < il; i6++) { + const morphAttribute = morphAttributesPosition[i6]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j2 = 0, jl = morphAttribute.count; j2 < jl; j2++) { + _vector$8.fromBufferAttribute(morphAttribute, j2); + if (morphTargetsRelative) { + _offset.fromBufferAttribute(position, j2); + _vector$8.add(_offset); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + /** + * Calculates and adds a tangent attribute to this geometry. + * + * The computation is only supported for indexed geometries and if position, normal, and uv attributes + * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by + * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead. + */ + computeTangents() { + const index = this.index; + const attributes = this.attributes; + if (index === null || attributes.position === void 0 || attributes.normal === void 0 || attributes.uv === void 0) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i6 = 0; i6 < positionAttribute.count; i6++) { + tan1[i6] = new Vector3(); + tan2[i6] = new Vector3(); + } + const vA = new Vector3(), vB = new Vector3(), vC = new Vector3(), uvA = new Vector2(), uvB = new Vector2(), uvC = new Vector2(), sdir = new Vector3(), tdir = new Vector3(); + function handleTriangle(a3, b3, c5) { + vA.fromBufferAttribute(positionAttribute, a3); + vB.fromBufferAttribute(positionAttribute, b3); + vC.fromBufferAttribute(positionAttribute, c5); + uvA.fromBufferAttribute(uvAttribute, a3); + uvB.fromBufferAttribute(uvAttribute, b3); + uvC.fromBufferAttribute(uvAttribute, c5); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r6 = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r6)) return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r6); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r6); + tan1[a3].add(sdir); + tan1[b3].add(sdir); + tan1[c5].add(sdir); + tan2[a3].add(tdir); + tan2[b3].add(tdir); + tan2[c5].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index.count + }]; + } + for (let i6 = 0, il = groups.length; i6 < il; ++i6) { + const group = groups[i6]; + const start = group.start; + const count = group.count; + for (let j2 = start, jl = start + count; j2 < jl; j2 += 3) { + handleTriangle( + index.getX(j2 + 0), + index.getX(j2 + 1), + index.getX(j2 + 2) + ); + } + } + const tmp = new Vector3(), tmp2 = new Vector3(); + const n7 = new Vector3(), n22 = new Vector3(); + function handleVertex(v2) { + n7.fromBufferAttribute(normalAttribute, v2); + n22.copy(n7); + const t6 = tan1[v2]; + tmp.copy(t6); + tmp.sub(n7.multiplyScalar(n7.dot(t6))).normalize(); + tmp2.crossVectors(n22, t6); + const test = tmp2.dot(tan2[v2]); + const w2 = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v2, tmp.x, tmp.y, tmp.z, w2); + } + for (let i6 = 0, il = groups.length; i6 < il; ++i6) { + const group = groups[i6]; + const start = group.start; + const count = group.count; + for (let j2 = start, jl = start + count; j2 < jl; j2 += 3) { + handleVertex(index.getX(j2 + 0)); + handleVertex(index.getX(j2 + 1)); + handleVertex(index.getX(j2 + 2)); + } + } + } + /** + * Computes vertex normals for the given vertex data. For indexed geometries, the method sets + * each vertex normal to be the average of the face normals of the faces that share that vertex. + * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal + * to be the same as the face normal. + */ + computeVertexNormals() { + const index = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== void 0) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === void 0) { + normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i6 = 0, il = normalAttribute.count; i6 < il; i6++) { + normalAttribute.setXYZ(i6, 0, 0, 0); + } + } + const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); + const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); + const cb = new Vector3(), ab = new Vector3(); + if (index) { + for (let i6 = 0, il = index.count; i6 < il; i6 += 3) { + const vA = index.getX(i6 + 0); + const vB = index.getX(i6 + 1); + const vC = index.getX(i6 + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i6 = 0, il = positionAttribute.count; i6 < il; i6 += 3) { + pA.fromBufferAttribute(positionAttribute, i6 + 0); + pB.fromBufferAttribute(positionAttribute, i6 + 1); + pC.fromBufferAttribute(positionAttribute, i6 + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i6 + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i6 + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i6 + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + /** + * Ensures every normal vector in a geometry will have a magnitude of `1`. This will + * correct lighting on the geometry surfaces. + */ + normalizeNormals() { + const normals = this.attributes.normal; + for (let i6 = 0, il = normals.count; i6 < il; i6++) { + _vector$8.fromBufferAttribute(normals, i6); + _vector$8.normalize(); + normals.setXYZ(i6, _vector$8.x, _vector$8.y, _vector$8.z); + } + } + /** + * Return a new non-index version of this indexed geometry. If the geometry + * is already non-indexed, the method is a NOOP. + * + * @return {BufferGeometry} The non-indexed version of this indexed geometry. + */ + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index = 0, index2 = 0; + for (let i6 = 0, l3 = indices2.length; i6 < l3; i6++) { + if (attribute.isInterleavedBufferAttribute) { + index = indices2[i6] * attribute.data.stride + attribute.offset; + } else { + index = indices2[i6] * itemSize; + } + for (let j2 = 0; j2 < itemSize; j2++) { + array2[index2++] = array[index++]; + } + } + return new BufferAttribute(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new _BufferGeometry(); + const indices = this.index.array; + const attributes = this.attributes; + for (const name in attributes) { + const attribute = attributes[name]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name]; + for (let i6 = 0, il = morphAttribute.length; i6 < il; i6++) { + const attribute = morphAttribute[i6]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i6 = 0, l3 = groups.length; i6 < l3; i6++) { + const group = groups[i6]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + /** + * Serializes the geometry into JSON. + * + * @return {Object} A JSON object representing the serialized geometry. + */ + toJSON() { + const data = { + metadata: { + version: 4.7, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data.uuid = this.uuid; + data.type = this.type; + if (this.name !== "") data.name = this.name; + if (Object.keys(this.userData).length > 0) data.userData = this.userData; + if (this.parameters !== void 0) { + const parameters = this.parameters; + for (const key in parameters) { + if (parameters[key] !== void 0) data[key] = parameters[key]; + } + return data; + } + data.data = { attributes: {} }; + const index = this.index; + if (index !== null) { + data.data.index = { + type: index.array.constructor.name, + array: Array.prototype.slice.call(index.array) + }; + } + const attributes = this.attributes; + for (const key in attributes) { + const attribute = attributes[key]; + data.data.attributes[key] = attribute.toJSON(data.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key in this.morphAttributes) { + const attributeArray = this.morphAttributes[key]; + const array = []; + for (let i6 = 0, il = attributeArray.length; i6 < il; i6++) { + const attribute = attributeArray[i6]; + array.push(attribute.toJSON(data.data)); + } + if (array.length > 0) { + morphAttributes[key] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data.data.morphAttributes = morphAttributes; + data.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data.data.boundingSphere = boundingSphere.toJSON(); + } + return data; + } + /** + * Returns a new geometry with copied values from this instance. + * + * @return {BufferGeometry} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } + /** + * Copies the values of the given geometry to this instance. + * + * @param {BufferGeometry} source - The geometry to copy. + * @return {BufferGeometry} A reference to this instance. + */ + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data = {}; + this.name = source.name; + const index = source.index; + if (index !== null) { + this.setIndex(index.clone()); + } + const attributes = source.attributes; + for (const name in attributes) { + const attribute = attributes[name]; + this.setAttribute(name, attribute.clone(data)); + } + const morphAttributes = source.morphAttributes; + for (const name in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name]; + for (let i6 = 0, l3 = morphAttribute.length; i6 < l3; i6++) { + array.push(morphAttribute[i6].clone(data)); + } + this.morphAttributes[name] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i6 = 0, l3 = groups.length; i6 < l3; i6++) { + const group = groups[i6]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + /** + * Frees the GPU-related resources allocated by this instance. Call this + * method whenever this instance is no longer used in your app. + * + * @fires BufferGeometry#dispose + */ + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +}; +var _inverseMatrix$3 = /* @__PURE__ */ new Matrix4(); +var _ray$3 = /* @__PURE__ */ new Ray(); +var _sphere$6 = /* @__PURE__ */ new Sphere(); +var _sphereHitAt = /* @__PURE__ */ new Vector3(); +var _vA$1 = /* @__PURE__ */ new Vector3(); +var _vB$1 = /* @__PURE__ */ new Vector3(); +var _vC$1 = /* @__PURE__ */ new Vector3(); +var _tempA = /* @__PURE__ */ new Vector3(); +var _morphA = /* @__PURE__ */ new Vector3(); +var _intersectionPoint = /* @__PURE__ */ new Vector3(); +var _intersectionPointWorld = /* @__PURE__ */ new Vector3(); +var Mesh = class extends Object3D { + /** + * Constructs a new mesh. + * + * @param {BufferGeometry} [geometry] - The mesh geometry. + * @param {Material|Array} [material] - The mesh material. + */ + constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.morphTargetDictionary = void 0; + this.morphTargetInfluences = void 0; + this.count = 1; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== void 0) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== void 0) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + /** + * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences} + * to make sure existing morph targets can influence this 3D object. + */ + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys = Object.keys(morphAttributes); + if (keys.length > 0) { + const morphAttribute = morphAttributes[keys[0]]; + if (morphAttribute !== void 0) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m2 = 0, ml = morphAttribute.length; m2 < ml; m2++) { + const name = morphAttribute[m2].name || String(m2); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name] = m2; + } + } + } + } + /** + * Returns the local-space position of the vertex at the given index, taking into + * account the current animation state of both morph targets and skinning. + * + * @param {number} index - The vertex index. + * @param {Vector3} target - The target object that is used to store the method's result. + * @return {Vector3} The vertex position in local space. + */ + getVertexPosition(index, target) { + const geometry = this.geometry; + const position = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position, index); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA.set(0, 0, 0); + for (let i6 = 0, il = morphPosition.length; i6 < il; i6++) { + const influence = morphInfluences[i6]; + const morphAttribute = morphPosition[i6]; + if (influence === 0) continue; + _tempA.fromBufferAttribute(morphAttribute, index); + if (morphTargetsRelative) { + _morphA.addScaledVector(_tempA, influence); + } else { + _morphA.addScaledVector(_tempA.sub(target), influence); + } + } + target.add(_morphA); + } + return target; + } + /** + * Computes intersection points between a casted ray and this line. + * + * @param {Raycaster} raycaster - The raycaster. + * @param {Array} intersects - The target array that holds the intersection points. + */ + raycast(raycaster, intersects) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === void 0) return; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$6.copy(geometry.boundingSphere); + _sphere$6.applyMatrix4(matrixWorld); + _ray$3.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$6.containsPoint(_ray$3.origin) === false) { + if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) return; + if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) return; + } + _inverseMatrix$3.copy(matrixWorld).invert(); + _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3); + if (geometry.boundingBox !== null) { + if (_ray$3.intersectsBox(geometry.boundingBox) === false) return; + } + this._computeIntersections(raycaster, intersects, _ray$3); + } + _computeIntersections(raycaster, intersects, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index = geometry.index; + const position = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index !== null) { + if (Array.isArray(material)) { + for (let i6 = 0, il = groups.length; i6 < il; i6++) { + const group = groups[i6]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j2 = start, jl = end; j2 < jl; j2 += 3) { + const a3 = index.getX(j2); + const b3 = index.getX(j2 + 1); + const c5 = index.getX(j2 + 2); + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a3, b3, c5); + if (intersection) { + intersection.faceIndex = Math.floor(j2 / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index.count, drawRange.start + drawRange.count); + for (let i6 = start, il = end; i6 < il; i6 += 3) { + const a3 = index.getX(i6); + const b3 = index.getX(i6 + 1); + const c5 = index.getX(i6 + 2); + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a3, b3, c5); + if (intersection) { + intersection.faceIndex = Math.floor(i6 / 3); + intersects.push(intersection); + } + } + } + } else if (position !== void 0) { + if (Array.isArray(material)) { + for (let i6 = 0, il = groups.length; i6 < il; i6++) { + const group = groups[i6]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j2 = start, jl = end; j2 < jl; j2 += 3) { + const a3 = j2; + const b3 = j2 + 1; + const c5 = j2 + 2; + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a3, b3, c5); + if (intersection) { + intersection.faceIndex = Math.floor(j2 / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position.count, drawRange.start + drawRange.count); + for (let i6 = start, il = end; i6 < il; i6 += 3) { + const a3 = i6; + const b3 = i6 + 1; + const c5 = i6 + 2; + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a3, b3, c5); + if (intersection) { + intersection.faceIndex = Math.floor(i6 / 3); + intersects.push(intersection); + } + } + } + } + } +}; +function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect; + if (material.side === BackSide) { + intersect = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point); + } + if (intersect === null) return null; + _intersectionPointWorld.copy(point); + _intersectionPointWorld.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); + if (distance < raycaster.near || distance > raycaster.far) return null; + return { + distance, + point: _intersectionPointWorld.clone(), + object + }; +} +function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a3, b3, c5) { + object.getVertexPosition(a3, _vA$1); + object.getVertexPosition(b3, _vB$1); + object.getVertexPosition(c5, _vC$1); + const intersection = checkIntersection$1(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); + if (intersection) { + const barycoord = new Vector3(); + Triangle.getBarycoord(_intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord); + if (uv) { + intersection.uv = Triangle.getInterpolatedAttribute(uv, a3, b3, c5, barycoord, new Vector2()); + } + if (uv1) { + intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a3, b3, c5, barycoord, new Vector2()); + } + if (normal) { + intersection.normal = Triangle.getInterpolatedAttribute(normal, a3, b3, c5, barycoord, new Vector3()); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a: a3, + b: b3, + c: c5, + normal: new Vector3(), + materialIndex: 0 + }; + Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; +} +var BoxGeometry = class _BoxGeometry extends BufferGeometry { + /** + * Constructs a new box geometry. + * + * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis. + * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis. + * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis. + * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides. + * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides. + * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides. + */ + constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width, + height, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function buildPlane(u3, v2, w2, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width2 / gridX; + const segmentHeight = height2 / gridY; + const widthHalf = width2 / 2; + const heightHalf = height2 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector3(); + for (let iy = 0; iy < gridY1; iy++) { + const y3 = iy * segmentHeight - heightHalf; + for (let ix = 0; ix < gridX1; ix++) { + const x2 = ix * segmentWidth - widthHalf; + vector[u3] = x2 * udir; + vector[v2] = y3 * vdir; + vector[w2] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u3] = 0; + vector[v2] = 0; + vector[w2] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0; iy < gridY; iy++) { + for (let ix = 0; ix < gridX; ix++) { + const a3 = numberOfVertices + ix + gridX1 * iy; + const b3 = numberOfVertices + ix + gridX1 * (iy + 1); + const c5 = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d3 = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a3, b3, d3); + indices.push(b3, c5, d3); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {BoxGeometry} A new instance. + */ + static fromJSON(data) { + return new _BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments); + } +}; +function cloneUniforms(src) { + const dst = {}; + for (const u3 in src) { + dst[u3] = {}; + for (const p3 in src[u3]) { + const property = src[u3][p3]; + if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) { + if (property.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u3][p3] = null; + } else { + dst[u3][p3] = property.clone(); + } + } else if (Array.isArray(property)) { + dst[u3][p3] = property.slice(); + } else { + dst[u3][p3] = property; + } + } + } + return dst; +} +function mergeUniforms(uniforms) { + const merged = {}; + for (let u3 = 0; u3 < uniforms.length; u3++) { + const tmp = cloneUniforms(uniforms[u3]); + for (const p3 in tmp) { + merged[p3] = tmp[p3]; + } + } + return merged; +} +function cloneUniformsGroups(src) { + const dst = []; + for (let u3 = 0; u3 < src.length; u3++) { + dst.push(src[u3].clone()); + } + return dst; +} +function getUnlitUniformColorSpace(renderer) { + const currentRenderTarget = renderer.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement.workingColorSpace; +} +var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; +var default_vertex = "void main() {\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; +var default_fragment = "void main() {\n gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; +var ShaderMaterial = class extends Material { + /** + * Constructs a new shader material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + // set to use vertex shader clipping + multiDraw: false + // set to use vertex shader multi_draw / enable gl_DrawID + }; + this.defaultAttributeValues = { + "color": [1, 1, 1], + "uv": [0, 0], + "uv1": [0, 0] + }; + this.index0AttributeName = void 0; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== void 0) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms(source.uniforms); + this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + data.glslVersion = this.glslVersion; + data.uniforms = {}; + for (const name in this.uniforms) { + const uniform = this.uniforms[name]; + const value = uniform.value; + if (value && value.isTexture) { + data.uniforms[name] = { + type: "t", + value: value.toJSON(meta).uuid + }; + } else if (value && value.isColor) { + data.uniforms[name] = { + type: "c", + value: value.getHex() + }; + } else if (value && value.isVector2) { + data.uniforms[name] = { + type: "v2", + value: value.toArray() + }; + } else if (value && value.isVector3) { + data.uniforms[name] = { + type: "v3", + value: value.toArray() + }; + } else if (value && value.isVector4) { + data.uniforms[name] = { + type: "v4", + value: value.toArray() + }; + } else if (value && value.isMatrix3) { + data.uniforms[name] = { + type: "m3", + value: value.toArray() + }; + } else if (value && value.isMatrix4) { + data.uniforms[name] = { + type: "m4", + value: value.toArray() + }; + } else { + data.uniforms[name] = { + value + }; + } + } + if (Object.keys(this.defines).length > 0) data.defines = this.defines; + data.vertexShader = this.vertexShader; + data.fragmentShader = this.fragmentShader; + data.lights = this.lights; + data.clipping = this.clipping; + const extensions = {}; + for (const key in this.extensions) { + if (this.extensions[key] === true) extensions[key] = true; + } + if (Object.keys(extensions).length > 0) data.extensions = extensions; + return data; + } +}; +var Camera = class extends Object3D { + /** + * Constructs a new camera. + */ + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix4(); + this.projectionMatrix = new Matrix4(); + this.projectionMatrixInverse = new Matrix4(); + this.coordinateSystem = WebGLCoordinateSystem; + this._reversedDepth = false; + } + /** + * The flag that indicates whether the camera uses a reversed depth buffer. + * + * @type {boolean} + * @default false + */ + get reversedDepth() { + return this._reversedDepth; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + /** + * Returns a vector representing the ("look") direction of the 3D object in world space. + * + * This method is overwritten since cameras have a different forward vector compared to other + * 3D objects. A camera looks down its local, negative z-axis by default. + * + * @param {Vector3} target - The target vector the result is stored to. + * @return {Vector3} The 3D object's direction in world space. + */ + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } +}; +var _v3$1 = /* @__PURE__ */ new Vector3(); +var _minTarget = /* @__PURE__ */ new Vector2(); +var _maxTarget = /* @__PURE__ */ new Vector2(); +var PerspectiveCamera = class extends Camera { + /** + * Constructs a new perspective camera. + * + * @param {number} [fov=50] - The vertical field of view. + * @param {number} [aspect=1] - The aspect ratio. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor(fov2 = 50, aspect2 = 1, near = 0.1, far = 2e3) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov2; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect2; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + /** + * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. + * + * The default film gauge is 35, so that the focal length can be specified for + * a 35mm (full frame) camera. + * + * @param {number} focalLength - Values for focal length and film gauge must have the same unit. + */ + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + /** + * Returns the focal length from the current {@link PerspectiveCamera#fov} and + * {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The computed focal length. + */ + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + /** + * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. + * + * @return {number} The effective FOV. + */ + getEffectiveFOV() { + return RAD2DEG * 2 * Math.atan( + Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom + ); + } + /** + * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + /** + * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or + * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. + * + * @return {number} The film width. + */ + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + /** + * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. + * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. + * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. + */ + getViewBounds(distance, minTarget, maxTarget) { + _v3$1.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + _v3$1.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + } + /** + * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. + * + * @param {number} distance - The viewing distance. + * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. + * @returns {Vector2} The view size. + */ + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget, _maxTarget); + return target.subVectors(_maxTarget, _minTarget); + } + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * For example, if you have 3x2 monitors and each monitor is 1920x1080 and + * the monitors are in grid like this + *``` + * +---+---+---+ + * | A | B | C | + * +---+---+---+ + * | D | E | F | + * +---+---+---+ + *``` + * then for each monitor you would call it like this: + *```js + * const w = 1920; + * const h = 1080; + * const fullWidth = w * 3; + * const fullHeight = h * 2; + * + * // --A-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); + * // --B-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); + * // --C-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); + * // --D-- + * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); + * // --E-- + * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); + * // --F-- + * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); + * ``` + * + * Note there is no reason monitors have to be the same size or in a grid. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + */ + setViewOffset(fullWidth, fullHeight, x2, y3, width, height) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x2; + this.view.offsetY = y3; + this.view.width = width; + this.view.height = height; + this.updateProjectionMatrix(); + } + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; + let height = 2 * top; + let width = this.aspect * height; + let left = -0.5 * width; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const fullWidth = view.fullWidth, fullHeight = view.fullHeight; + left += view.offsetX * width / fullWidth; + top -= view.offsetY * height / fullHeight; + width *= view.width / fullWidth; + height *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.fov = this.fov; + data.object.zoom = this.zoom; + data.object.near = this.near; + data.object.far = this.far; + data.object.focus = this.focus; + data.object.aspect = this.aspect; + if (this.view !== null) data.object.view = Object.assign({}, this.view); + data.object.filmGauge = this.filmGauge; + data.object.filmOffset = this.filmOffset; + return data; + } +}; +var fov = -90; +var aspect = 1; +var CubeCamera = class extends Object3D { + /** + * Constructs a new cube camera. + * + * @param {number} near - The camera's near plane. + * @param {number} far - The camera's far plane. + * @param {WebGLCubeRenderTarget} renderTarget - The cube render target. + */ + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera(fov, aspect, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera(fov, aspect, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera(fov, aspect, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera(fov, aspect, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + /** + * Must be called when the coordinate system of the cube camera is changed. + */ + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + /** + * Calling this method will render the given scene with the given renderer + * into the cube render target of the camera. + * + * @param {(Renderer|WebGLRenderer)} renderer - The renderer. + * @param {Scene} scene - The scene to render. + */ + update(renderer, scene) { + if (this.parent === null) this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer.coordinateSystem) { + this.coordinateSystem = renderer.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer.getRenderTarget(); + const currentActiveCubeFace = renderer.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer.getActiveMipmapLevel(); + const currentXrEnabled = renderer.xr.enabled; + renderer.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer.render(scene, cameraPX); + renderer.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer.render(scene, cameraNX); + renderer.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer.render(scene, cameraPY); + renderer.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer.render(scene, cameraNY); + renderer.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer.render(scene, cameraNZ); + renderer.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } +}; +var CubeTexture = class extends Texture { + /** + * Constructs a new cube texture. + * + * @param {Array} [images=[]] - An array holding a image for each side of a cube. + * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. + * @param {number} [format=RGBAFormat] - The texture format. + * @param {number} [type=UnsignedByteType] - The texture type. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {string} [colorSpace=NoColorSpace] - The color space value. + */ + constructor(images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + /** + * Alias for {@link CubeTexture#image}. + * + * @type {Array} + */ + get images() { + return this.image; + } + set images(value) { + this.image = value; + } +}; +var WebGLCubeRenderTarget = class extends WebGLRenderTarget { + /** + * Constructs a new cube render target. + * + * @param {number} [size=1] - The size of the render target. + * @param {RenderTarget~Options} [options] - The configuration object. + */ + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture(images); + this._setTextureOptions(options); + this.texture.isRenderTargetTexture = true; + } + /** + * Converts the given equirectangular texture to a cube map. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {Texture} texture - The equirectangular texture. + * @return {WebGLCubeRenderTarget} A reference to this cube render target. + */ + fromEquirectangularTexture(renderer, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ( + /* glsl */ + ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + ` + ), + fragmentShader: ( + /* glsl */ + ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + ) + }; + const geometry = new BoxGeometry(5, 5, 5); + const material = new ShaderMaterial({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter; + const camera = new CubeCamera(1, 10, this); + camera.update(renderer, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + /** + * Clears this cube render target. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. + * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. + * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. + */ + clear(renderer, color = true, depth = true, stencil = true) { + const currentRenderTarget = renderer.getRenderTarget(); + for (let i6 = 0; i6 < 6; i6++) { + renderer.setRenderTarget(this, i6); + renderer.clear(color, depth, stencil); + } + renderer.setRenderTarget(currentRenderTarget); + } +}; +var Group = class extends Object3D { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } +}; +var _moveEvent = { type: "move" }; +var WebXRController = class { + /** + * Constructs a new XR controller. + */ + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + /** + * Returns a group representing the hand space of the XR controller. + * + * @return {Group} A group representing the hand space of the XR controller. + */ + getHandSpace() { + if (this._hand === null) { + this._hand = new Group(); + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + /** + * Returns a group representing the target ray space of the XR controller. + * + * @return {Group} A group representing the target ray space of the XR controller. + */ + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group(); + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3(); + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3(); + } + return this._targetRay; + } + /** + * Returns a group representing the grip space of the XR controller. + * + * @return {Group} A group representing the grip space of the XR controller. + */ + getGripSpace() { + if (this._grip === null) { + this._grip = new Group(); + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3(); + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3(); + } + return this._grip; + } + /** + * Dispatches the given event to the groups representing + * the different coordinate spaces of the XR controller. + * + * @param {Object} event - The event to dispatch. + * @return {WebXRController} A reference to this instance. + */ + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + /** + * Connects the controller with the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + /** + * Disconnects the controller from the given XR input source. + * + * @param {XRInputSource} inputSource - The input source. + * @return {WebXRController} A reference to this instance. + */ + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + /** + * Updates the controller with the given input source, XR frame and reference space. + * This updates the transformations of the groups that represent the different + * coordinate systems of the controller. + * + * @param {XRInputSource} inputSource - The input source. + * @param {XRFrame} frame - The XR frame. + * @param {XRReferenceSpace} referenceSpace - The reference space. + * @return {WebXRController} A reference to this instance. + */ + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 5e-3; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + /** + * Returns a group representing the hand joint for the given input joint. + * + * @private + * @param {Group} hand - The group representing the hand space. + * @param {XRJointSpace} inputjoint - The hand joint data. + * @return {Group} A group representing the hand joint for the given input joint. + */ + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === void 0) { + const joint = new Group(); + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } +}; +var Scene = class extends Object3D { + /** + * Constructs a new scene. + */ + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler(); + this.environmentIntensity = 1; + this.environmentRotation = new Euler(); + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) this.background = source.background.clone(); + if (source.environment !== null) this.environment = source.environment.clone(); + if (source.fog !== null) this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.fog !== null) data.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) data.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) data.object.backgroundIntensity = this.backgroundIntensity; + data.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) data.object.environmentIntensity = this.environmentIntensity; + data.object.environmentRotation = this.environmentRotation.toArray(); + return data; + } +}; +var _vector1 = /* @__PURE__ */ new Vector3(); +var _vector2 = /* @__PURE__ */ new Vector3(); +var _normalMatrix = /* @__PURE__ */ new Matrix3(); +var Plane = class { + /** + * Constructs a new plane. + * + * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane. + * @param {number} [constant=0] - The signed distance from the origin to the plane. + */ + constructor(normal = new Vector3(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + /** + * Sets the plane components by copying the given values. + * + * @param {Vector3} normal - The normal. + * @param {number} constant - The constant. + * @return {Plane} A reference to this plane. + */ + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + /** + * Sets the plane components by defining `x`, `y`, `z` as the + * plane normal and `w` as the constant. + * + * @param {number} x - The value for the normal's x component. + * @param {number} y - The value for the normal's y component. + * @param {number} z - The value for the normal's z component. + * @param {number} w - The constant value. + * @return {Plane} A reference to this plane. + */ + setComponents(x2, y3, z2, w2) { + this.normal.set(x2, y3, z2); + this.constant = w2; + return this; + } + /** + * Sets the plane from the given normal and coplanar point (that is a point + * that lies onto the plane). + * + * @param {Vector3} normal - The normal. + * @param {Vector3} point - A coplanar point. + * @return {Plane} A reference to this plane. + */ + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + /** + * Sets the plane from three coplanar points. The winding order is + * assumed to be counter-clockwise, and determines the direction of + * the plane normal. + * + * @param {Vector3} a - The first coplanar point. + * @param {Vector3} b - The second coplanar point. + * @param {Vector3} c - The third coplanar point. + * @return {Plane} A reference to this plane. + */ + setFromCoplanarPoints(a3, b3, c5) { + const normal = _vector1.subVectors(c5, b3).cross(_vector2.subVectors(a3, b3)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a3); + return this; + } + /** + * Copies the values of the given plane to this instance. + * + * @param {Plane} plane - The plane to copy. + * @return {Plane} A reference to this plane. + */ + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + /** + * Normalizes the plane normal and adjusts the constant accordingly. + * + * @return {Plane} A reference to this plane. + */ + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + /** + * Negates both the plane normal and the constant. + * + * @return {Plane} A reference to this plane. + */ + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + /** + * Returns the signed distance from the given point to this plane. + * + * @param {Vector3} point - The point to compute the distance for. + * @return {number} The signed distance. + */ + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + /** + * Returns the signed distance from the given sphere to this plane. + * + * @param {Sphere} sphere - The sphere to compute the distance for. + * @return {number} The signed distance. + */ + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + /** + * Projects a the given point onto the plane. + * + * @param {Vector3} point - The point to project. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The projected point on the plane. + */ + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + /** + * Returns the intersection point of the passed line and the plane. Returns + * `null` if the line does not intersect. Returns the line's starting point if + * the line is coplanar with the plane. + * + * @param {Line3} line - The line to compute the intersection for. + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {?Vector3} The intersection point. + */ + intersectLine(line, target) { + const direction = line.delta(_vector1); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t6 = -(line.start.dot(this.normal) + this.constant) / denominator; + if (t6 < 0 || t6 > 1) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t6); + } + /** + * Returns `true` if the given line segment intersects with (passes through) the plane. + * + * @param {Line3} line - The line to test. + * @return {boolean} Whether the given line segment intersects with the plane or not. + */ + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + /** + * Returns `true` if the given bounding box intersects with the plane. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the given bounding box intersects with the plane or not. + */ + intersectsBox(box) { + return box.intersectsPlane(this); + } + /** + * Returns `true` if the given bounding sphere intersects with the plane. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the given bounding sphere intersects with the plane or not. + */ + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + /** + * Returns a coplanar vector to the plane, by calculating the + * projection of the normal at the origin onto the plane. + * + * @param {Vector3} target - The target vector that is used to store the method's result. + * @return {Vector3} The coplanar point. + */ + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + /** + * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform. + * + * The optional normal matrix can be pre-computed like so: + * ```js + * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); + * ``` + * + * @param {Matrix4} matrix - The transformation matrix. + * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix. + * @return {Plane} A reference to this plane. + */ + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + /** + * Translates the plane by the distance defined by the given offset vector. + * Note that this only affects the plane constant and will not affect the normal vector. + * + * @param {Vector3} offset - The offset vector. + * @return {Plane} A reference to this plane. + */ + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + /** + * Returns `true` if this plane is equal with the given one. + * + * @param {Plane} plane - The plane to test for equality. + * @return {boolean} Whether this plane is equal with the given one. + */ + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + /** + * Returns a new plane with copied values from this instance. + * + * @return {Plane} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } +}; +var _sphere$3 = /* @__PURE__ */ new Sphere(); +var _defaultSpriteCenter = /* @__PURE__ */ new Vector2(0.5, 0.5); +var _vector$6 = /* @__PURE__ */ new Vector3(); +var Frustum = class { + /** + * Constructs a new frustum. + * + * @param {Plane} [p0] - The first plane that encloses the frustum. + * @param {Plane} [p1] - The second plane that encloses the frustum. + * @param {Plane} [p2] - The third plane that encloses the frustum. + * @param {Plane} [p3] - The fourth plane that encloses the frustum. + * @param {Plane} [p4] - The fifth plane that encloses the frustum. + * @param {Plane} [p5] - The sixth plane that encloses the frustum. + */ + constructor(p0 = new Plane(), p1 = new Plane(), p22 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) { + this.planes = [p0, p1, p22, p3, p4, p5]; + } + /** + * Sets the frustum planes by copying the given planes. + * + * @param {Plane} [p0] - The first plane that encloses the frustum. + * @param {Plane} [p1] - The second plane that encloses the frustum. + * @param {Plane} [p2] - The third plane that encloses the frustum. + * @param {Plane} [p3] - The fourth plane that encloses the frustum. + * @param {Plane} [p4] - The fifth plane that encloses the frustum. + * @param {Plane} [p5] - The sixth plane that encloses the frustum. + * @return {Frustum} A reference to this frustum. + */ + set(p0, p1, p22, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p22); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + /** + * Copies the values of the given frustum to this instance. + * + * @param {Frustum} frustum - The frustum to copy. + * @return {Frustum} A reference to this frustum. + */ + copy(frustum) { + const planes = this.planes; + for (let i6 = 0; i6 < 6; i6++) { + planes[i6].copy(frustum.planes[i6]); + } + return this; + } + /** + * Sets the frustum planes from the given projection matrix. + * + * @param {Matrix4} m - The projection matrix. + * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system. + * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. + * @return {Frustum} A reference to this frustum. + */ + setFromProjectionMatrix(m2, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false) { + const planes = this.planes; + const me = m2.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + if (reversedDepth) { + planes[4].setComponents(me2, me6, me10, me14).normalize(); + planes[5].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + } else { + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + } + return this; + } + /** + * Returns `true` if the 3D object's bounding sphere is intersecting this frustum. + * + * Note that the 3D object must have a geometry so that the bounding sphere can be calculated. + * + * @param {Object3D} object - The 3D object to test. + * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not. + */ + intersectsObject(object) { + if (object.boundingSphere !== void 0) { + if (object.boundingSphere === null) object.computeBoundingSphere(); + _sphere$3.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$3); + } + /** + * Returns `true` if the given sprite is intersecting this frustum. + * + * @param {Sprite} sprite - The sprite to test. + * @return {boolean} Whether the sprite is intersecting this frustum or not. + */ + intersectsSprite(sprite) { + _sphere$3.center.set(0, 0, 0); + const offset = _defaultSpriteCenter.distanceTo(sprite.center); + _sphere$3.radius = 0.7071067811865476 + offset; + _sphere$3.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$3); + } + /** + * Returns `true` if the given bounding sphere is intersecting this frustum. + * + * @param {Sphere} sphere - The bounding sphere to test. + * @return {boolean} Whether the bounding sphere is intersecting this frustum or not. + */ + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i6 = 0; i6 < 6; i6++) { + const distance = planes[i6].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + /** + * Returns `true` if the given bounding box is intersecting this frustum. + * + * @param {Box3} box - The bounding box to test. + * @return {boolean} Whether the bounding box is intersecting this frustum or not. + */ + intersectsBox(box) { + const planes = this.planes; + for (let i6 = 0; i6 < 6; i6++) { + const plane = planes[i6]; + _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$6) < 0) { + return false; + } + } + return true; + } + /** + * Returns `true` if the given point lies within the frustum. + * + * @param {Vector3} point - The point to test. + * @return {boolean} Whether the point lies within this frustum or not. + */ + containsPoint(point) { + const planes = this.planes; + for (let i6 = 0; i6 < 6; i6++) { + if (planes[i6].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + /** + * Returns a new frustum with copied values from this instance. + * + * @return {Frustum} A clone of this instance. + */ + clone() { + return new this.constructor().copy(this); + } +}; +var DepthTexture = class extends Texture { + /** + * Constructs a new depth texture. + * + * @param {number} width - The width of the texture. + * @param {number} height - The height of the texture. + * @param {number} [type=UnsignedIntType] - The texture type. + * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. + * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. + * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. + * @param {number} [magFilter=LinearFilter] - The mag filter value. + * @param {number} [minFilter=LinearFilter] - The min filter value. + * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. + * @param {number} [format=DepthFormat] - The texture format. + * @param {number} [depth=1] - The depth of the texture. + */ + constructor(width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1) { + if (format !== DepthFormat && format !== DepthStencilFormat) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + const image = { width, height, depth }; + super(image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.source = new Source(Object.assign({}, source.image)); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data = super.toJSON(meta); + if (this.compareFunction !== null) data.compareFunction = this.compareFunction; + return data; + } +}; +var ExternalTexture = class extends Texture { + /** + * Creates a new raw texture. + * + * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture. + */ + constructor(sourceTexture = null) { + super(); + this.sourceTexture = sourceTexture; + this.isExternalTexture = true; + } + copy(source) { + super.copy(source); + this.sourceTexture = source.sourceTexture; + return this; + } +}; +var PlaneGeometry = class _PlaneGeometry extends BufferGeometry { + /** + * Constructs a new plane geometry. + * + * @param {number} [width=1] - The width along the X axis. + * @param {number} [height=1] - The height along the Y axis + * @param {number} [widthSegments=1] - The number of segments along the X axis. + * @param {number} [heightSegments=1] - The number of segments along the Y axis. + */ + constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width, + height, + widthSegments, + heightSegments + }; + const width_half = width / 2; + const height_half = height / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width / gridX; + const segment_height = height / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0; iy < gridY1; iy++) { + const y3 = iy * segment_height - height_half; + for (let ix = 0; ix < gridX1; ix++) { + const x2 = ix * segment_width - width_half; + vertices.push(x2, -y3, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0; iy < gridY; iy++) { + for (let ix = 0; ix < gridX; ix++) { + const a3 = ix + gridX1 * iy; + const b3 = ix + gridX1 * (iy + 1); + const c5 = ix + 1 + gridX1 * (iy + 1); + const d3 = ix + 1 + gridX1 * iy; + indices.push(a3, b3, d3); + indices.push(b3, c5, d3); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {PlaneGeometry} A new instance. + */ + static fromJSON(data) { + return new _PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments); + } +}; +var SphereGeometry = class _SphereGeometry extends BufferGeometry { + /** + * Constructs a new sphere geometry. + * + * @param {number} [radius=1] - The sphere radius. + * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`. + * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`. + * @param {number} [phiStart=0] - The horizontal starting angle in radians. + * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size. + * @param {number} [thetaStart=0] - The vertical starting angle in radians. + * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size. + */ + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index = 0; + const grid = []; + const vertex2 = new Vector3(); + const normal = new Vector3(); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0; iy <= heightSegments; iy++) { + const verticesRow = []; + const v2 = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0; ix <= widthSegments; ix++) { + const u3 = ix / widthSegments; + vertex2.x = -radius * Math.cos(phiStart + u3 * phiLength) * Math.sin(thetaStart + v2 * thetaLength); + vertex2.y = radius * Math.cos(thetaStart + v2 * thetaLength); + vertex2.z = radius * Math.sin(phiStart + u3 * phiLength) * Math.sin(thetaStart + v2 * thetaLength); + vertices.push(vertex2.x, vertex2.y, vertex2.z); + normal.copy(vertex2).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u3 + uOffset, 1 - v2); + verticesRow.push(index++); + } + grid.push(verticesRow); + } + for (let iy = 0; iy < heightSegments; iy++) { + for (let ix = 0; ix < widthSegments; ix++) { + const a3 = grid[iy][ix + 1]; + const b3 = grid[iy][ix]; + const c5 = grid[iy + 1][ix]; + const d3 = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) indices.push(a3, b3, d3); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b3, c5, d3); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + /** + * Factory method for creating an instance of this class from the given + * JSON object. + * + * @param {Object} data - A JSON object representing the serialized geometry. + * @return {SphereGeometry} A new instance. + */ + static fromJSON(data) { + return new _SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength); + } +}; +var MeshDepthMaterial = class extends Material { + /** + * Constructs a new mesh depth material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } +}; +var MeshDistanceMaterial = class extends Material { + /** + * Constructs a new mesh distance material. + * + * @param {Object} [parameters] - An object with one or more properties + * defining the material's appearance. Any property of the material + * (including any property from inherited materials) can be passed + * in here. Color values can be passed any type of value accepted + * by {@link Color#set}. + */ + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } +}; +function convertArray(array, type) { + if (!array || array.constructor === type) return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); +} +function isTypedArray(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); +} +var Interpolant = class { + /** + * Constructs a new interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== void 0 ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + /** + * Evaluate the interpolant at position `t`. + * + * @param {number} t - The interpolation factor. + * @return {TypedArray} The result buffer. + */ + evaluate(t6) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: if (!(t6 < t1)) { + for (let giveUpAt = i1 + 2; ; ) { + if (t1 === void 0) { + if (t6 < t0) break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) break; + t0 = t1; + t1 = pp[++i1]; + if (t6 < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t6 >= t0)) { + const t1global = pp[1]; + if (t6 < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2; ; ) { + if (t0 === void 0) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t6 >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t6 < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === void 0) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === void 0) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t6, t1); + } + /** + * Returns the interpolation settings. + * + * @return {Object} The interpolation settings. + */ + getSettings_() { + return this.settings || this.DefaultSettings_; + } + /** + * Copies a sample value to the result buffer. + * + * @param {number} index - An index into the sample value buffer. + * @return {TypedArray} The result buffer. + */ + copySampleValue_(index) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride; + for (let i6 = 0; i6 !== stride; ++i6) { + result[i6] = values[offset + i6]; + } + return result; + } + /** + * Copies a sample value to the result buffer. + * + * @abstract + * @param {number} i1 - An index into the sample value buffer. + * @param {number} t0 - The previous interpolation factor. + * @param {number} t - The current interpolation factor. + * @param {number} t1 - The next interpolation factor. + * @return {TypedArray} The result buffer. + */ + interpolate_() { + throw new Error("call to abstract method"); + } + /** + * Optional method that is executed when the interval has changed. + * + * @param {number} i1 - An index into the sample value buffer. + * @param {number} t0 - The previous interpolation factor. + * @param {number} t - The current interpolation factor. + */ + intervalChanged_() { + } +}; +var CubicInterpolant = class extends Interpolant { + /** + * Constructs a new cubic interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === void 0) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === void 0) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t6, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p3 = (t6 - t0) / (t1 - t0), pp = p3 * p3, ppp = pp * p3; + const sP = -wP * ppp + 2 * wP * pp - wP * p3; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p3 + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p3; + const sN = wN * ppp - wN * pp; + for (let i6 = 0; i6 !== stride; ++i6) { + result[i6] = sP * values[oP + i6] + s0 * values[o0 + i6] + s1 * values[o1 + i6] + sN * values[oN + i6]; + } + return result; + } +}; +var LinearInterpolant = class extends Interpolant { + /** + * Constructs a new linear interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t6, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t6 - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i6 = 0; i6 !== stride; ++i6) { + result[i6] = values[offset0 + i6] * weight0 + values[offset1 + i6] * weight1; + } + return result; + } +}; +var DiscreteInterpolant = class extends Interpolant { + /** + * Constructs a new discrete interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } +}; +var KeyframeTrack = class { + /** + * Constructs a new keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + if (name === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === void 0 || times.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name); + this.name = name; + this.times = convertArray(times, this.TimeBufferType); + this.values = convertArray(values, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + /** + * Converts the keyframe track to JSON. + * + * @static + * @param {KeyframeTrack} track - The keyframe track to serialize. + * @return {Object} The serialized keyframe track as JSON. + */ + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + "name": track.name, + "times": convertArray(track.times, Array), + "values": convertArray(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + /** + * Factory method for creating a new discrete interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {DiscreteInterpolant} The new interpolant. + */ + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); + } + /** + * Factory method for creating a new linear interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {LinearInterpolant} The new interpolant. + */ + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + /** + * Factory method for creating a new smooth interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {CubicInterpolant} The new interpolant. + */ + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); + } + /** + * Defines the interpolation factor method for this keyframe track. + * + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === void 0) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === void 0) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + /** + * Returns the current interpolation type. + * + * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type. + */ + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth; + } + } + /** + * Returns the value size. + * + * @return {number} The value size. + */ + getValueSize() { + return this.values.length / this.times.length; + } + /** + * Moves all keyframes either forward or backward in time. + * + * @param {number} timeOffset - The offset to move the time values. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i6 = 0, n7 = times.length; i6 !== n7; ++i6) { + times[i6] += timeOffset; + } + } + return this; + } + /** + * Scale all keyframe times by a factor (useful for frame - seconds conversions). + * + * @param {number} timeScale - The time scale. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i6 = 0, n7 = times.length; i6 !== n7; ++i6) { + times[i6] *= timeScale; + } + } + return this; + } + /** + * Removes keyframes before and after animation without changing any values within the defined time range. + * + * Note: The method does not shift around keys to the start of the track time, because for interpolated + * keys this will change their values + * + * @param {number} startTime - The start time. + * @param {number} endTime - The end time. + * @return {KeyframeTrack} A reference to this keyframe track. + */ + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + /** + * Performs minimal validation on the keyframe track. Returns `true` if the values + * are valid. + * + * @return {boolean} Whether the keyframes are valid or not. + */ + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i6 = 0; i6 !== nKeys; i6++) { + const currTime = times[i6]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i6, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i6, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values !== void 0) { + if (isTypedArray(values)) { + for (let i6 = 0, n7 = values.length; i6 !== n7; ++i6) { + const value = values[i6]; + if (isNaN(value)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i6, value); + valid = false; + break; + } + } + } + } + return valid; + } + /** + * Optimizes this keyframe track by removing equivalent sequential keys (which are + * common in morph target sequences). + * + * @return {AnimationClip} A reference to this animation clip. + */ + optimize() { + const times = this.times.slice(), values = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i6 = 1; i6 < lastIndex; ++i6) { + let keep = false; + const time = times[i6]; + const timeNext = times[i6 + 1]; + if (time !== timeNext && (i6 !== 1 || time !== times[0])) { + if (!smoothInterpolation) { + const offset = i6 * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j2 = 0; j2 !== stride; ++j2) { + const value = values[offset + j2]; + if (value !== values[offsetP + j2] || value !== values[offsetN + j2]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i6 !== writeIndex) { + times[writeIndex] = times[i6]; + const readOffset = i6 * stride, writeOffset = writeIndex * stride; + for (let j2 = 0; j2 !== stride; ++j2) { + values[writeOffset + j2] = values[readOffset + j2]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j2 = 0; j2 !== stride; ++j2) { + values[writeOffset + j2] = values[readOffset + j2]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values; + } + return this; + } + /** + * Returns a new keyframe track with copied values from this instance. + * + * @return {KeyframeTrack} A clone of this instance. + */ + clone() { + const times = this.times.slice(); + const values = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values); + track.createInterpolant = this.createInterpolant; + return track; + } +}; +KeyframeTrack.prototype.ValueTypeName = ""; +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; +var BooleanKeyframeTrack = class extends KeyframeTrack { + /** + * Constructs a new boolean keyframe track. + * + * This keyframe track type has no `interpolation` parameter because the + * interpolation is always discrete. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + */ + constructor(name, times, values) { + super(name, times, values); + } +}; +BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; +var ColorKeyframeTrack = class extends KeyframeTrack { + /** + * Constructs a new color keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } +}; +ColorKeyframeTrack.prototype.ValueTypeName = "color"; +var NumberKeyframeTrack = class extends KeyframeTrack { + /** + * Constructs a new number keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } +}; +NumberKeyframeTrack.prototype.ValueTypeName = "number"; +var QuaternionLinearInterpolant = class extends Interpolant { + /** + * Constructs a new SLERP interpolant. + * + * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors. + * @param {TypedArray} sampleValues - The sample values. + * @param {number} sampleSize - The sample size + * @param {TypedArray} [resultBuffer] - The result buffer. + */ + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t6, t1) { + const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, alpha = (t6 - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride; offset !== end; offset += 4) { + Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha); + } + return result; + } +}; +var QuaternionKeyframeTrack = class extends KeyframeTrack { + /** + * Constructs a new Quaternion keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } + /** + * Overwritten so the method returns Quaternion based interpolant. + * + * @static + * @param {TypedArray} [result] - The result buffer. + * @return {QuaternionLinearInterpolant} The new interpolant. + */ + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); + } +}; +QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; +var StringKeyframeTrack = class extends KeyframeTrack { + /** + * Constructs a new string keyframe track. + * + * This keyframe track type has no `interpolation` parameter because the + * interpolation is always discrete. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + */ + constructor(name, times, values) { + super(name, times, values); + } +}; +StringKeyframeTrack.prototype.ValueTypeName = "string"; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; +var VectorKeyframeTrack = class extends KeyframeTrack { + /** + * Constructs a new vector keyframe track. + * + * @param {string} name - The keyframe track's name. + * @param {Array} times - A list of keyframe times. + * @param {Array} values - A list of keyframe values. + * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type. + */ + constructor(name, times, values, interpolation) { + super(name, times, values, interpolation); + } +}; +VectorKeyframeTrack.prototype.ValueTypeName = "vector"; +var LoadingManager = class { + /** + * Constructs a new loading manager. + * + * @param {Function} [onLoad] - Executes when all items have been loaded. + * @param {Function} [onProgress] - Executes when single items have been loaded. + * @param {Function} [onError] - Executes when an error occurs. + */ + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = void 0; + const handlers = []; + this.onStart = void 0; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.abortController = new AbortController(); + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== void 0) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== void 0) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== void 0) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== void 0) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform) { + urlModifier = transform; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index = handlers.indexOf(regex); + if (index !== -1) { + handlers.splice(index, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i6 = 0, l3 = handlers.length; i6 < l3; i6 += 2) { + const regex = handlers[i6]; + const loader = handlers[i6 + 1]; + if (regex.global) regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + this.abort = function() { + this.abortController.abort(); + this.abortController = new AbortController(); + return this; + }; + } +}; +var DefaultLoadingManager = /* @__PURE__ */ new LoadingManager(); +var Loader = class { + /** + * Constructs a new loader. + * + * @param {LoadingManager} [manager] - The loading manager. + */ + constructor(manager) { + this.manager = manager !== void 0 ? manager : DefaultLoadingManager; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + /** + * This method needs to be implemented by all concrete loaders. It holds the + * logic for loading assets from the backend. + * + * @abstract + * @param {string} url - The path/URL of the file to be loaded. + * @param {Function} onLoad - Executed when the loading process has been finished. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @param {onErrorCallback} [onError] - Executed when errors occur. + */ + load() { + } + /** + * A async version of {@link Loader#load}. + * + * @param {string} url - The path/URL of the file to be loaded. + * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress. + * @return {Promise} A Promise that resolves when the asset has been loaded. + */ + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject) { + scope.load(url, resolve, onProgress, reject); + }); + } + /** + * This method needs to be implemented by all concrete loaders. It holds the + * logic for parsing the asset into three.js entities. + * + * @abstract + * @param {any} data - The data to parse. + */ + parse() { + } + /** + * Sets the `crossOrigin` String to implement CORS for loading the URL + * from a different domain that allows CORS. + * + * @param {string} crossOrigin - The `crossOrigin` value. + * @return {Loader} A reference to this instance. + */ + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + /** + * Whether the XMLHttpRequest uses credentials such as cookies, authorization + * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}. + * + * Note: This setting has no effect if you are loading files locally or from the same domain. + * + * @param {boolean} value - The `withCredentials` value. + * @return {Loader} A reference to this instance. + */ + setWithCredentials(value) { + this.withCredentials = value; + return this; + } + /** + * Sets the base path for the asset. + * + * @param {string} path - The base path. + * @return {Loader} A reference to this instance. + */ + setPath(path) { + this.path = path; + return this; + } + /** + * Sets the base path for dependent resources like textures. + * + * @param {string} resourcePath - The resource path. + * @return {Loader} A reference to this instance. + */ + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + /** + * Sets the given request header. + * + * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header} + * for configuring the HTTP request. + * @return {Loader} A reference to this instance. + */ + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } + /** + * This method can be implemented in loaders for aborting ongoing requests. + * + * @abstract + * @return {Loader} A reference to this instance. + */ + abort() { + return this; + } +}; +Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT"; +var OrthographicCamera = class extends Camera { + /** + * Constructs a new orthographic camera. + * + * @param {number} [left=-1] - The left plane of the camera's frustum. + * @param {number} [right=1] - The right plane of the camera's frustum. + * @param {number} [top=1] - The top plane of the camera's frustum. + * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. + * @param {number} [near=0.1] - The camera's near plane. + * @param {number} [far=2000] - The camera's far plane. + */ + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2e3) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + /** + * Sets an offset in a larger frustum. This is useful for multi-window or + * multi-monitor/multi-machine setups. + * + * @param {number} fullWidth - The full width of multiview setup. + * @param {number} fullHeight - The full height of multiview setup. + * @param {number} x - The horizontal offset of the subcamera. + * @param {number} y - The vertical offset of the subcamera. + * @param {number} width - The width of subcamera. + * @param {number} height - The height of subcamera. + * @see {@link PerspectiveCamera#setViewOffset} + */ + setViewOffset(fullWidth, fullHeight, x2, y3, width, height) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x2; + this.view.offsetY = y3; + this.view.width = width; + this.view.height = height; + this.updateProjectionMatrix(); + } + /** + * Removes the view offset from the projection matrix. + */ + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + /** + * Updates the camera's projection matrix. Must be called after any change of + * camera properties. + */ + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data = super.toJSON(meta); + data.object.zoom = this.zoom; + data.object.left = this.left; + data.object.right = this.right; + data.object.top = this.top; + data.object.bottom = this.bottom; + data.object.near = this.near; + data.object.far = this.far; + if (this.view !== null) data.object.view = Object.assign({}, this.view); + return data; + } +}; +var ArrayCamera = class extends PerspectiveCamera { + /** + * Constructs a new array camera. + * + * @param {Array} [array=[]] - An array of perspective sub cameras. + */ + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.isMultiViewCamera = false; + this.cameras = array; + } +}; +var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; +var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); +var _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; +var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; +var _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); +var _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); +var _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); +var _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); +var _trackRe = new RegExp( + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$" +); +var _supportedObjectNames = ["material", "materials", "bones", "map"]; +var Composite = class { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== void 0) binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i6 = this._targetGroup.nCachedObjects_, n7 = bindings.length; i6 !== n7; ++i6) { + bindings[i6].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i6 = this._targetGroup.nCachedObjects_, n7 = bindings.length; i6 !== n7; ++i6) { + bindings[i6].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i6 = this._targetGroup.nCachedObjects_, n7 = bindings.length; i6 !== n7; ++i6) { + bindings[i6].unbind(); + } + } +}; +var PropertyBinding = class _PropertyBinding { + /** + * Constructs a new property binding. + * + * @param {Object} rootNode - The root node. + * @param {string} path - The path. + * @param {?Object} [parsedPath] - The parsed path. + */ + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || _PropertyBinding.parseTrackName(path); + this.node = _PropertyBinding.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + /** + * Factory method for creating a property binding from the given parameters. + * + * @static + * @param {Object} root - The root node. + * @param {string} path - The path. + * @param {?Object} [parsedPath] - The parsed path. + * @return {PropertyBinding|Composite} The created property binding or composite. + */ + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new _PropertyBinding(root, path, parsedPath); + } else { + return new _PropertyBinding.Composite(root, path, parsedPath); + } + } + /** + * Replaces spaces with underscores and removes unsupported characters from + * node names, to ensure compatibility with parseTrackName(). + * + * @param {string} name - Node name to be sanitized. + * @return {string} The sanitized node name. + */ + static sanitizeNodeName(name) { + return name.replace(/\s/g, "_").replace(_reservedRe, ""); + } + /** + * Parses the given track name (an object path to an animated property) and + * returns an object with information about the path. Matches strings in the following forms: + * + * - nodeName.property + * - nodeName.property[accessor] + * - nodeName.material.property[accessor] + * - uuid.property[accessor] + * - uuid.objectName[objectIndex].propertyName[propertyIndex] + * - parentName/nodeName.property + * - parentName/parentName/nodeName.property[index] + * - .bone[Armature.DEF_cog].position + * - scene:helium_balloon_model:helium_balloon_model.position + * + * @static + * @param {string} trackName - The track name to parse. + * @return {Object} The parsed track name as an object. + */ + static parseTrackName(trackName) { + const matches = _trackRe.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + // directoryName: matches[ 1 ], // (tschw) currently unused + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + // required + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== void 0 && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + /** + * Searches for a node in the hierarchy of the given root object by the given + * node name. + * + * @static + * @param {Object} root - The root object. + * @param {string|number} nodeName - The name of the node. + * @return {?Object} The found node. Returns `null` if no object was found. + */ + static findNode(root, nodeName) { + if (nodeName === void 0 || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== void 0) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i6 = 0; i6 < children.length; i6++) { + const childNode = children[i6]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + // these are used to "bind" a nonexistent property + _getValue_unavailable() { + } + _setValue_unavailable() { + } + // Getters + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i6 = 0, n7 = source.length; i6 !== n7; ++i6) { + buffer[offset++] = source[i6]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + // Direct + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + // EntireArray + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i6 = 0, n7 = dest.length; i6 !== n7; ++i6) { + dest[i6] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i6 = 0, n7 = dest.length; i6 !== n7; ++i6) { + dest[i6] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i6 = 0, n7 = dest.length; i6 !== n7; ++i6) { + dest[i6] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + // ArrayElement + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + // HasToFromArray + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + /** + * Creates a getter / setter pair for the property tracked by this binding. + */ + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = _PropertyBinding.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i6 = 0; i6 < targetObject.length; i6++) { + if (targetObject[i6].name === objectIndex) { + objectIndex = i6; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === void 0) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== void 0) { + if (targetObject[objectIndex] === void 0) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === void 0) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== void 0) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== void 0) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== void 0 && nodeProperty.toArray !== void 0) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + /** + * Unbinds the property. + */ + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } +}; +PropertyBinding.Composite = Composite; +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; +PropertyBinding.prototype.GetterByBindingType = [ + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray +]; +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + [ + // Direct + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + // EntireArray + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + // ArrayElement + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + // HasToFromArray + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] +]; +var _controlInterpolantsResultBuffer = new Float32Array(1); +function getByteLength(width, height, format, type) { + const typeByteLength = getTextureTypeByteLength(type); + switch (format) { + // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml + case AlphaFormat: + return width * height; + case RedFormat: + return width * height / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat: + return width * height / typeByteLength.components * typeByteLength.byteLength; + case RGFormat: + return width * height * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat: + return width * height * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat: + return width * height * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat: + return width * height * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat: + return width * height * 4 / typeByteLength.components * typeByteLength.byteLength; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/ + case RGB_S3TC_DXT1_Format: + case RGBA_S3TC_DXT1_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format: + case RGBA_S3TC_DXT5_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/ + case RGB_PVRTC_2BPPV1_Format: + case RGBA_PVRTC_2BPPV1_Format: + return Math.max(width, 16) * Math.max(height, 8) / 4; + case RGB_PVRTC_4BPPV1_Format: + case RGBA_PVRTC_4BPPV1_Format: + return Math.max(width, 8) * Math.max(height, 8) / 2; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/ + case RGB_ETC1_Format: + case RGB_ETC2_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; + // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/ + case RGBA_ASTC_4x4_Format: + return Math.floor((width + 3) / 4) * Math.floor((height + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format: + return Math.floor((width + 4) / 5) * Math.floor((height + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format: + return Math.floor((width + 4) / 5) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format: + return Math.floor((width + 5) / 6) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format: + return Math.floor((width + 5) / 6) * Math.floor((height + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format: + return Math.floor((width + 7) / 8) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format: + return Math.floor((width + 7) / 8) * Math.floor((height + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format: + return Math.floor((width + 7) / 8) * Math.floor((height + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format: + return Math.floor((width + 9) / 10) * Math.floor((height + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format: + return Math.floor((width + 11) / 12) * Math.floor((height + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format: + return Math.floor((width + 11) / 12) * Math.floor((height + 11) / 12) * 16; + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/ + case RGBA_BPTC_Format: + case RGB_BPTC_SIGNED_Format: + case RGB_BPTC_UNSIGNED_Format: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16; + // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/ + case RED_RGTC1_Format: + case SIGNED_RED_RGTC1_Format: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8; + case RED_GREEN_RGTC2_Format: + case SIGNED_RED_GREEN_RGTC2_Format: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16; + } + throw new Error( + `Unable to determine texture byte length for ${format} format.` + ); +} +function getTextureTypeByteLength(type) { + switch (type) { + case UnsignedByteType: + case ByteType: + return { byteLength: 1, components: 1 }; + case UnsignedShortType: + case ShortType: + case HalfFloatType: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type: + case UnsignedShort5551Type: + return { byteLength: 2, components: 4 }; + case UnsignedIntType: + case IntType: + case FloatType: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type: + case UnsignedInt101111Type: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); +} +if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION + } })); +} +if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION; + } +} + +// node_modules/three/build/three.module.js +function WebGLAnimation() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time, frame) { + animationLoop(time, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) return; + if (animationLoop === null) return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value) { + context = value; + } + }; +} +function WebGLAttributes(gl) { + const buffers = /* @__PURE__ */ new WeakMap(); + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (typeof Float16Array !== "undefined" && array instanceof Float16Array) { + type = gl.HALF_FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a3, b3) => a3.start - b3.start); + let mergeIndex = 0; + for (let i6 = 1; i6 < updateRanges.length; i6++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i6]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i6 = 0, l3 = updateRanges.length; i6 < l3; i6++) { + const range = updateRanges[i6]; + gl.bufferSubData( + bufferType, + range.start * array.BYTES_PER_ELEMENT, + array, + range.start, + range.count + ); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + const data = buffers.get(attribute); + if (data) { + gl.deleteBuffer(data.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data = buffers.get(attribute); + if (data === void 0) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data.version < attribute.version) { + if (data.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data.buffer, attribute, bufferType); + data.version = attribute.version; + } + } + return { + get, + remove, + update + }; +} +var alphahash_fragment = "#ifdef USE_ALPHAHASH\n if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif"; +var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n const float ALPHA_HASH_SCALE = 0.05;\n float hash2D( vec2 value ) {\n return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n }\n float hash3D( vec3 value ) {\n return hash2D( vec2( hash2D( value.xy ), value.z ) );\n }\n float getAlphaHashThreshold( vec3 position ) {\n float maxDeriv = max(\n length( dFdx( position.xyz ) ),\n length( dFdy( position.xyz ) )\n );\n float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n vec2 pixScales = vec2(\n exp2( floor( log2( pixScale ) ) ),\n exp2( ceil( log2( pixScale ) ) )\n );\n vec2 alpha = vec2(\n hash3D( floor( pixScales.x * position.xyz ) ),\n hash3D( floor( pixScales.y * position.xyz ) )\n );\n float lerpFactor = fract( log2( pixScale ) );\n float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n float a = min( lerpFactor, 1.0 - lerpFactor );\n vec3 cases = vec3(\n x * x / ( 2.0 * a * ( 1.0 - a ) ),\n ( x - 0.5 * a ) / ( 1.0 - a ),\n 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n );\n float threshold = ( x < ( 1.0 - a ) )\n ? ( ( x < a ) ? cases.x : cases.y )\n : cases.z;\n return clamp( threshold , 1.0e-6, 1.0 );\n }\n#endif"; +var alphamap_fragment = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif"; +var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; +var alphatest_fragment = "#ifdef USE_ALPHATEST\n #ifdef ALPHA_TO_COVERAGE\n diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n if ( diffuseColor.a == 0.0 ) discard;\n #else\n if ( diffuseColor.a < alphaTest ) discard;\n #endif\n#endif"; +var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n uniform float alphaTest;\n#endif"; +var aomap_fragment = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_CLEARCOAT ) \n clearcoatSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_SHEEN ) \n sheenSpecularIndirect *= ambientOcclusion;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n #endif\n#endif"; +var aomap_pars_fragment = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif"; +var batching_pars_vertex = "#ifdef USE_BATCHING\n #if ! defined( GL_ANGLE_multi_draw )\n #define gl_DrawID _gl_DrawID\n uniform int _gl_DrawID;\n #endif\n uniform highp sampler2D batchingTexture;\n uniform highp usampler2D batchingIdTexture;\n mat4 getBatchingMatrix( const in float i ) {\n int size = textureSize( batchingTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n float getIndirectIndex( const in int i ) {\n int size = textureSize( batchingIdTexture, 0 ).x;\n int x = i % size;\n int y = i / size;\n return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n }\n#endif\n#ifdef USE_BATCHING_COLOR\n uniform sampler2D batchingColorTexture;\n vec3 getBatchingColor( const in float i ) {\n int size = textureSize( batchingColorTexture, 0 ).x;\n int j = int( i );\n int x = j % size;\n int y = j / size;\n return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n }\n#endif"; +var batching_vertex = "#ifdef USE_BATCHING\n mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif"; +var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n vPosition = vec3( position );\n#endif"; +var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n vec3 objectTangent = vec3( tangent.xyz );\n#endif"; +var bsdfs = "float G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( specularColor, 1.0, dotVH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n} // validated"; +var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n vec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n }\n vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n }\n float IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n }\n vec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 rgb = XYZ_TO_REC709 * xyz;\n return rgb;\n }\n vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++ m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n }\n#endif"; +var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vBumpMapUv );\n vec2 dSTdy = dFdy( vBumpMapUv );\n float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 ) * faceDirection;\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif"; +var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n vec4 plane;\n #ifdef ALPHA_TO_COVERAGE\n float distanceToPlane, distanceGradient;\n float clipOpacity = 1.0;\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n distanceGradient = fwidth( distanceToPlane ) / 2.0;\n clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n if ( clipOpacity == 0.0 ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n float unionClipOpacity = 1.0;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n distanceGradient = fwidth( distanceToPlane ) / 2.0;\n unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n }\n #pragma unroll_loop_end\n clipOpacity *= 1.0 - unionClipOpacity;\n #endif\n diffuseColor.a *= clipOpacity;\n if ( diffuseColor.a == 0.0 ) discard;\n #else\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n bool clipped = true;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n }\n #pragma unroll_loop_end\n if ( clipped ) discard;\n #endif\n #endif\n#endif"; +var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; +var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n#endif"; +var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n vClipPosition = - mvPosition.xyz;\n#endif"; +var color_fragment = "#if defined( USE_COLOR_ALPHA )\n diffuseColor *= vColor;\n#elif defined( USE_COLOR )\n diffuseColor.rgb *= vColor;\n#endif"; +var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR )\n varying vec3 vColor;\n#endif"; +var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n varying vec3 vColor;\n#endif"; +var color_vertex = "#if defined( USE_COLOR_ALPHA )\n vColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n vColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n vColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n vColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n vColor.xyz *= batchingColor.xyz;\n#endif"; +var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n float precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n float precisionSafeLength( vec3 v ) {\n float maxComponent = max3( abs( v ) );\n return length( v / maxComponent ) * maxComponent;\n }\n#endif\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n varying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n return vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated"; +var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n #define cubeUV_minMipLevel 4.0\n #define cubeUV_minTileSize 16.0\n float getFace( vec3 direction ) {\n vec3 absDirection = abs( direction );\n float face = - 1.0;\n if ( absDirection.x > absDirection.z ) {\n if ( absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if ( absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n }\n vec2 getUV( vec3 direction, float face ) {\n vec2 uv;\n if ( face == 0.0 ) {\n uv = vec2( direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 1.0 ) {\n uv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n } else if ( face == 2.0 ) {\n uv = vec2( - direction.x, direction.y ) / abs( direction.z );\n } else if ( face == 3.0 ) {\n uv = vec2( - direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 4.0 ) {\n uv = vec2( - direction.x, direction.z ) / abs( direction.y );\n } else {\n uv = vec2( direction.x, direction.y ) / abs( direction.z );\n }\n return 0.5 * ( uv + 1.0 );\n }\n vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n float face = getFace( direction );\n float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n mipInt = max( mipInt, cubeUV_minMipLevel );\n float faceSize = exp2( mipInt );\n highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n if ( face > 2.0 ) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n uv.x += filterInt * 3.0 * cubeUV_minTileSize;\n uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n uv.x *= CUBEUV_TEXEL_WIDTH;\n uv.y *= CUBEUV_TEXEL_HEIGHT;\n #ifdef texture2DGradEXT\n return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n #else\n return texture2D( envMap, uv ).rgb;\n #endif\n }\n #define cubeUV_r0 1.0\n #define cubeUV_m0 - 2.0\n #define cubeUV_r1 0.8\n #define cubeUV_m1 - 1.0\n #define cubeUV_r4 0.4\n #define cubeUV_m4 2.0\n #define cubeUV_r5 0.305\n #define cubeUV_m5 3.0\n #define cubeUV_r6 0.21\n #define cubeUV_m6 4.0\n float roughnessToMip( float roughness ) {\n float mip = 0.0;\n if ( roughness >= cubeUV_r1 ) {\n mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n } else if ( roughness >= cubeUV_r4 ) {\n mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n } else if ( roughness >= cubeUV_r5 ) {\n mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n } else if ( roughness >= cubeUV_r6 ) {\n mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n } else {\n mip = - 2.0 * log2( 1.16 * roughness ); }\n return mip;\n }\n vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n float mipF = fract( mip );\n float mipInt = floor( mip );\n vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n if ( mipF == 0.0 ) {\n return vec4( color0, 1.0 );\n } else {\n vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n return vec4( mix( color0, color1, mipF ), 1.0 );\n }\n }\n#endif"; +var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n vec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n mat3 bm = mat3( batchingMatrix );\n transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n transformedNormal = bm * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = bm * transformedTangent;\n #endif\n#endif\n#ifdef USE_INSTANCING\n mat3 im = mat3( instanceMatrix );\n transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n transformedNormal = im * transformedNormal;\n #ifdef USE_TANGENT\n transformedTangent = im * transformedTangent;\n #endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n transformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n #ifdef FLIP_SIDED\n transformedTangent = - transformedTangent;\n #endif\n#endif"; +var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif"; +var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif"; +var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n emissiveColor = sRGBTransferEOTF( emissiveColor );\n #endif\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; +var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif"; +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; +var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n return value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; +var envmap_fragment = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vec3 cameraToFrag;\n if ( isOrthographic ) {\n cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToFrag = normalize( vWorldPosition - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToFrag, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #else\n vec4 envColor = vec4( 0.0 );\n #endif\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif"; +var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n uniform float envMapIntensity;\n uniform float flipEnvMap;\n uniform mat3 envMapRotation;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n \n#endif"; +var envmap_pars_fragment = "#ifdef USE_ENVMAP\n uniform float reflectivity;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n varying vec3 vWorldPosition;\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif"; +var envmap_pars_vertex = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n \n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif"; +var envmap_vertex = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex;\n if ( isOrthographic ) {\n cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif"; +var fog_vertex = "#ifdef USE_FOG\n vFogDepth = - mvPosition.z;\n#endif"; +var fog_pars_vertex = "#ifdef USE_FOG\n varying float vFogDepth;\n#endif"; +var fog_fragment = "#ifdef USE_FOG\n #ifdef FOG_EXP2\n float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; +var fog_pars_fragment = "#ifdef USE_FOG\n uniform vec3 fogColor;\n varying float vFogDepth;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif"; +var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n uniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n float dotNL = dot( normal, lightDirection );\n vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n #ifdef USE_GRADIENTMAP\n return vec3( texture2D( gradientMap, coord ).r );\n #else\n vec2 fw = fwidth( coord ) * 0.5;\n return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n #endif\n}"; +var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif"; +var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; +var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n vec3 diffuseColor;\n float specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Lambert\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert"; +var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n uniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n float x = normal.x, y = normal.y, z = normal.z;\n vec3 result = shCoefficients[ 0 ] * 0.886227;\n result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n return result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n return irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n return irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n if ( cutoffDistance > 0.0 ) {\n distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n }\n return distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n return smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n light.color = directionalLight.color;\n light.direction = directionalLight.direction;\n light.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = pointLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float lightDistance = length( lVector );\n light.color = pointLight.color;\n light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n vec3 lVector = spotLight.position - geometryPosition;\n light.direction = normalize( lVector );\n float angleCos = dot( light.direction, spotLight.direction );\n float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n if ( spotAttenuation > 0.0 ) {\n float lightDistance = length( lVector );\n light.color = spotLight.color * spotAttenuation;\n light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n } else {\n light.color = vec3( 0.0 );\n light.visible = false;\n }\n }\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n struct RectAreaLight {\n vec3 color;\n vec3 position;\n vec3 halfWidth;\n vec3 halfHeight;\n };\n uniform sampler2D ltc_1; uniform sampler2D ltc_2;\n uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n float dotNL = dot( normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n return irradiance;\n }\n#endif"; +var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n vec3 getIBLIrradiance( const in vec3 normal ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n return PI * envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 reflectVec = reflect( - viewDir, normal );\n reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n return envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n #ifdef USE_ANISOTROPY\n vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n #ifdef ENVMAP_TYPE_CUBE_UV\n vec3 bentNormal = cross( bitangent, viewDir );\n bentNormal = normalize( cross( bentNormal, bitangent ) );\n bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n return getIBLRadiance( viewDir, bentNormal, roughness );\n #else\n return vec3( 0.0 );\n #endif\n }\n #endif\n#endif"; +var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; +var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n vec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Toon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon"; +var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; +var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong"; +var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n material.ior = ior;\n #ifdef USE_SPECULAR\n float specularIntensityFactor = specularIntensity;\n vec3 specularColorFactor = specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n #endif\n material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n #else\n float specularIntensityFactor = 1.0;\n vec3 specularColorFactor = vec3( 1.0 );\n material.specularF90 = 1.0;\n #endif\n material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n material.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n material.clearcoat = clearcoat;\n material.clearcoatRoughness = clearcoatRoughness;\n material.clearcoatF0 = vec3( 0.04 );\n material.clearcoatF90 = 1.0;\n #ifdef USE_CLEARCOATMAP\n material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n #endif\n #ifdef USE_CLEARCOAT_ROUGHNESSMAP\n material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n #endif\n material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n material.clearcoatRoughness += geometryRoughness;\n material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n material.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n material.iridescence = iridescence;\n material.iridescenceIOR = iridescenceIOR;\n #ifdef USE_IRIDESCENCEMAP\n material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n #endif\n #ifdef USE_IRIDESCENCE_THICKNESSMAP\n material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n #else\n material.iridescenceThickness = iridescenceThicknessMaximum;\n #endif\n#endif\n#ifdef USE_SHEEN\n material.sheenColor = sheenColor;\n #ifdef USE_SHEEN_COLORMAP\n material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n #endif\n material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n #ifdef USE_SHEEN_ROUGHNESSMAP\n material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n #ifdef USE_ANISOTROPYMAP\n mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n #else\n vec2 anisotropyV = anisotropyVector;\n #endif\n material.anisotropy = length( anisotropyV );\n if( material.anisotropy == 0.0 ) {\n anisotropyV = vec2( 1.0, 0.0 );\n } else {\n anisotropyV /= material.anisotropy;\n material.anisotropy = saturate( material.anisotropy );\n }\n material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif"; +var lights_physical_pars_fragment = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float roughness;\n vec3 specularColor;\n float specularF90;\n float dispersion;\n #ifdef USE_CLEARCOAT\n float clearcoat;\n float clearcoatRoughness;\n vec3 clearcoatF0;\n float clearcoatF90;\n #endif\n #ifdef USE_IRIDESCENCE\n float iridescence;\n float iridescenceIOR;\n float iridescenceThickness;\n vec3 iridescenceFresnel;\n vec3 iridescenceF0;\n #endif\n #ifdef USE_SHEEN\n vec3 sheenColor;\n float sheenRoughness;\n #endif\n #ifdef IOR\n float ior;\n #endif\n #ifdef USE_TRANSMISSION\n float transmission;\n float transmissionAlpha;\n float thickness;\n float attenuationDistance;\n vec3 attenuationColor;\n #endif\n #ifdef USE_ANISOTROPY\n float anisotropy;\n float alphaT;\n vec3 anisotropyT;\n vec3 anisotropyB;\n #endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n float v = 0.5 / ( gv + gl );\n return saturate(v);\n }\n float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n float a2 = alphaT * alphaB;\n highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n highp float v2 = dot( v, v );\n float w2 = a2 / v2;\n return RECIPROCAL_PI * a2 * pow2 ( w2 );\n }\n#endif\n#ifdef USE_CLEARCOAT\n vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n vec3 f0 = material.clearcoatF0;\n float f90 = material.clearcoatF90;\n float roughness = material.clearcoatRoughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( V * D );\n }\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n vec3 f0 = material.specularColor;\n float f90 = material.specularF90;\n float roughness = material.roughness;\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n #ifdef USE_IRIDESCENCE\n F = mix( F, material.iridescenceFresnel, material.iridescence );\n #endif\n #ifdef USE_ANISOTROPY\n float dotTL = dot( material.anisotropyT, lightDir );\n float dotTV = dot( material.anisotropyT, viewDir );\n float dotTH = dot( material.anisotropyT, halfDir );\n float dotBL = dot( material.anisotropyB, lightDir );\n float dotBV = dot( material.anisotropyB, viewDir );\n float dotBH = dot( material.anisotropyB, halfDir );\n float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n #else\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n #endif\n return F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n vec3 lightNormal = cross( v1, v2 );\n if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = - cross( N, T1 );\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n float alpha = pow2( roughness );\n float invAlpha = 1.0 / alpha;\n float cos2h = dotNH * dotNH;\n float sin2h = max( 1.0 - cos2h, 0.0078125 );\n return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float D = D_Charlie( sheenRoughness, dotNH );\n float V = V_Neubelt( dotNV, dotNL );\n return sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n float r2 = roughness * roughness;\n float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n return saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n return fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n return specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n #ifdef USE_IRIDESCENCE\n vec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n #else\n vec3 Fr = specularColor;\n #endif\n vec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n float Ess = fab.x + fab.y;\n float Ems = 1.0 - Ess;\n vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n singleScatter += FssEss;\n multiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 normal = geometryNormal;\n vec3 viewDir = geometryViewDir;\n vec3 position = geometryPosition;\n vec3 lightPos = rectAreaLight.position;\n vec3 halfWidth = rectAreaLight.halfWidth;\n vec3 halfHeight = rectAreaLight.halfHeight;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.roughness;\n vec3 rectCoords[ 4 ];\n rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n vec2 uv = LTC_Uv( normal, viewDir, roughness );\n vec4 t1 = texture2D( ltc_1, uv );\n vec4 t2 = texture2D( ltc_2, uv );\n mat3 mInv = mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifdef USE_CLEARCOAT\n float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n vec3 ccIrradiance = dotNLcc * directLight.color;\n clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n #endif\n reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n #ifdef USE_CLEARCOAT\n clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n #endif\n #ifdef USE_SHEEN\n sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n #endif\n vec3 singleScattering = vec3( 0.0 );\n vec3 multiScattering = vec3( 0.0 );\n vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n #ifdef USE_IRIDESCENCE\n computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n #else\n computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n #endif\n vec3 totalScattering = singleScattering + multiScattering;\n vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n reflectedLight.indirectSpecular += radiance * singleScattering;\n reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_Direct_RectArea RE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; +var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n geometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n float dotNVi = saturate( dot( normal, geometryViewDir ) );\n if ( material.iridescenceThickness == 0.0 ) {\n material.iridescence = 0.0;\n } else {\n material.iridescence = saturate( material.iridescence );\n }\n if ( material.iridescence > 0.0 ) {\n material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n }\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointLightInfo( pointLight, geometryPosition, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n vec4 spotColor;\n vec3 spotLightCoord;\n bool inSpotLightMap;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotLightInfo( spotLight, geometryPosition, directLight );\n #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n #else\n #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #endif\n #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n #endif\n #undef SPOT_LIGHT_MAP_INDEX\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalLightInfo( directionalLight, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n RectAreaLight rectAreaLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n rectAreaLight = rectAreaLights[ i ];\n RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 iblIrradiance = vec3( 0.0 );\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #if defined( USE_LIGHT_PROBES )\n irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if defined( RE_IndirectSpecular )\n vec3 radiance = vec3( 0.0 );\n vec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; +var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n irradiance += lightMapIrradiance;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n iblIrradiance += getIBLIrradiance( geometryNormal );\n #endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n #ifdef USE_ANISOTROPY\n radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n #else\n radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n #endif\n #ifdef USE_CLEARCOAT\n clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n #endif\n#endif"; +var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif"; +var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; +var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n uniform float logDepthBufFC;\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif"; +var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif"; +var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n vFragDepth = 1.0 + gl_Position.w;\n vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif"; +var map_fragment = "#ifdef USE_MAP\n vec4 sampledDiffuseColor = texture2D( map, vMapUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n #endif\n diffuseColor *= sampledDiffuseColor;\n#endif"; +var map_pars_fragment = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif"; +var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n #if defined( USE_POINTS_UV )\n vec2 uv = vUv;\n #else\n vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n #endif\n#endif\n#ifdef USE_MAP\n diffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; +var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n varying vec2 vUv;\n#else\n #if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n uniform mat3 uvTransform;\n #endif\n#endif\n#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; +var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n metalnessFactor *= texelMetalness.b;\n#endif"; +var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif"; +var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n }\n#endif"; +var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n vColor *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n #if defined( USE_COLOR_ALPHA )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n #elif defined( USE_COLOR )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n #endif\n }\n#endif"; +var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n objectNormal *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n }\n#endif"; +var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n #ifndef USE_INSTANCING_MORPH\n uniform float morphTargetBaseInfluence;\n uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n #endif\n uniform sampler2DArray morphTargetsTexture;\n uniform ivec2 morphTargetsTextureSize;\n vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n int y = texelIndex / morphTargetsTextureSize.x;\n int x = texelIndex - y * morphTargetsTextureSize.x;\n ivec3 morphUV = ivec3( x, y, morphTargetIndex );\n return texelFetch( morphTargetsTexture, morphUV, 0 );\n }\n#endif"; +var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n transformed *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n }\n#endif"; +var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal *= faceDirection;\n #endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n #ifdef USE_TANGENT\n mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn = getTangentFrame( - vViewPosition, normal,\n #if defined( USE_NORMALMAP )\n vNormalMapUv\n #elif defined( USE_CLEARCOAT_NORMALMAP )\n vClearcoatNormalMapUv\n #else\n vUv\n #endif\n );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn[0] *= faceDirection;\n tbn[1] *= faceDirection;\n #endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n #ifdef USE_TANGENT\n mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n #else\n mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n #endif\n #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n tbn2[0] *= faceDirection;\n tbn2[1] *= faceDirection;\n #endif\n#endif\nvec3 nonPerturbedNormal = normal;"; +var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n #ifdef FLIP_SIDED\n normal = - normal;\n #endif\n #ifdef DOUBLE_SIDED\n normal = normal * faceDirection;\n #endif\n normal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n normal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; +var normal_pars_fragment = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; +var normal_pars_vertex = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; +var normal_vertex = "#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #ifdef USE_TANGENT\n vTangent = normalize( transformedTangent );\n vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n #endif\n#endif"; +var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n uniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( uv.st );\n vec2 st1 = dFdy( uv.st );\n vec3 N = surf_norm;\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n return mat3( T * scale, B * scale, N );\n }\n#endif"; +var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n vec3 clearcoatNormal = nonPerturbedNormal;\n#endif"; +var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n clearcoatMapN.xy *= clearcoatNormalScale;\n clearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif"; +var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n uniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform sampler2D clearcoatNormalMap;\n uniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform sampler2D clearcoatRoughnessMap;\n#endif"; +var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n uniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform sampler2D iridescenceThicknessMap;\n#endif"; +var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; +var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n if( v <= 0.0 )\n return vec4( 0., 0., 0., 0. );\n if( v >= 1.0 )\n return vec4( 1., 1., 1., 1. );\n float vuf;\n float af = modf( v * PackFactors.a, vuf );\n float bf = modf( vuf * ShiftRight8, vuf );\n float gf = modf( vuf * ShiftRight8, vuf );\n return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n if( v <= 0.0 )\n return vec3( 0., 0., 0. );\n if( v >= 1.0 )\n return vec3( 1., 1., 1. );\n float vuf;\n float bf = modf( v * PackFactors.b, vuf );\n float gf = modf( vuf * ShiftRight8, vuf );\n return vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n if( v <= 0.0 )\n return vec2( 0., 0. );\n if( v >= 1.0 )\n return vec2( 1., 1. );\n float vuf;\n float gf = modf( v * 256., vuf );\n return vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n return dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n return depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * depth - far );\n}"; +var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif"; +var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n mvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n mvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; +var dithering_fragment = "#ifdef DITHERING\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; +var dithering_pars_fragment = "#ifdef DITHERING\n vec3 dithering( vec3 color ) {\n float grid_position = rand( gl_FragCoord.xy );\n vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n return color + dither_shift_RGB;\n }\n#endif"; +var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n roughnessFactor *= texelRoughness.g;\n#endif"; +var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif"; +var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n struct SpotLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n float depth = unpackRGBAToDepth( texture2D( depths, uv ) );\n #ifdef USE_REVERSED_DEPTH_BUFFER\n return step( depth, compare );\n #else\n return step( compare, depth );\n #endif\n }\n vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n return unpackRGBATo2Half( texture2D( shadow, uv ) );\n }\n float VSMShadow( sampler2D shadow, vec2 uv, float compare ) {\n float occlusion = 1.0;\n vec2 distribution = texture2DDistribution( shadow, uv );\n #ifdef USE_REVERSED_DEPTH_BUFFER\n float hard_shadow = step( distribution.x, compare );\n #else\n float hard_shadow = step( compare, distribution.x );\n #endif\n if ( hard_shadow != 1.0 ) {\n float distance = compare - distribution.x;\n float variance = max( 0.00000, distribution.y * distribution.y );\n float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n }\n return occlusion;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\n bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n bool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n float dx2 = dx0 / 2.0;\n float dy2 = dy0 / 2.0;\n float dx3 = dx1 / 2.0;\n float dy3 = dy1 / 2.0;\n shadow = (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 17.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx = texelSize.x;\n float dy = texelSize.y;\n vec2 uv = shadowCoord.xy;\n vec2 f = fract( uv * shadowMapSize + 0.5 );\n uv -= f * texelSize;\n shadow = (\n texture2DCompare( shadowMap, uv, shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n f.x ),\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n f.x ),\n f.y )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_VSM )\n shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n #else\n shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n float shadow = 1.0;\n vec3 lightToPosition = shadowCoord.xyz;\n \n float lightToPositionLength = length( lightToPosition );\n if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;\n vec3 bd3D = normalize( lightToPosition );\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n shadow = (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n return mix( 1.0, shadow, shadowIntensity );\n }\n#endif"; +var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n struct SpotLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowIntensity;\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n#endif"; +var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n vec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n #if NUM_DIR_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n shadowWorldPosition = worldPosition;\n #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n #endif\n vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n#endif"; +var shadowmask_pars_fragment = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n directionalLight = directionalLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n spotLight = spotLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n pointLight = pointLightShadows[ i ];\n shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #endif\n return shadow;\n}"; +var skinbase_vertex = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; +var skinning_pars_vertex = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture;\n mat4 getBoneMatrix( const in float i ) {\n int size = textureSize( boneTexture, 0 ).x;\n int j = int( i ) * 4;\n int x = j % size;\n int y = j / size;\n vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n return mat4( v1, v2, v3, v4 );\n }\n#endif"; +var skinning_vertex = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n transformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; +var skinnormal_vertex = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n #ifdef USE_TANGENT\n objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n #endif\n#endif"; +var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif"; +var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif"; +var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; +var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n return saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color *= toneMappingExposure / 0.6;\n color = ACESInputMat * color;\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n return saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n vec3( 1.6605, - 0.1246, - 0.0182 ),\n vec3( - 0.5876, 1.1329, - 0.1006 ),\n vec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n vec3( 0.6274, 0.0691, 0.0164 ),\n vec3( 0.3293, 0.9195, 0.0880 ),\n vec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n vec3 x2 = x * x;\n vec3 x4 = x2 * x2;\n return + 15.5 * x4 * x2\n - 40.14 * x4 * x\n + 31.96 * x4\n - 6.868 * x2 * x\n + 0.4298 * x2\n + 0.1191 * x\n - 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n const mat3 AgXInsetMatrix = mat3(\n vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n );\n const mat3 AgXOutsetMatrix = mat3(\n vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n );\n const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069;\n color *= toneMappingExposure;\n color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n color = AgXInsetMatrix * color;\n color = max( color, 1e-10 ); color = log2( color );\n color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n color = clamp( color, 0.0, 1.0 );\n color = agxDefaultContrastApprox( color );\n color = AgXOutsetMatrix * color;\n color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n color = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n color = clamp( color, 0.0, 1.0 );\n return color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n const float StartCompression = 0.8 - 0.04;\n const float Desaturation = 0.15;\n color *= toneMappingExposure;\n float x = min( color.r, min( color.g, color.b ) );\n float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n color -= offset;\n float peak = max( color.r, max( color.g, color.b ) );\n if ( peak < StartCompression ) return color;\n float d = 1. - StartCompression;\n float newPeak = 1. - d * d / ( peak + d - StartCompression );\n color *= newPeak / peak;\n float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n return mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; +var transmission_fragment = "#ifdef USE_TRANSMISSION\n material.transmission = transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n #endif\n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec4 transmitted = getIBLVolumeRefraction(\n n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n material.attenuationColor, material.attenuationDistance );\n material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif"; +var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n uniform float transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n float w0( float a ) {\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n }\n float w1( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n }\n float w2( float a ){\n return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n }\n float w3( float a ) {\n return ( 1.0 / 6.0 ) * ( a * a * a );\n }\n float g0( float a ) {\n return w0( a ) + w1( a );\n }\n float g1( float a ) {\n return w2( a ) + w3( a );\n }\n float h0( float a ) {\n return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n }\n float h1( float a ) {\n return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n }\n vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n uv = uv * texelSize.zw + 0.5;\n vec2 iuv = floor( uv );\n vec2 fuv = fract( uv );\n float g0x = g0( fuv.x );\n float g1x = g1( fuv.x );\n float h0x = h0( fuv.x );\n float h1x = h1( fuv.x );\n float h0y = h0( fuv.y );\n float h1y = h1( fuv.y );\n vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n }\n vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n vec2 fLodSizeInv = 1.0 / fLodSize;\n vec2 cLodSizeInv = 1.0 / cLodSize;\n vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n return mix( fSample, cSample, fract( lod ) );\n }\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n }\n vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n return vec3( 1.0 );\n } else {\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec4 transmittedLight;\n vec3 transmittance;\n #ifdef USE_DISPERSION\n float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n for ( int i = 0; i < 3; i ++ ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n transmittedLight[ i ] = transmissionSample[ i ];\n transmittedLight.a += transmissionSample.a;\n transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n }\n transmittedLight.a /= 3.0;\n #else\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n #endif\n vec3 attenuatedColor = transmittance * transmittedLight.rgb;\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n }\n#endif"; +var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif"; +var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n varying vec2 vUv;\n#endif\n#ifdef USE_MAP\n uniform mat3 mapTransform;\n varying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n uniform mat3 alphaMapTransform;\n varying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n uniform mat3 lightMapTransform;\n varying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n uniform mat3 aoMapTransform;\n varying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n uniform mat3 bumpMapTransform;\n varying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n uniform mat3 normalMapTransform;\n varying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n uniform mat3 displacementMapTransform;\n varying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n uniform mat3 emissiveMapTransform;\n varying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n uniform mat3 metalnessMapTransform;\n varying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n uniform mat3 roughnessMapTransform;\n varying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n uniform mat3 anisotropyMapTransform;\n varying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n uniform mat3 clearcoatMapTransform;\n varying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform mat3 clearcoatNormalMapTransform;\n varying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform mat3 clearcoatRoughnessMapTransform;\n varying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n uniform mat3 sheenColorMapTransform;\n varying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n uniform mat3 sheenRoughnessMapTransform;\n varying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n uniform mat3 iridescenceMapTransform;\n varying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform mat3 iridescenceThicknessMapTransform;\n varying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n uniform mat3 specularMapTransform;\n varying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n uniform mat3 specularColorMapTransform;\n varying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n uniform mat3 specularIntensityMapTransform;\n varying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n uniform mat3 transmissionMapTransform;\n varying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n uniform mat3 thicknessMapTransform;\n varying vec2 vThicknessMapUv;\n#endif"; +var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n vUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif"; +var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n vec4 worldPosition = vec4( transformed, 1.0 );\n #ifdef USE_BATCHING\n worldPosition = batchingMatrix * worldPosition;\n #endif\n #ifdef USE_INSTANCING\n worldPosition = instanceMatrix * worldPosition;\n #endif\n worldPosition = modelMatrix * worldPosition;\n#endif"; +var vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n gl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; +var fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n vec4 texColor = texture2D( t2D, vUv );\n #ifdef DECODE_VIDEO_TEXTURE\n texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include \n #include \n}"; +var vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; +var fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n uniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n #ifdef ENVMAP_TYPE_CUBE\n vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n #else\n vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #endif\n texColor.rgb *= backgroundIntensity;\n gl_FragColor = texColor;\n #include \n #include \n}"; +var vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; +var fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n gl_FragColor = texColor;\n gl_FragColor.a *= opacity;\n #include \n #include \n}"; +var vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n #include \n #include \n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vHighPrecisionZW = gl_Position.zw;\n}"; +var fragment$e = "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n vec4 diffuseColor = vec4( 1.0 );\n #include \n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include \n #include \n #include \n #include \n #include \n #ifdef USE_REVERSED_DEPTH_BUFFER\n float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n #else\n float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n #endif\n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( fragCoordZ );\n #elif DEPTH_PACKING == 3202\n gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n #elif DEPTH_PACKING == 3203\n gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n #endif\n}"; +var vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vWorldPosition = worldPosition.xyz;\n}"; +var fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n vec4 diffuseColor = vec4( 1.0 );\n #include \n #include \n #include \n #include \n #include \n float dist = length( vWorldPosition - referencePosition );\n dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n dist = saturate( dist );\n gl_FragColor = packDepthToRGBA( dist );\n}"; +var vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n}"; +var fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n vec3 direction = normalize( vWorldDirection );\n vec2 sampleUV = equirectUv( direction );\n gl_FragColor = texture2D( tEquirect, sampleUV );\n #include \n #include \n}"; +var vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vLineDistance = scale * lineDistance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n #include \n #include \n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n #include \n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; +var fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n}"; +var fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 viewDir = normalize( vViewPosition );\n vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n vec3 y = cross( viewDir, x );\n vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n #ifdef USE_MATCAP\n vec4 matcapColor = texture2D( matcap, uv );\n #else\n vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n #endif\n vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n vViewPosition = - mvPosition.xyz;\n#endif\n}"; +var fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n #include \n #include \n #include \n #include \n gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n #ifdef OPAQUE\n gl_FragColor.a = 1.0;\n #endif\n}"; +var vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; +var fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n varying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n#ifdef USE_TRANSMISSION\n vWorldPosition = worldPosition.xyz;\n#endif\n}"; +var fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n #define IOR\n #define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n uniform float ior;\n#endif\n#ifdef USE_SPECULAR\n uniform float specularIntensity;\n uniform vec3 specularColor;\n #ifdef USE_SPECULAR_COLORMAP\n uniform sampler2D specularColorMap;\n #endif\n #ifdef USE_SPECULAR_INTENSITYMAP\n uniform sampler2D specularIntensityMap;\n #endif\n#endif\n#ifdef USE_CLEARCOAT\n uniform float clearcoat;\n uniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n uniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n uniform float iridescence;\n uniform float iridescenceIOR;\n uniform float iridescenceThicknessMinimum;\n uniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n uniform vec3 sheenColor;\n uniform float sheenRoughness;\n #ifdef USE_SHEEN_COLORMAP\n uniform sampler2D sheenColorMap;\n #endif\n #ifdef USE_SHEEN_ROUGHNESSMAP\n uniform sampler2D sheenRoughnessMap;\n #endif\n#endif\n#ifdef USE_ANISOTROPY\n uniform vec2 anisotropyVector;\n #ifdef USE_ANISOTROPYMAP\n uniform sampler2D anisotropyMap;\n #endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n #include \n vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n #ifdef USE_SHEEN\n float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n #endif\n #ifdef USE_CLEARCOAT\n float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n}"; +var fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n varying vec2 vUv;\n uniform mat3 uvTransform;\n#endif\nvoid main() {\n #ifdef USE_POINTS_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n gl_PointSize = size;\n #ifdef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n #endif\n #include \n #include \n #include \n #include \n}"; +var fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n vec3 outgoingLight = vec3( 0.0 );\n #include \n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; +var vertex$2 = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; +var fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n #include \n #include \n #include \n}"; +var vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 mvPosition = modelViewMatrix[ 3 ];\n vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n #ifndef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) scale *= - mvPosition.z;\n #endif\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n mvPosition.xy += rotatedPosition;\n gl_Position = projectionMatrix * mvPosition;\n #include \n #include \n #include \n}"; +var fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n vec3 outgoingLight = vec3( 0.0 );\n #include \n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n}"; +var ShaderChunk = { + alphahash_fragment, + alphahash_pars_fragment, + alphamap_fragment, + alphamap_pars_fragment, + alphatest_fragment, + alphatest_pars_fragment, + aomap_fragment, + aomap_pars_fragment, + batching_pars_vertex, + batching_vertex, + begin_vertex, + beginnormal_vertex, + bsdfs, + iridescence_fragment, + bumpmap_pars_fragment, + clipping_planes_fragment, + clipping_planes_pars_fragment, + clipping_planes_pars_vertex, + clipping_planes_vertex, + color_fragment, + color_pars_fragment, + color_pars_vertex, + color_vertex, + common, + cube_uv_reflection_fragment, + defaultnormal_vertex, + displacementmap_pars_vertex, + displacementmap_vertex, + emissivemap_fragment, + emissivemap_pars_fragment, + colorspace_fragment, + colorspace_pars_fragment, + envmap_fragment, + envmap_common_pars_fragment, + envmap_pars_fragment, + envmap_pars_vertex, + envmap_physical_pars_fragment, + envmap_vertex, + fog_vertex, + fog_pars_vertex, + fog_fragment, + fog_pars_fragment, + gradientmap_pars_fragment, + lightmap_pars_fragment, + lights_lambert_fragment, + lights_lambert_pars_fragment, + lights_pars_begin, + lights_toon_fragment, + lights_toon_pars_fragment, + lights_phong_fragment, + lights_phong_pars_fragment, + lights_physical_fragment, + lights_physical_pars_fragment, + lights_fragment_begin, + lights_fragment_maps, + lights_fragment_end, + logdepthbuf_fragment, + logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex, + logdepthbuf_vertex, + map_fragment, + map_pars_fragment, + map_particle_fragment, + map_particle_pars_fragment, + metalnessmap_fragment, + metalnessmap_pars_fragment, + morphinstance_vertex, + morphcolor_vertex, + morphnormal_vertex, + morphtarget_pars_vertex, + morphtarget_vertex, + normal_fragment_begin, + normal_fragment_maps, + normal_pars_fragment, + normal_pars_vertex, + normal_vertex, + normalmap_pars_fragment, + clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps, + clearcoat_pars_fragment, + iridescence_pars_fragment, + opaque_fragment, + packing, + premultiplied_alpha_fragment, + project_vertex, + dithering_fragment, + dithering_pars_fragment, + roughnessmap_fragment, + roughnessmap_pars_fragment, + shadowmap_pars_fragment, + shadowmap_pars_vertex, + shadowmap_vertex, + shadowmask_pars_fragment, + skinbase_vertex, + skinning_pars_vertex, + skinning_vertex, + skinnormal_vertex, + specularmap_fragment, + specularmap_pars_fragment, + tonemapping_fragment, + tonemapping_pars_fragment, + transmission_fragment, + transmission_pars_fragment, + uv_pars_fragment, + uv_pars_vertex, + uv_vertex, + worldpos_vertex, + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; +var UniformsLib = { + common: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix3() }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + // basic, lambert, phong + ior: { value: 1.5 }, + // physical + refractionRatio: { value: 0.98 } + // basic, lambert, phong + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 25e-5 }, + fogNear: { value: 1 }, + fogFar: { value: 2e3 }, + fogColor: { value: /* @__PURE__ */ new Color(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix3() } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + alphaTest: { value: 0 } + } +}; +var ShaderLib = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + specular: { value: /* @__PURE__ */ new Color(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.points, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap + ]), + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.sprite, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix3() }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix3() } + }, + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector3() }, + nearDistance: { value: 1 }, + farDistance: { value: 1e3 } + } + ]), + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /* @__PURE__ */ new Color(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + } +}; +ShaderLib.physical = { + uniforms: /* @__PURE__ */ mergeUniforms([ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2() }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color(0) }, + specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3() }, + anisotropyVector: { value: /* @__PURE__ */ new Vector2() }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3() } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag +}; +var _rgb = { r: 0, b: 0, g: 0 }; +var _e1$1 = /* @__PURE__ */ new Euler(); +var _m1$12 = /* @__PURE__ */ new Matrix4(); +function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { + if (boxMesh === void 0) { + boxMesh = new Mesh( + new BoxGeometry(1, 1, 1), + new ShaderMaterial({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + }) + ); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer2, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$1.copy(scene.backgroundRotation); + _e1$1.x *= -1; + _e1$1.y *= -1; + _e1$1.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$1.y *= -1; + _e1$1.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$12.makeRotationFromEuler(_e1$1)); + boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === void 0) { + planeMesh = new Mesh( + new PlaneGeometry(2, 2), + new ShaderMaterial({ + name: "BackgroundMaterial", + uniforms: cloneUniforms(ShaderLib.background.uniforms), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false, + allowOverride: false + }) + ); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb, getUnlitUniformColorSpace(renderer)); + state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== void 0) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = void 0; + } + if (planeMesh !== void 0) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = void 0; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; +} +function WebGLBindingStates(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index); + if (updateBuffers) saveCache(object, geometry, program, index); + if (index !== null) { + attributes.update(index, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === void 0) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === void 0) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === void 0) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i6 = 0; i6 < maxVertexAttributes; i6++) { + newAttributes[i6] = 0; + enabledAttributes[i6] = 0; + attributeDivisors[i6] = 0; + } + return { + // for backward compatibility on non-VAO support browser + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name]; + let geometryAttribute = geometryAttributes[name]; + if (geometryAttribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; + } + if (cachedAttribute === void 0) return true; + if (cachedAttribute.attribute !== geometryAttribute) return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) return true; + if (currentState.index !== index) return true; + return false; + } + function saveCache(object, geometry, program, index) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name]; + if (attribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) attribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) attribute = object.instanceColor; + } + const data = {}; + data.attribute = attribute; + if (attribute && attribute.data) { + data.data = attribute.data; + } + cache[name] = data; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i6 = 0, il = newAttributes.length; i6 < il; i6++) { + newAttributes[i6] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i6 = 0, il = enabledAttributes.length; i6 < il; i6++) { + if (enabledAttributes[i6] !== newAttributes[i6]) { + gl.disableVertexAttribArray(i6); + enabledAttributes[i6] = 0; + } + } + } + function vertexAttribPointer(index, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name in programAttributes) { + const programAttribute = programAttributes[name]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name]; + if (geometryAttribute === void 0) { + if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; + if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== void 0) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === void 0) continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data = geometryAttribute.data; + const stride = data.stride; + const offset = geometryAttribute.offset; + if (data.isInstancedInterleavedBuffer) { + for (let i6 = 0; i6 < programAttribute.locationSize; i6++) { + enableAttributeAndDivisor(programAttribute.location + i6, data.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { + geometry._maxInstanceCount = data.meshPerAttribute * data.count; + } + } else { + for (let i6 = 0; i6 < programAttribute.locationSize; i6++) { + enableAttribute(programAttribute.location + i6); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i6 = 0; i6 < programAttribute.locationSize; i6++) { + vertexAttribPointer( + programAttribute.location + i6, + size / programAttribute.locationSize, + type, + normalized, + stride * bytesPerElement, + (offset + size / programAttribute.locationSize * i6) * bytesPerElement, + integer + ); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i6 = 0; i6 < programAttribute.locationSize; i6++) { + enableAttributeAndDivisor(programAttribute.location + i6, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i6 = 0; i6 < programAttribute.locationSize; i6++) { + enableAttribute(programAttribute.location + i6); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i6 = 0; i6 < programAttribute.locationSize; i6++) { + vertexAttribPointer( + programAttribute.location + i6, + size / programAttribute.locationSize, + type, + normalized, + size * bytesPerElement, + size / programAttribute.locationSize * i6 * bytesPerElement, + integer + ); + } + } + } else if (materialDefaultAttributeValues !== void 0) { + const value = materialDefaultAttributeValues[name]; + if (value !== void 0) { + switch (value.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === void 0) return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === void 0) continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; +} +function WebGLBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value) { + mode = value; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i6 = 0; i6 < drawCount; i6++) { + elementCount += counts[i6]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i6 = 0; i6 < starts.length; i6++) { + renderInstances(starts[i6], counts[i6], primcount[i6]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i6 = 0; i6 < drawCount; i6++) { + elementCount += counts[i6] * primcount[i6]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLCapabilities(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== void 0) return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513) + textureType !== FloatType && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== void 0 ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + // keeping this for backwards compatibility + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reversedDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; +} +function WebGLClipping(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to + // run another frame in order to reset the state: + numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const planes = material.clippingPlanes, clipIntersection = material.clipIntersection, clipShadows = material.clipShadows; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i6 = 0; i6 !== lGlobal; ++i6) { + dstArray[i6] = globalState[i6]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i6 = 0, i42 = dstOffset; i6 !== nPlanes; ++i6, i42 += 4) { + plane.copy(planes[i6]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i42); + dstArray[i42 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } +} +function WebGLCubeMaps(renderer) { + let cubemaps = /* @__PURE__ */ new WeakMap(); + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping) { + texture.mapping = CubeReflectionMapping; + } else if (mapping === EquirectangularRefractionMapping) { + texture.mapping = CubeRefractionMapping; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget(image.height); + renderTarget.fromEquirectangularTexture(renderer, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== void 0) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; +} +var LOD_MIN = 4; +var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; +var MAX_SAMPLES = 20; +var _flatCamera = /* @__PURE__ */ new OrthographicCamera(); +var _clearColor = /* @__PURE__ */ new Color(); +var _oldTarget = null; +var _oldActiveCubeFace = 0; +var _oldActiveMipmapLevel = 0; +var _oldXrEnabled = false; +var PHI = (1 + Math.sqrt(5)) / 2; +var INV_PHI = 1 / PHI; +var _axisDirections = [ + /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI), + /* @__PURE__ */ new Vector3(0, PHI, INV_PHI), + /* @__PURE__ */ new Vector3(-1, 1, -1), + /* @__PURE__ */ new Vector3(1, 1, -1), + /* @__PURE__ */ new Vector3(-1, 1, 1), + /* @__PURE__ */ new Vector3(1, 1, 1) +]; +var _origin = /* @__PURE__ */ new Vector3(); +var PMREMGenerator = class { + /** + * Constructs a new PMREM generator. + * + * @param {WebGLRenderer} renderer - The renderer. + */ + constructor(renderer) { + this._renderer = renderer; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + /** + * Generates a PMREM from a supplied Scene, which can be faster than using an + * image if networking bandwidth is low. Optional sigma specifies a blur radius + * in radians to be applied to the scene before PMREM generation. Optional near + * and far planes ensure the scene is rendered in its entirety. + * + * @param {Scene} scene - The scene to be captured. + * @param {number} [sigma=0] - The blur radius in radians. + * @param {number} [near=0.1] - The near plane distance. + * @param {number} [far=100] - The far plane distance. + * @param {Object} [options={}] - The configuration options. + * @param {number} [options.size=256] - The texture size of the PMREM. + * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromScene(scene, sigma = 0, near = 0.1, far = 100, options = {}) { + const { + size = 256, + position = _origin + } = options; + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(size); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget, position); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + /** + * Generates a PMREM from an equirectangular texture, which can be either LDR + * or HDR. The ideal input image size is 1k (1024 x 512), + * as this matches best with the 256 x 256 cubemap output. + * + * @param {Texture} equirectangular - The equirectangular texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + /** + * Generates a PMREM from an cubemap texture, which can be either LDR + * or HDR. The ideal input cube size is 256 x 256, + * as this matches best with the 256 x 256 cubemap output. + * + * @param {Texture} cubemap - The cubemap texture to be converted. + * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. + * @return {WebGLRenderTarget} The resulting PMREM. + */ + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + /** + * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial(this._cubemapMaterial); + } + } + /** + * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during + * your texture's network fetch for increased concurrency. + */ + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial(this._equirectMaterial); + } + } + /** + * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, + * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on + * one of them will cause any others to also become unusable. + */ + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) this._equirectMaterial.dispose(); + } + // private interface + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose(); + for (let i6 = 0; i6 < this._lodPlanes.length; i6++) { + this._lodPlanes[i6].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel); + this._renderer.xr.enabled = _oldXrEnabled; + outputTarget.scissorTest = false; + _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width = 3 * Math.max(this._cubeSize, 16 * 7); + const height = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget(width, height, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget(width, height, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax)); + this._blurMaterial = _getBlurShader(_lodMax, width, height); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget, position) { + const fov2 = 90; + const aspect2 = 1; + const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer = this._renderer; + const originalAutoClear = renderer.autoClear; + const toneMapping = renderer.toneMapping; + renderer.getClearColor(_clearColor); + renderer.toneMapping = NoToneMapping; + renderer.autoClear = false; + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + if (reversedDepthBuffer) { + renderer.setRenderTarget(cubeUVRenderTarget); + renderer.clearDepth(); + renderer.setRenderTarget(null); + } + const backgroundMaterial = new MeshBasicMaterial({ + name: "PMREM.Background", + side: BackSide, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor); + useSolidColor = true; + } + for (let i6 = 0; i6 < 6; i6++) { + const col = i6 % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i6], 0); + cubeCamera.position.set(position.x, position.y, position.z); + cubeCamera.lookAt(position.x + forwardSign[i6], position.y, position.z); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i6]); + cubeCamera.position.set(position.x, position.y, position.z); + cubeCamera.lookAt(position.x, position.y + forwardSign[i6], position.z); + } else { + cubeCamera.up.set(0, upSign[i6], 0); + cubeCamera.position.set(position.x, position.y, position.z); + cubeCamera.lookAt(position.x, position.y, position.z + forwardSign[i6]); + } + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, col * size, i6 > 2 ? size : 0, size, size); + renderer.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer.render(backgroundBox, cubeCamera); + } + renderer.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer.toneMapping = toneMapping; + renderer.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer.setRenderTarget(cubeUVRenderTarget); + renderer.render(mesh, _flatCamera); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer = this._renderer; + const autoClear = renderer.autoClear; + renderer.autoClear = false; + const n7 = this._lodPlanes.length; + for (let i6 = 1; i6 < n7; i6++) { + const sigma = Math.sqrt(this._sigmas[i6] * this._sigmas[i6] - this._sigmas[i6 - 1] * this._sigmas[i6 - 1]); + const poleAxis = _axisDirections[(n7 - i6 - 1) % _axisDirections.length]; + this._blur(cubeUVRenderTarget, i6 - 1, i6, sigma, poleAxis); + } + renderer.autoClear = autoClear; + } + /** + * This is a two-pass Gaussian blur for a cubemap. Normally this is done + * vertically and horizontally, but this breaks down on a cube. Here we apply + * the blur latitudinally (around the poles), and then longitudinally (towards + * the poles) to approximate the orthogonally-separable blur. It is least + * accurate at the poles, but still does a decent job. + * + * @private + * @param {WebGLRenderTarget} cubeUVRenderTarget + * @param {number} lodIn + * @param {number} lodOut + * @param {number} sigma + * @param {Vector3} [poleAxis] + */ + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur( + cubeUVRenderTarget, + pingPongRenderTarget, + lodIn, + lodOut, + sigma, + "latitudinal", + poleAxis + ); + this._halfBlur( + pingPongRenderTarget, + cubeUVRenderTarget, + lodOut, + lodOut, + sigma, + "longitudinal", + poleAxis + ); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error( + "blur direction must be either latitudinal or longitudinal!" + ); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; + if (samples > MAX_SAMPLES) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); + } + const weights = []; + let sum = 0; + for (let i6 = 0; i6 < MAX_SAMPLES; ++i6) { + const x3 = i6 / sigmaPixels; + const weight = Math.exp(-x3 * x3 / 2); + weights.push(weight); + if (i6 === 0) { + sum += weight; + } else if (i6 < samples) { + sum += 2 * weight; + } + } + for (let i6 = 0; i6 < weights.length; i6++) { + weights[i6] = weights[i6] / sum; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x2 = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y3 = 4 * (this._cubeSize - outputSize); + _setViewport(targetOut, x2, y3, 3 * outputSize, 2 * outputSize); + renderer.setRenderTarget(targetOut); + renderer.render(blurMesh, _flatCamera); + } +}; +function _createPlanes(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + for (let i6 = 0; i6 < totalLods; i6++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i6 > lodMax - LOD_MIN) { + sigma = EXTRA_LOD_SIGMA[i6 - lodMax + LOD_MIN - 1]; + } else if (i6 === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0; face < cubeFaces; face++) { + const x2 = face % 3 * 2 / 3 - 1; + const y3 = face > 2 ? 0 : -1; + const coordinates = [ + x2, + y3, + 0, + x2 + 2 / 3, + y3, + 0, + x2 + 2 / 3, + y3 + 1, + 0, + x2, + y3, + 0, + x2 + 2 / 3, + y3 + 1, + 0, + x2, + y3 + 1, + 0 + ]; + position.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill = [face, face, face, face, face, face]; + faceIndex.set(fill, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry(); + planes.setAttribute("position", new BufferAttribute(position, positionSize)); + planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; +} +function _createRenderTarget(width, height, params) { + const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; +} +function _setViewport(target, x2, y3, width, height) { + target.viewport.set(x2, y3, width, height); + target.scissor.set(x2, y3, width, height); +} +function _getBlurShader(lodMax, width, height) { + const weights = new Float32Array(MAX_SAMPLES); + const poleAxis = new Vector3(0, 1, 0); + const shaderMaterial = new ShaderMaterial({ + name: "SphericalGaussianBlur", + defines: { + "n": MAX_SAMPLES, + "CUBEUV_TEXEL_WIDTH": 1 / width, + "CUBEUV_TEXEL_HEIGHT": 1 / height, + "CUBEUV_MAX_MIP": `${lodMax}.0` + }, + uniforms: { + "envMap": { value: null }, + "samples": { value: 1 }, + "weights": { value: weights }, + "latitudinal": { value: false }, + "dTheta": { value: 0 }, + "mipInt": { value: 0 }, + "poleAxis": { value: poleAxis } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; +} +function _getEquirectMaterial() { + return new ShaderMaterial({ + name: "EquirectangularToCubeUV", + uniforms: { + "envMap": { value: null } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCubemapMaterial() { + return new ShaderMaterial({ + name: "CubemapToCubeUV", + uniforms: { + "envMap": { value: null }, + "flipEnvMap": { value: -1 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + ` + ), + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCommonVertexShader() { + return ( + /* glsl */ + ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + ` + ); +} +function WebGLCubeUVMaps(renderer) { + let cubeUVmaps = /* @__PURE__ */ new WeakMap(); + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; + const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== void 0 ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== void 0) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length = 6; + for (let i6 = 0; i6 < length; i6++) { + if (image[i6] !== void 0) count++; + } + return count === length; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== void 0) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = /* @__PURE__ */ new WeakMap(); + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; +} +function WebGLExtensions(gl) { + const extensions = {}; + function getExtension(name) { + if (extensions[name] !== void 0) { + return extensions[name]; + } + let extension; + switch (name) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name); + } + extensions[name] = extension; + return extension; + } + return { + has: function(name) { + return getExtension(name) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name) { + const extension = getExtension(name); + if (extension === null) { + warnOnce("THREE.WebGLRenderer: " + name + " extension not supported."); + } + return extension; + } + }; +} +function WebGLGeometries(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = /* @__PURE__ */ new WeakMap(); + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name in geometry.attributes) { + attributes.remove(geometry.attributes[name]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name in geometryAttributes) { + attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i6 = 0, l3 = array.length; i6 < l3; i6 += 3) { + const a3 = array[i6 + 0]; + const b3 = array[i6 + 1]; + const c5 = array[i6 + 2]; + indices.push(a3, b3, b3, c5, c5, a3); + } + } else if (geometryPosition !== void 0) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i6 = 0, l3 = array.length / 3 - 1; i6 < l3; i6 += 3) { + const a3 = i6 + 0; + const b3 = i6 + 1; + const c5 = i6 + 2; + indices.push(a3, b3, b3, c5, c5, a3); + } + } else { + return; + } + const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; +} +function WebGLIndexedBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value) { + mode = value; + } + let type, bytesPerElement; + function setIndex(value) { + type = value.type; + bytesPerElement = value.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i6 = 0; i6 < drawCount; i6++) { + elementCount += counts[i6]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i6 = 0; i6 < starts.length; i6++) { + renderInstances(starts[i6] / bytesPerElement, counts[i6], primcount[i6]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i6 = 0; i6 < drawCount; i6++) { + elementCount += counts[i6] * primcount[i6]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLInfo(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; +} +function WebGLMorphtargets(gl, capabilities, textures) { + const morphTextures = /* @__PURE__ */ new WeakMap(); + const morph = new Vector4(); + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === void 0 || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== void 0) entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== void 0; + const hasMorphNormals = geometry.morphAttributes.normal !== void 0; + const hasMorphColors = geometry.morphAttributes.color !== void 0; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) vertexDataCount = 1; + if (hasMorphNormals === true) vertexDataCount = 2; + if (hasMorphColors === true) vertexDataCount = 3; + let width = geometry.attributes.position.count * vertexDataCount; + let height = 1; + if (width > capabilities.maxTextureSize) { + height = Math.ceil(width / capabilities.maxTextureSize); + width = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width * height * 4 * morphTargetsCount); + const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount); + texture.type = FloatType; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i6 = 0; i6 < morphTargetsCount; i6++) { + const morphTarget = morphTargets[i6]; + const morphNormal = morphNormals[i6]; + const morphColor = morphColors[i6]; + const offset = width * height * 4 * i6; + for (let j2 = 0; j2 < morphTarget.count; j2++) { + const stride = j2 * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j2); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j2); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j2); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector2(width, height) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i6 = 0; i6 < objectInfluences.length; i6++) { + morphInfluencesSum += objectInfluences[i6]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; +} +function WebGLObjects(gl, geometries, attributes, info) { + let updateMap = /* @__PURE__ */ new WeakMap(); + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = /* @__PURE__ */ new WeakMap(); + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; +} +var emptyTexture = /* @__PURE__ */ new Texture(); +var emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1); +var emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture(); +var empty3dTexture = /* @__PURE__ */ new Data3DTexture(); +var emptyCubeTexture = /* @__PURE__ */ new CubeTexture(); +var arrayCacheF32 = []; +var arrayCacheI32 = []; +var mat4array = new Float32Array(16); +var mat3array = new Float32Array(9); +var mat2array = new Float32Array(4); +function flatten(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) return array; + const n7 = nBlocks * blockSize; + let r6 = arrayCacheF32[n7]; + if (r6 === void 0) { + r6 = new Float32Array(n7); + arrayCacheF32[n7] = r6; + } + if (nBlocks !== 0) { + firstElem.toArray(r6, 0); + for (let i6 = 1, offset = 0; i6 !== nBlocks; ++i6) { + offset += blockSize; + array[i6].toArray(r6, offset); + } + } + return r6; +} +function arraysEqual(a3, b3) { + if (a3.length !== b3.length) return false; + for (let i6 = 0, l3 = a3.length; i6 < l3; i6++) { + if (a3[i6] !== b3[i6]) return false; + } + return true; +} +function copyArray(a3, b3) { + for (let i6 = 0, l3 = b3.length; i6 < l3; i6++) { + a3[i6] = b3[i6]; + } +} +function allocTexUnits(textures, n7) { + let r6 = arrayCacheI32[n7]; + if (r6 === void 0) { + r6 = new Int32Array(n7); + arrayCacheI32[n7] = r6; + } + for (let i6 = 0; i6 !== n7; ++i6) { + r6[i6] = textures.allocateTextureUnit(); + } + return r6; +} +function setValueV1f(gl, v2) { + const cache = this.cache; + if (cache[0] === v2) return; + gl.uniform1f(this.addr, v2); + cache[0] = v2; +} +function setValueV2f(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y) { + gl.uniform2f(this.addr, v2.x, v2.y); + cache[0] = v2.x; + cache[1] = v2.y; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform2fv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV3f(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z) { + gl.uniform3f(this.addr, v2.x, v2.y, v2.z); + cache[0] = v2.x; + cache[1] = v2.y; + cache[2] = v2.z; + } + } else if (v2.r !== void 0) { + if (cache[0] !== v2.r || cache[1] !== v2.g || cache[2] !== v2.b) { + gl.uniform3f(this.addr, v2.r, v2.g, v2.b); + cache[0] = v2.r; + cache[1] = v2.g; + cache[2] = v2.b; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform3fv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV4f(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z || cache[3] !== v2.w) { + gl.uniform4f(this.addr, v2.x, v2.y, v2.z, v2.w); + cache[0] = v2.x; + cache[1] = v2.y; + cache[2] = v2.z; + cache[3] = v2.w; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform4fv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueM2(gl, v2) { + const cache = this.cache; + const elements = v2.elements; + if (elements === void 0) { + if (arraysEqual(cache, v2)) return; + gl.uniformMatrix2fv(this.addr, false, v2); + copyArray(cache, v2); + } else { + if (arraysEqual(cache, elements)) return; + mat2array.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array); + copyArray(cache, elements); + } +} +function setValueM3(gl, v2) { + const cache = this.cache; + const elements = v2.elements; + if (elements === void 0) { + if (arraysEqual(cache, v2)) return; + gl.uniformMatrix3fv(this.addr, false, v2); + copyArray(cache, v2); + } else { + if (arraysEqual(cache, elements)) return; + mat3array.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array); + copyArray(cache, elements); + } +} +function setValueM4(gl, v2) { + const cache = this.cache; + const elements = v2.elements; + if (elements === void 0) { + if (arraysEqual(cache, v2)) return; + gl.uniformMatrix4fv(this.addr, false, v2); + copyArray(cache, v2); + } else { + if (arraysEqual(cache, elements)) return; + mat4array.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array); + copyArray(cache, elements); + } +} +function setValueV1i(gl, v2) { + const cache = this.cache; + if (cache[0] === v2) return; + gl.uniform1i(this.addr, v2); + cache[0] = v2; +} +function setValueV2i(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y) { + gl.uniform2i(this.addr, v2.x, v2.y); + cache[0] = v2.x; + cache[1] = v2.y; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform2iv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV3i(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z) { + gl.uniform3i(this.addr, v2.x, v2.y, v2.z); + cache[0] = v2.x; + cache[1] = v2.y; + cache[2] = v2.z; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform3iv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV4i(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z || cache[3] !== v2.w) { + gl.uniform4i(this.addr, v2.x, v2.y, v2.z, v2.w); + cache[0] = v2.x; + cache[1] = v2.y; + cache[2] = v2.z; + cache[3] = v2.w; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform4iv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV1ui(gl, v2) { + const cache = this.cache; + if (cache[0] === v2) return; + gl.uniform1ui(this.addr, v2); + cache[0] = v2; +} +function setValueV2ui(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y) { + gl.uniform2ui(this.addr, v2.x, v2.y); + cache[0] = v2.x; + cache[1] = v2.y; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform2uiv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV3ui(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z) { + gl.uniform3ui(this.addr, v2.x, v2.y, v2.z); + cache[0] = v2.x; + cache[1] = v2.y; + cache[2] = v2.z; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform3uiv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueV4ui(gl, v2) { + const cache = this.cache; + if (v2.x !== void 0) { + if (cache[0] !== v2.x || cache[1] !== v2.y || cache[2] !== v2.z || cache[3] !== v2.w) { + gl.uniform4ui(this.addr, v2.x, v2.y, v2.z, v2.w); + cache[0] = v2.x; + cache[1] = v2.y; + cache[2] = v2.z; + cache[3] = v2.w; + } + } else { + if (arraysEqual(cache, v2)) return; + gl.uniform4uiv(this.addr, v2); + copyArray(cache, v2); + } +} +function setValueT1(gl, v2, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture.compareFunction = LessEqualCompare; + emptyTexture2D = emptyShadowTexture; + } else { + emptyTexture2D = emptyTexture; + } + textures.setTexture2D(v2 || emptyTexture2D, unit); +} +function setValueT3D1(gl, v2, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v2 || empty3dTexture, unit); +} +function setValueT6(gl, v2, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v2 || emptyCubeTexture, unit); +} +function setValueT2DArray1(gl, v2, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v2 || emptyArrayTexture, unit); +} +function getSingularSetter(type) { + switch (type) { + case 5126: + return setValueV1f; + // FLOAT + case 35664: + return setValueV2f; + // _VEC2 + case 35665: + return setValueV3f; + // _VEC3 + case 35666: + return setValueV4f; + // _VEC4 + case 35674: + return setValueM2; + // _MAT2 + case 35675: + return setValueM3; + // _MAT3 + case 35676: + return setValueM4; + // _MAT4 + case 5124: + case 35670: + return setValueV1i; + // INT, BOOL + case 35667: + case 35671: + return setValueV2i; + // _VEC2 + case 35668: + case 35672: + return setValueV3i; + // _VEC3 + case 35669: + case 35673: + return setValueV4i; + // _VEC4 + case 5125: + return setValueV1ui; + // UINT + case 36294: + return setValueV2ui; + // _VEC2 + case 36295: + return setValueV3ui; + // _VEC3 + case 36296: + return setValueV4ui; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return setValueT1; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return setValueT3D1; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return setValueT6; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return setValueT2DArray1; + } +} +function setValueV1fArray(gl, v2) { + gl.uniform1fv(this.addr, v2); +} +function setValueV2fArray(gl, v2) { + const data = flatten(v2, this.size, 2); + gl.uniform2fv(this.addr, data); +} +function setValueV3fArray(gl, v2) { + const data = flatten(v2, this.size, 3); + gl.uniform3fv(this.addr, data); +} +function setValueV4fArray(gl, v2) { + const data = flatten(v2, this.size, 4); + gl.uniform4fv(this.addr, data); +} +function setValueM2Array(gl, v2) { + const data = flatten(v2, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data); +} +function setValueM3Array(gl, v2) { + const data = flatten(v2, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data); +} +function setValueM4Array(gl, v2) { + const data = flatten(v2, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data); +} +function setValueV1iArray(gl, v2) { + gl.uniform1iv(this.addr, v2); +} +function setValueV2iArray(gl, v2) { + gl.uniform2iv(this.addr, v2); +} +function setValueV3iArray(gl, v2) { + gl.uniform3iv(this.addr, v2); +} +function setValueV4iArray(gl, v2) { + gl.uniform4iv(this.addr, v2); +} +function setValueV1uiArray(gl, v2) { + gl.uniform1uiv(this.addr, v2); +} +function setValueV2uiArray(gl, v2) { + gl.uniform2uiv(this.addr, v2); +} +function setValueV3uiArray(gl, v2) { + gl.uniform3uiv(this.addr, v2); +} +function setValueV4uiArray(gl, v2) { + gl.uniform4uiv(this.addr, v2); +} +function setValueT1Array(gl, v2, textures) { + const cache = this.cache; + const n7 = v2.length; + const units = allocTexUnits(textures, n7); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i6 = 0; i6 !== n7; ++i6) { + textures.setTexture2D(v2[i6] || emptyTexture, units[i6]); + } +} +function setValueT3DArray(gl, v2, textures) { + const cache = this.cache; + const n7 = v2.length; + const units = allocTexUnits(textures, n7); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i6 = 0; i6 !== n7; ++i6) { + textures.setTexture3D(v2[i6] || empty3dTexture, units[i6]); + } +} +function setValueT6Array(gl, v2, textures) { + const cache = this.cache; + const n7 = v2.length; + const units = allocTexUnits(textures, n7); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i6 = 0; i6 !== n7; ++i6) { + textures.setTextureCube(v2[i6] || emptyCubeTexture, units[i6]); + } +} +function setValueT2DArrayArray(gl, v2, textures) { + const cache = this.cache; + const n7 = v2.length; + const units = allocTexUnits(textures, n7); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i6 = 0; i6 !== n7; ++i6) { + textures.setTexture2DArray(v2[i6] || emptyArrayTexture, units[i6]); + } +} +function getPureArraySetter(type) { + switch (type) { + case 5126: + return setValueV1fArray; + // FLOAT + case 35664: + return setValueV2fArray; + // _VEC2 + case 35665: + return setValueV3fArray; + // _VEC3 + case 35666: + return setValueV4fArray; + // _VEC4 + case 35674: + return setValueM2Array; + // _MAT2 + case 35675: + return setValueM3Array; + // _MAT3 + case 35676: + return setValueM4Array; + // _MAT4 + case 5124: + case 35670: + return setValueV1iArray; + // INT, BOOL + case 35667: + case 35671: + return setValueV2iArray; + // _VEC2 + case 35668: + case 35672: + return setValueV3iArray; + // _VEC3 + case 35669: + case 35673: + return setValueV4iArray; + // _VEC4 + case 5125: + return setValueV1uiArray; + // UINT + case 36294: + return setValueV2uiArray; + // _VEC2 + case 36295: + return setValueV3uiArray; + // _VEC3 + case 36296: + return setValueV4uiArray; + // _VEC4 + case 35678: + // SAMPLER_2D + case 36198: + // SAMPLER_EXTERNAL_OES + case 36298: + // INT_SAMPLER_2D + case 36306: + // UNSIGNED_INT_SAMPLER_2D + case 35682: + return setValueT1Array; + case 35679: + // SAMPLER_3D + case 36299: + // INT_SAMPLER_3D + case 36307: + return setValueT3DArray; + case 35680: + // SAMPLER_CUBE + case 36300: + // INT_SAMPLER_CUBE + case 36308: + // UNSIGNED_INT_SAMPLER_CUBE + case 36293: + return setValueT6Array; + case 36289: + // SAMPLER_2D_ARRAY + case 36303: + // INT_SAMPLER_2D_ARRAY + case 36311: + // UNSIGNED_INT_SAMPLER_2D_ARRAY + case 36292: + return setValueT2DArrayArray; + } +} +var SingleUniform = class { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter(activeInfo.type); + } +}; +var PureArrayUniform = class { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter(activeInfo.type); + } +}; +var StructuredUniform = class { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value, textures) { + const seq = this.seq; + for (let i6 = 0, n7 = seq.length; i6 !== n7; ++i6) { + const u3 = seq[i6]; + u3.setValue(gl, value[u3.id], textures); + } + } +}; +var RePathPart = /(\w+)(\])?(\[|\.)?/g; +function addUniform(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; +} +function parseUniform(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart.lastIndex = 0; + while (true) { + const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) id = id | 0; + if (subscript === void 0 || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform(container, subscript === void 0 ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); + break; + } else { + const map = container.map; + let next = map[id]; + if (next === void 0) { + next = new StructuredUniform(id); + addUniform(container, next); + } + container = next; + } + } +} +var WebGLUniforms = class { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n7 = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i6 = 0; i6 < n7; ++i6) { + const info = gl.getActiveUniform(program, i6), addr = gl.getUniformLocation(program, info.name); + parseUniform(info, addr, this); + } + } + setValue(gl, name, value, textures) { + const u3 = this.map[name]; + if (u3 !== void 0) u3.setValue(gl, value, textures); + } + setOptional(gl, object, name) { + const v2 = object[name]; + if (v2 !== void 0) this.setValue(gl, name, v2); + } + static upload(gl, seq, values, textures) { + for (let i6 = 0, n7 = seq.length; i6 !== n7; ++i6) { + const u3 = seq[i6], v2 = values[u3.id]; + if (v2.needsUpdate !== false) { + u3.setValue(gl, v2.value, textures); + } + } + } + static seqWithValue(seq, values) { + const r6 = []; + for (let i6 = 0, n7 = seq.length; i6 !== n7; ++i6) { + const u3 = seq[i6]; + if (u3.id in values) r6.push(u3); + } + return r6; + } +}; +function WebGLShader(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; +} +var COMPLETION_STATUS_KHR = 37297; +var programIdCount = 0; +function handleSource(string, errorLine) { + const lines = string.split("\n"); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i6 = from; i6 < to; i6++) { + const line = i6 + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i6]}`); + } + return lines2.join("\n"); +} +var _m0 = /* @__PURE__ */ new Matrix3(); +function getEncodingComponents(colorSpace) { + ColorManagement._getMatrix(_m0, ColorManagement.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m0.elements.map((v2) => v2.toFixed(4))} )`; + switch (ColorManagement.getTransfer(colorSpace)) { + case LinearTransfer: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } +} +function getShaderErrors(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const shaderInfoLog = gl.getShaderInfoLog(shader) || ""; + const errors = shaderInfoLog.trim(); + if (status && errors === "") return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + "\n\n" + errors + "\n\n" + handleSource(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } +} +function getTexelEncodingFunction(functionName, colorSpace) { + const components = getEncodingComponents(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join("\n"); +} +function getToneMappingFunction(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping: + toneMappingName = "AgX"; + break; + case NeutralToneMapping: + toneMappingName = "Neutral"; + break; + case CustomToneMapping: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; +} +var _v0 = /* @__PURE__ */ new Vector3(); +function getLuminanceFunction() { + ColorManagement.getLuminanceCoefficients(_v0); + const r6 = _v0.x.toFixed(4); + const g2 = _v0.y.toFixed(4); + const b3 = _v0.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r6}, ${g2}, ${b3} );`, + " return dot( weights, rgb );", + "}" + ].join("\n"); +} +function generateVertexExtensions(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine).join("\n"); +} +function generateDefines(defines) { + const chunks = []; + for (const name in defines) { + const value = defines[name]; + if (value === false) continue; + chunks.push("#define " + name + " " + value); + } + return chunks.join("\n"); +} +function fetchAttributeLocations(gl, program) { + const attributes = {}; + const n7 = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i6 = 0; i6 < n7; i6++) { + const info = gl.getActiveAttrib(program, i6); + const name = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) locationSize = 2; + if (info.type === gl.FLOAT_MAT3) locationSize = 3; + if (info.type === gl.FLOAT_MAT4) locationSize = 4; + attributes[name] = { + type: info.type, + location: gl.getAttribLocation(program, name), + locationSize + }; + } + return attributes; +} +function filterEmptyLine(string) { + return string !== ""; +} +function replaceLightNums(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); +} +function replaceClippingPlaneNums(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); +} +var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; +function resolveIncludes(string) { + return string.replace(includePattern, includeReplacer); +} +var shaderChunkMap = /* @__PURE__ */ new Map(); +function includeReplacer(match, include) { + let string = ShaderChunk[include]; + if (string === void 0) { + const newInclude = shaderChunkMap.get(include); + if (newInclude !== void 0) { + string = ShaderChunk[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes(string); +} +var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; +function unrollLoops(string) { + return string.replace(unrollLoopPattern, loopReplacer); +} +function loopReplacer(match, start, end, snippet) { + let string = ""; + for (let i6 = parseInt(start); i6 < parseInt(end); i6++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i6 + " ]").replace(/UNROLLED_LOOP_INDEX/g, i6); + } + return string; +} +function generatePrecision(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += "\n#define HIGH_PRECISION"; + } else if (parameters.precision === "mediump") { + precisionstring += "\n#define MEDIUM_PRECISION"; + } else if (parameters.precision === "lowp") { + precisionstring += "\n#define LOW_PRECISION"; + } + return precisionstring; +} +function generateShadowMapTypeDefine(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; +} +function generateEnvMapTypeDefine(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; +} +function generateEnvMapModeDefine(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; +} +function generateEnvMapBlendingDefine(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; +} +function generateCubeUVSize(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; +} +function WebGLProgram(renderer, cacheKey, parameters, bindingStates) { + const gl = renderer.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine(parameters); + const envMapModeDefine = generateEnvMapModeDefine(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); + const envMapCubeUVSize = generateCubeUVSize(parameters); + const customVertexExtensions = generateVertexExtensions(parameters); + const customDefines = generateDefines(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + "\n" : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join("\n"); + if (prefixVertex.length > 0) { + prefixVertex += "\n"; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join("\n"); + if (prefixFragment.length > 0) { + prefixFragment += "\n"; + } + } else { + prefixVertex = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + // + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + // + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", + parameters.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + " attribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + " attribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + " uniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + " attribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + " attribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + " attribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + " attribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + " attribute vec4 color;", + "#elif defined( USE_COLOR )", + " attribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + " attribute vec4 skinIndex;", + " attribute vec4 skinWeight;", + "#endif", + "\n" + ].filter(filterEmptyLine).join("\n"); + prefixFragment = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", + parameters.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", + // this code is required here because it is used by the toneMapping() function defined below + parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk["colorspace_pars_fragment"], + // this code is required here because it is used by the various encoding/decoding function defined below + getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + "\n" + ].filter(filterEmptyLine).join("\n"); + } + vertexShader = resolveIncludes(vertexShader); + vertexShader = replaceLightNums(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums(vertexShader, parameters); + fragmentShader = resolveIncludes(fragmentShader); + fragmentShader = replaceLightNums(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); + vertexShader = unrollLoops(vertexShader); + fragmentShader = unrollLoops(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = "#version 300 es\n"; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join("\n") + "\n" + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join("\n") + "\n" + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== void 0) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer.debug.checkShaderErrors) { + const programInfoLog = gl.getProgramInfoLog(program) || ""; + const vertexShaderInfoLog = gl.getShaderInfoLog(glVertexShader) || ""; + const fragmentShaderInfoLog = gl.getShaderInfoLog(glFragmentShader) || ""; + const programLog = programInfoLog.trim(); + const vertexLog = vertexShaderInfoLog.trim(); + const fragmentLog = fragmentShaderInfoLog.trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer.debug.onShaderError === "function") { + renderer.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); + console.error( + "THREE.WebGLProgram: Shader Error " + gl.getError() + " - VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + "\n\nMaterial Name: " + self2.name + "\nMaterial Type: " + self2.type + "\n\nProgram Info Log: " + programLog + "\n" + vertexErrors + "\n" + fragmentErrors + ); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms(gl, program); + cachedAttributes = fetchAttributeLocations(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === void 0) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === void 0) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = void 0; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; +} +var _id = 0; +var WebGLShaderCache = class { + constructor() { + this.shaderCache = /* @__PURE__ */ new Map(); + this.materialCache = /* @__PURE__ */ new Map(); + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === void 0) { + set = /* @__PURE__ */ new Set(); + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === void 0) { + stage = new WebGLShaderStage(code); + cache.set(code, stage); + } + return stage; + } +}; +var WebGLShaderStage = class { + constructor(code) { + this.id = _id++; + this.code = code; + this.usedTimes = 0; + } +}; +function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers(); + const _customShaders = new WebGLShaderCache(); + const _activeChannels = /* @__PURE__ */ new Set(); + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value) { + _activeChannels.add(value); + if (value === 0) return "uv"; + return `uv${value}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== void 0) morphTextureStride = 1; + if (geometry.morphAttributes.normal !== void 0) morphTextureStride = 2; + if (geometry.morphAttributes.color !== void 0) morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer.getRenderTarget(); + const reversedDepthBuffer = renderer.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + // + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + // + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true && material.wireframe === false, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reversedDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== void 0, + morphNormals: geometry.morphAttributes.normal !== void 0, + morphColors: geometry.morphAttributes.color !== void 0, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== void 0) { + for (const name in parameters.defines) { + array.push(name); + array.push(parameters.defines[name]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + if (parameters.gradientMap) + _programLayers.enable(22); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reversedDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib[shaderID]; + uniforms = UniformsUtils.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p3 = 0, pl = programs.length; p3 < pl; p3++) { + const preexistingProgram = programs[p3]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === void 0) { + program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i6 = programs.indexOf(program); + programs[i6] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + // Exposed for resource monitoring & error feedback via renderer.info: + programs, + dispose + }; +} +function WebGLProperties() { + let properties = /* @__PURE__ */ new WeakMap(); + function has(object) { + return properties.has(object); + } + function get(object) { + let map = properties.get(object); + if (map === void 0) { + map = {}; + properties.set(object, map); + } + return map; + } + function remove(object) { + properties.delete(object); + } + function update(object, key, value) { + properties.get(object)[key] = value; + } + function dispose() { + properties = /* @__PURE__ */ new WeakMap(); + } + return { + has, + get, + remove, + update, + dispose + }; +} +function painterSortStable(a3, b3) { + if (a3.groupOrder !== b3.groupOrder) { + return a3.groupOrder - b3.groupOrder; + } else if (a3.renderOrder !== b3.renderOrder) { + return a3.renderOrder - b3.renderOrder; + } else if (a3.material.id !== b3.material.id) { + return a3.material.id - b3.material.id; + } else if (a3.z !== b3.z) { + return a3.z - b3.z; + } else { + return a3.id - b3.id; + } +} +function reversePainterSortStable(a3, b3) { + if (a3.groupOrder !== b3.groupOrder) { + return a3.groupOrder - b3.groupOrder; + } else if (a3.renderOrder !== b3.renderOrder) { + return a3.renderOrder - b3.renderOrder; + } else if (a3.z !== b3.z) { + return b3.z - a3.z; + } else { + return a3.id - b3.id; + } +} +function WebGLRenderList() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z2, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === void 0) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z: z2, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z2; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z2, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z2, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z2, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z2, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable); + if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable); + if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable); + } + function finish() { + for (let i6 = renderItemsIndex, il = renderItems.length; i6 < il; i6++) { + const renderItem = renderItems[i6]; + if (renderItem.id === null) break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; +} +function WebGLRenderLists() { + let lists = /* @__PURE__ */ new WeakMap(); + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === void 0) { + list = new WebGLRenderList(); + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList(); + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; +} +function UniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== void 0) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector3(), + color: new Color() + }; + break; + case "SpotLight": + uniforms = { + position: new Vector3(), + direction: new Vector3(), + color: new Color(), + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector3(), + color: new Color(), + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector3(), + skyColor: new Color(), + groundColor: new Color() + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color(), + position: new Vector3(), + halfWidth: new Vector3(), + halfHeight: new Vector3() + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +function ShadowUniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== void 0) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2() + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2(), + shadowCameraNear: 1, + shadowCameraFar: 1e3 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +var nextVersion = 0; +function shadowCastingAndTexturingLightsFirst(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); +} +function WebGLLights(extensions) { + const cache = new UniformsCache(); + const shadowCache = ShadowUniformsCache(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i6 = 0; i6 < 9; i6++) state.probe.push(new Vector3()); + const vector3 = new Vector3(); + const matrix4 = new Matrix4(); + const matrix42 = new Matrix4(); + function setup(lights) { + let r6 = 0, g2 = 0, b3 = 0; + for (let i6 = 0; i6 < 9; i6++) state.probe[i6].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst); + for (let i6 = 0, l3 = lights.length; i6 < l3; i6++) { + const light = lights[i6]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r6 += color.r * intensity; + g2 += color.g * intensity; + b3 += color.b * intensity; + } else if (light.isLightProbe) { + for (let j2 = 0; j2 < 9; j2++) { + state.probe[j2].addScaledVector(light.sh.coefficients[j2], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } + } + state.ambient[0] = r6; + state.ambient[1] = g2; + state.ambient[2] = b3; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i6 = 0, l3 = lights.length; i6 < l3; i6++) { + const light = lights[i6]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; +} +function WebGLRenderState(extensions) { + const lights = new WebGLLights(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; +} +function WebGLRenderStates(extensions) { + let renderStates = /* @__PURE__ */ new WeakMap(); + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === void 0) { + renderState = new WebGLRenderState(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = /* @__PURE__ */ new WeakMap(); + } + return { + get, + dispose + }; +} +var vertex = "void main() {\n gl_Position = vec4( position, 1.0 );\n}"; +var fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n const float samples = float( VSM_SAMPLES );\n float mean = 0.0;\n float squared_mean = 0.0;\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n for ( float i = 0.0; i < samples; i ++ ) {\n float uvOffset = uvStart + i * uvStride;\n #ifdef HORIZONTAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean / samples;\n squared_mean = squared_mean / samples;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; +function WebGLShadowMap(renderer, objects, capabilities) { + let _frustum = new Frustum(); + const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), _viewport = new Vector4(), _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial(), _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide }; + const shadowMaterialVertical = new ShaderMaterial({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2() }, + radius: { value: 4 } + }, + vertexShader: vertex, + fragmentShader: fragment + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry(); + fullScreenTri.setAttribute( + "position", + new BufferAttribute( + new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), + 3 + ) + ); + const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) return; + if (scope.autoUpdate === false && scope.needsUpdate === false) return; + if (lights.length === 0) return; + const currentRenderTarget = renderer.getRenderTarget(); + const activeCubeFace = renderer.getActiveCubeFace(); + const activeMipmapLevel = renderer.getActiveMipmapLevel(); + const _state = renderer.state; + _state.setBlending(NoBlending); + if (_state.buffers.depth.getReversed() === true) { + _state.buffers.color.setClear(0, 0, 0, 0); + } else { + _state.buffers.color.setClear(1, 1, 1, 1); + } + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap && this.type === VSMShadowMap; + const fromVSM = _previousType === VSMShadowMap && this.type !== VSMShadowMap; + for (let i6 = 0, il = lights.length; i6 < il; i6++) { + const light = lights[i6]; + const shadow = light.shadow; + if (shadow === void 0) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer.setRenderTarget(shadow.map); + renderer.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0; vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport.set( + _viewportSize.x * viewport.x, + _viewportSize.y * viewport.y, + _viewportSize.x * viewport.z, + _viewportSize.y * viewport.w + ); + _state.viewport(_viewport); + shadow.updateMatrices(light, vp); + _frustum = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget(shadow.mapPass); + renderer.clear(); + renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer.setRenderTarget(shadow.map); + renderer.clear(); + renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== void 0) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0 || material.alphaToCoverage === true) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === void 0) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === void 0) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaToCoverage === true ? 0.5 : material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k2 = 0, kl = groups.length; k2 < kl; k2++) { + const group = groups[k2]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + renderObject(children[i6], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } +} +var reversedFuncs = { + [NeverDepth]: AlwaysDepth, + [LessDepth]: GreaterDepth, + [EqualDepth]: NotEqualDepth, + [LessEqualDepth]: GreaterEqualDepth, + [AlwaysDepth]: NeverDepth, + [GreaterDepth]: LessDepth, + [NotEqualDepth]: EqualDepth, + [GreaterEqualDepth]: LessEqualDepth +}; +function WebGLState(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector4(); + let currentColorMask = null; + const currentColorClear = new Vector4(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r6, g2, b3, a3, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r6 *= a3; + g2 *= a3; + b3 *= a3; + } + color.set(r6, g2, b3, a3); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r6, g2, b3, a3); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let currentReversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(reversed) { + if (currentReversed !== reversed) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + currentReversed = reversed; + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + }, + getReversed: function() { + return currentReversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (currentReversed) depthFunc = reversedFuncs[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (currentReversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + currentReversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer(); + const depthBuffer = new DepthBuffer(); + const stencilBuffer = new StencilBuffer(); + const uboBindings = /* @__PURE__ */ new WeakMap(); + const uboProgramMap = /* @__PURE__ */ new WeakMap(); + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = /* @__PURE__ */ new WeakMap(); + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector4().fromArray(scissorParam); + const currentViewport = new Vector4().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i6 = 0; i6 < count; i6++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } else { + gl.texImage2D(target + i6, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth); + setFlipSided(false); + setCullFace(CullFaceBack); + enable(gl.CULL_FACE); + setBlending(NoBlending); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === void 0) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i6 = 0, il = textures.length; i6 < il; i6++) { + drawBuffers2[i6] = gl.COLOR_ATTACHMENT0 + i6; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation]: gl.FUNC_ADD, + [SubtractEquation]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation] = gl.MIN; + equationToGL[MaxEquation] = gl.MAX; + const factorToGL = { + [ZeroFactor]: gl.ZERO, + [OneFactor]: gl.ONE, + [SrcColorFactor]: gl.SRC_COLOR, + [SrcAlphaFactor]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor]: gl.DST_COLOR, + [DstAlphaFactor]: gl.DST_ALPHA, + [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFuncSeparate(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true"); + break; + case MultiplyBlending: + console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true"); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide; + if (frontFaceCW) flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width) { + if (width !== currentLineWidth) { + if (lineWidthAvailable) gl.lineWidth(width); + currentLineWidth = width; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === void 0) webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === void 0) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === void 0) { + boundTexture = { type: void 0, texture: void 0 }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== void 0 && boundTexture.type !== void 0) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = void 0; + boundTexture.texture = void 0; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D(...arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === void 0) { + mapping = /* @__PURE__ */ new WeakMap(); + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === void 0) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = /* @__PURE__ */ new WeakMap(); + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; +} +function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector2(); + const _videoTextures = /* @__PURE__ */ new WeakMap(); + let _canvas2; + const _sources = /* @__PURE__ */ new WeakMap(); + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width, height) { + return useOffscreenCanvas ? ( + // eslint-disable-next-line compat/compat + new OffscreenCanvas(width, height) + ) : createElementNS("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width = Math.floor(scale * dimensions.width); + const height = Math.floor(scale * dimensions.height); + if (_canvas2 === void 0) _canvas2 = createCanvas(width, height); + const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas2; + canvas.width = width; + canvas.height = height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width, height); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width + "x" + height + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== void 0) return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) internalFormat = _gl.R8I; + if (glType === _gl.SHORT) internalFormat = _gl.R16I; + if (glType === _gl.INT) internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) internalFormat = _gl.RG16I; + if (glType === _gl.INT) internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) internalFormat = _gl.RGB16I; + if (glType === _gl.INT) internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) internalFormat = _gl.RGB9_E5; + if (glType === _gl.UNSIGNED_INT_10F_11F_11F_REV) internalFormat = _gl.R11F_G11F_B10F; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace); + if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== void 0 && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === void 0) return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i6 = 0; i6 < 6; i6++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i6])) { + for (let level = 0; level < renderTargetProperties.__webglFramebuffer[i6].length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i6][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i6]); + } + if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i6]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level++) _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i6 = 0; i6 < renderTargetProperties.__webglColorRenderbuffer.length; i6++) { + if (renderTargetProperties.__webglColorRenderbuffer[i6]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i6]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i6 = 0, il = textures.length; i6 < il; i6++) { + const attachmentProperties = properties.get(textures[i6]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i6]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } else if (texture.isExternalTexture) { + textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null; + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping]: _gl.REPEAT, + [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter]: _gl.NEAREST, + [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter]: _gl.LINEAR, + [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare]: _gl.NEVER, + [AlwaysCompare]: _gl.ALWAYS, + [LessCompare]: _gl.LESS, + [LessEqualCompare]: _gl.LEQUAL, + [EqualCompare]: _gl.EQUAL, + [GreaterEqualCompare]: _gl.GEQUAL, + [GreaterCompare]: _gl.GREATER, + [NotEqualCompare]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter) return; + if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) return; + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === void 0) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === void 0) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === void 0) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== void 0) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function getRow(index, rowLength, componentStride) { + return Math.floor(Math.floor(index / componentStride) / rowLength); + } + function updateTexture(texture, image, glFormat, glType) { + const componentStride = 4; + const updateRanges = texture.updateRanges; + if (updateRanges.length === 0) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } else { + updateRanges.sort((a3, b3) => a3.start - b3.start); + let mergeIndex = 0; + for (let i6 = 1; i6 < updateRanges.length; i6++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i6]; + const previousEnd = previousRange.start + previousRange.count; + const currentRow = getRow(range.start, image.width, componentStride); + const previousRow = getRow(previousRange.start, image.width, componentStride); + if (range.start <= previousEnd + 1 && currentRow === previousRow && getRow(range.start + range.count - 1, image.width, componentStride) === currentRow) { + previousRange.count = Math.max( + previousRange.count, + range.start + range.count - previousRange.start + ); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + for (let i6 = 0, l3 = updateRanges.length; i6 < l3; i6++) { + const range = updateRanges[i6]; + const pixelStart = Math.floor(range.start / componentStride); + const pixelCount = Math.ceil(range.count / componentStride); + const x2 = pixelStart % image.width; + const y3 = Math.floor(pixelStart / image.width); + const width = pixelCount; + const height = 1; + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, x2); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, y3); + state.texSubImage2D(_gl.TEXTURE_2D, 0, x2, y3, width, height, glFormat, glType, image.data); + } + texture.clearUpdateRanges(); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + } + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i6 = 0, il = mipmaps.length; i6 < il; i6++) { + mipmap = mipmaps[i6]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i6, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i6, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + updateTexture(texture, image, glFormat, glType); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i6 = 0, il = mipmaps.length; i6 < il; i6++) { + mipmap = mipmaps[i6]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray( + layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, + (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT + ); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i6, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i6, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i6, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i6, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i6, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i6 = 0, il = mipmaps.length; i6 < il; i6++) { + mipmap = mipmaps[i6]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i6, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i6, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i6, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i6, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray( + layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, + (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT + ); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let width = image.width, height = image.height; + for (let i6 = 0; i6 < levels; i6++) { + state.texImage2D(_gl.TEXTURE_2D, i6, glInternalFormat, width, height, 0, glFormat, glType, null); + width >>= 1; + height >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i6 = 0, il = mipmaps.length; i6 < il; i6++) { + mipmap = mipmaps[i6]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i6, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i6, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i6 = 0; i6 < 6; i6++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i6] = resizeImage(texture.image[i6], true, capabilities.maxCubemapSize); + } else { + cubeImage[i6] = isDataTexture ? texture.image[i6].image : texture.image[i6]; + } + cubeImage[i6] = verifyColorSpace(texture, cubeImage[i6]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i6 = 0; i6 < 6; i6++) { + mipmaps = cubeImage[i6].mipmaps; + for (let j2 = 0; j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i6 = 0; i6 < 6; i6++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, 0, 0, 0, cubeImage[i6].width, cubeImage[i6].height, glFormat, glType, cubeImage[i6].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, 0, glInternalFormat, cubeImage[i6].width, cubeImage[i6].height, 0, glFormat, glType, cubeImage[i6].data); + } + for (let j2 = 0; j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + const mipmapImage = mipmap.image[i6].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2 + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2 + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, 0, 0, 0, glFormat, glType, cubeImage[i6]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, 0, glInternalFormat, glFormat, glType, cubeImage[i6]); + } + for (let j2 = 0; j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2 + 1, 0, 0, glFormat, glType, mipmap.image[i6]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, j2 + 1, glInternalFormat, glFormat, glType, mipmap.image[i6]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width = Math.max(1, renderTarget.width >> level); + const height = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i6 = 0; i6 < textures.length; i6++) { + const texture = textures[i6]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) throw new Error("target.depthTexture not supported in Cube render targets"); + const mipmaps = renderTarget.texture.mipmaps; + if (mipmaps && mipmaps.length > 0) { + setupDepthTexture(renderTargetProperties.__webglFramebuffer[0], renderTarget); + } else { + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i6 = 0; i6 < 6; i6++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i6]); + if (renderTargetProperties.__webglDepthbuffer[i6] === void 0) { + renderTargetProperties.__webglDepthbuffer[i6] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i6], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i6]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + const mipmaps = renderTarget.texture.mipmaps; + if (mipmaps && mipmaps.length > 0) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[0]); + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer === void 0) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== void 0) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== void 0) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === void 0) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i6 = 0; i6 < 6; i6++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i6] = []; + for (let level = 0; level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i6][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i6] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0; level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i6 = 0, il = textures.length; i6 < il; i6++) { + const attachmentProperties = properties.get(textures[i6]); + if (attachmentProperties.__webglTexture === void 0) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i6 = 0; i6 < textures.length; i6++) { + const texture2 = textures[i6]; + renderTargetProperties.__webglColorRenderbuffer[i6] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i6]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i6, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i6]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i6 = 0; i6 < 6; i6++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0; level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i6][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i6], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i6, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i6 = 0, il = textures.length; i6 < il; i6++) { + const attachment = textures[i6]; + const attachmentProperties = properties.get(attachment); + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, attachmentProperties.__webglTexture); + setTextureParameters(glTextureType, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i6, glTextureType, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(glTextureType); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0; level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i6 = 0, il = textures.length; i6 < il; i6++) { + const texture = textures[i6]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width = renderTarget.width; + const height = renderTarget.height; + let mask = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i6 = 0; i6 < textures.length; i6++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i6, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i6, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + const mipmaps = renderTarget.texture.mipmaps; + if (mipmaps && mipmaps.length > 0) { + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[0]); + } else { + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + } + for (let i6 = 0; i6 < textures.length; i6++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i6]); + const webglTexture = properties.get(textures[i6]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i6); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i6 = 0; i6 < textures.length; i6++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i6, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i6]); + const webglTexture = properties.get(textures[i6]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i6, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) return image; + if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) { + if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) { + if (format !== RGBAFormat || type !== UnsignedByteType) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; +} +function WebGLUtils(gl, extensions) { + function convert(p3, colorSpace = NoColorSpace) { + let extension; + const transfer = ColorManagement.getTransfer(colorSpace); + if (p3 === UnsignedByteType) return gl.UNSIGNED_BYTE; + if (p3 === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4; + if (p3 === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1; + if (p3 === UnsignedInt5999Type) return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p3 === UnsignedInt101111Type) return gl.UNSIGNED_INT_10F_11F_11F_REV; + if (p3 === ByteType) return gl.BYTE; + if (p3 === ShortType) return gl.SHORT; + if (p3 === UnsignedShortType) return gl.UNSIGNED_SHORT; + if (p3 === IntType) return gl.INT; + if (p3 === UnsignedIntType) return gl.UNSIGNED_INT; + if (p3 === FloatType) return gl.FLOAT; + if (p3 === HalfFloatType) return gl.HALF_FLOAT; + if (p3 === AlphaFormat) return gl.ALPHA; + if (p3 === RGBFormat) return gl.RGB; + if (p3 === RGBAFormat) return gl.RGBA; + if (p3 === DepthFormat) return gl.DEPTH_COMPONENT; + if (p3 === DepthStencilFormat) return gl.DEPTH_STENCIL; + if (p3 === RedFormat) return gl.RED; + if (p3 === RedIntegerFormat) return gl.RED_INTEGER; + if (p3 === RGFormat) return gl.RG; + if (p3 === RGIntegerFormat) return gl.RG_INTEGER; + if (p3 === RGBAIntegerFormat) return gl.RGBA_INTEGER; + if (p3 === RGB_S3TC_DXT1_Format || p3 === RGBA_S3TC_DXT1_Format || p3 === RGBA_S3TC_DXT3_Format || p3 === RGBA_S3TC_DXT5_Format) { + if (transfer === SRGBTransfer) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p3 === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p3 === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p3 === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p3 === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p3 === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p3 === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p3 === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p3 === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p3 === RGB_PVRTC_4BPPV1_Format || p3 === RGB_PVRTC_2BPPV1_Format || p3 === RGBA_PVRTC_4BPPV1_Format || p3 === RGBA_PVRTC_2BPPV1_Format) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p3 === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p3 === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p3 === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p3 === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p3 === RGB_ETC1_Format || p3 === RGB_ETC2_Format || p3 === RGBA_ETC2_EAC_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p3 === RGB_ETC1_Format || p3 === RGB_ETC2_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p3 === RGBA_ETC2_EAC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p3 === RGBA_ASTC_4x4_Format || p3 === RGBA_ASTC_5x4_Format || p3 === RGBA_ASTC_5x5_Format || p3 === RGBA_ASTC_6x5_Format || p3 === RGBA_ASTC_6x6_Format || p3 === RGBA_ASTC_8x5_Format || p3 === RGBA_ASTC_8x6_Format || p3 === RGBA_ASTC_8x8_Format || p3 === RGBA_ASTC_10x5_Format || p3 === RGBA_ASTC_10x6_Format || p3 === RGBA_ASTC_10x8_Format || p3 === RGBA_ASTC_10x10_Format || p3 === RGBA_ASTC_12x10_Format || p3 === RGBA_ASTC_12x12_Format) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p3 === RGBA_ASTC_4x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p3 === RGBA_ASTC_5x4_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p3 === RGBA_ASTC_5x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p3 === RGBA_ASTC_6x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p3 === RGBA_ASTC_6x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p3 === RGBA_ASTC_8x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p3 === RGBA_ASTC_8x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p3 === RGBA_ASTC_8x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p3 === RGBA_ASTC_10x5_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p3 === RGBA_ASTC_10x6_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p3 === RGBA_ASTC_10x8_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p3 === RGBA_ASTC_10x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p3 === RGBA_ASTC_12x10_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p3 === RGBA_ASTC_12x12_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p3 === RGBA_BPTC_Format || p3 === RGB_BPTC_SIGNED_Format || p3 === RGB_BPTC_UNSIGNED_Format) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p3 === RGBA_BPTC_Format) return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p3 === RGB_BPTC_SIGNED_Format) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p3 === RGB_BPTC_UNSIGNED_Format) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p3 === RED_RGTC1_Format || p3 === SIGNED_RED_RGTC1_Format || p3 === RED_GREEN_RGTC2_Format || p3 === SIGNED_RED_GREEN_RGTC2_Format) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p3 === RED_RGTC1_Format) return extension.COMPRESSED_RED_RGTC1_EXT; + if (p3 === SIGNED_RED_RGTC1_Format) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p3 === RED_GREEN_RGTC2_Format) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p3 === SIGNED_RED_GREEN_RGTC2_Format) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p3 === UnsignedInt248Type) return gl.UNSIGNED_INT_24_8; + return gl[p3] !== void 0 ? gl[p3] : null; + } + return { convert }; +} +var _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; +var _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; +var WebXRDepthSensing = class { + /** + * Constructs a new depth sensing module. + */ + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + /** + * Inits the depth sensing module + * + * @param {XRWebGLDepthInformation} depthData - The XR depth data. + * @param {XRRenderState} renderState - The XR render state. + */ + init(depthData, renderState) { + if (this.texture === null) { + const texture = new ExternalTexture(depthData.texture); + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + /** + * Returns a plane mesh that visualizes the depth texture. + * + * @param {ArrayCamera} cameraXR - The XR camera. + * @return {?Mesh} The plane mesh. + */ + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial({ + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh(new PlaneGeometry(20, 20), material); + } + } + return this.mesh; + } + /** + * Resets the module + */ + reset() { + this.texture = null; + this.mesh = null; + } + /** + * Returns a texture representing the depth of the user's environment. + * + * @return {?ExternalTexture} The depth texture. + */ + getDepthTexture() { + return this.texture; + } +}; +var WebXRManager = class extends EventDispatcher { + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer} renderer - The renderer. + * @param {WebGL2RenderingContext} gl - The rendering context. + */ + constructor(renderer, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const supportsGlBinding = typeof XRWebGLBinding !== "undefined"; + const depthSensing = new WebXRDepthSensing(); + const cameraAccessTextures = {}; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector2(); + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera(); + cameraL.viewport = new Vector4(); + const cameraR = new PerspectiveCamera(); + cameraR.viewport = new Vector4(); + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera(); + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index) { + let controller = controllers[index]; + if (controller === void 0) { + controller = new WebXRController(); + controllers[index] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== void 0) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i6 = 0; i6 < controllers.length; i6++) { + const inputSource = controllerInputSources[i6]; + if (inputSource === null) continue; + controllerInputSources[i6] = null; + controllers[i6].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + for (const key in cameraAccessTextures) { + delete cameraAccessTextures[key]; + } + renderer.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer.setPixelRatio(currentPixelRatio); + renderer.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value) { + framebufferScaleFactor = value; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value) { + referenceSpaceType = value; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + if (glBinding === null && supportsGlBinding) { + glBinding = new XRWebGLBinding(session, gl); + } + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value) { + session = value; + if (session !== null) { + initialRenderTarget = renderer.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer.getPixelRatio(); + renderer.getSize(currentSize); + const supportsLayers = supportsGlBinding && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!supportsLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer.setPixelRatio(1); + renderer.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget( + glBaseLayer.framebufferWidth, + glBaseLayer.framebufferHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer.outputColorSpace, + stencilBuffer: attributes.stencil, + resolveDepthBuffer: glBaseLayer.ignoreDepthValues === false, + resolveStencilBuffer: glBaseLayer.ignoreDepthValues === false + } + ); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = this.getBinding(); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer.setPixelRatio(1); + renderer.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget( + glProjLayer.textureWidth, + glProjLayer.textureHeight, + { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, void 0, void 0, void 0, void 0, void 0, void 0, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false, + resolveStencilBuffer: glProjLayer.ignoreDepthValues === false + } + ); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i6 = 0; i6 < event.removed.length; i6++) { + const inputSource = event.removed[i6]; + const index = controllerInputSources.indexOf(inputSource); + if (index >= 0) { + controllerInputSources[index] = null; + controllers[index].disconnect(inputSource); + } + } + for (let i6 = 0; i6 < event.added.length; i6++) { + const inputSource = event.added[i6]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i7 = 0; i7 < controllers.length; i7++) { + if (i7 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i7; + break; + } else if (controllerInputSources[i7] === null) { + controllerInputSources[i7] = inputSource; + controllerIndex = i7; + break; + } + } + if (controllerIndex === -1) break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector3(); + const cameraRPos = new Vector3(); + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent) { + if (parent === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraXR.layers.mask = camera.layers.mask | 6; + cameraL.layers.mask = cameraXR.layers.mask & 3; + cameraR.layers.mask = cameraXR.layers.mask & 5; + const parent = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent); + for (let i6 = 0; i6 < cameras2.length; i6++) { + updateCamera(cameras2[i6], parent); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent); + }; + function updateUserCamera(camera, cameraXR2, parent) { + if (parent === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return void 0; + } + return foveation; + }; + this.setFoveation = function(value) { + foveation = value; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== void 0) { + glBaseLayer.fixedFoveation = value; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + this.getCameraTexture = function(xrCamera) { + return cameraAccessTextures[xrCamera]; + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i6 = 0; i6 < views.length; i6++) { + const view = views[i6]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i6 === 0) { + renderer.setRenderTargetTextures( + newRenderTarget, + glSubImage.colorTexture, + glSubImage.depthStencilTexture + ); + renderer.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i6]; + if (camera === void 0) { + camera = new PerspectiveCamera(); + camera.layers.enable(i6); + camera.viewport = new Vector4(); + cameras[i6] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i6 === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && supportsGlBinding) { + glBinding = scope.getBinding(); + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(depthData, session.renderState); + } + } + const cameraAccessEnabled = enabledFeatures && enabledFeatures.includes("camera-access"); + if (cameraAccessEnabled && supportsGlBinding) { + renderer.state.unbindTexture(); + glBinding = scope.getBinding(); + for (let i6 = 0; i6 < views.length; i6++) { + const camera = views[i6].camera; + if (camera) { + let cameraTex = cameraAccessTextures[camera]; + if (!cameraTex) { + cameraTex = new ExternalTexture(); + cameraAccessTextures[camera] = cameraTex; + } + const glTexture = glBinding.getCameraImage(camera); + cameraTex.sourceTexture = glTexture; + } + } + } + } + for (let i6 = 0; i6 < controllers.length; i6++) { + const inputSource = controllerInputSources[i6]; + const controller = controllers[i6]; + if (inputSource !== null && controller !== void 0) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation(); + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } +}; +var _e1 = /* @__PURE__ */ new Euler(); +var _m12 = /* @__PURE__ */ new Matrix4(); +function WebGLMaterials(renderer, properties) { + function refreshTransformUniform(map, uniform) { + if (map.matrixAutoUpdate === true) { + map.updateMatrix(); + } + uniform.value.copy(map.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e1.copy(envMapRotation); + _e1.x *= -1; + _e1.y *= -1; + _e1.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e1.y *= -1; + _e1.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m12.makeRotationFromEuler(_e1)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 1e-4); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; +} +function WebGLUniformsGroups(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === void 0) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i6 = 0; i6 < maxBindingPoints; i6++) { + if (allocatedBindingPoints.indexOf(i6) === -1) { + allocatedBindingPoints.push(i6); + return i6; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i6 = 0, il = uniforms.length; i6 < il; i6++) { + const uniformArray = Array.isArray(uniforms[i6]) ? uniforms[i6] : [uniforms[i6]]; + for (let j2 = 0, jl = uniformArray.length; j2 < jl; j2++) { + const uniform = uniformArray[j2]; + if (hasUniformChanged(uniform, i6, j2, cache) === true) { + const offset = uniform.__offset; + const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k2 = 0; k2 < values.length; k2++) { + const value = values[k2]; + const info2 = getUniformSize(value); + if (typeof value === "number" || typeof value === "boolean") { + uniform.__data[0] = value; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value.isMatrix3) { + uniform.__data[0] = value.elements[0]; + uniform.__data[1] = value.elements[1]; + uniform.__data[2] = value.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value.elements[3]; + uniform.__data[5] = value.elements[4]; + uniform.__data[6] = value.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value.elements[6]; + uniform.__data[9] = value.elements[7]; + uniform.__data[10] = value.elements[8]; + uniform.__data[11] = 0; + } else { + value.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index, indexArray, cache) { + const value = uniform.value; + const indexString = index + "_" + indexArray; + if (cache[indexString] === void 0) { + if (typeof value === "number" || typeof value === "boolean") { + cache[indexString] = value; + } else { + cache[indexString] = value.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value === "number" || typeof value === "boolean") { + if (cachedObject !== value) { + cache[indexString] = value; + return true; + } + } else { + if (cachedObject.equals(value) === false) { + cachedObject.copy(value); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i6 = 0, l3 = uniforms.length; i6 < l3; i6++) { + const uniformArray = Array.isArray(uniforms[i6]) ? uniforms[i6] : [uniforms[i6]]; + for (let j2 = 0, jl = uniformArray.length; j2 < jl; j2++) { + const uniform = uniformArray[j2]; + const values = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k2 = 0, kl = values.length; k2 < kl; k2++) { + const value = values[k2]; + const info2 = getUniformSize(value); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value) { + const info2 = { + boundary: 0, + // bytes + storage: 0 + // bytes + }; + if (typeof value === "number" || typeof value === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value.isVector3 || value.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; +} +var WebGLRenderer = class { + /** + * Constructs a new WebGL renderer. + * + * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. + */ + constructor(parameters = {}) { + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reversedDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + /** + * Enables error checking and reporting when shader programs are being compiled. + * @type {boolean} + */ + checkShaderErrors: true, + /** + * Callback for custom error reporting. + * @type {?Function} + */ + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1; + this.transmissionResolutionScale = 1; + const _this = this; + let _isContextLost = false; + this._outputColorSpace = SRGBColorSpace; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector4(); + const _currentScissor = new Vector4(); + let _currentScissorTest = null; + const _currentClearColor = new Color(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector4(0, 0, _width, _height); + const _scissor = new Vector4(0, 0, _width, _height); + let _scissorTest = false; + const _frustum = new Frustum(); + let _clippingEnabled = false; + let _localClippingEnabled = false; + const _projScreenMatrix = new Matrix4(); + const _vector3 = new Vector3(); + const _vector4 = new Vector4(); + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) canvas.setAttribute("data-engine", `three.js r${REVISION}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions(_gl); + extensions.init(); + utils = new WebGLUtils(_gl, extensions); + capabilities = new WebGLCapabilities(_gl, extensions, parameters, utils); + state = new WebGLState(_gl, extensions); + if (capabilities.reversedDepthBuffer && reversedDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo(_gl); + properties = new WebGLProperties(); + textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps(_this); + cubeuvmaps = new WebGLCubeUVMaps(_this); + attributes = new WebGLAttributes(_gl); + bindingStates = new WebGLBindingStates(_gl, attributes); + geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); + objects = new WebGLObjects(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); + clipping = new WebGLClipping(properties); + programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials(_this, properties); + renderLists = new WebGLRenderLists(); + renderStates = new WebGLRenderStates(extensions); + background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value) { + if (value === void 0) return; + _pixelRatio = value; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width, height, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width; + _height = height; + canvas.width = Math.floor(width * _pixelRatio); + canvas.height = Math.floor(height * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width + "px"; + canvas.style.height = height + "px"; + } + this.setViewport(0, 0, width, height); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width, height, pixelRatio) { + _width = width; + _height = height; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width * pixelRatio); + canvas.height = Math.floor(height * pixelRatio); + this.setViewport(0, 0, width, height); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x2, y3, width, height) { + if (x2.isVector4) { + _viewport.set(x2.x, x2.y, x2.z, x2.w); + } else { + _viewport.set(x2, y3, width, height); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x2, y3, width, height) { + if (x2.isVector4) { + _scissor.set(x2.x, x2.y, x2.z, x2.w); + } else { + _scissor.set(x2, y3, width, height); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor(...arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha(...arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || targetFormat === RGIntegerFormat || targetFormat === RedIntegerFormat; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || targetType === UnsignedIntType || targetType === UnsignedShortType || targetType === UnsignedInt248Type || targetType === UnsignedShort4444Type || targetType === UnsignedShort5551Type; + const clearColor = background.getClearColor(); + const a3 = background.getClearAlpha(); + const r6 = clearColor.r; + const g2 = clearColor.g; + const b3 = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r6; + uintClearColor[1] = g2; + uintClearColor[2] = b3; + uintClearColor[3] = a3; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r6; + intClearColor[1] = g2; + intClearColor[2] = b3; + intClearColor[3] = a3; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== void 0) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index = geometries.getWireframeAttribute(geometry); + if (index === void 0) return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index.count); + } else if (position !== void 0 && position !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) return; + bindingStates.setup(object, material, program, geometry, index); + let attribute; + let renderer = bufferRenderer; + if (index !== null) { + attribute = attributes.get(index); + renderer = indexedBufferRenderer; + renderer.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer.setMode(_gl.LINES); + } else { + renderer.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === void 0) lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer.setMode(_gl.LINE_LOOP); + } else { + renderer.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + warnOnce("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."); + renderer.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index ? attributes.get(index).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i6 = 0; i6 < drawCount2; i6++) { + uniforms.setValue(_gl, "_gl_DrawID", i6); + renderer.render(starts[i6] / bytesPerElement, counts[i6]); + } + } else { + renderer.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== void 0 ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = /* @__PURE__ */ new Set(); + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i6 = 0; i6 < material.length; i6++) { + const material2 = material[i6]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + currentRenderState = renderStateStack.pop(); + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time) { + if (onAnimationFrameCallback) onAnimationFrameCallback(time); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation(); + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== void 0 && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) return; + if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum.setFromProjectionMatrix(_projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) clipping.endShadows(); + if (this.info.autoReset === true) this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i6 = 0, l3 = cameras.length; i6 < l3; i6++) { + const camera2 = cameras[i6]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) background.render(scene); + for (let i6 = 0, l3 = cameras.length; i6 < l3; i6++) { + const camera2 = cameras[i6]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum.intersectsSprite(object)) { + if (sortObjects) { + _vector4.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== void 0) { + if (object.boundingSphere === null) object.computeBoundingSphere(); + _vector4.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); + _vector4.copy(geometry.boundingSphere.center); + } + _vector4.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i6 = 0, l3 = groups.length; i6 < l3; i6++) { + const group = groups[i6]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector4.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } + } + const children = object.children; + for (let i6 = 0, l3 = children.length; i6 < l3; i6++) { + projectObject(children[i6], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === void 0) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + const currentActiveCubeFace = _this.getActiveCubeFace(); + const currentActiveMipmapLevel = _this.getActiveMipmapLevel(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== void 0) camera.viewport = void 0; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i6 = 0, l3 = transmissiveObjects.length; i6 < l3; i6++) { + const renderItem = transmissiveObjects[i6]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== void 0) camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i6 = 0, l3 = renderList.length; i6 < l3; i6++) { + const renderItem = renderList[i6]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const group = renderItem.group; + let material = renderItem.material; + if (material.allowOverride === true && overrideMaterial !== null) { + material = overrideMaterial; + } + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === void 0) { + material.addEventListener("dispose", onMaterialDispose); + programs = /* @__PURE__ */ new Map(); + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== void 0) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== void 0 && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reversedDepthBuffer2 = state.buffers.depth.getReversed(); + if (reversedDepthBuffer2 && camera.reversedDepth !== true) { + camera._reversedDepth = true; + camera.updateProjectionMatrix(); + } + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== void 0) { + uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue( + _gl, + "logDepthBufFC", + 2 / (Math.log(camera.far + 1) / Math.LN2) + ); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== void 0 || morphAttributes.normal !== void 0 || morphAttributes.color !== void 0) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i6 = 0, l3 = groups.length; i6 < l3; i6++) { + const group = groups[i6]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value) { + uniforms.ambientLightColor.needsUpdate = value; + uniforms.lightProbe.needsUpdate = value; + uniforms.directionalLights.needsUpdate = value; + uniforms.directionalLightShadows.needsUpdate = value; + uniforms.pointLights.needsUpdate = value; + uniforms.pointLightShadows.needsUpdate = value; + uniforms.spotLights.needsUpdate = value; + uniforms.spotLightShadows.needsUpdate = value; + uniforms.rectAreaLights.needsUpdate = value; + uniforms.hemisphereLights.needsUpdate = value; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false; + if (renderTargetProperties.__autoAllocateDepthBuffer === false) { + renderTargetProperties.__useRenderToTexture = false; + } + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? void 0 : depthTexture; + renderTargetProperties.__hasExternalTextures = true; + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === void 0; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== void 0) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === void 0) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const layer = activeCubeFace; + for (let i6 = 0; i6 < renderTarget.textures.length; i6++) { + const textureProperties = properties.get(renderTarget.textures[i6]); + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i6, textureProperties.__webglTexture, activeMipmapLevel, layer); + } + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x2, y3, width, height, buffer, activeCubeFaceIndex, textureIndex = 0) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.textures[textureIndex]; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x2 >= 0 && x2 <= renderTarget.width - width && (y3 >= 0 && y3 <= renderTarget.height - height)) { + if (renderTarget.textures.length > 1) _gl.readBuffer(_gl.COLOR_ATTACHMENT0 + textureIndex); + _gl.readPixels(x2, y3, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x2, y3, width, height, buffer, activeCubeFaceIndex, textureIndex = 0) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + if (x2 >= 0 && x2 <= renderTarget.width - width && (y3 >= 0 && y3 <= renderTarget.height - height)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const texture = renderTarget.textures[textureIndex]; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + if (renderTarget.textures.length > 1) _gl.readBuffer(_gl.COLOR_ATTACHMENT0 + textureIndex); + _gl.readPixels(x2, y3, width, height, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position = null, level = 0) { + const levelScale = Math.pow(2, -level); + const width = Math.floor(texture.image.width * levelScale); + const height = Math.floor(texture.image.height * levelScale); + const x2 = position !== null ? position.x : 0; + const y3 = position !== null ? position.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x2, y3, width, height); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width, height, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width = srcRegion.max.x - srcRegion.min.x; + height = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width = Math.floor(image.width * levelScale); + height = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i6 = 0; i6 < depth2; i6++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i6); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i6); + } + _gl.blitFramebuffer(minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i6 = 0; i6 < depth2; i6++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i6); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i6); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i6, minX, minY, width, height); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width, height); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === void 0) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + /** + * Defines the coordinate system of the renderer. + * + * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`. + * + * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem} + * @default WebGLCoordinateSystem + * @readonly + */ + get coordinateSystem() { + return WebGLCoordinateSystem; + } + /** + * Defines the output color space of the renderer. + * + * @type {SRGBColorSpace|LinearSRGBColorSpace} + * @default SRGBColorSpace + */ + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + } +}; + +// src/components/OrbAnimation.ts +var OrbAnimation = class extends i4 { + constructor() { + super(...arguments); + this.time = 0; + this.currentIsDark = false; + this.animateOrb = () => { + if (!this.scene || !this.camera || !this.renderer || !this.orb || !this.innerOrb || !this.outerOrb) { + return; + } + const isDark = document.documentElement.classList.contains("dark"); + if (isDark !== this.currentIsDark) { + this.currentIsDark = isDark; + this.updateTheme(isDark); + } + this.time += 0.01; + this.orb.material.uniforms.time.value = this.time; + this.innerOrb.material.uniforms.time.value = this.time * 1.5; + this.outerOrb.material.uniforms.time.value = this.time * 0.7; + this.orb.rotation.y = this.time * 0.3; + this.orb.rotation.x = Math.sin(this.time * 0.5) * 0.4; + this.orb.rotation.z = Math.cos(this.time * 0.3) * 0.2; + this.innerOrb.rotation.y = -this.time * 0.4; + this.innerOrb.rotation.x = Math.cos(this.time * 0.6) * 0.5; + this.innerOrb.rotation.z = Math.sin(this.time * 0.4) * 0.3; + this.outerOrb.rotation.y = this.time * 0.15; + this.outerOrb.rotation.x = Math.sin(this.time * 0.25) * 0.3; + this.outerOrb.rotation.z = -Math.cos(this.time * 0.35) * 0.25; + const breathe = 1 + Math.sin(this.time * 0.8) * 0.05; + this.orb.scale.set(breathe, breathe, breathe); + const breathe2 = 1 + Math.cos(this.time * 1.1) * 0.07; + this.innerOrb.scale.set(breathe2, breathe2, breathe2); + const breathe3 = 1 + Math.sin(this.time * 0.6) * 0.08; + this.outerOrb.scale.set(breathe3, breathe3, breathe3); + this.renderer.render(this.scene, this.camera); + this.animationFrame = requestAnimationFrame(this.animateOrb); + }; + } + createRenderRoot() { + return this; + } + firstUpdated() { + this.container = this.querySelector(".orb-container"); + if (!this.container) return; + requestAnimationFrame(() => { + this.initThreeJS(); + this.animateOrb(); + }); + } + disconnectedCallback() { + super.disconnectedCallback(); + if (this.animationFrame) { + cancelAnimationFrame(this.animationFrame); + } + if (this.renderer) { + this.renderer.dispose(); + } + } + initThreeJS() { + if (!this.container) return; + this.currentIsDark = document.documentElement.classList.contains("dark"); + this.scene = new Scene(); + this.camera = new PerspectiveCamera( + 75, + this.container.clientWidth / this.container.clientHeight, + 0.1, + 1e3 + ); + this.renderer = new WebGLRenderer({ antialias: true, alpha: true }); + this.renderer.setSize(this.container.clientWidth, this.container.clientHeight); + this.renderer.setPixelRatio(window.devicePixelRatio); + this.renderer.setClearColor(0, 0); + this.container.appendChild(this.renderer.domElement); + this.camera.position.z = 4.5; + const vertexShader = ` + varying vec3 vNormal; + varying vec3 vPosition; + varying vec3 vWorldPosition; + uniform float time; + + void main() { + vNormal = normalize(normalMatrix * normal); + vPosition = position; + + // Intense morphing distortion + vec3 pos = position; + float t = time * 0.8; + + // Multiple sine waves creating organic motion + float distort = sin(pos.x * 2.0 + t) * cos(pos.y * 1.5 + t * 1.3) * 0.15; + distort += sin(pos.y * 3.0 + t * 1.7) * cos(pos.z * 2.0 + t * 0.9) * 0.12; + distort += cos(pos.z * 2.5 + t * 1.1) * sin(pos.x * 1.8 + t * 1.5) * 0.1; + + // Swirling motion + float swirl = sin(length(pos.xy) * 3.0 - t * 2.0) * 0.08; + + pos += normal * (distort + swirl); + + vec4 worldPos = modelMatrix * vec4(pos, 1.0); + vWorldPosition = worldPos.xyz; + + gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0); + } + `; + const fragmentShader = ` + varying vec3 vNormal; + varying vec3 vPosition; + varying vec3 vWorldPosition; + uniform float time; + uniform vec3 color1; + uniform vec3 color2; + uniform vec3 color3; + + void main() { + vec3 viewDirection = normalize(cameraPosition - vWorldPosition); + float fresnel = pow(1.0 - abs(dot(viewDirection, vNormal)), 3.0); + + // Plasma-like color mixing + float t = time * 0.5; + float plasma = sin(vPosition.x * 4.0 + t) + + sin(vPosition.y * 3.0 + t * 1.3) + + sin((vPosition.x + vPosition.y) * 2.0 + t * 0.7) + + cos(length(vPosition.xy) * 5.0 - t * 2.0); + plasma = plasma * 0.25 + 0.5; + + // Swirling color bands + float bands = sin(length(vPosition.xy) * 8.0 - t * 3.0 + plasma * 2.0) * 0.5 + 0.5; + + vec3 color = mix(color1, color2, plasma); + color = mix(color, color3, bands); + + // Lower opacity to prevent white washout, but keep it visible + float pulse = sin(t * 2.0) * 0.1 + 0.9; + float opacity = (0.25 + fresnel * 0.45) * pulse; + + // Darken the colors for better visibility on light backgrounds + float edge = pow(fresnel, 0.8) * 0.8; + vec3 finalColor = color * (0.5 + edge); + + gl_FragColor = vec4(finalColor, opacity); + } + `; + const orbGeometry = new SphereGeometry(1.5, 128, 128); + const orbMaterial = new ShaderMaterial({ + vertexShader, + fragmentShader, + uniforms: { + time: { value: 0 }, + // Brighter colors for light theme, darker for dark theme + color1: { value: this.currentIsDark ? new Color(14241536) : new Color(16747520) }, + color2: { value: this.currentIsDark ? new Color(16739072) : new Color(16753920) }, + color3: { value: this.currentIsDark ? new Color(13935872) : new Color(16758528) } + }, + transparent: true, + blending: AdditiveBlending, + side: DoubleSide, + depthWrite: false + }); + this.orb = new Mesh(orbGeometry, orbMaterial); + this.scene.add(this.orb); + const innerGeometry = new SphereGeometry(1.2, 128, 128); + const innerMaterial = new ShaderMaterial({ + vertexShader, + fragmentShader, + uniforms: { + time: { value: 0 }, + color1: { value: this.currentIsDark ? new Color(2984765) : new Color(5025616) }, + color2: { value: this.currentIsDark ? new Color(1402304) : new Color(2201331) }, + color3: { value: this.currentIsDark ? new Color(8069026) : new Color(10233776) } + }, + transparent: true, + blending: AdditiveBlending, + // @ts-expect-error - BackSide exists at runtime but may not be in types + side: BackSide, + depthWrite: false + }); + this.innerOrb = new Mesh(innerGeometry, innerMaterial); + this.scene.add(this.innerOrb); + const outerGeometry = new SphereGeometry(1.8, 64, 64); + const outerMaterial = new ShaderMaterial({ + vertexShader, + fragmentShader, + uniforms: { + time: { value: 0 }, + color1: { value: this.currentIsDark ? new Color(12720219) : new Color(15277667) }, + color2: { value: this.currentIsDark ? new Color(14172949) : new Color(16733986) }, + color3: { value: this.currentIsDark ? new Color(5320104) : new Color(6765239) } + }, + transparent: true, + blending: AdditiveBlending, + side: DoubleSide, + depthWrite: false + }); + this.outerOrb = new Mesh(outerGeometry, outerMaterial); + this.scene.add(this.outerOrb); + } + updateTheme(isDark) { + if (!this.orb || !this.innerOrb || !this.outerOrb) { + return; + } + const orbMaterial = this.orb.material; + orbMaterial.uniforms.color1.value = isDark ? new Color(14241536) : new Color(16747520); + orbMaterial.uniforms.color2.value = isDark ? new Color(16739072) : new Color(16753920); + orbMaterial.uniforms.color3.value = isDark ? new Color(13935872) : new Color(16758528); + const innerMaterial = this.innerOrb.material; + innerMaterial.uniforms.color1.value = isDark ? new Color(2984765) : new Color(5025616); + innerMaterial.uniforms.color2.value = isDark ? new Color(1402304) : new Color(2201331); + innerMaterial.uniforms.color3.value = isDark ? new Color(8069026) : new Color(10233776); + const outerMaterial = this.outerOrb.material; + outerMaterial.uniforms.color1.value = isDark ? new Color(12720219) : new Color(15277667); + outerMaterial.uniforms.color2.value = isDark ? new Color(14172949) : new Color(16733986); + outerMaterial.uniforms.color3.value = isDark ? new Color(5320104) : new Color(6765239); + } + render() { + return b2`
`; + } +}; +OrbAnimation = __decorateClass([ + t5("orb-animation") +], OrbAnimation); + +// src/icons.ts +var ICON_SIZES = [ + { size: 16, name: "icon-16.png" }, + { size: 48, name: "icon-48.png" }, + { size: 128, name: "icon-128.png" } +]; +function captureOrbAsImage(size) { + return new Promise((resolve, reject) => { + const container = document.createElement("div"); + container.style.position = "fixed"; + container.style.left = "-9999px"; + container.style.width = `${size * 2}px`; + container.style.height = `${size * 2}px`; + document.body.appendChild(container); + const orb = document.createElement("orb-animation"); + container.appendChild(orb); + setTimeout(() => { + try { + const canvas = container.querySelector("canvas"); + if (!canvas) { + throw new Error("Canvas not found in orb animation"); + } + const outputCanvas = document.createElement("canvas"); + outputCanvas.width = size; + outputCanvas.height = size; + const ctx = outputCanvas.getContext("2d"); + if (!ctx) { + throw new Error("Failed to get 2D context"); + } + const cropSize = canvas.width * 0.6; + const cropOffset = (canvas.width - cropSize) / 2; + ctx.drawImage( + canvas, + cropOffset, + cropOffset, + cropSize, + cropSize, + // Source: center crop + 0, + 0, + size, + size + // Destination: full icon size + ); + outputCanvas.toBlob( + (blob) => { + document.body.removeChild(container); + if (blob) { + resolve(blob); + } else { + reject(new Error("Failed to create blob from canvas")); + } + }, + "image/png", + 1 + ); + } catch (error) { + document.body.removeChild(container); + reject(error); + } + }, 500); + }); +} +function downloadBlob(blob, filename) { + const url = URL.createObjectURL(blob); + const a3 = document.createElement("a"); + a3.href = url; + a3.download = filename; + document.body.appendChild(a3); + a3.click(); + document.body.removeChild(a3); + URL.revokeObjectURL(url); +} +async function generateIcon(iconSize) { + const statusEl = document.getElementById(`status-${iconSize.size}`); + const downloadBtnWrapper = document.getElementById(`download-${iconSize.size}`); + const downloadBtn = downloadBtnWrapper?.querySelector("button"); + const previewEl = document.getElementById(`preview-${iconSize.size}`); + if (statusEl) statusEl.textContent = "Generating..."; + if (downloadBtn) downloadBtn.disabled = true; + if (previewEl) previewEl.innerHTML = ""; + try { + const blob = await captureOrbAsImage(iconSize.size); + if (previewEl) { + const img = document.createElement("img"); + img.src = URL.createObjectURL(blob); + img.style.maxWidth = "100%"; + img.style.maxHeight = "100%"; + img.style.width = "auto"; + img.style.height = "auto"; + img.style.objectFit = "contain"; + img.style.imageRendering = "pixelated"; + previewEl.appendChild(img); + } + if (statusEl) statusEl.textContent = "\u2713 Ready"; + if (downloadBtn) { + downloadBtn.disabled = false; + downloadBtn.onclick = () => downloadBlob(blob, iconSize.name); + } + } catch (error) { + console.error(`Failed to generate ${iconSize.name}:`, error); + if (statusEl) statusEl.textContent = `\u2717 Error: ${error}`; + if (downloadBtn) downloadBtn.disabled = true; + if (previewEl) previewEl.innerHTML = ""; + } +} +async function generateAllIcons() { + const generateAllBtnWrapper = document.getElementById("generate-all-btn"); + const generateAllBtn = generateAllBtnWrapper?.querySelector("button"); + if (generateAllBtn) generateAllBtn.disabled = true; + for (const iconSize of ICON_SIZES) { + await generateIcon(iconSize); + } + if (generateAllBtn) generateAllBtn.disabled = false; +} +function createPreviewOrb() { + const previewContainer = document.getElementById("orb-preview"); + if (!previewContainer) return; + previewContainer.innerHTML = ""; + const orb = document.createElement("orb-animation"); + previewContainer.appendChild(orb); +} +function renderIconsPage() { + const container = document.getElementById("app"); + if (!container) return; + const template = b2` +
+ +
+
+ ${Button({ + variant: "ghost", + size: "sm", + children: b2`${icon(ArrowLeft, "sm")} Back to Debug`, + onClick: () => { + window.location.href = "/debug.html"; + } + })} +

Icon Generator

+
+ + +
+

Instructions

+
    +
  1. Preview the orb animation below
  2. +
  3. Click "Generate All Icons" or generate individual sizes
  4. +
  5. Download each icon using the download buttons
  6. +
  7. Replace the icon files in the static/ directory
  8. +
+
+ + +
+

Preview

+
+
+
+
+ + +
+
+

Generate Icons

+
+ ${Button({ + children: b2`${icon(Download, "sm")} Generate All Icons`, + onClick: generateAllIcons + })} +
+
+ +
+ ${ICON_SIZES.map( + (iconSize) => b2` +
+
+
+ ${iconSize.size}×${iconSize.size} +
+
+
${iconSize.name}
+
Not generated
+
+
+
+ ${Button({ + size: "sm", + variant: "outline", + children: "Generate", + onClick: () => generateIcon(iconSize) + })} +
+ ${Button({ + size: "sm", + disabled: true, + children: b2`${icon(Download, "sm")} Download`, + onClick: () => { + } + // Will be replaced dynamically + })} +
+
+
+ ` + )} +
+
+
+
+ `; + D(template, container); + requestAnimationFrame(() => { + createPreviewOrb(); + }); +} +renderIconsPage(); +/*! Bundled license information: + +@lit/reactive-element/css-tag.js: + (** + * @license + * Copyright 2019 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +@lit/reactive-element/reactive-element.js: +lit-html/lit-html.js: +lit-element/lit-element.js: +lit-html/directive.js: +lit-html/async-directive.js: +lit-html/directives/unsafe-html.js: +@lit/reactive-element/decorators/custom-element.js: +@lit/reactive-element/decorators/property.js: +@lit/reactive-element/decorators/state.js: +@lit/reactive-element/decorators/event-options.js: +@lit/reactive-element/decorators/base.js: +@lit/reactive-element/decorators/query.js: +@lit/reactive-element/decorators/query-all.js: +@lit/reactive-element/decorators/query-async.js: +@lit/reactive-element/decorators/query-assigned-nodes.js: + (** + * @license + * Copyright 2017 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lit-html/is-server.js: + (** + * @license + * Copyright 2022 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lit-html/directive-helpers.js: +lit-html/directives/ref.js: + (** + * @license + * Copyright 2020 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +lucide/dist/esm/defaultAttributes.js: +lucide/dist/esm/createElement.js: +lucide/dist/esm/lucide.js: +lucide/dist/esm/icons/arrow-left.js: +lucide/dist/esm/icons/download.js: +lucide/dist/esm/lucide.js: + (** + * @license lucide v0.544.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + *) + +@lit/reactive-element/decorators/query-assigned-elements.js: + (** + * @license + * Copyright 2021 Google LLC + * SPDX-License-Identifier: BSD-3-Clause + *) + +three/build/three.core.js: +three/build/three.module.js: + (** + * @license + * Copyright 2010-2025 Three.js Authors + * SPDX-License-Identifier: MIT + *) +*/ +//# sourceMappingURL=icons.js.map diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..b2d86c4 --- /dev/null +++ b/manifest.json @@ -0,0 +1,54 @@ +{ + "manifest_version": 3, + "minimum_chrome_version": "141", + "name": "sitegeist", + "description": "Your AI companion for the web - Research, automate, create", + "version": "1.0.0", + "action": { + "default_title": "Click to open side panel" + }, + "background": { + "service_worker": "background.js", + "type": "module" + }, + "icons": { + "16": "icon-16.png", + "48": "icon-48.png", + "128": "icon-128.png" + }, + "side_panel": { + "default_path": "sidepanel.html" + }, + "commands": { + "toggle-sidepanel": { + "suggested_key": { + "default": "Ctrl+Shift+S", + "mac": "Command+Shift+S" + }, + "description": "Toggle side panel" + } + }, + "permissions": [ + "storage", + "unlimitedStorage", + "activeTab", + "scripting", + "sidePanel", + "userScripts", + "webNavigation", + "debugger" + ], + "host_permissions": [ + "http://*/*", + "https://*/*", + "http://localhost/*", + "http://127.0.0.1/*" + ], + "sandbox": { + "pages": ["sandbox.html"] + }, + "content_security_policy": { + "extension_pages": "script-src 'self'; object-src 'self'", + "sandbox": "sandbox allow-scripts allow-modals; default-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net/ https://unpkg.com/ https://cdnjs.cloudflare.com/ https://esm.sh/ https://esm.run/ https://cdn.skypack.dev/ https://cdn.tailwindcss.com; script-src-elem 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net/ https://unpkg.com/ https://cdnjs.cloudflare.com/ https://esm.sh/ https://esm.run/ https://cdn.skypack.dev/ https://cdn.tailwindcss.com; connect-src https://cdn.jsdelivr.net/ https://unpkg.com/ https://cdnjs.cloudflare.com/ https://esm.sh/ https://esm.run/ https://cdn.skypack.dev/ https://cdn.tailwindcss.com https://t1.gstatic.com/; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net/ https://cdnjs.cloudflare.com/ https://cdn.tailwindcss.com; img-src 'self' data: blob: https:; font-src 'self' data: https://cdn.jsdelivr.net/ https://cdnjs.cloudflare.com/; object-src 'none'; base-uri 'none'; form-action 'none'" + } +} diff --git a/pdfjs-dist/build/pdf.worker.min.mjs b/pdfjs-dist/build/pdf.worker.min.mjs new file mode 100644 index 0000000..924a202 --- /dev/null +++ b/pdfjs-dist/build/pdf.worker.min.mjs @@ -0,0 +1,28 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2024 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ +/** + * pdfjsVersion = 5.4.394 + * pdfjsBuild = 2cc809ade + */const e=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),t=[.001,0,0,.001,0,0],a=1.35,r=.35,i=.25925925925925924,n=1,s=2,o=4,c=8,l=16,h=64,u=128,d=256,f="pdfjs_internal_editor_",g=3,p=9,m=13,b=15,y=101,w={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},x=1,S=2,k=3,C=0,v=4,F=1,T=2,O=3,M={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},D="Group",R="R",N=1,E=2,L=4,_=16,U=32,j=128,X=512,q=1,H=2,W=4096,G=8192,z=32768,$=65536,V=131072,K=1048576,J=2097152,Y=8388608,Z=16777216,Q=1,ee=2,te=3,ae=4,re=5,ie={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},ne={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},se={O:"PageOpen",C:"PageClose"},oe=1,ce=5,le=1,he=2,ue=3,de=4,fe=5,ge=6,pe=7,me=8,be=9,ye=10,we=11,xe=12,Se=13,Ae=14,ke=15,Ce=16,ve=17,Fe=18,Ie=19,Te=20,Oe=21,Me=22,De=23,Be=24,Re=25,Ne=26,Ee=27,Pe=28,Le=29,_e=30,Ue=31,je=32,Xe=33,qe=34,He=35,We=36,Ge=37,ze=38,$e=39,Ve=40,Ke=41,Je=42,Ye=43,Ze=44,Qe=45,et=46,tt=47,at=48,rt=49,it=50,nt=51,st=52,ot=53,ct=54,lt=55,ht=56,ut=57,dt=58,ft=59,gt=60,pt=61,mt=62,bt=63,yt=64,wt=65,xt=66,St=67,At=68,kt=69,Ct=70,vt=71,Ft=72,It=73,Tt=74,Ot=75,Mt=76,Dt=77,Bt=80,Rt=81,Nt=83,Et=84,Pt=85,Lt=86,_t=87,Ut=88,jt=89,Xt=90,qt=91,Ht=92,Wt=93,Gt=94,zt=0,$t=1,Vt=2,Kt=3,Jt=4,Yt=1,Zt=2;let Qt=oe;function getVerbosityLevel(){return Qt}function info(e){Qt>=ce&&console.info(`Info: ${e}`)}function warn(e){Qt>=oe&&console.warn(`Warning: ${e}`)}function unreachable(e){throw new Error(e)}function assert(e,t){e||unreachable(t)}function createValidAbsoluteUrl(e,t=null,a=null){if(!e)return null;if(a&&"string"==typeof e){if(a.addDefaultProtocol&&e.startsWith("www.")){const t=e.match(/\./g);t?.length>=2&&(e=`http://${e}`)}if(a.tryConvertEncoding)try{e=stringToUTF8String(e)}catch{}}const r=t?URL.parse(e,t):URL.parse(e);return function _isValidProtocol(e){switch(e?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(r)?r:null}function shadow(e,t,a,r=!1){Object.defineProperty(e,t,{value:a,enumerable:!r,configurable:!0,writable:!1});return a}const ea=function BaseExceptionClosure(){function BaseException(e,t){this.message=e;this.name=t}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();class PasswordException extends ea{constructor(e,t){super(e,"PasswordException");this.code=t}}class UnknownErrorException extends ea{constructor(e,t){super(e,"UnknownErrorException");this.details=t}}class InvalidPDFException extends ea{constructor(e){super(e,"InvalidPDFException")}}class ResponseException extends ea{constructor(e,t,a){super(e,"ResponseException");this.status=t;this.missing=a}}class FormatError extends ea{constructor(e){super(e,"FormatError")}}class AbortException extends ea{constructor(e){super(e,"AbortException")}}function bytesToString(e){"object"==typeof e&&void 0!==e?.length||unreachable("Invalid argument for bytesToString");const t=e.length,a=8192;if(t>24&255,e>>16&255,e>>8&255,255&e)}function objectSize(e){return Object.keys(e).length}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",function isLittleEndian(){const e=new Uint8Array(4);e[0]=1;return 1===new Uint32Array(e.buffer,0,1)[0]}())}static get isEvalSupported(){return shadow(this,"isEvalSupported",function isEvalSupported(){try{new Function("");return!0}catch{return!1}}())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get isImageDecoderSupported(){return shadow(this,"isImageDecoderSupported","undefined"!=typeof ImageDecoder)}static get isFloat16ArraySupported(){return shadow(this,"isFloat16ArraySupported","undefined"!=typeof Float16Array)}static get isSanitizerSupported(){return shadow(this,"isSanitizerSupported","undefined"!=typeof Sanitizer)}static get platform(){const{platform:e,userAgent:t}=navigator;return shadow(this,"platform",{isAndroid:t.includes("Android"),isLinux:e.includes("Linux"),isMac:e.includes("Mac"),isWindows:e.includes("Win"),isFirefox:t.includes("Firefox")})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const ta=Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,"0"));class Util{static makeHexColor(e,t,a){return`#${ta[e]}${ta[t]}${ta[a]}`}static domMatrixToTransform(e){return[e.a,e.b,e.c,e.d,e.e,e.f]}static scaleMinMax(e,t){let a;if(e[0]){if(e[0]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[0];t[2]*=e[0];if(e[3]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[3];t[3]*=e[3]}else{a=t[0];t[0]=t[1];t[1]=a;a=t[2];t[2]=t[3];t[3]=a;if(e[1]<0){a=t[1];t[1]=t[3];t[3]=a}t[1]*=e[1];t[3]*=e[1];if(e[2]<0){a=t[0];t[0]=t[2];t[2]=a}t[0]*=e[2];t[2]*=e[2]}t[0]+=e[4];t[1]+=e[5];t[2]+=e[4];t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static multiplyByDOMMatrix(e,t){return[e[0]*t.a+e[2]*t.b,e[1]*t.a+e[3]*t.b,e[0]*t.c+e[2]*t.d,e[1]*t.c+e[3]*t.d,e[0]*t.e+e[2]*t.f+e[4],e[1]*t.e+e[3]*t.f+e[5]]}static applyTransform(e,t,a=0){const r=e[a],i=e[a+1];e[a]=r*t[0]+i*t[2]+t[4];e[a+1]=r*t[1]+i*t[3]+t[5]}static applyTransformToBezier(e,t,a=0){const r=t[0],i=t[1],n=t[2],s=t[3],o=t[4],c=t[5];for(let t=0;t<6;t+=2){const l=e[a+t],h=e[a+t+1];e[a+t]=l*r+h*n+o;e[a+t+1]=l*i+h*s+c}}static applyInverseTransform(e,t){const a=e[0],r=e[1],i=t[0]*t[3]-t[1]*t[2];e[0]=(a*t[3]-r*t[2]+t[2]*t[5]-t[4]*t[3])/i;e[1]=(-a*t[1]+r*t[0]+t[4]*t[1]-t[5]*t[0])/i}static axialAlignedBoundingBox(e,t,a){const r=t[0],i=t[1],n=t[2],s=t[3],o=t[4],c=t[5],l=e[0],h=e[1],u=e[2],d=e[3];let f=r*l+o,g=f,p=r*u+o,m=p,b=s*h+c,y=b,w=s*d+c,x=w;if(0!==i||0!==n){const e=i*l,t=i*u,a=n*h,r=n*d;f+=a;m+=a;p+=r;g+=r;b+=e;x+=e;w+=t;y+=t}a[0]=Math.min(a[0],f,p,g,m);a[1]=Math.min(a[1],b,w,y,x);a[2]=Math.max(a[2],f,p,g,m);a[3]=Math.max(a[3],b,w,y,x)}static inverseTransform(e){const t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e,t){const a=e[0],r=e[1],i=e[2],n=e[3],s=a**2+r**2,o=a*i+r*n,c=i**2+n**2,l=(s+c)/2,h=Math.sqrt(l**2-(s*c-o**2));t[0]=Math.sqrt(l+h||1);t[1]=Math.sqrt(l-h||1)}static normalizeRect(e){const t=e.slice(0);if(e[0]>e[2]){t[0]=e[2];t[2]=e[0]}if(e[1]>e[3]){t[1]=e[3];t[3]=e[1]}return t}static intersect(e,t){const a=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(a>r)return null;const i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),n=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>n?null:[a,i,r,n]}static pointBoundingBox(e,t,a){a[0]=Math.min(a[0],e);a[1]=Math.min(a[1],t);a[2]=Math.max(a[2],e);a[3]=Math.max(a[3],t)}static rectBoundingBox(e,t,a,r,i){i[0]=Math.min(i[0],e,a);i[1]=Math.min(i[1],t,r);i[2]=Math.max(i[2],e,a);i[3]=Math.max(i[3],t,r)}static#e(e,t,a,r,i,n,s,o,c,l){if(c<=0||c>=1)return;const h=1-c,u=c*c,d=u*c,f=h*(h*(h*e+3*c*t)+3*u*a)+d*r,g=h*(h*(h*i+3*c*n)+3*u*s)+d*o;l[0]=Math.min(l[0],f);l[1]=Math.min(l[1],g);l[2]=Math.max(l[2],f);l[3]=Math.max(l[3],g)}static#t(e,t,a,r,i,n,s,o,c,l,h,u){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,a,r,i,n,s,o,-h/l,u);return}const d=l**2-4*h*c;if(d<0)return;const f=Math.sqrt(d),g=2*c;this.#e(e,t,a,r,i,n,s,o,(-l+f)/g,u);this.#e(e,t,a,r,i,n,s,o,(-l-f)/g,u)}static bezierBoundingBox(e,t,a,r,i,n,s,o,c){c[0]=Math.min(c[0],e,s);c[1]=Math.min(c[1],t,o);c[2]=Math.max(c[2],e,s);c[3]=Math.max(c[3],t,o);this.#t(e,a,i,s,t,r,n,o,3*(3*(a-i)-e+s),6*(e-2*a+i),3*(a-e),c);this.#t(e,a,i,s,t,r,n,o,3*(3*(r-n)-t+o),6*(t-2*r+n),3*(r-t),c)}}const aa=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,728,711,710,729,733,731,730,732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8226,8224,8225,8230,8212,8211,402,8260,8249,8250,8722,8240,8222,8220,8221,8216,8217,8218,8482,64257,64258,321,338,352,376,381,305,322,339,353,382,0,8364];function stringToPDFString(e,t=!1){if(e[0]>="ï"){let a;if("þ"===e[0]&&"ÿ"===e[1]){a="utf-16be";e.length%2==1&&(e=e.slice(0,-1))}else if("ÿ"===e[0]&&"þ"===e[1]){a="utf-16le";e.length%2==1&&(e=e.slice(0,-1))}else"ï"===e[0]&&"»"===e[1]&&"¿"===e[2]&&(a="utf-8");if(a)try{const r=new TextDecoder(a,{fatal:!0}),i=stringToBytes(e),n=r.decode(i);return t||!n.includes("")?n:n.replaceAll(/\x1b[^\x1b]*(?:\x1b|$)/g,"")}catch(e){warn(`stringToPDFString: "${e}".`)}}const a=[];for(let r=0,i=e.length;rta[e]).join("")}"function"!=typeof Promise.try&&(Promise.try=function(e,...t){return new Promise(a=>{a(e(...t))})});"function"!=typeof Math.sumPrecise&&(Math.sumPrecise=function(e){return e.reduce((e,t)=>e+t,0)});const na=Symbol("CIRCULAR_REF"),sa=Symbol("EOF");let oa=Object.create(null),ca=Object.create(null),la=Object.create(null);class Name{constructor(e){this.name=e}static get(e){return ca[e]||=new Name(e)}}class Cmd{constructor(e){this.cmd=e}static get(e){return oa[e]||=new Cmd(e)}}const ha=function nonSerializableClosure(){return ha};class Dict{constructor(e=null){this._map=new Map;this.xref=e;this.objId=null;this.suppressEncryption=!1;this.__nonSerializable__=ha}assignXref(e){this.xref=e}get size(){return this._map.size}get(e,t,a){let r=this._map.get(e);if(void 0===r&&void 0!==t){r=this._map.get(t);void 0===r&&void 0!==a&&(r=this._map.get(a))}return r instanceof Ref&&this.xref?this.xref.fetch(r,this.suppressEncryption):r}async getAsync(e,t,a){let r=this._map.get(e);if(void 0===r&&void 0!==t){r=this._map.get(t);void 0===r&&void 0!==a&&(r=this._map.get(a))}return r instanceof Ref&&this.xref?this.xref.fetchAsync(r,this.suppressEncryption):r}getArray(e,t,a){let r=this._map.get(e);if(void 0===r&&void 0!==t){r=this._map.get(t);void 0===r&&void 0!==a&&(r=this._map.get(a))}r instanceof Ref&&this.xref&&(r=this.xref.fetch(r,this.suppressEncryption));if(Array.isArray(r)){r=r.slice();for(let e=0,t=r.length;e{unreachable("Should not call `set` on the empty dictionary.")};return shadow(this,"empty",e)}static merge({xref:e,dictArray:t,mergeSubDicts:a=!1}){const r=new Dict(e),i=new Map;for(const e of t)if(e instanceof Dict)for(const[t,r]of e._map){let e=i.get(t);if(void 0===e){e=[];i.set(t,e)}else if(!(a&&r instanceof Dict))continue;e.push(r)}for(const[t,a]of i){if(1===a.length||!(a[0]instanceof Dict)){r._map.set(t,a[0]);continue}const i=new Dict(e);for(const e of a)for(const[t,a]of e._map)i._map.has(t)||i._map.set(t,a);i.size>0&&r._map.set(t,i)}i.clear();return r.size>0?r:Dict.empty}clone(){const e=new Dict(this.xref);for(const t of this.getKeys())e.set(t,this.getRaw(t));return e}delete(e){this._map.delete(e)}}class Ref{constructor(e,t){this.num=e;this.gen=t}toString(){return 0===this.gen?`${this.num}R`:`${this.num}R${this.gen}`}static fromString(e){const t=la[e];if(t)return t;const a=/^(\d+)R(\d*)$/.exec(e);return a&&"0"!==a[1]?la[e]=new Ref(parseInt(a[1]),a[2]?parseInt(a[2]):0):null}static get(e,t){const a=0===t?`${e}R`:`${e}R${t}`;return la[a]||=new Ref(e,t)}}class RefSet{constructor(e=null){this._set=new Set(e?._set)}has(e){return this._set.has(e.toString())}put(e){this._set.add(e.toString())}remove(e){this._set.delete(e.toString())}[Symbol.iterator](){return this._set.values()}clear(){this._set.clear()}}class RefSetCache{constructor(){this._map=new Map}get size(){return this._map.size}get(e){return this._map.get(e.toString())}has(e){return this._map.has(e.toString())}put(e,t){this._map.set(e.toString(),t)}putAlias(e,t){this._map.set(e.toString(),this.get(t))}[Symbol.iterator](){return this._map.values()}clear(){this._map.clear()}*values(){yield*this._map.values()}*items(){for(const[e,t]of this._map)yield[Ref.fromString(e),t]}}function isName(e,t){return e instanceof Name&&(void 0===t||e.name===t)}function isCmd(e,t){return e instanceof Cmd&&(void 0===t||e.cmd===t)}function isDict(e,t){return e instanceof Dict&&(void 0===t||isName(e.get("Type"),t))}function isRefsEqual(e,t){return e.num===t.num&&e.gen===t.gen}class BaseStream{get length(){unreachable("Abstract getter `length` accessed")}get isEmpty(){unreachable("Abstract getter `isEmpty` accessed")}get isDataLoaded(){return shadow(this,"isDataLoaded",!0)}getByte(){unreachable("Abstract method `getByte` called")}getBytes(e){unreachable("Abstract method `getBytes` called")}async getImageData(e,t){return this.getBytes(e,t)}async asyncGetBytes(){unreachable("Abstract method `asyncGetBytes` called")}get isAsync(){return!1}get isAsyncDecoder(){return!1}get canAsyncDecodeImageFromBuffer(){return!1}async getTransferableImage(){return null}peekByte(){const e=this.getByte();-1!==e&&this.pos--;return e}peekBytes(e){const t=this.getBytes(e);this.pos-=t.length;return t}getUint16(){const e=this.getByte(),t=this.getByte();return-1===e||-1===t?-1:(e<<8)+t}getInt32(){return(this.getByte()<<24)+(this.getByte()<<16)+(this.getByte()<<8)+this.getByte()}getByteRange(e,t){unreachable("Abstract method `getByteRange` called")}getString(e){return bytesToString(this.getBytes(e))}skip(e){this.pos+=e||1}reset(){unreachable("Abstract method `reset` called")}moveStart(){unreachable("Abstract method `moveStart` called")}makeSubStream(e,t,a=null){unreachable("Abstract method `makeSubStream` called")}getBaseStreams(){return null}getOriginalStream(){return this.stream?.getOriginalStream()||this}}const ua=/^[1-9]\.\d$/,da=2**31-1,fa=[1,0,0,1,0,0],ga=["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"],pa=["ExtGState","Font","Properties","XObject"];function getLookupTableFactory(e){let t;return function(){if(e){t=Object.create(null);e(t);e=null}return t}}class MissingDataException extends ea{constructor(e,t){super(`Missing data [${e}, ${t})`,"MissingDataException");this.begin=e;this.end=t}}class ParserEOFException extends ea{constructor(e){super(e,"ParserEOFException")}}class XRefEntryException extends ea{constructor(e){super(e,"XRefEntryException")}}class XRefParseException extends ea{constructor(e){super(e,"XRefParseException")}}function arrayBuffersToBytes(e){const t=e.length;if(0===t)return new Uint8Array(0);if(1===t)return new Uint8Array(e[0]);let a=0;for(let r=0;r0,"The number should be a positive integer.");const a="M".repeat(e/1e3|0)+ma[e%1e3/100|0]+ma[10+(e%100/10|0)]+ma[20+e%10];return t?a.toLowerCase():a}function log2(e){return e>0?Math.ceil(Math.log2(e)):0}function readInt8(e,t){return e[t]<<24>>24}function readInt16(e,t){return(e[t]<<24|e[t+1]<<16)>>16}function readUint16(e,t){return e[t]<<8|e[t+1]}function readUint32(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}function isWhiteSpace(e){return 32===e||9===e||13===e||10===e}function isNumberArray(e,t){return Array.isArray(e)?(null===t||e.length===t)&&e.every(e=>"number"==typeof e):ArrayBuffer.isView(e)&&!(e instanceof BigInt64Array||e instanceof BigUint64Array)&&(null===t||e.length===t)}function lookupMatrix(e,t){return isNumberArray(e,6)?e:t}function lookupRect(e,t){return isNumberArray(e,4)?e:t}function lookupNormalRect(e,t){return isNumberArray(e,4)?Util.normalizeRect(e):t}function parseXFAPath(e){const t=/(.+)\[(\d+)\]$/;return e.split(".").map(e=>{const a=e.match(t);return a?{name:a[1],pos:parseInt(a[2],10)}:{name:e,pos:0}})}function escapePDFName(e){const t=[];let a=0;for(let r=0,i=e.length;r126||35===i||40===i||41===i||60===i||62===i||91===i||93===i||123===i||125===i||47===i||37===i){a"\n"===e?"\\n":"\r"===e?"\\r":`\\${e}`)}function _collectJS(e,t,a,r){if(!e)return;let i=null;if(e instanceof Ref){if(r.has(e))return;i=e;r.put(i);e=t.fetch(e)}if(Array.isArray(e))for(const i of e)_collectJS(i,t,a,r);else if(e instanceof Dict){if(isName(e.get("S"),"JavaScript")){const t=e.get("JS");let r;t instanceof BaseStream?r=t.getString():"string"==typeof t&&(r=t);r&&=stringToPDFString(r,!0).replaceAll("\0","");r&&a.push(r.trim())}_collectJS(e.getRaw("Next"),t,a,r)}i&&r.remove(i)}function collectActions(e,t,a){const r=Object.create(null),i=getInheritableProperty({dict:t,key:"AA",stopWhenFound:!1});if(i)for(let t=i.length-1;t>=0;t--){const n=i[t];if(n instanceof Dict)for(const t of n.getKeys()){const i=a[t];if(!i)continue;const s=[];_collectJS(n.getRaw(t),e,s,new RefSet);s.length>0&&(r[i]=s)}}if(t.has("A")){const a=[];_collectJS(t.get("A"),e,a,new RefSet);a.length>0&&(r.Action=a)}return objectSize(r)>0?r:null}const ba={60:"<",62:">",38:"&",34:""",39:"'"};function*codePointIter(e){for(let t=0,a=e.length;t55295&&(a<57344||a>65533)&&t++;yield a}}function encodeToXmlString(e){const t=[];let a=0;for(let r=0,i=e.length;r55295&&(i<57344||i>65533)&&r++;a=r+1}}if(0===t.length)return e;a: ${e}.`);return!1}return!0}function validateCSSFont(e){const t=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily:a,fontWeight:r,italicAngle:i}=e;if(!validateFontName(a,!0))return!1;const n=r?r.toString():"";e.fontWeight=t.has(n)?n:"400";const s=parseFloat(i);e.italicAngle=isNaN(s)||s<-90||s>90?"14":i.toString();return!0}function recoverJsURL(e){const t=new RegExp("^\\s*("+["app.launchURL","window.open","xfa.host.gotoURL"].join("|").replaceAll(".","\\.")+")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))","i").exec(e);return t?.[2]?{url:t[2],newWindow:"app.launchURL"===t[1]&&"true"===t[3]}:null}function numberToString(e){if(Number.isInteger(e))return e.toString();const t=Math.round(100*e);return t%100==0?(t/100).toString():t%10==0?e.toFixed(1):e.toFixed(2)}function getNewAnnotationsMap(e){if(!e)return null;const t=new Map;for(const[a,r]of e){if(!a.startsWith(f))continue;let e=t.get(r.pageIndex);if(!e){e=[];t.set(r.pageIndex,e)}e.push(r)}return t.size>0?t:null}function stringToAsciiOrUTF16BE(e){return null==e||function isAscii(e){if("string"!=typeof e)return!1;return!e||/^[\x00-\x7F]*$/.test(e)}(e)?e:stringToUTF16String(e,!0)}function stringToUTF16HexString(e){const t=[];for(let a=0,r=e.length;a>8&255],ta[255&r])}return t.join("")}function stringToUTF16String(e,t=!1){const a=[];t&&a.push("þÿ");for(let t=0,r=e.length;t>8&255),String.fromCharCode(255&r))}return a.join("")}function getRotationMatrix(e,t,a){switch(e){case 90:return[0,1,-1,0,t,0];case 180:return[-1,0,0,-1,t,a];case 270:return[0,-1,1,0,0,a];default:throw new Error("Invalid rotation")}}function getSizeInBytes(e){return Math.ceil(Math.ceil(Math.log2(1+e))/8)}class QCMS{static#a=null;static _memory=null;static _mustAddAlpha=!1;static _destBuffer=null;static _destOffset=0;static _destLength=0;static _cssColor="";static _makeHexColor=null;static get _memoryArray(){const e=this.#a;return e?.byteLength?e:this.#a=new Uint8Array(this._memory.buffer)}}let ya;const wa="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&wa.decode();let xa=null;function getUint8ArrayMemory0(){null!==xa&&0!==xa.byteLength||(xa=new Uint8Array(ya.memory.buffer));return xa}let Sa=0;function passArray8ToWasm0(e,t){const a=t(1*e.length,1)>>>0;getUint8ArrayMemory0().set(e,a/1);Sa=e.length;return a}const Aa=Object.freeze({RGB8:0,0:"RGB8",RGBA8:1,1:"RGBA8",BGRA8:2,2:"BGRA8",Gray8:3,3:"Gray8",GrayA8:4,4:"GrayA8",CMYK:5,5:"CMYK"}),ka=Object.freeze({Perceptual:0,0:"Perceptual",RelativeColorimetric:1,1:"RelativeColorimetric",Saturation:2,2:"Saturation",AbsoluteColorimetric:3,3:"AbsoluteColorimetric"});function __wbg_get_imports(){const e={wbg:{}};e.wbg.__wbg_copyresult_b08ee7d273f295dd=function(e,t){!function copy_result(e,t){const{_mustAddAlpha:a,_destBuffer:r,_destOffset:i,_destLength:n,_memoryArray:s}=QCMS;if(t!==n)if(a)for(let a=e,n=e+t,o=i;a>>0,t>>>0)};e.wbg.__wbg_copyrgb_d60ce17bb05d9b67=function(e){!function copy_rgb(e){const{_destBuffer:t,_destOffset:a,_memoryArray:r}=QCMS;t[a]=r[e];t[a+1]=r[e+1];t[a+2]=r[e+2]}(e>>>0)};e.wbg.__wbg_makecssRGB_893bf0cd9fdb302d=function(e){!function make_cssRGB(e){const{_memoryArray:t}=QCMS;QCMS._cssColor=QCMS._makeHexColor(t[e],t[e+1],t[e+2])}(e>>>0)};e.wbg.__wbindgen_init_externref_table=function(){const e=ya.__wbindgen_export_0,t=e.grow(4);e.set(0,void 0);e.set(t+0,void 0);e.set(t+1,null);e.set(t+2,!0);e.set(t+3,!1)};e.wbg.__wbindgen_throw=function(e,t){throw new Error(function getStringFromWasm0(e,t){e>>>=0;return wa.decode(getUint8ArrayMemory0().subarray(e,e+t))}(e,t))};return e}function __wbg_finalize_init(e,t){ya=e.exports;__wbg_init.__wbindgen_wasm_module=t;xa=null;ya.__wbindgen_start();return ya}async function __wbg_init(e){if(void 0!==ya)return ya;void 0!==e&&(Object.getPrototypeOf(e)===Object.prototype?({module_or_path:e}=e):console.warn("using deprecated parameters for the initialization function; pass a single object instead"));const t=__wbg_get_imports();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:a,module:r}=await async function __wbg_load(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const a=await e.arrayBuffer();return await WebAssembly.instantiate(a,t)}{const a=await WebAssembly.instantiate(e,t);return a instanceof WebAssembly.Instance?{instance:a,module:e}:a}}(await e,t);return __wbg_finalize_init(a,r)}class ColorSpace{static#r=new Uint8ClampedArray(3);constructor(e,t){this.name=e;this.numComps=t}getRgb(e,t,a=new Uint8ClampedArray(3)){this.getRgbItem(e,t,a,0);return a}getRgbHex(e,t){const a=this.getRgb(e,t,ColorSpace.#r);return Util.makeHexColor(a[0],a[1],a[2])}getRgbItem(e,t,a,r){unreachable("Should not call ColorSpace.getRgbItem")}getRgbBuffer(e,t,a,r,i,n,s){unreachable("Should not call ColorSpace.getRgbBuffer")}getOutputLength(e,t){unreachable("Should not call ColorSpace.getOutputLength")}isPassthrough(e){return!1}isDefaultDecode(e,t){return ColorSpace.isDefaultDecode(e,this.numComps)}fillRgb(e,t,a,r,i,n,s,o,c){const l=t*a;let h=null;const u=1<u&&"DeviceGray"!==this.name&&"DeviceRGB"!==this.name){const t=s<=8?new Uint8Array(u):new Uint16Array(u);for(let e=0;e=.99554525?1:MathClamp(1.055*e**(1/2.4)-.055,0,1)}#b(e){return e<0?-this.#b(-e):e>8?((e+16)/116)**3:e*CalRGBCS.#d}#y(e,t,a){if(0===e[0]&&0===e[1]&&0===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=this.#b(0),i=(1-r)/(1-this.#b(e[0])),n=1-i,s=(1-r)/(1-this.#b(e[1])),o=1-s,c=(1-r)/(1-this.#b(e[2])),l=1-c;a[0]=t[0]*i+n;a[1]=t[1]*s+o;a[2]=t[2]*c+l}#w(e,t,a){if(1===e[0]&&1===e[2]){a[0]=t[0];a[1]=t[1];a[2]=t[2];return}const r=a;this.#f(CalRGBCS.#n,t,r);const i=CalRGBCS.#l;this.#g(e,r,i);this.#f(CalRGBCS.#s,i,a)}#x(e,t,a){const r=a;this.#f(CalRGBCS.#n,t,r);const i=CalRGBCS.#l;this.#p(e,r,i);this.#f(CalRGBCS.#s,i,a)}#i(e,t,a,r,i){const n=MathClamp(e[t]*i,0,1),s=MathClamp(e[t+1]*i,0,1),o=MathClamp(e[t+2]*i,0,1),c=1===n?1:n**this.GR,l=1===s?1:s**this.GG,h=1===o?1:o**this.GB,u=this.MXA*c+this.MXB*l+this.MXC*h,d=this.MYA*c+this.MYB*l+this.MYC*h,f=this.MZA*c+this.MZB*l+this.MZC*h,g=CalRGBCS.#h;g[0]=u;g[1]=d;g[2]=f;const p=CalRGBCS.#u;this.#w(this.whitePoint,g,p);const m=CalRGBCS.#h;this.#y(this.blackPoint,p,m);const b=CalRGBCS.#u;this.#x(CalRGBCS.#c,m,b);const y=CalRGBCS.#h;this.#f(CalRGBCS.#o,b,y);a[r]=255*this.#m(y[0]);a[r+1]=255*this.#m(y[1]);a[r+2]=255*this.#m(y[2])}getRgbItem(e,t,a,r){this.#i(e,t,a,r,1)}getRgbBuffer(e,t,a,r,i,n,s){const o=1/((1<this.amax||this.bmin>this.bmax){info("Invalid Range, falling back to defaults");this.amin=-100;this.amax=100;this.bmin=-100;this.bmax=100}}#S(e){return e>=6/29?e**3:108/841*(e-4/29)}#A(e,t,a,r){return a+e*(r-a)/t}#i(e,t,a,r,i){let n=e[t],s=e[t+1],o=e[t+2];if(!1!==a){n=this.#A(n,a,0,100);s=this.#A(s,a,this.amin,this.amax);o=this.#A(o,a,this.bmin,this.bmax)}s>this.amax?s=this.amax:sthis.bmax?o=this.bmax:ofunction qcms_convert_one(e,t,a){ya.qcms_convert_one(e,t,a)}(this.#k,255*e[t],a);break;case 3:r=Aa.RGB8;this.#C=(e,t,a)=>function qcms_convert_three(e,t,a,r,i){ya.qcms_convert_three(e,t,a,r,i)}(this.#k,255*e[t],255*e[t+1],255*e[t+2],a);break;case 4:r=Aa.CMYK;this.#C=(e,t,a)=>function qcms_convert_four(e,t,a,r,i,n){ya.qcms_convert_four(e,t,a,r,i,n)}(this.#k,255*e[t],255*e[t+1],255*e[t+2],255*e[t+3],a);break;default:throw new Error(`Unsupported number of components: ${a}`)}this.#k=function qcms_transformer_from_memory(e,t,a){const r=passArray8ToWasm0(e,ya.__wbindgen_malloc),i=Sa;return ya.qcms_transformer_from_memory(r,i,t,a)>>>0}(e,r,ka.Perceptual);if(!this.#k)throw new Error("Failed to create ICC color space");IccColorSpace.#I||=new FinalizationRegistry(e=>{!function qcms_drop_transformer(e){ya.qcms_drop_transformer(e)}(e)});IccColorSpace.#I.register(this,this.#k)}getRgbHex(e,t){this.#C(e,t,!0);return QCMS._cssColor}getRgbItem(e,t,a,r){QCMS._destBuffer=a;QCMS._destOffset=r;QCMS._destLength=3;this.#C(e,t,!1);QCMS._destBuffer=null}getRgbBuffer(e,t,a,r,i,n,s){e=e.subarray(t,t+a*this.numComps);if(8!==n){const t=255/((1<=this.end?-1:this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e)return t.subarray(a,r);let i=a+e;i>r&&(i=r);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);return this.bytes.subarray(e,t)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(e,t,a=null){return new Stream(this.bytes.buffer,e,t,a)}}class StringStream extends Stream{constructor(e){super(stringToBytes(e))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(e,t,a){super(new Uint8Array(e),0,e,null);this.chunkSize=t;this._loadedChunks=new Set;this.numChunks=Math.ceil(e/t);this.manager=a;this.progressiveDataLength=0;this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){const e=[];for(let t=0,a=this.numChunks;t=this.end?this.numChunks:Math.floor(t/this.chunkSize);for(let e=a;ethis.numChunks)&&t!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(t))throw new MissingDataException(e,e+1);this.lastSuccessfulEnsureByteChunk=t}}ensureRange(e,t){if(e>=t)return;if(t<=this.progressiveDataLength)return;const a=Math.floor(e/this.chunkSize);if(a>this.numChunks)return;const r=Math.min(Math.floor((t-1)/this.chunkSize)+1,this.numChunks);for(let i=a;i=this.end)return-1;e>=this.progressiveDataLength&&this.ensureByte(e);return this.bytes[this.pos++]}getBytes(e){const t=this.bytes,a=this.pos,r=this.end;if(!e){r>this.progressiveDataLength&&this.ensureRange(a,r);return t.subarray(a,r)}let i=a+e;i>r&&(i=r);i>this.progressiveDataLength&&this.ensureRange(a,i);this.pos=i;return t.subarray(a,i)}getByteRange(e,t){e<0&&(e=0);t>this.end&&(t=this.end);t>this.progressiveDataLength&&this.ensureRange(e,t);return this.bytes.subarray(e,t)}makeSubStream(e,t,a=null){t?e+t>this.progressiveDataLength&&this.ensureRange(e,e+t):e>=this.progressiveDataLength&&this.ensureByte(e);function ChunkedStreamSubstream(){}ChunkedStreamSubstream.prototype=Object.create(this);ChunkedStreamSubstream.prototype.getMissingChunks=function(){const e=this.chunkSize,t=Math.floor(this.start/e),a=Math.floor((this.end-1)/e)+1,r=[];for(let e=t;e{const readChunk=({value:n,done:s})=>{try{if(s){const t=arrayBuffersToBytes(r);r=null;e(t);return}i+=n.byteLength;a.isStreamingSupported&&this.onProgress({loaded:i});r.push(n);a.read().then(readChunk,t)}catch(e){t(e)}};a.read().then(readChunk,t)}).then(t=>{this.aborted||this.onReceiveData({chunk:t,begin:e})})}requestAllChunks(e=!1){if(!e){const e=this.stream.getMissingChunks();this._requestChunks(e)}return this._loadedStreamCapability.promise}_requestChunks(e){const t=this.currRequestId++,a=new Set;this._chunksNeededByRequest.set(t,a);for(const t of e)this.stream.hasChunk(t)||a.add(t);if(0===a.size)return Promise.resolve();const r=Promise.withResolvers();this._promisesByRequest.set(t,r);const i=[];for(const e of a){let a=this._requestsByChunk.get(e);if(!a){a=[];this._requestsByChunk.set(e,a);i.push(e)}a.push(t)}if(i.length>0){const e=this.groupChunks(i);for(const t of e){const e=t.beginChunk*this.chunkSize,a=Math.min(t.endChunk*this.chunkSize,this.length);this.sendRequest(e,a).catch(r.reject)}}return r.promise.catch(e=>{if(!this.aborted)throw e})}getStream(){return this.stream}requestRange(e,t){t=Math.min(t,this.length);const a=this.getBeginChunk(e),r=this.getEndChunk(t),i=[];for(let e=a;ee-t);return this._requestChunks(t)}groupChunks(e){const t=[];let a=-1,r=-1;for(let i=0,n=e.length;i=0&&r+1!==n){t.push({beginChunk:a,endChunk:r+1});a=n}i+1===e.length&&t.push({beginChunk:a,endChunk:n+1});r=n}return t}onProgress(e){this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize+e.loaded,total:this.length})}onReceiveData(e){const t=e.chunk,a=void 0===e.begin,r=a?this.progressiveDataLength:e.begin,i=r+t.byteLength,n=Math.floor(r/this.chunkSize),s=i0||o.push(a)}}}if(!this.disableAutoFetch&&0===this._requestsByChunk.size){let e;if(1===this.stream.numChunksLoaded){const t=this.stream.numChunks-1;this.stream.hasChunk(t)||(e=t)}else e=this.stream.nextEmptyChunk(s);Number.isInteger(e)&&this._requestChunks([e])}for(const e of o){const t=this._promisesByRequest.get(e);this._promisesByRequest.delete(e);t.resolve()}this.msgHandler.send("DocProgress",{loaded:this.stream.numChunksLoaded*this.chunkSize,total:this.length})}onError(e){this._loadedStreamCapability.reject(e)}getBeginChunk(e){return Math.floor(e/this.chunkSize)}getEndChunk(e){return Math.floor((e-1)/this.chunkSize)+1}abort(e){this.aborted=!0;this.pdfNetworkStream?.cancelAllRequests(e);for(const t of this._promisesByRequest.values())t.reject(e)}}function convertToRGBA(e){switch(e.kind){case F:return convertBlackAndWhiteToRGBA(e);case T:return function convertRGBToRGBA({src:e,srcPos:t=0,dest:a,destPos:r=0,width:i,height:n}){let s=0;const o=i*n*3,c=o>>2,l=new Uint32Array(e.buffer,t,c);if(FeatureTest.isLittleEndian){for(;s>>24|t<<8|4278190080;a[r+2]=t>>>16|i<<16|4278190080;a[r+3]=i>>>8|4278190080}for(let i=4*s,n=t+o;i>>8|255;a[r+2]=t<<16|i>>>16|255;a[r+3]=i<<8|255}for(let i=4*s,n=t+o;i>3,u=7&r,d=e.length;a=new Uint32Array(a.buffer);let f=0;for(let r=0;ra||t>a)return!0;const r=e*t;if(this._hasMaxArea)return r>this.MAX_AREA;if(r(this.MAX_AREA=this.#O**2)}static getReducePowerForJPX(e,t,a){const r=e*t,i=2**30/(4*a);if(!this.needsToBeResized(e,t))return r>i?Math.ceil(Math.log2(r/i)):0;const{MAX_DIM:n,MAX_AREA:s}=this,o=Math.max(e/n,t/n,Math.sqrt(r/Math.min(i,s)));return Math.ceil(Math.log2(o))}static get MAX_DIM(){return shadow(this,"MAX_DIM",this._guessMax(2048,65537,0,1))}static get MAX_AREA(){this._hasMaxArea=!0;return shadow(this,"MAX_AREA",this._guessMax(this.#O,this.MAX_DIM,128,0)**2)}static set MAX_AREA(e){if(e>=0){this._hasMaxArea=!0;shadow(this,"MAX_AREA",e)}}static setOptions({canvasMaxAreaInBytes:e=-1,isImageDecoderSupported:t=!1}){this._hasMaxArea||(this.MAX_AREA=e>>2);this.#M=t}static _areGoodDims(e,t){try{const a=new OffscreenCanvas(e,t),r=a.getContext("2d");r.fillRect(0,0,1,1);const i=r.getImageData(0,0,1,1).data[3];a.width=a.height=1;return 0!==i}catch{return!1}}static _guessMax(e,t,a,r){for(;e+a+1da){const e=this.#D();if(e)return e}const r=this._encodeBMP();let i,n;if(await ImageResizer.canUseImageDecoder){i=new ImageDecoder({data:r,type:"image/bmp",preferAnimation:!1,transfer:[r.buffer]});n=i.decode().catch(e=>{warn(`BMP image decoding failed: ${e}`);return createImageBitmap(new Blob([this._encodeBMP().buffer],{type:"image/bmp"}))}).finally(()=>{i.close()})}else n=createImageBitmap(new Blob([r.buffer],{type:"image/bmp"}));const{MAX_AREA:s,MAX_DIM:o}=ImageResizer,c=Math.max(t/o,a/o,Math.sqrt(t*a/s)),l=Math.max(c,2),h=Math.round(10*(c+1.25))/10/l,u=Math.floor(Math.log2(h)),d=new Array(u+2).fill(2);d[0]=l;d.splice(-1,1,h/(1<>s,c=r>>s;let l,h=r;try{l=new Uint8Array(n)}catch{let e=Math.floor(Math.log2(n+1));for(;;)try{l=new Uint8Array(2**e-1);break}catch{e-=1}h=Math.floor((2**e-1)/(4*a));const t=a*h*4;t>s;e>3,s=a+3&-4;if(a!==s){const e=new Uint8Array(s*t);let r=0;for(let n=0,o=t*a;ni&&(r=i)}else{for(;!this.eof;)this.readBlock(t);r=this.bufferLength}this.pos=r;return this.buffer.subarray(a,r)}async getImageData(e,t){if(!this.canAsyncDecodeImageFromBuffer)return this.isAsyncDecoder?this.decodeImage(null,t):this.getBytes(e,t);const a=await this.stream.asyncGetBytes();return this.decodeImage(a,t)}reset(){this.pos=0}makeSubStream(e,t,a=null){if(void 0===t)for(;!this.eof;)this.readBlock();else{const a=e+t;for(;this.bufferLength<=a&&!this.eof;)this.readBlock()}return new Stream(this.buffer,e,t,a)}getBaseStreams(){return this.stream?this.stream.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(e,t=null){e=e.filter(e=>e instanceof BaseStream);let a=0;for(const t of e)a+=t instanceof DecodeStream?t._rawMinBufferLength:t.length;super(a);this.streams=e;this._onError=t}readBlock(){const e=this.streams;if(0===e.length){this.eof=!0;return}const t=e.shift();let a;try{a=t.getBytes()}catch(e){if(this._onError){this._onError(e,t.dict?.objId);return}throw e}const r=this.bufferLength,i=r+a.length;this.ensureBuffer(i).set(a,r);this.bufferLength=i}getBaseStreams(){const e=[];for(const t of this.streams){const a=t.getBaseStreams();a&&e.push(...a)}return e.length>0?e:null}}class ColorSpaceUtils{static parse({cs:e,xref:t,resources:a=null,pdfFunctionFactory:r,globalColorSpaceCache:i,localColorSpaceCache:n,asyncIfNotCached:s=!1}){const o={xref:t,resources:a,pdfFunctionFactory:r,globalColorSpaceCache:i,localColorSpaceCache:n};let c,l,h;if(e instanceof Ref){l=e;const a=i.getByRef(l)||n.getByRef(l);if(a)return a;e=t.fetch(e)}if(e instanceof Name){c=e.name;const t=n.getByName(c);if(t)return t}try{h=this.#B(e,o)}catch(e){if(s&&!(e instanceof MissingDataException))return Promise.reject(e);throw e}if(c||l){n.set(c,l,h);l&&i.set(null,l,h)}return s?Promise.resolve(h):h}static#R(e,t){const{globalColorSpaceCache:a}=t;let r;if(e instanceof Ref){r=e;const t=a.getByRef(r);if(t)return t}const i=this.#B(e,t);r&&a.set(null,r,i);return i}static#B(e,t){const{xref:a,resources:r,pdfFunctionFactory:i,globalColorSpaceCache:n}=t;if((e=a.fetchIfRef(e))instanceof Name)switch(e.name){case"G":case"DeviceGray":return this.gray;case"RGB":case"DeviceRGB":return this.rgb;case"DeviceRGBA":return this.rgba;case"CMYK":case"DeviceCMYK":return this.cmyk;case"Pattern":return new PatternCS(null);default:if(r instanceof Dict){const a=r.get("ColorSpace");if(a instanceof Dict){const r=a.get(e.name);if(r){if(r instanceof Name)return this.#B(r,t);e=r;break}}}warn(`Unrecognized ColorSpace: ${e.name}`);return this.gray}if(Array.isArray(e)){const r=a.fetchIfRef(e[0]).name;let s,o,c,l,h,u;switch(r){case"G":case"DeviceGray":return this.gray;case"RGB":case"DeviceRGB":return this.rgb;case"CMYK":case"DeviceCMYK":return this.cmyk;case"CalGray":s=a.fetchIfRef(e[1]);l=s.getArray("WhitePoint");h=s.getArray("BlackPoint");u=s.get("Gamma");return new CalGrayCS(l,h,u);case"CalRGB":s=a.fetchIfRef(e[1]);l=s.getArray("WhitePoint");h=s.getArray("BlackPoint");u=s.getArray("Gamma");const d=s.getArray("Matrix");return new CalRGBCS(l,h,u,d);case"ICCBased":const f=e[1]instanceof Ref;if(f){const t=n.getByRef(e[1]);if(t)return t}const g=a.fetchIfRef(e[1]),p=g.dict;o=p.get("N");if(IccColorSpace.isUsable)try{const t=new IccColorSpace(g.getBytes(),"ICCBased",o);f&&n.set(null,e[1],t);return t}catch(t){if(t instanceof MissingDataException)throw t;warn(`ICCBased color space (${e[1]}): "${t}".`)}const m=p.getRaw("Alternate");if(m){const e=this.#R(m,t);if(e.numComps===o)return e;warn("ICCBased color space: Ignoring incorrect /Alternate entry.")}if(1===o)return this.gray;if(3===o)return this.rgb;if(4===o)return this.cmyk;break;case"Pattern":c=e[1]||null;c&&(c=this.#R(c,t));return new PatternCS(c);case"I":case"Indexed":c=this.#R(e[1],t);const b=MathClamp(a.fetchIfRef(e[2]),0,255),y=a.fetchIfRef(e[3]);return new IndexedCS(c,b,y);case"Separation":case"DeviceN":const w=a.fetchIfRef(e[1]);o=Array.isArray(w)?w.length:1;c=this.#R(e[2],t);const x=i.create(e[3]);return new AlternateCS(o,c,x);case"Lab":s=a.fetchIfRef(e[1]);l=s.getArray("WhitePoint");h=s.getArray("BlackPoint");const S=s.getArray("Range");return new LabCS(l,h,S);default:warn(`Unimplemented ColorSpace object: ${r}`);return this.gray}}warn(`Unrecognized ColorSpace object: ${e}`);return this.gray}static get gray(){return shadow(this,"gray",new DeviceGrayCS)}static get rgb(){return shadow(this,"rgb",new DeviceRgbCS)}static get rgba(){return shadow(this,"rgba",new DeviceRgbaCS)}static get cmyk(){if(CmykICCBasedCS.isUsable)try{return shadow(this,"cmyk",new CmykICCBasedCS)}catch{warn("CMYK fallback: DeviceCMYK")}return shadow(this,"cmyk",new DeviceCmykCS)}}class JpegError extends ea{constructor(e){super(e,"JpegError")}}class DNLMarkerError extends ea{constructor(e,t){super(e,"DNLMarkerError");this.scanLines=t}}class EOIMarkerError extends ea{constructor(e){super(e,"EOIMarkerError")}}const va=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),Fa=4017,Ia=799,Ta=3406,Oa=2276,Ma=1567,Da=3784,Ba=5793,Ra=2896;function buildHuffmanTable(e,t){let a,r,i=0,n=16;for(;n>0&&!e[n-1];)n--;const s=[{children:[],index:0}];let o,c=s[0];for(a=0;a0;)c=s.pop();c.index++;s.push(c);for(;s.length<=a;){s.push(o={children:[],index:0});c.children[c.index]=o.children;c=o}i++}if(a+10){g--;return f>>g&1}f=e[t++];if(255===f){const r=e[t++];if(r){if(220===r&&l){const r=readUint16(e,t+=2);t+=2;if(r>0&&r!==a.scanLines)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",r)}else if(217===r){if(l){const e=y*(8===a.precision?8:0);if(e>0&&Math.round(a.scanLines/e)>=5)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",e)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new JpegError(`unexpected marker ${(f<<8|r).toString(16)}`)}}g=7;return f>>>7}function decodeHuffman(e){let t=e;for(;;){t=t[readBit()];switch(typeof t){case"number":return t;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(e){let t=0;for(;e>0;){t=t<<1|readBit();e--}return t}function receiveAndExtend(e){if(1===e)return 1===readBit()?1:-1;const t=receive(e);return t>=1<0){p--;return}let a=n;const r=s;for(;a<=r;){const r=decodeHuffman(e.huffmanTableAC),i=15&r,n=r>>4;if(0===i){if(n<15){p=receive(n)+(1<>4;if(0===i)if(l<15){p=receive(l)+(1<>4;if(0===r){if(n<15)break;i+=16;continue}i+=n;const s=va[i];e.blockData[t+s]=receiveAndExtend(r);i++}};let T,O=0;const M=1===w?r[0].blocksPerLine*r[0].blocksPerColumn:h*a.mcusPerColumn;let D,R;for(;O<=M;){const a=i?Math.min(M-O,i):M;if(a>0){for(S=0;S0?"unexpected":"excessive"} MCU data, current marker is: ${T.invalid}`);t=T.offset}if(!(T.marker>=65488&&T.marker<=65495))break;t+=2}return t-d}function quantizeAndInverse(e,t,a){const r=e.quantizationTable,i=e.blockData;let n,s,o,c,l,h,u,d,f,g,p,m,b,y,w,x,S;if(!r)throw new JpegError("missing required Quantization Table.");for(let e=0;e<64;e+=8){f=i[t+e];g=i[t+e+1];p=i[t+e+2];m=i[t+e+3];b=i[t+e+4];y=i[t+e+5];w=i[t+e+6];x=i[t+e+7];f*=r[e];if(0!==(g|p|m|b|y|w|x)){g*=r[e+1];p*=r[e+2];m*=r[e+3];b*=r[e+4];y*=r[e+5];w*=r[e+6];x*=r[e+7];n=Ba*f+128>>8;s=Ba*b+128>>8;o=p;c=w;l=Ra*(g-x)+128>>8;d=Ra*(g+x)+128>>8;h=m<<4;u=y<<4;n=n+s+1>>1;s=n-s;S=o*Da+c*Ma+128>>8;o=o*Ma-c*Da+128>>8;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Oa+d*Ta+2048>>12;l=l*Ta-d*Oa+2048>>12;d=S;S=h*Ia+u*Fa+2048>>12;h=h*Fa-u*Ia+2048>>12;u=S;a[e]=n+d;a[e+7]=n-d;a[e+1]=s+u;a[e+6]=s-u;a[e+2]=o+h;a[e+5]=o-h;a[e+3]=c+l;a[e+4]=c-l}else{S=Ba*f+512>>10;a[e]=S;a[e+1]=S;a[e+2]=S;a[e+3]=S;a[e+4]=S;a[e+5]=S;a[e+6]=S;a[e+7]=S}}for(let e=0;e<8;++e){f=a[e];g=a[e+8];p=a[e+16];m=a[e+24];b=a[e+32];y=a[e+40];w=a[e+48];x=a[e+56];if(0!==(g|p|m|b|y|w|x)){n=Ba*f+2048>>12;s=Ba*b+2048>>12;o=p;c=w;l=Ra*(g-x)+2048>>12;d=Ra*(g+x)+2048>>12;h=m;u=y;n=4112+(n+s+1>>1);s=n-s;S=o*Da+c*Ma+2048>>12;o=o*Ma-c*Da+2048>>12;c=S;l=l+u+1>>1;u=l-u;d=d+h+1>>1;h=d-h;n=n+c+1>>1;c=n-c;s=s+o+1>>1;o=s-o;S=l*Oa+d*Ta+2048>>12;l=l*Ta-d*Oa+2048>>12;d=S;S=h*Ia+u*Fa+2048>>12;h=h*Fa-u*Ia+2048>>12;u=S;f=n+d;x=n-d;g=s+u;w=s-u;p=o+h;y=o-h;m=c+l;b=c-l;f<16?f=0:f>=4080?f=255:f>>=4;g<16?g=0:g>=4080?g=255:g>>=4;p<16?p=0:p>=4080?p=255:p>>=4;m<16?m=0:m>=4080?m=255:m>>=4;b<16?b=0:b>=4080?b=255:b>>=4;y<16?y=0:y>=4080?y=255:y>>=4;w<16?w=0:w>=4080?w=255:w>>=4;x<16?x=0:x>=4080?x=255:x>>=4;i[t+e]=f;i[t+e+8]=g;i[t+e+16]=p;i[t+e+24]=m;i[t+e+32]=b;i[t+e+40]=y;i[t+e+48]=w;i[t+e+56]=x}else{S=Ba*f+8192>>14;S=S<-2040?0:S>=2024?255:S+2056>>4;i[t+e]=S;i[t+e+8]=S;i[t+e+16]=S;i[t+e+24]=S;i[t+e+32]=S;i[t+e+40]=S;i[t+e+48]=S;i[t+e+56]=S}}}function buildComponentData(e,t){const a=t.blocksPerLine,r=t.blocksPerColumn,i=new Int16Array(64);for(let e=0;e=r)return null;const n=readUint16(e,t);if(n>=65472&&n<=65534)return{invalid:null,marker:n,offset:t};let s=readUint16(e,i);for(;!(s>=65472&&s<=65534);){if(++i>=r)return null;s=readUint16(e,i)}return{invalid:n.toString(16),marker:s,offset:i}}function prepareComponents(e){const t=Math.ceil(e.samplesPerLine/8/e.maxH),a=Math.ceil(e.scanLines/8/e.maxV);for(const r of e.components){const i=Math.ceil(Math.ceil(e.samplesPerLine/8)*r.h/e.maxH),n=Math.ceil(Math.ceil(e.scanLines/8)*r.v/e.maxV),s=t*r.h,o=64*(a*r.v)*(s+1);r.blockData=new Int16Array(o);r.blocksPerLine=i;r.blocksPerColumn=n}e.mcusPerLine=t;e.mcusPerColumn=a}function readDataBlock(e,t){const a=readUint16(e,t);let r=(t+=2)+a-2;const i=findNextFileMarker(e,r,t);if(i?.invalid){warn("readDataBlock - incorrect length, current marker is: "+i.invalid);r=i.offset}const n=e.subarray(t,r);return{appData:n,oldOffset:t,newOffset:t+n.length}}function skipData(e,t){const a=readUint16(e,t),r=(t+=2)+a-2,i=findNextFileMarker(e,r,t);return i?.invalid?i.offset:r}class JpegImage{constructor({decodeTransform:e=null,colorTransform:t=-1}={}){this._decodeTransform=e;this._colorTransform=t}static canUseImageDecoder(e,t=-1){let a=null,r=0,i=null,n=readUint16(e,r);r+=2;if(65496!==n)throw new JpegError("SOI not found");n=readUint16(e,r);r+=2;e:for(;65497!==n;){switch(n){case 65505:const{appData:t,oldOffset:s,newOffset:o}=readDataBlock(e,r);r=o;if(69===t[0]&&120===t[1]&&105===t[2]&&102===t[3]&&0===t[4]&&0===t[5]){if(a)throw new JpegError("Duplicate EXIF-blocks found.");a={exifStart:s+6,exifEnd:o}}n=readUint16(e,r);r+=2;continue;case 65472:case 65473:case 65474:i=e[r+7];break e;case 65535:255!==e[r]&&r--}r=skipData(e,r);n=readUint16(e,r);r+=2}return 4===i||3===i&&0===t?null:a||{}}parse(e,{dnlScanLines:t=null}={}){let a,r,i=0,n=null,s=null,o=0;const c=[],l=[],h=[];let u=readUint16(e,i);i+=2;if(65496!==u)throw new JpegError("SOI not found");u=readUint16(e,i);i+=2;e:for(;65497!==u;){let d,f,g;switch(u){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:const{appData:p,newOffset:m}=readDataBlock(e,i);i=m;65504===u&&74===p[0]&&70===p[1]&&73===p[2]&&70===p[3]&&0===p[4]&&(n={version:{major:p[5],minor:p[6]},densityUnits:p[7],xDensity:p[8]<<8|p[9],yDensity:p[10]<<8|p[11],thumbWidth:p[12],thumbHeight:p[13],thumbData:p.subarray(14,14+3*p[12]*p[13])});65518===u&&65===p[0]&&100===p[1]&&111===p[2]&&98===p[3]&&101===p[4]&&(s={version:p[5]<<8|p[6],flags0:p[7]<<8|p[8],flags1:p[9]<<8|p[10],transformCode:p[11]});break;case 65499:const b=readUint16(e,i);i+=2;const y=b+i-2;let w;for(;i>4){if(t>>4!=1)throw new JpegError("DQT - invalid table spec");for(f=0;f<64;f++){w=va[f];a[w]=readUint16(e,i);i+=2}}else for(f=0;f<64;f++){w=va[f];a[w]=e[i++]}c[15&t]=a}break;case 65472:case 65473:case 65474:if(a)throw new JpegError("Only single frame JPEGs supported");i+=2;a={};a.extended=65473===u;a.progressive=65474===u;a.precision=e[i++];const x=readUint16(e,i);i+=2;a.scanLines=t||x;a.samplesPerLine=readUint16(e,i);i+=2;a.components=[];a.componentIds={};const S=e[i++];let k=0,C=0;for(d=0;d>4,n=15&e[i+1];k>4?l:h)[15&t]=buildHuffmanTable(a,n)}break;case 65501:i+=2;r=readUint16(e,i);i+=2;break;case 65498:const F=1===++o&&!t;i+=2;const T=e[i++],O=[];for(d=0;d>4];n.huffmanTableAC=l[15&s];O.push(n)}const M=e[i++],D=e[i++],R=e[i++];try{i+=decodeScan(e,i,a,O,r,M,D,R>>4,15&R,F)}catch(t){if(t instanceof DNLMarkerError){warn(`${t.message} -- attempting to re-parse the JPEG image.`);return this.parse(e,{dnlScanLines:t.scanLines})}if(t instanceof EOIMarkerError){warn(`${t.message} -- ignoring the rest of the image data.`);break e}throw t}break;case 65500:i+=4;break;case 65535:255!==e[i]&&i--;break;default:const N=findNextFileMarker(e,i-2,i-3);if(N?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+N.invalid);i=N.offset;break}if(!N||i>=e.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break e}throw new JpegError("JpegImage.parse - unknown marker: "+u.toString(16))}u=readUint16(e,i);i+=2}if(!a)throw new JpegError("JpegImage.parse - no frame data found.");this.width=a.samplesPerLine;this.height=a.scanLines;this.jfif=n;this.adobe=s;this.components=[];for(const e of a.components){const t=c[e.quantizationId];t&&(e.quantizationTable=t);this.components.push({index:e.index,output:buildComponentData(0,e),scaleX:e.h/a.maxH,scaleY:e.v/a.maxV,blocksPerLine:e.blocksPerLine,blocksPerColumn:e.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(e,t,a=!1){const r=this.width/e,i=this.height/t;let n,s,o,c,l,h,u,d,f,g,p,m=0;const b=this.components.length,y=e*t*b,w=new Uint8ClampedArray(y),x=new Uint32Array(e),S=4294967288;let k;for(u=0;u>8)+C[f+1];return w}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(e){let t,a,r;for(let i=0,n=e.length;i4)throw new JpegError("Unsupported color mode");const n=this._getLinearizedBlockData(e,t,i);if(1===this.numComponents&&(a||r)){const e=n.length*(a?4:3),t=new Uint8ClampedArray(e);let r=0;if(a)!function grayToRGBA(e,t){if(FeatureTest.isLittleEndian)for(let a=0,r=e.length;a0&&(e=e.subarray(t));break}return e}decodeImage(e){if(this.eof)return this.buffer;e=this.#N(e||this.bytes);const t=new JpegImage(this.jpegOptions);t.parse(e);const a=t.getData({width:this.drawWidth,height:this.drawHeight,forceRGBA:this.forceRGBA,forceRGB:this.forceRGB,isSourcePDF:!0});this.buffer=a;this.bufferLength=a.length;this.eof=!0;return this.buffer}get canAsyncDecodeImageFromBuffer(){return this.stream.isAsync}async getTransferableImage(){if(!await JpegStream.canUseImageDecoder)return null;const e=this.jpegOptions;if(e.decodeTransform)return null;let t;try{const a=this.canAsyncDecodeImageFromBuffer&&await this.stream.asyncGetBytes()||this.bytes;if(!a)return null;let r=this.#N(a);const i=JpegImage.canUseImageDecoder(r,e.colorTransform);if(!i)return null;if(i.exifStart){r=r.slice();r.fill(0,i.exifStart,i.exifEnd)}t=new ImageDecoder({data:r,type:"image/jpeg",preferAnimation:!1});return(await t.decode()).image}catch(e){warn(`getTransferableImage - failed: "${e}".`);return null}finally{t?.close()}}}const Na=async function OpenJPEG(e={}){var t=e,a="./this.program",quit_=(e,t)=>{throw t},r=import.meta.url;try{new URL(".",r).href}catch{}0;var i,n,s,o,c,l,h,u,d=console.log.bind(console),f=console.error.bind(console),g=!1,p=!1;function updateMemoryViews(){var e=o.buffer;c=new Int8Array(e);new Int16Array(e);l=new Uint8Array(e);new Uint16Array(e);h=new Int32Array(e);u=new Uint32Array(e);new Float32Array(e);new Float64Array(e);new BigInt64Array(e);new BigUint64Array(e)}class ExitStatus{name="ExitStatus";constructor(e){this.message=`Program terminated with exit(${e})`;this.status=e}}var m,callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(t)},b=[],addOnPostRun=e=>b.push(e),y=[],addOnPreRun=e=>y.push(e),w=!0,x=0,S={},handleException=e=>{if(e instanceof ExitStatus||"unwind"==e)return i;quit_(0,e)},keepRuntimeAlive=()=>w||x>0,_proc_exit=e=>{i=e;if(!keepRuntimeAlive()){t.onExit?.(e);g=!0}quit_(0,new ExitStatus(e))},_exit=(e,t)=>{i=e;_proc_exit(e)},callUserCallback=e=>{if(!g)try{e();(()=>{if(!keepRuntimeAlive())try{_exit(i)}catch(e){handleException(e)}})()}catch(e){handleException(e)}},alignMemory=(e,t)=>Math.ceil(e/t)*t,growMemory=e=>{var t=(e-o.buffer.byteLength+65535)/65536|0;try{o.grow(t);updateMemoryViews();return 1}catch(e){}},k={},getEnvStrings=()=>{if(!getEnvStrings.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.language||"C").replace("-","_")+".UTF-8",_:a||"./this.program"};for(var t in k)void 0===k[t]?delete e[t]:e[t]=k[t];var r=[];for(var t in e)r.push(`${t}=${e[t]}`);getEnvStrings.strings=r}return getEnvStrings.strings},stringToUTF8=(e,t,a)=>((e,t,a,r)=>{if(!(r>0))return 0;for(var i=a,n=a+r-1,s=0;s=n)break;t[a++]=o}else if(o<=2047){if(a+1>=n)break;t[a++]=192|o>>6;t[a++]=128|63&o}else if(o<=65535){if(a+2>=n)break;t[a++]=224|o>>12;t[a++]=128|o>>6&63;t[a++]=128|63&o}else{if(a+3>=n)break;t[a++]=240|o>>18;t[a++]=128|o>>12&63;t[a++]=128|o>>6&63;t[a++]=128|63&o;s++}}t[a]=0;return a-i})(e,l,t,a),lengthBytesUTF8=e=>{for(var t=0,a=0;a=55296&&r<=57343){t+=4;++a}else t+=3}return t},C=[null,[],[]],v="undefined"!=typeof TextDecoder?new TextDecoder:void 0,UTF8ArrayToString=(e,t=0,a,r)=>{var i=((e,t,a,r)=>{var i=t+a;if(r)return i;for(;e[t]&&!(t>=i);)++t;return t})(e,t,a,r);if(i-t>16&&e.buffer&&v)return v.decode(e.subarray(t,i));for(var n="";t>10,56320|1023&l)}}else n+=String.fromCharCode((31&s)<<6|o)}else n+=String.fromCharCode(s)}return n},printChar=(e,t)=>{var a=C[e];if(0===t||10===t){(1===e?d:f)(UTF8ArrayToString(a));a.length=0}else a.push(t)},UTF8ToString=(e,t,a)=>e?UTF8ArrayToString(l,e,t,a):"";t.noExitRuntime&&(w=t.noExitRuntime);t.print&&(d=t.print);t.printErr&&(f=t.printErr);t.wasmBinary&&t.wasmBinary;t.arguments&&t.arguments;t.thisProgram&&(a=t.thisProgram);if(t.preInit){"function"==typeof t.preInit&&(t.preInit=[t.preInit]);for(;t.preInit.length>0;)t.preInit.shift()()}t.writeArrayToMemory=(e,t)=>{c.set(e,t)};var F,T={k:()=>function abort(e){t.onAbort?.(e);f(e="Aborted("+e+")");g=!0;e+=". Build with -sASSERTIONS for more info.";var a=new WebAssembly.RuntimeError(e);s?.(a);throw a}(""),j:()=>{w=!1;x=0},l:(e,t)=>{if(S[e]){clearTimeout(S[e].id);delete S[e]}if(!t)return 0;var a=setTimeout(()=>{delete S[e];callUserCallback(()=>m(e,performance.now()))},t);S[e]={id:a,timeout_ms:t};return 0},f:function _copy_pixels_1(e,a){e>>=2;const r=t.imageData=new Uint8ClampedArray(a),i=h.subarray(e,e+a);r.set(i)},e:function _copy_pixels_3(e,a,r,i){e>>=2;a>>=2;r>>=2;const n=t.imageData=new Uint8ClampedArray(3*i),s=h.subarray(e,e+i),o=h.subarray(a,a+i),c=h.subarray(r,r+i);for(let e=0;e>=2;a>>=2;r>>=2;i>>=2;const s=t.imageData=new Uint8ClampedArray(4*n),o=h.subarray(e,e+n),c=h.subarray(a,a+n),l=h.subarray(r,r+n),u=h.subarray(i,i+n);for(let e=0;e{var t=l.length,a=2147483648;if((e>>>=0)>a)return!1;for(var r=1;r<=4;r*=2){var i=t*(1+.2/r);i=Math.min(i,e+100663296);var n=Math.min(a,alignMemory(Math.max(e,i),65536));if(growMemory(n))return!0}return!1},o:(e,t)=>{var a=0,r=0;for(var i of getEnvStrings()){var n=t+a;u[e+r>>2]=n;a+=stringToUTF8(i,n,1/0)+1;r+=4}return 0},p:(e,t)=>{var a=getEnvStrings();u[e>>2]=a.length;var r=0;for(var i of a)r+=lengthBytesUTF8(i)+1;u[t>>2]=r;return 0},n:function _fd_seek(e,t,a,r){t=(i=t)<-9007199254740992||i>9007199254740992?NaN:Number(i);var i;return 70},b:(e,t,a,r)=>{for(var i=0,n=0;n>2],o=u[t+4>>2];t+=8;for(var c=0;c>2]=i;return 0},q:function _gray_to_rgba(e,a){e>>=2;const r=t.imageData=new Uint8ClampedArray(4*a),i=h.subarray(e,e+a);for(let e=0;e>=2;a>>=2;const i=t.imageData=new Uint8ClampedArray(4*r),n=h.subarray(e,e+r),s=h.subarray(a,a+r);for(let e=0;e>=2;a>>=2;r>>=2;const n=t.imageData=new Uint8ClampedArray(4*i),s=h.subarray(e,e+i),o=h.subarray(a,a+i),c=h.subarray(r,r+i);for(let e=0;e{t.instantiateWasm(e,(e,t)=>{a(receiveInstance(e))})})}();!function run(){!function preRun(){if(t.preRun){"function"==typeof t.preRun&&(t.preRun=[t.preRun]);for(;t.preRun.length;)addOnPreRun(t.preRun.shift())}callRuntimeCallbacks(y)}();function doRun(){t.calledRun=!0;if(!g){!function initRuntime(){p=!0;F.s()}();n?.(t);t.onRuntimeInitialized?.();!function postRun(){if(t.postRun){"function"==typeof t.postRun&&(t.postRun=[t.postRun]);for(;t.postRun.length;)addOnPostRun(t.postRun.shift())}callRuntimeCallbacks(b)}()}}if(t.setStatus){t.setStatus("Running...");setTimeout(()=>{setTimeout(()=>t.setStatus(""),1);doRun()},1)}else doRun()}();return p?t:new Promise((e,t)=>{n=e;s=t})};class JpxError extends ea{constructor(e){super(e,"JpxError")}}class JpxImage{static#E=null;static#P=null;static#L=null;static#v=!0;static#_=!0;static#F=null;static setOptions({handler:e,useWasm:t,useWorkerFetch:a,wasmUrl:r}){this.#v=t;this.#_=a;this.#F=r;a||(this.#P=e)}static async#U(e){const t=`${this.#F}openjpeg_nowasm_fallback.js`;let a=null;try{a=(await import( +/*webpackIgnore: true*/ +/*@vite-ignore*/ +t)).default()}catch(e){warn(`JpxImage#getJsModule: ${e}`)}e(a)}static async#j(e,t,a){const r="openjpeg.wasm";try{this.#E||(this.#_?this.#E=await fetchBinaryData(`${this.#F}${r}`):this.#E=await this.#P.sendWithPromise("FetchBinaryData",{type:"wasmFactory",filename:r}));return a((await WebAssembly.instantiate(this.#E,t)).instance)}catch(t){warn(`JpxImage#instantiateWasm: ${t}`);this.#U(e);return null}finally{this.#P=null}}static async decode(e,{numComponents:t=4,isIndexedColormap:a=!1,smaskInData:r=!1,reducePower:i=0}={}){if(!this.#L){const{promise:e,resolve:t}=Promise.withResolvers(),a=[e];this.#v?a.push(Na({warn,instantiateWasm:this.#j.bind(this,t)})):this.#U(t);this.#L=Promise.race(a)}const n=await this.#L;if(!n)throw new JpxError("OpenJPEG failed to initialize");let s;try{const o=e.length;s=n._malloc(o);n.writeArrayToMemory(e,s);if(n._jp2_decode(s,o,t>0?t:0,!!a,!!r,i)){const{errorMessages:e}=n;if(e){delete n.errorMessages;throw new JpxError(e)}throw new JpxError("Unknown error")}const{imageData:c}=n;n.imageData=null;return c}finally{s&&n._free(s)}}static cleanup(){this.#L=null}static parseImageProperties(e){let t=e.getByte();for(;t>=0;){const a=t;t=e.getByte();if(65361===(a<<8|t)){e.skip(4);const t=e.getInt32()>>>0,a=e.getInt32()>>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0;e.skip(16);return{width:t-r,height:a-i,bitsPerComponent:8,componentsCount:e.getUint16()}}}throw new JpxError("No size marker found in JPX stream")}}function addState(e,t,a,r,i){let n=e;for(let e=0,a=t.length-1;e1e3){l=Math.max(l,d);f+=u+2;d=0;u=0}h.push({transform:t,x:d,y:f,w:a.width,h:a.height});d+=a.width+2;u=Math.max(u,a.height)}const g=Math.max(l,d)+1,p=f+u+1,m=new Uint8Array(g*p*4),b=g<<2;for(let e=0;e=0;){t[n-4]=t[n];t[n-3]=t[n+1];t[n-2]=t[n+2];t[n-1]=t[n+3];t[n+a]=t[n+a-4];t[n+a+1]=t[n+a-3];t[n+a+2]=t[n+a-2];t[n+a+3]=t[n+a-1];n-=b}}const y={width:g,height:p};if(e.isOffscreenCanvasSupported){const e=new OffscreenCanvas(g,p);e.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(m.buffer),g,p),0,0);y.bitmap=e.transferToImageBitmap();y.data=null}else{y.kind=O;y.data=m}a.splice(n,4*c,_t);r.splice(n,4*c,[y,h]);return n+1});addState(Ea,[ye,xe,Nt,we],null,function iterateImageMaskGroup(e,t){const a=e.fnArray,r=(t-(e.iCurr-3))%4;switch(r){case 0:return a[t]===ye;case 1:return a[t]===xe;case 2:return a[t]===Nt;case 3:return a[t]===we}throw new Error(`iterateImageMaskGroup - invalid pos: ${r}`)},function foundImageMaskGroup(e,t){const a=e.fnArray,r=e.argsArray,i=e.iCurr,n=i-3,s=i-2,o=i-1;let c=Math.floor((t-n)/4);if(c<10)return t-(t-n)%4;let l,h,u=!1;const d=r[o][0],f=r[s][0],g=r[s][1],p=r[s][2],m=r[s][3];if(g===p){u=!0;l=s+4;let e=o+4;for(let t=1;t=4&&a[n-4]===a[s]&&a[n-3]===a[o]&&a[n-2]===a[c]&&a[n-1]===a[l]&&r[n-4][0]===h&&r[n-4][1]===u){d++;f-=5}let g=f+4;for(let e=1;e{const t=e.argsArray,a=t[e.iCurr-1][0];if(a!==Te&&a!==Oe&&a!==Be&&a!==Re&&a!==Ne&&a!==Ee)return!0;const r=t[e.iCurr-2];return 1===r[0]&&0===r[1]&&0===r[2]&&1===r[3]},()=>!1,(e,t)=>{const{fnArray:a,argsArray:r}=e,i=e.iCurr,n=i-3,s=i-2,o=r[i-1],c=r[s],[,[l],h]=o;if(h){Util.scaleMinMax(c,h);for(let e=0,t=l.length;e=a)break}r=(r||Ea)[e[t]];if(r&&!Array.isArray(r)){n.iCurr=t;t++;if(!r.checkFn||(0,r.checkFn)(n)){i=r;r=null}else r=null}else t++}this.state=r;this.match=i;this.lastProcessed=t}flush(){for(;this.match;){const e=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,e);this.match=null;this.state=null;this._optimize()}}reset(){this.state=null;this.match=null;this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;static isOffscreenCanvasSupported=!1;constructor(e=0,t){this._streamSink=t;this.fnArray=[];this.argsArray=[];this.optimizer=!t||e&d?new NullOptimizer(this):new QueueOptimizer(this);this.dependencies=new Set;this._totalLength=0;this.weight=0;this._resolved=t?null:Promise.resolve()}static setOptions({isOffscreenCanvasSupported:e}){this.isOffscreenCanvasSupported=e}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(e,t){this.optimizer.push(e,t);this.weight++;this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(e===we||e===je))&&this.flush()}addImageOps(e,t,a,r=!1){if(r){this.addOp(ye);this.addOp(be,[[["SMask",!1]]])}void 0!==a&&this.addOp(Ct,["OC",a]);this.addOp(e,t);void 0!==a&&this.addOp(vt,[]);r&&this.addOp(we)}addDependency(e){if(!this.dependencies.has(e)){this.dependencies.add(e);this.addOp(le,[e])}}addDependencies(e){for(const t of e)this.addDependency(t)}addOpList(e){if(e instanceof OperatorList){for(const t of e.dependencies)this.dependencies.add(t);for(let t=0,a=e.length;t>>0}function hexToStr(e,t){return 1===t?String.fromCharCode(e[0],e[1]):3===t?String.fromCharCode(e[0],e[1],e[2],e[3]):String.fromCharCode(...e.subarray(0,t+1))}function addHex(e,t,a){let r=0;for(let i=a;i>=0;i--){r+=e[i]+t[i];e[i]=255&r;r>>=8}}function incHex(e,t){let a=1;for(let r=t;r>=0&&a>0;r--){a+=e[r];e[r]=255&a;a>>=8}}const Pa=16;class BinaryCMapStream{constructor(e){this.buffer=e;this.pos=0;this.end=e.length;this.tmpBuf=new Uint8Array(19)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let e,t=0;do{const a=this.readByte();if(a<0)throw new FormatError("unexpected EOF in bcmap");e=!(128&a);t=t<<7|127&a}while(!e);return t}readSigned(){const e=this.readNumber();return 1&e?~(e>>>1):e>>>1}readHex(e,t){e.set(this.buffer.subarray(this.pos,this.pos+t+1));this.pos+=t+1}readHexNumber(e,t){let a;const r=this.tmpBuf;let i=0;do{const e=this.readByte();if(e<0)throw new FormatError("unexpected EOF in bcmap");a=!(128&e);r[i++]=127&e}while(!a);let n=t,s=0,o=0;for(;n>=0;){for(;o<8&&r.length>0;){s|=r[--i]<>=8;o-=8}}readHexSigned(e,t){this.readHexNumber(e,t);const a=1&e[t]?255:0;let r=0;for(let i=0;i<=t;i++){r=(1&r)<<8|e[i];e[i]=r>>1^a}}readString(){const e=this.readNumber(),t=new Array(e);for(let a=0;a=0;){const e=d>>5;if(7===e){switch(31&d){case 0:r.readString();break;case 1:n=r.readString()}continue}const a=!!(16&d),i=15&d;if(i+1>Pa)throw new Error("BinaryCMapReader.process: Invalid dataSize.");const f=1,g=r.readNumber();switch(e){case 0:r.readHex(s,i);r.readHexNumber(o,i);addHex(o,s,i);t.addCodespaceRange(i+1,hexToInt(s,i),hexToInt(o,i));for(let e=1;e=0;--i){r[a+i]=255&s;s>>=8}}}}class AsciiHexStream extends DecodeStream{constructor(e,t){t&&(t*=.5);super(t);this.stream=e;this.dict=e.dict;this.firstDigit=-1}readBlock(){const e=this.stream.getBytes(8e3);if(!e.length){this.eof=!0;return}const t=e.length+1>>1,a=this.ensureBuffer(this.bufferLength+t);let r=this.bufferLength,i=this.firstDigit;for(const t of e){let e;if(t>=48&&t<=57)e=15&t;else{if(!(t>=65&&t<=70||t>=97&&t<=102)){if(62===t){this.eof=!0;break}continue}e=9+(15&t)}if(i<0)i=e;else{a[r++]=i<<4|e;i=-1}}if(i>=0&&this.eof){a[r++]=i<<4;i=-1}this.firstDigit=i;this.bufferLength=r}}const La=-1,_a=[[-1,-1],[-1,-1],[7,8],[7,7],[6,6],[6,6],[6,5],[6,5],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[4,0],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[3,3],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2],[1,2]],Ua=[[-1,-1],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],ja=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],Xa=[[-1,-1],[-1,-1],[12,-2],[12,-2],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],qa=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],Ha=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(e,t={}){if("function"!=typeof e?.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=e;this.eof=!1;this.encoding=t.K||0;this.eoline=t.EndOfLine||!1;this.byteAlign=t.EncodedByteAlign||!1;this.columns=t.Columns||1728;this.rows=t.Rows||0;this.eoblock=t.EndOfBlock??!0;this.black=t.BlackIs1||!1;this.codingLine=new Uint32Array(this.columns+1);this.refLine=new Uint32Array(this.columns+2);this.codingLine[0]=this.columns;this.codingPos=0;this.row=0;this.nextLine2D=this.encoding<0;this.inputBits=0;this.inputBuf=0;this.outputBits=0;this.rowsDone=!1;let a;for(;0===(a=this._lookBits(12));)this._eatBits(1);1===a&&this._eatBits(12);if(this.encoding>0){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}}readNextChar(){if(this.eof)return-1;const e=this.refLine,t=this.codingLine,a=this.columns;let r,i,n,s,o;if(0===this.outputBits){this.rowsDone&&(this.eof=!0);if(this.eof)return-1;this.err=!1;let n,o,c;if(this.nextLine2D){for(s=0;t[s]=64);do{o+=c=this._getWhiteCode()}while(c>=64)}else{do{n+=c=this._getWhiteCode()}while(c>=64);do{o+=c=this._getBlackCode()}while(c>=64)}this._addPixels(t[this.codingPos]+n,i);t[this.codingPos]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]0?--r:++r;for(;e[r]<=t[this.codingPos]&&e[r]=64);else do{n+=c=this._getWhiteCode()}while(c>=64);this._addPixels(t[this.codingPos]+n,i);i^=1}}let l=!1;this.byteAlign&&(this.inputBits&=-8);if(this.eoblock||this.row!==this.rows-1){n=this._lookBits(12);if(this.eoline)for(;n!==La&&1!==n;){this._eatBits(1);n=this._lookBits(12)}else for(;0===n;){this._eatBits(1);n=this._lookBits(12)}if(1===n){this._eatBits(12);l=!0}else n===La&&(this.eof=!0)}else this.rowsDone=!0;if(!this.eof&&this.encoding>0&&!this.rowsDone){this.nextLine2D=!this._lookBits(1);this._eatBits(1)}if(this.eoblock&&l&&this.byteAlign){n=this._lookBits(12);if(1===n){this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}if(this.encoding>=0)for(s=0;s<4;++s){n=this._lookBits(12);1!==n&&info("bad rtc code: "+n);this._eatBits(12);if(this.encoding>0){this._lookBits(1);this._eatBits(1)}}this.eof=!0}}else if(this.err&&this.eoline){for(;;){n=this._lookBits(13);if(n===La){this.eof=!0;return-1}if(n>>1==1)break;this._eatBits(1)}this._eatBits(12);if(this.encoding>0){this._eatBits(1);this.nextLine2D=!(1&n)}}this.outputBits=t[0]>0?t[this.codingPos=0]:t[this.codingPos=1];this.row++}if(this.outputBits>=8){o=1&this.codingPos?0:255;this.outputBits-=8;if(0===this.outputBits&&t[this.codingPos]n){o<<=n;1&this.codingPos||(o|=255>>8-n);this.outputBits-=n;n=0}else{o<<=this.outputBits;1&this.codingPos||(o|=255>>8-this.outputBits);n-=this.outputBits;this.outputBits=0;if(t[this.codingPos]0){o<<=n;n=0}}}while(n)}this.black&&(o^=255);return o}_addPixels(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}this.codingPos=r}_addPixelsNeg(e,t){const a=this.codingLine;let r=this.codingPos;if(e>a[r]){if(e>this.columns){info("row is wrong length");this.err=!0;e=this.columns}1&r^t&&++r;a[r]=e}else if(e0&&e=i){const t=a[e-i];if(t[0]===r){this._eatBits(r);return[!0,t[1],!0]}}}return[!1,0,!1]}_getTwoDimCode(){let e,t=0;if(this.eoblock){t=this._lookBits(7);e=_a[t];if(e?.[0]>0){this._eatBits(e[0]);return e[1]}}else{const e=this._findTableCode(1,7,_a);if(e[0]&&e[2])return e[1]}info("Bad two dim code");return La}_getWhiteCode(){let e,t=0;if(this.eoblock){t=this._lookBits(12);if(t===La)return 1;e=t>>5?ja[t>>3]:Ua[t];if(e[0]>0){this._eatBits(e[0]);return e[1]}}else{let e=this._findTableCode(1,9,ja);if(e[0])return e[1];e=this._findTableCode(11,12,Ua);if(e[0])return e[1]}info("bad white code");this._eatBits(1);return 1}_getBlackCode(){let e,t;if(this.eoblock){e=this._lookBits(13);if(e===La)return 1;t=e>>7?!(e>>9)&&e>>7?qa[(e>>1)-64]:Ha[e>>7]:Xa[e];if(t[0]>0){this._eatBits(t[0]);return t[1]}}else{let e=this._findTableCode(2,6,Ha);if(e[0])return e[1];e=this._findTableCode(7,12,qa,64);if(e[0])return e[1];e=this._findTableCode(10,13,Xa);if(e[0])return e[1]}info("bad black code");this._eatBits(1);return 1}_lookBits(e){let t;for(;this.inputBits>16-e;this.inputBuf=this.inputBuf<<8|t;this.inputBits+=8}return this.inputBuf>>this.inputBits-e&65535>>16-e}_eatBits(e){(this.inputBits-=e)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.dict=e.dict;a instanceof Dict||(a=Dict.empty);const r={next:()=>e.getByte()};this.ccittFaxDecoder=new CCITTFaxDecoder(r,{K:a.get("K"),EndOfLine:a.get("EndOfLine"),EncodedByteAlign:a.get("EncodedByteAlign"),Columns:a.get("Columns"),Rows:a.get("Rows"),EndOfBlock:a.get("EndOfBlock"),BlackIs1:a.get("BlackIs1")})}readBlock(){for(;!this.eof;){const e=this.ccittFaxDecoder.readNextChar();if(-1===e){this.eof=!0;return}this.ensureBuffer(this.bufferLength+1);this.buffer[this.bufferLength++]=e}}}const Wa=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ga=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),za=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),$a=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],Va=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(e,t){super(t);this.stream=e;this.dict=e.dict;const a=e.getByte(),r=e.getByte();if(-1===a||-1===r)throw new FormatError(`Invalid header in flate stream: ${a}, ${r}`);if(8!=(15&a))throw new FormatError(`Unknown compression method in flate stream: ${a}, ${r}`);if(((a<<8)+r)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${a}, ${r}`);if(32&r)throw new FormatError(`FDICT bit set in flate stream: ${a}, ${r}`);this.codeSize=0;this.codeBuf=0}async getImageData(e,t){const a=await this.asyncGetBytes();return a?a.length<=e?a:a.subarray(0,e):this.getBytes(e)}async asyncGetBytes(){this.stream.reset();const e=this.stream.getBytes();try{const{readable:t,writable:a}=new DecompressionStream("deflate"),r=a.getWriter();await r.ready;r.write(e).then(async()=>{await r.ready;await r.close()}).catch(()=>{});const i=[];let n=0;for await(const e of t){i.push(e);n+=e.byteLength}const s=new Uint8Array(n);let o=0;for(const e of i){s.set(e,o);o+=e.byteLength}return s}catch{this.stream=new Stream(e,2,e.length,this.stream.dict);this.reset();return null}}get isAsync(){return!0}getBits(e){const t=this.stream;let a,r=this.codeSize,i=this.codeBuf;for(;r>e;this.codeSize=r-=e;return a}getCode(e){const t=this.stream,a=e[0],r=e[1];let i,n=this.codeSize,s=this.codeBuf;for(;n>16,l=65535&o;if(c<1||n>c;this.codeSize=n-c;return l}generateHuffmanTable(e){const t=e.length;let a,r=0;for(a=0;ar&&(r=e[a]);const i=1<>=1}for(a=e;a>=1;if(0===t){let t;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}let a=t;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}a|=t<<8;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}let i=t;if(-1===(t=r.getByte())){this.#X("Bad block header in flate stream");return}i|=t<<8;if(i!==(65535&~a)&&(0!==a||0!==i))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;const n=this.bufferLength,s=n+a;e=this.ensureBuffer(s);this.bufferLength=s;if(0===a)-1===r.peekByte()&&(this.eof=!0);else{const t=r.getBytes(a);e.set(t,n);t.length0;)h[o++]=f}i=this.generateHuffmanTable(h.subarray(0,e));n=this.generateHuffmanTable(h.subarray(e,l))}}e=this.buffer;let s=e?e.length:0,o=this.bufferLength;for(;;){let t=this.getCode(i);if(t<256){if(o+1>=s){e=this.ensureBuffer(o+1);s=e.length}e[o++]=t;continue}if(256===t){this.bufferLength=o;return}t-=257;t=Ga[t];let r=t>>16;r>0&&(r=this.getBits(r));a=(65535&t)+r;t=this.getCode(n);t=za[t];r=t>>16;r>0&&(r=this.getBits(r));const c=(65535&t)+r;if(o+a>=s){e=this.ensureBuffer(o+a);s=e.length}for(let t=0;t>9&127;this.clow=this.clow<<7&65535;this.ct-=7;this.a=32768}byteIn(){const e=this.data;let t=this.bp;if(255===e[t])if(e[t+1]>143){this.clow+=65280;this.ct=8}else{t++;this.clow+=e[t]<<9;this.ct=7;this.bp=t}else{t++;this.clow+=t65535){this.chigh+=this.clow>>16;this.clow&=65535}}readBit(e,t){let a=e[t]>>1,r=1&e[t];const i=Ka[a],n=i.qe;let s,o=this.a-n;if(this.chigh>15&1;this.clow=this.clow<<1&65535;this.ct--}while(!(32768&o));this.a=o;e[t]=a<<1|r;return s}}class Jbig2Error extends ea{constructor(e){super(e,"Jbig2Error")}}class ContextCache{getContexts(e){return e in this?this[e]:this[e]=new Int8Array(65536)}}class DecodingContext{constructor(e,t,a){this.data=e;this.start=t;this.end=a}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}function decodeInteger(e,t,a){const r=e.getContexts(t);let i=1;function readBits(e){let t=0;for(let n=0;n>>0}const n=readBits(1),s=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let o;0===n?o=s:s>0&&(o=-s);return o>=-2147483648&&o<=da?o:null}function decodeIAID(e,t,a){const r=e.getContexts("IAID");let i=1;for(let e=0;ee.y-t.y||e.x-t.x);const h=l.length,u=new Int8Array(h),d=new Int8Array(h),f=[];let g,p,m=0,b=0,y=0,w=0;for(p=0;p=v&&E=F){q=q<<1&m;for(p=0;p=0&&_=0){U=D[L][_];U&&(q|=U<=e?l<<=1:l=l<<1|S[o][c]}for(f=0;f=w||c<0||c>=y?l<<=1:l=l<<1|r[o][c]}const g=k.readBit(C,l);t[s]=g}}return S}function decodeTextRegion(e,t,a,r,i,n,s,o,c,l,h,u,d,f,g,p,m,b,y){if(e&&t)throw new Jbig2Error("refinement with Huffman is not supported");const w=[];let x,S;for(x=0;x1&&(i=e?y.readBits(b):decodeInteger(C,"IAIT",k));const n=s*v+i,F=e?f.symbolIDTable.decode(y):decodeIAID(C,k,c),T=t&&(e?y.readBit():decodeInteger(C,"IARI",k));let O=o[F],M=O[0].length,D=O.length;if(T){const e=decodeInteger(C,"IARDW",k),t=decodeInteger(C,"IARDH",k);M+=e;D+=t;O=decodeRefinement(M,D,g,O,(e>>1)+decodeInteger(C,"IARDX",k),(t>>1)+decodeInteger(C,"IARDY",k),!1,p,m)}let R=0;l?1&u?R=D-1:r+=D-1:u>1?r+=M-1:R=M-1;const N=n-(1&u?0:D-1),E=r-(2&u?M-1:0);let L,_,U;if(l)for(L=0;L>5&7;const c=[31&s];let l=t+6;if(7===s){o=536870911&readUint32(e,l-1);l+=3;let t=o+7>>3;c[0]=e[l++];for(;--t>0;)c.push(e[l++])}else if(5===s||6===s)throw new Jbig2Error("invalid referred-to flags");a.retainBits=c;let h=4;a.number<=256?h=1:a.number<=65536&&(h=2);const u=[];let d,f;for(d=0;d>>24&255;n[3]=t.height>>16&255;n[4]=t.height>>8&255;n[5]=255&t.height;for(d=l,f=e.length;d>2&3;e.huffmanDWSelector=t>>4&3;e.bitmapSizeSelector=t>>6&1;e.aggregationInstancesSelector=t>>7&1;e.bitmapCodingContextUsed=!!(256&t);e.bitmapCodingContextRetained=!!(512&t);e.template=t>>10&3;e.refinementTemplate=t>>12&1;l+=2;if(!e.huffman){c=0===e.template?4:1;s=[];for(o=0;o>2&3;h.stripSize=1<>4&3;h.transposed=!!(64&u);h.combinationOperator=u>>7&3;h.defaultPixelValue=u>>9&1;h.dsOffset=u<<17>>27;h.refinementTemplate=u>>15&1;if(h.huffman){const e=readUint16(r,l);l+=2;h.huffmanFS=3&e;h.huffmanDS=e>>2&3;h.huffmanDT=e>>4&3;h.huffmanRefinementDW=e>>6&3;h.huffmanRefinementDH=e>>8&3;h.huffmanRefinementDX=e>>10&3;h.huffmanRefinementDY=e>>12&3;h.huffmanRefinementSizeSelector=!!(16384&e)}if(h.refinement&&!h.refinementTemplate){s=[];for(o=0;o<2;o++){s.push({x:readInt8(r,l),y:readInt8(r,l+1)});l+=2}h.refinementAt=s}h.numberOfSymbolInstances=readUint32(r,l);l+=4;n=[h,a.referredTo,r,l,i];break;case 16:const d={},f=r[l++];d.mmr=!!(1&f);d.template=f>>1&3;d.patternWidth=r[l++];d.patternHeight=r[l++];d.maxPatternIndex=readUint32(r,l);l+=4;n=[d,a.number,r,l,i];break;case 22:case 23:const g={};g.info=readRegionSegmentInformation(r,l);l+=tr;const p=r[l++];g.mmr=!!(1&p);g.template=p>>1&3;g.enableSkip=!!(8&p);g.combinationOperator=p>>4&7;g.defaultPixelValue=p>>7&1;g.gridWidth=readUint32(r,l);l+=4;g.gridHeight=readUint32(r,l);l+=4;g.gridOffsetX=4294967295&readUint32(r,l);l+=4;g.gridOffsetY=4294967295&readUint32(r,l);l+=4;g.gridVectorX=readUint16(r,l);l+=2;g.gridVectorY=readUint16(r,l);l+=2;n=[g,a.referredTo,r,l,i];break;case 38:case 39:const m={};m.info=readRegionSegmentInformation(r,l);l+=tr;const b=r[l++];m.mmr=!!(1&b);m.template=b>>1&3;m.prediction=!!(8&b);if(!m.mmr){c=0===m.template?4:1;s=[];for(o=0;o>2&1;y.combinationOperator=w>>3&3;y.requiresBuffer=!!(32&w);y.combinationOperatorOverride=!!(64&w);n=[y];break;case 49:case 50:case 51:case 62:break;case 53:n=[a.number,r,l,i];break;default:throw new Jbig2Error(`segment type ${a.typeName}(${a.type}) is not implemented`)}const h="on"+a.typeName;h in t&&t[h].apply(t,n)}function processSegments(e,t){for(let a=0,r=e.length;a>3,a=new Uint8ClampedArray(t*e.height);e.defaultPixelValue&&a.fill(255);this.buffer=a}drawBitmap(e,t){const a=this.currentPageInfo,r=e.width,i=e.height,n=a.width+7>>3,s=a.combinationOperatorOverride?e.combinationOperator:a.combinationOperator,o=this.buffer,c=128>>(7&e.x);let l,h,u,d,f=e.y*n+(e.x>>3);switch(s){case 0:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;case 2:for(l=0;l>=1;if(!u){u=128;d++}}f+=n}break;default:throw new Jbig2Error(`operator ${s} is not supported`)}}onImmediateGenericRegion(e,t,a,r){const i=e.info,n=new DecodingContext(t,a,r),s=decodeBitmap(e.mmr,i.width,i.height,e.template,e.prediction,null,e.at,n);this.drawBitmap(i,s)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(e,t,a,r,i,n){let s,o;if(e.huffman){s=function getSymbolDictionaryHuffmanTables(e,t,a){let r,i,n,s,o=0;switch(e.huffmanDHSelector){case 0:case 1:r=getStandardTable(e.huffmanDHSelector+4);break;case 3:r=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DH selector")}switch(e.huffmanDWSelector){case 0:case 1:i=getStandardTable(e.huffmanDWSelector+2);break;case 3:i=getCustomHuffmanTable(o,t,a);o++;break;default:throw new Jbig2Error("invalid Huffman DW selector")}if(e.bitmapSizeSelector){n=getCustomHuffmanTable(o,t,a);o++}else n=getStandardTable(1);s=e.aggregationInstancesSelector?getCustomHuffmanTable(o,t,a):getStandardTable(1);return{tableDeltaHeight:r,tableDeltaWidth:i,tableBitmapSize:n,tableAggregateInstances:s}}(e,a,this.customTables);o=new Reader(r,i,n)}let c=this.symbols;c||(this.symbols=c={});const l=[];for(const e of a){const t=c[e];t&&l.push(...t)}const h=new DecodingContext(r,i,n);c[t]=function decodeSymbolDictionary(e,t,a,r,i,n,s,o,c,l,h,u){if(e&&t)throw new Jbig2Error("symbol refinement with Huffman is not supported");const d=[];let f=0,g=log2(a.length+r);const p=h.decoder,m=h.contextCache;let b,y;if(e){b=getStandardTable(1);y=[];g=Math.max(g,1)}for(;d.length1)w=decodeTextRegion(e,t,r,f,0,i,1,a.concat(d),g,0,0,1,0,n,c,l,h,0,u);else{const e=decodeIAID(m,p,g),t=decodeInteger(m,"IARDX",p),i=decodeInteger(m,"IARDY",p);w=decodeRefinement(r,f,c,e=32){let a,r,s;switch(t){case 32:if(0===e)throw new Jbig2Error("no previous value in symbol ID table");r=i.readBits(2)+3;a=n[e-1].prefixLength;break;case 33:r=i.readBits(3)+3;a=0;break;case 34:r=i.readBits(7)+11;a=0;break;default:throw new Jbig2Error("invalid code length in symbol ID table")}for(s=0;s=0;m--){O=e?decodeMMRBitmap(T,c,l,!0):decodeBitmap(!1,c,l,a,!1,null,v,g);F[m]=O}for(M=0;M=0;b--){R^=F[b][M][D];N|=R<>8;_=u+M*d-D*f>>8;if(L>=0&&L+S<=r&&_>=0&&_+k<=i)for(m=0;m=i)){j=p[t];U=E[m];for(b=0;b=0&&e>1&7),c=1+(r>>4&7),l=[];let h,u,d=i;do{h=s.readBits(o);u=s.readBits(c);l.push(new HuffmanLine([d,h,u,0]));d+=1<>t&1;if(t<=0)this.children[a]=new HuffmanTreeNode(e);else{let r=this.children[a];r||(this.children[a]=r=new HuffmanTreeNode(null));r.buildTree(e,t-1)}}decodeNode(e){if(this.isLeaf){if(this.isOOB)return null;const t=e.readBits(this.rangeLength);return this.rangeLow+(this.isLowerRange?-t:t)}const t=this.children[e.readBit()];if(!t)throw new Jbig2Error("invalid Huffman data");return t.decodeNode(e)}}class HuffmanTable{constructor(e,t){t||this.assignPrefixCodes(e);this.rootNode=new HuffmanTreeNode(null);for(let t=0,a=e.length;t0&&this.rootNode.buildTree(a,a.prefixLength-1)}}decode(e){return this.rootNode.decodeNode(e)}assignPrefixCodes(e){const t=e.length;let a=0;for(let r=0;r=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++];this.shift=7}const e=this.currentByte>>this.shift&1;this.shift--;return e}readBits(e){let t,a=0;for(t=e-1;t>=0;t--)a|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(e,t,a){let r=0;for(let i=0,n=t.length;i>a&1;a--}}if(r&&!o){const e=5;for(let t=0;t>>t&(1<0;if(e<256){d[0]=e;f=1}else{if(!(e>=258)){if(256===e){h=9;s=258;f=0;continue}this.eof=!0;delete this.lzwState;break}if(e=0;t--){d[t]=o[a];a=l[a]}}else d[f++]=d[0]}if(i){l[s]=u;c[s]=c[u]+1;o[s]=d[0];s++;h=s+n&s+n-1?h:0|Math.min(Math.log(s+n)/.6931471805599453+1,12)}u=e;g+=f;if(r15))throw new FormatError(`Unsupported predictor: ${r}`);this.readBlock=2===r?this.readBlockTiff:this.readBlockPng;this.stream=e;this.dict=e.dict;const i=this.colors=a.get("Colors")||1,n=this.bits=a.get("BPC","BitsPerComponent")||8,s=this.columns=a.get("Columns")||1;this.pixBytes=i*n+7>>3;this.rowBytes=s*i*n+7>>3;return this}readBlockTiff(){const e=this.rowBytes,t=this.bufferLength,a=this.ensureBuffer(t+e),r=this.bits,i=this.colors,n=this.stream.getBytes(e);this.eof=!n.length;if(this.eof)return;let s,o=0,c=0,l=0,h=0,u=t;if(1===r&&1===i)for(s=0;s>1;e^=e>>2;e^=e>>4;o=(1&e)<<7;a[u++]=e}else if(8===r){for(s=0;s>8&255;a[u++]=255&e}}else{const e=new Uint8Array(i+1),u=(1<>l-r)&u;l-=r;c=c<=8){a[f++]=c>>h-8&255;h-=8}}h>0&&(a[f++]=(c<<8-h)+(o&(1<<8-h)-1))}this.bufferLength+=e}readBlockPng(){const e=this.rowBytes,t=this.pixBytes,a=this.stream.getByte(),r=this.stream.getBytes(e);this.eof=!r.length;if(this.eof)return;const i=this.bufferLength,n=this.ensureBuffer(i+e);let s=n.subarray(i-e,i);0===s.length&&(s=new Uint8Array(e));let o,c,l,h=i;switch(a){case 0:for(o=0;o>1)+r[o];for(;o>1)+r[o]&255;h++}break;case 4:for(o=0;o0){const e=this.stream.getBytes(r);t.set(e,a);a+=r}}else{r=257-r;t=this.ensureBuffer(a+r+1);t.fill(e[1],a,a+r);a+=r}this.bufferLength=a}}class Parser{constructor({lexer:e,xref:t,allowStreams:a=!1,recoveryMode:r=!1}){this.lexer=e;this.xref=t;this.allowStreams=a;this.recoveryMode=r;this.imageCache=Object.create(null);this._imageId=0;this.refill()}refill(){this.buf1=this.lexer.getObj();this.buf2=this.lexer.getObj()}shift(){if(this.buf2 instanceof Cmd&&"ID"===this.buf2.cmd){this.buf1=this.buf2;this.buf2=null}else{this.buf1=this.buf2;this.buf2=this.lexer.getObj()}}tryShift(){try{this.shift();return!0}catch(e){if(e instanceof MissingDataException)throw e;return!1}}getObj(e=null){const t=this.buf1;this.shift();if(t instanceof Cmd)switch(t.cmd){case"BI":return this.makeInlineImage(e);case"[":const a=[];for(;!isCmd(this.buf1,"]")&&this.buf1!==sa;)a.push(this.getObj(e));if(this.buf1===sa){if(this.recoveryMode)return a;throw new ParserEOFException("End of file inside array.")}this.shift();return a;case"<<":const r=new Dict(this.xref);for(;!isCmd(this.buf1,">>")&&this.buf1!==sa;){if(!(this.buf1 instanceof Name)){info("Malformed dictionary: key must be a name object");this.shift();continue}const t=this.buf1.name;this.shift();if(this.buf1===sa)break;r.set(t,this.getObj(e))}if(this.buf1===sa){if(this.recoveryMode)return r;throw new ParserEOFException("End of file inside dictionary.")}if(isCmd(this.buf2,"stream"))return this.allowStreams?this.makeStream(r,e):r;this.shift();return r;default:return t}if(Number.isInteger(t)){if(Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")){const e=Ref.get(t,this.buf1);this.shift();this.shift();return e}return t}return"string"==typeof t&&e?e.decryptString(t):t}findDefaultInlineStreamEnd(e){const{knownCommands:t}=this.lexer,a=e.pos;let r,i,n=0;for(;-1!==(r=e.getByte());)if(0===n)n=69===r?1:0;else if(1===n)n=73===r?2:0;else if(32===r||10===r||13===r){i=e.pos;const a=e.peekBytes(15),s=a.length;if(0===s)break;for(let e=0;e127))){n=0;break}}if(2!==n)continue;if(!t){warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.");continue}const o=new Lexer(new Stream(e.peekBytes(75)),t);o._hexStringWarn=()=>{};let c=0;for(;;){const e=o.getObj();if(e===sa){n=0;break}if(e instanceof Cmd){const a=t[e.cmd];if(!a){n=0;break}if(a.variableArgs?c<=a.numArgs:c===a.numArgs)break;c=0;continue}c++}if(2===n)break}else n=0;if(-1===r){warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker");if(i){warn('... trying to recover by using the last "EI" occurrence.');e.skip(-(e.pos-i))}}let s=4;e.skip(-s);r=e.peekByte();e.skip(s);isWhiteSpace(r)||s--;return e.pos-s-a}findDCTDecodeInlineStreamEnd(e){const t=e.pos;let a,r,i=!1;for(;-1!==(a=e.getByte());)if(255===a){switch(e.getByte()){case 0:break;case 255:e.skip(-1);break;case 217:i=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:r=e.getUint16();r>2?e.skip(r-2):e.skip(-2)}if(i)break}const n=e.pos-t;if(-1===a){warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead.");e.skip(-n);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return n}findASCII85DecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte());)if(126===a){const t=e.pos;a=e.peekByte();for(;isWhiteSpace(a);){e.skip();a=e.peekByte()}if(62===a){e.skip();break}if(e.pos>t){const t=e.peekBytes(2);if(69===t[0]&&73===t[1])break}}const r=e.pos-t;if(-1===a){warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}findASCIIHexDecodeInlineStreamEnd(e){const t=e.pos;let a;for(;-1!==(a=e.getByte())&&62!==a;);const r=e.pos-t;if(-1===a){warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead.");e.skip(-r);return this.findDefaultInlineStreamEnd(e)}this.inlineStreamSkipEI(e);return r}inlineStreamSkipEI(e){let t,a=0;for(;-1!==(t=e.getByte());)if(0===a)a=69===t?1:0;else if(1===a)a=73===t?2:0;else if(2===a)break}makeInlineImage(e){const t=this.lexer,a=t.stream,r=Object.create(null);let i;for(;!isCmd(this.buf1,"ID")&&this.buf1!==sa;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");const t=this.buf1.name;this.shift();if(this.buf1===sa)break;r[t]=this.getObj(e)}-1!==t.beginInlineImagePos&&(i=a.pos-t.beginInlineImagePos);const n=this.xref.fetchIfRef(r.F||r.Filter);let s;if(n instanceof Name)s=n.name;else if(Array.isArray(n)){const e=this.xref.fetchIfRef(n[0]);e instanceof Name&&(s=e.name)}const o=a.pos;let c,l;switch(s){case"DCT":case"DCTDecode":c=this.findDCTDecodeInlineStreamEnd(a);break;case"A85":case"ASCII85Decode":c=this.findASCII85DecodeInlineStreamEnd(a);break;case"AHx":case"ASCIIHexDecode":c=this.findASCIIHexDecodeInlineStreamEnd(a);break;default:c=this.findDefaultInlineStreamEnd(a)}if(c<1e3&&i>0){const e=a.pos;a.pos=t.beginInlineImagePos;l=function getInlineImageCacheKey(e){const t=[],a=e.length;let r=0;for(;r=r){let r=!1;for(const e of i){const t=e.length;let i=0;for(;i=n){r=!0;break}if(i>=t){if(isWhiteSpace(s[c+o+i])){info(`Found "${bytesToString([...a,...e])}" when searching for endstream command.`);r=!0}break}}if(r){t.pos+=c;return t.pos-e}}c++}t.pos+=o}return-1}makeStream(e,t){const a=this.lexer;let r=a.stream;a.skipToNextLine();const i=r.pos-1;let n=e.get("Length");if(!Number.isInteger(n)){info(`Bad length "${n&&n.toString()}" in stream.`);n=0}r.pos=i+n;a.nextChar();if(this.tryShift()&&isCmd(this.buf2,"endstream"))this.shift();else{n=this.#q(i);if(n<0)throw new FormatError("Missing endstream command.");a.nextChar();this.shift();this.shift()}this.shift();r=r.makeSubStream(i,n,e);t&&(r=t.createStream(r,n));r=this.filter(r,e,n);r.dict=e;return r}filter(e,t,a){let r=t.get("F","Filter"),i=t.get("DP","DecodeParms");if(r instanceof Name){Array.isArray(i)&&warn("/DecodeParms should not be an Array, when /Filter is a Name.");return this.makeFilter(e,r.name,a,i)}let n=a;if(Array.isArray(r)){const t=r,a=i;for(let s=0,o=t.length;s=48&&e<=57?15&e:e>=65&&e<=70||e>=97&&e<=102?9+(15&e):-1}class Lexer{constructor(e,t=null){this.stream=e;this.nextChar();this.strBuf=[];this.knownCommands=t;this._hexStringNumWarn=0;this.beginInlineImagePos=-1}nextChar(){return this.currentChar=this.stream.getByte()}peekChar(){return this.stream.peekByte()}getNumber(){let e=this.currentChar,t=!1,a=0,r=1;if(45===e){r=-1;e=this.nextChar();45===e&&(e=this.nextChar())}else 43===e&&(e=this.nextChar());if(10===e||13===e)do{e=this.nextChar()}while(10===e||13===e);if(46===e){a=10;e=this.nextChar()}if(e<48||e>57){const t=`Invalid number: ${String.fromCharCode(e)} (charCode ${e})`;if(isWhiteSpace(e)||40===e||60===e||-1===e){info(`Lexer.getNumber - "${t}".`);return 0}throw new FormatError(t)}let i=e-48,n=0,s=1;for(;(e=this.nextChar())>=0;)if(e>=48&&e<=57){const r=e-48;if(t)n=10*n+r;else{0!==a&&(a*=10);i=10*i+r}}else if(46===e){if(0!==a)break;a=1}else if(45===e)warn("Badly formatted number: minus sign in the middle");else{if(69!==e&&101!==e)break;e=this.peekChar();if(43===e||45===e){s=45===e?-1:1;this.nextChar()}else if(e<48||e>57)break;t=!0}0!==a&&(i/=a);t&&(i*=10**(s*n));return r*i}getString(){let e=1,t=!1;const a=this.strBuf;a.length=0;let r=this.nextChar();for(;;){let i=!1;switch(0|r){case-1:warn("Unterminated string");t=!0;break;case 40:++e;a.push("(");break;case 41:if(0===--e){this.nextChar();t=!0}else a.push(")");break;case 92:r=this.nextChar();switch(r){case-1:warn("Unterminated string");t=!0;break;case 110:a.push("\n");break;case 114:a.push("\r");break;case 116:a.push("\t");break;case 98:a.push("\b");break;case 102:a.push("\f");break;case 92:case 40:case 41:a.push(String.fromCharCode(r));break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:let e=15&r;r=this.nextChar();i=!0;if(r>=48&&r<=55){e=(e<<3)+(15&r);r=this.nextChar();if(r>=48&&r<=55){i=!1;e=(e<<3)+(15&r)}}a.push(String.fromCharCode(e));break;case 13:10===this.peekChar()&&this.nextChar();break;case 10:break;default:a.push(String.fromCharCode(r))}break;default:a.push(String.fromCharCode(r))}if(t)break;i||(r=this.nextChar())}return a.join("")}getName(){let e,t;const a=this.strBuf;a.length=0;for(;(e=this.nextChar())>=0&&!rr[e];)if(35===e){e=this.nextChar();if(rr[e]){warn("Lexer_getName: NUMBER SIGN (#) should be followed by a hexadecimal number.");a.push("#");break}const r=toHexDigit(e);if(-1!==r){t=e;e=this.nextChar();const i=toHexDigit(e);if(-1===i){warn(`Lexer_getName: Illegal digit (${String.fromCharCode(e)}) in hexadecimal number.`);a.push("#",String.fromCharCode(t));if(rr[e])break;a.push(String.fromCharCode(e));continue}a.push(String.fromCharCode(r<<4|i))}else a.push("#",String.fromCharCode(e))}else a.push(String.fromCharCode(e));a.length>127&&warn(`Name token is longer than allowed by the spec: ${a.length}`);return Name.get(a.join(""))}_hexStringWarn(e){5!==this._hexStringNumWarn++?this._hexStringNumWarn>5||warn(`getHexString - ignoring invalid character: ${e}`):warn("getHexString - ignoring additional invalid characters.")}getHexString(){const e=this.strBuf;e.length=0;let t=this.currentChar,a=-1,r=-1;this._hexStringNumWarn=0;for(;;){if(t<0){warn("Unterminated hex string");break}if(62===t){this.nextChar();break}if(1!==rr[t]){r=toHexDigit(t);if(-1===r)this._hexStringWarn(t);else if(-1===a)a=r;else{e.push(String.fromCharCode(a<<4|r));a=-1}t=this.nextChar()}else t=this.nextChar()}-1!==a&&e.push(String.fromCharCode(a<<4));return e.join("")}getObj(){let e=!1,t=this.currentChar;for(;;){if(t<0)return sa;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(1!==rr[t])break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return this.getNumber();case 40:return this.getString();case 47:return this.getName();case 91:this.nextChar();return Cmd.get("[");case 93:this.nextChar();return Cmd.get("]");case 60:t=this.nextChar();if(60===t){this.nextChar();return Cmd.get("<<")}return this.getHexString();case 62:t=this.nextChar();if(62===t){this.nextChar();return Cmd.get(">>")}return Cmd.get(">");case 123:this.nextChar();return Cmd.get("{");case 125:this.nextChar();return Cmd.get("}");case 41:this.nextChar();throw new FormatError(`Illegal character: ${t}`)}let a=String.fromCharCode(t);if(t<32||t>127){const e=this.peekChar();if(e>=32&&e<=127){this.nextChar();return Cmd.get(a)}}const r=this.knownCommands;let i=void 0!==r?.[a];for(;(t=this.nextChar())>=0&&!rr[t];){const e=a+String.fromCharCode(t);if(i&&void 0===r[e])break;if(128===a.length)throw new FormatError(`Command token too long: ${a.length}`);a=e;i=void 0!==r?.[a]}if("true"===a)return!0;if("false"===a)return!1;if("null"===a)return null;"BI"===a&&(this.beginInlineImagePos=this.stream.pos);return Cmd.get(a)}skipToNextLine(){let e=this.currentChar;for(;e>=0;){if(13===e){e=this.nextChar();10===e&&this.nextChar();break}if(10===e){this.nextChar();break}e=this.nextChar()}}}class Linearization{static create(e){function getInt(e,t,a=!1){const r=e.get(t);if(Number.isInteger(r)&&(a?r>=0:r>0))return r;throw new Error(`The "${t}" parameter in the linearization dictionary is invalid.`)}const t=new Parser({lexer:new Lexer(e),xref:null}),a=t.getObj(),r=t.getObj(),i=t.getObj(),n=t.getObj();let s,o;if(!(Number.isInteger(a)&&Number.isInteger(r)&&isCmd(i,"obj")&&n instanceof Dict&&"number"==typeof(s=n.get("Linearized"))&&s>0))return null;if((o=getInt(n,"L"))!==e.length)throw new Error('The "L" parameter in the linearization dictionary does not equal the stream length.');return{length:o,hints:function getHints(e){const t=e.get("H");let a;if(Array.isArray(t)&&(2===(a=t.length)||4===a)){for(let e=0;e0))throw new Error(`Hint (${e}) in the linearization dictionary is invalid.`)}return t}throw new Error("Hint array in the linearization dictionary is invalid.")}(n),objectNumberFirst:getInt(n,"O"),endFirst:getInt(n,"E"),numPages:getInt(n,"N"),mainXRefEntriesOffset:getInt(n,"T"),pageFirst:n.has("P")?getInt(n,"P",!0):0}}}const ir=["Adobe-GB1-UCS2","Adobe-CNS1-UCS2","Adobe-Japan1-UCS2","Adobe-Korea1-UCS2","78-EUC-H","78-EUC-V","78-H","78-RKSJ-H","78-RKSJ-V","78-V","78ms-RKSJ-H","78ms-RKSJ-V","83pv-RKSJ-H","90ms-RKSJ-H","90ms-RKSJ-V","90msp-RKSJ-H","90msp-RKSJ-V","90pv-RKSJ-H","90pv-RKSJ-V","Add-H","Add-RKSJ-H","Add-RKSJ-V","Add-V","Adobe-CNS1-0","Adobe-CNS1-1","Adobe-CNS1-2","Adobe-CNS1-3","Adobe-CNS1-4","Adobe-CNS1-5","Adobe-CNS1-6","Adobe-GB1-0","Adobe-GB1-1","Adobe-GB1-2","Adobe-GB1-3","Adobe-GB1-4","Adobe-GB1-5","Adobe-Japan1-0","Adobe-Japan1-1","Adobe-Japan1-2","Adobe-Japan1-3","Adobe-Japan1-4","Adobe-Japan1-5","Adobe-Japan1-6","Adobe-Korea1-0","Adobe-Korea1-1","Adobe-Korea1-2","B5-H","B5-V","B5pc-H","B5pc-V","CNS-EUC-H","CNS-EUC-V","CNS1-H","CNS1-V","CNS2-H","CNS2-V","ETHK-B5-H","ETHK-B5-V","ETen-B5-H","ETen-B5-V","ETenms-B5-H","ETenms-B5-V","EUC-H","EUC-V","Ext-H","Ext-RKSJ-H","Ext-RKSJ-V","Ext-V","GB-EUC-H","GB-EUC-V","GB-H","GB-V","GBK-EUC-H","GBK-EUC-V","GBK2K-H","GBK2K-V","GBKp-EUC-H","GBKp-EUC-V","GBT-EUC-H","GBT-EUC-V","GBT-H","GBT-V","GBTpc-EUC-H","GBTpc-EUC-V","GBpc-EUC-H","GBpc-EUC-V","H","HKdla-B5-H","HKdla-B5-V","HKdlb-B5-H","HKdlb-B5-V","HKgccs-B5-H","HKgccs-B5-V","HKm314-B5-H","HKm314-B5-V","HKm471-B5-H","HKm471-B5-V","HKscs-B5-H","HKscs-B5-V","Hankaku","Hiragana","KSC-EUC-H","KSC-EUC-V","KSC-H","KSC-Johab-H","KSC-Johab-V","KSC-V","KSCms-UHC-H","KSCms-UHC-HW-H","KSCms-UHC-HW-V","KSCms-UHC-V","KSCpc-EUC-H","KSCpc-EUC-V","Katakana","NWP-H","NWP-V","RKSJ-H","RKSJ-V","Roman","UniCNS-UCS2-H","UniCNS-UCS2-V","UniCNS-UTF16-H","UniCNS-UTF16-V","UniCNS-UTF32-H","UniCNS-UTF32-V","UniCNS-UTF8-H","UniCNS-UTF8-V","UniGB-UCS2-H","UniGB-UCS2-V","UniGB-UTF16-H","UniGB-UTF16-V","UniGB-UTF32-H","UniGB-UTF32-V","UniGB-UTF8-H","UniGB-UTF8-V","UniJIS-UCS2-H","UniJIS-UCS2-HW-H","UniJIS-UCS2-HW-V","UniJIS-UCS2-V","UniJIS-UTF16-H","UniJIS-UTF16-V","UniJIS-UTF32-H","UniJIS-UTF32-V","UniJIS-UTF8-H","UniJIS-UTF8-V","UniJIS2004-UTF16-H","UniJIS2004-UTF16-V","UniJIS2004-UTF32-H","UniJIS2004-UTF32-V","UniJIS2004-UTF8-H","UniJIS2004-UTF8-V","UniJISPro-UCS2-HW-V","UniJISPro-UCS2-V","UniJISPro-UTF8-V","UniJISX0213-UTF32-H","UniJISX0213-UTF32-V","UniJISX02132004-UTF32-H","UniJISX02132004-UTF32-V","UniKS-UCS2-H","UniKS-UCS2-V","UniKS-UTF16-H","UniKS-UTF16-V","UniKS-UTF32-H","UniKS-UTF32-V","UniKS-UTF8-H","UniKS-UTF8-V","V","WP-Symbol"],nr=2**24-1;class CMap{constructor(e=!1){this.codespaceRanges=[[],[],[],[]];this.numCodespaceRanges=0;this._map=[];this.name="";this.vertical=!1;this.useCMap=null;this.builtInCMap=e}addCodespaceRange(e,t,a){this.codespaceRanges[e-1].push(t,a);this.numCodespaceRanges++}mapCidRange(e,t,a){if(t-e>nr)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;e<=t;)this._map[e++]=a++}mapBfRange(e,t,a){if(t-e>nr)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");const r=a.length-1;for(;e<=t;){this._map[e++]=a;const t=a.charCodeAt(r)+1;t>255?a=a.substring(0,r-1)+String.fromCharCode(a.charCodeAt(r-1)+1)+"\0":a=a.substring(0,r)+String.fromCharCode(t)}}mapBfRangeToArray(e,t,a){if(t-e>nr)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");const r=a.length;let i=0;for(;e<=t&&i>>0;const s=i[n];for(let e=0,t=s.length;e=t&&r<=i){a.charcode=r;a.length=n+1;return}}}a.charcode=0;a.length=1}getCharCodeLength(e){const t=this.codespaceRanges;for(let a=0,r=t.length;a=i&&e<=n)return a+1}}return 1}get length(){return this._map.length}get isIdentityCMap(){if("Identity-H"!==this.name&&"Identity-V"!==this.name)return!1;if(65536!==this._map.length)return!1;for(let e=0;e<65536;e++)if(this._map[e]!==e)return!1;return!0}}class IdentityCMap extends CMap{constructor(e,t){super();this.vertical=e;this.addCodespaceRange(t,0,65535)}mapCidRange(e,t,a){unreachable("should not call mapCidRange")}mapBfRange(e,t,a){unreachable("should not call mapBfRange")}mapBfRangeToArray(e,t,a){unreachable("should not call mapBfRangeToArray")}mapOne(e,t){unreachable("should not call mapCidOne")}lookup(e){return Number.isInteger(e)&&e<=65535?e:void 0}contains(e){return Number.isInteger(e)&&e<=65535}forEach(e){for(let t=0;t<=65535;t++)e(t,t)}charCodeOf(e){return Number.isInteger(e)&&e<=65535?e:-1}getMap(){const e=new Array(65536);for(let t=0;t<=65535;t++)e[t]=t;return e}get length(){return 65536}get isIdentityCMap(){unreachable("should not access .isIdentityCMap")}}function strToInt(e){let t=0;for(let a=0;a>>0}function expectString(e){if("string"!=typeof e)throw new FormatError("Malformed CMap: expected string.")}function expectInt(e){if(!Number.isInteger(e))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endbfchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=a;e.mapOne(r,i)}}function parseBfRange(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endbfrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();if(Number.isInteger(a)||"string"==typeof a){const t=Number.isInteger(a)?String.fromCharCode(a):a;e.mapBfRange(r,i,t)}else{if(!isCmd(a,"["))break;{a=t.getObj();const n=[];for(;!isCmd(a,"]")&&a!==sa;){n.push(a);a=t.getObj()}e.mapBfRangeToArray(r,i,n)}}}throw new FormatError("Invalid bf range.")}function parseCidChar(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endcidchar"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectInt(a);const i=a;e.mapOne(r,i)}}function parseCidRange(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endcidrange"))return;expectString(a);const r=strToInt(a);a=t.getObj();expectString(a);const i=strToInt(a);a=t.getObj();expectInt(a);const n=a;e.mapCidRange(r,i,n)}}function parseCodespaceRange(e,t){for(;;){let a=t.getObj();if(a===sa)break;if(isCmd(a,"endcodespacerange"))return;if("string"!=typeof a)break;const r=strToInt(a);a=t.getObj();if("string"!=typeof a)break;const i=strToInt(a);e.addCodespaceRange(a.length,r,i)}throw new FormatError("Invalid codespace range.")}function parseWMode(e,t){const a=t.getObj();Number.isInteger(a)&&(e.vertical=!!a)}function parseCMapName(e,t){const a=t.getObj();a instanceof Name&&(e.name=a.name)}async function parseCMap(e,t,a,r){let i,n;e:for(;;)try{const a=t.getObj();if(a===sa)break;if(a instanceof Name){"WMode"===a.name?parseWMode(e,t):"CMapName"===a.name&&parseCMapName(e,t);i=a}else if(a instanceof Cmd)switch(a.cmd){case"endcmap":break e;case"usecmap":i instanceof Name&&(n=i.name);break;case"begincodespacerange":parseCodespaceRange(e,t);break;case"beginbfchar":parseBfChar(e,t);break;case"begincidchar":parseCidChar(e,t);break;case"beginbfrange":parseBfRange(e,t);break;case"begincidrange":parseCidRange(e,t)}}catch(e){if(e instanceof MissingDataException)throw e;warn("Invalid cMap data: "+e);continue}!r&&n&&(r=n);return r?extendCMap(e,a,r):e}async function extendCMap(e,t,a){e.useCMap=await createBuiltInCMap(a,t);if(0===e.numCodespaceRanges){const t=e.useCMap.codespaceRanges;for(let a=0;aextendCMap(i,t,e));const n=new Lexer(new Stream(a));return parseCMap(i,n,t,null)}class CMapFactory{static async create({encoding:e,fetchBuiltInCMap:t,useCMap:a}){if(e instanceof Name)return createBuiltInCMap(e.name,t);if(e instanceof BaseStream){const r=await parseCMap(new CMap,new Lexer(e),t,a);return r.isIdentityCMap?createBuiltInCMap(r.name,t):r}throw new Error("Encoding required.")}}const sr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],or=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],cr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],lr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],hr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],ur=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],dr=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(e){switch(e){case"WinAnsiEncoding":return hr;case"StandardEncoding":return lr;case"MacRomanEncoding":return cr;case"SymbolSetEncoding":return ur;case"ZapfDingbatsEncoding":return dr;case"ExpertEncoding":return sr;case"MacExpertEncoding":return or;default:return null}}const fr=getLookupTableFactory(function(e){e.A=65;e.AE=198;e.AEacute=508;e.AEmacron=482;e.AEsmall=63462;e.Aacute=193;e.Aacutesmall=63457;e.Abreve=258;e.Abreveacute=7854;e.Abrevecyrillic=1232;e.Abrevedotbelow=7862;e.Abrevegrave=7856;e.Abrevehookabove=7858;e.Abrevetilde=7860;e.Acaron=461;e.Acircle=9398;e.Acircumflex=194;e.Acircumflexacute=7844;e.Acircumflexdotbelow=7852;e.Acircumflexgrave=7846;e.Acircumflexhookabove=7848;e.Acircumflexsmall=63458;e.Acircumflextilde=7850;e.Acute=63177;e.Acutesmall=63412;e.Acyrillic=1040;e.Adblgrave=512;e.Adieresis=196;e.Adieresiscyrillic=1234;e.Adieresismacron=478;e.Adieresissmall=63460;e.Adotbelow=7840;e.Adotmacron=480;e.Agrave=192;e.Agravesmall=63456;e.Ahookabove=7842;e.Aiecyrillic=1236;e.Ainvertedbreve=514;e.Alpha=913;e.Alphatonos=902;e.Amacron=256;e.Amonospace=65313;e.Aogonek=260;e.Aring=197;e.Aringacute=506;e.Aringbelow=7680;e.Aringsmall=63461;e.Asmall=63329;e.Atilde=195;e.Atildesmall=63459;e.Aybarmenian=1329;e.B=66;e.Bcircle=9399;e.Bdotaccent=7682;e.Bdotbelow=7684;e.Becyrillic=1041;e.Benarmenian=1330;e.Beta=914;e.Bhook=385;e.Blinebelow=7686;e.Bmonospace=65314;e.Brevesmall=63220;e.Bsmall=63330;e.Btopbar=386;e.C=67;e.Caarmenian=1342;e.Cacute=262;e.Caron=63178;e.Caronsmall=63221;e.Ccaron=268;e.Ccedilla=199;e.Ccedillaacute=7688;e.Ccedillasmall=63463;e.Ccircle=9400;e.Ccircumflex=264;e.Cdot=266;e.Cdotaccent=266;e.Cedillasmall=63416;e.Chaarmenian=1353;e.Cheabkhasiancyrillic=1212;e.Checyrillic=1063;e.Chedescenderabkhasiancyrillic=1214;e.Chedescendercyrillic=1206;e.Chedieresiscyrillic=1268;e.Cheharmenian=1347;e.Chekhakassiancyrillic=1227;e.Cheverticalstrokecyrillic=1208;e.Chi=935;e.Chook=391;e.Circumflexsmall=63222;e.Cmonospace=65315;e.Coarmenian=1361;e.Csmall=63331;e.D=68;e.DZ=497;e.DZcaron=452;e.Daarmenian=1332;e.Dafrican=393;e.Dcaron=270;e.Dcedilla=7696;e.Dcircle=9401;e.Dcircumflexbelow=7698;e.Dcroat=272;e.Ddotaccent=7690;e.Ddotbelow=7692;e.Decyrillic=1044;e.Deicoptic=1006;e.Delta=8710;e.Deltagreek=916;e.Dhook=394;e.Dieresis=63179;e.DieresisAcute=63180;e.DieresisGrave=63181;e.Dieresissmall=63400;e.Digammagreek=988;e.Djecyrillic=1026;e.Dlinebelow=7694;e.Dmonospace=65316;e.Dotaccentsmall=63223;e.Dslash=272;e.Dsmall=63332;e.Dtopbar=395;e.Dz=498;e.Dzcaron=453;e.Dzeabkhasiancyrillic=1248;e.Dzecyrillic=1029;e.Dzhecyrillic=1039;e.E=69;e.Eacute=201;e.Eacutesmall=63465;e.Ebreve=276;e.Ecaron=282;e.Ecedillabreve=7708;e.Echarmenian=1333;e.Ecircle=9402;e.Ecircumflex=202;e.Ecircumflexacute=7870;e.Ecircumflexbelow=7704;e.Ecircumflexdotbelow=7878;e.Ecircumflexgrave=7872;e.Ecircumflexhookabove=7874;e.Ecircumflexsmall=63466;e.Ecircumflextilde=7876;e.Ecyrillic=1028;e.Edblgrave=516;e.Edieresis=203;e.Edieresissmall=63467;e.Edot=278;e.Edotaccent=278;e.Edotbelow=7864;e.Efcyrillic=1060;e.Egrave=200;e.Egravesmall=63464;e.Eharmenian=1335;e.Ehookabove=7866;e.Eightroman=8551;e.Einvertedbreve=518;e.Eiotifiedcyrillic=1124;e.Elcyrillic=1051;e.Elevenroman=8554;e.Emacron=274;e.Emacronacute=7702;e.Emacrongrave=7700;e.Emcyrillic=1052;e.Emonospace=65317;e.Encyrillic=1053;e.Endescendercyrillic=1186;e.Eng=330;e.Enghecyrillic=1188;e.Enhookcyrillic=1223;e.Eogonek=280;e.Eopen=400;e.Epsilon=917;e.Epsilontonos=904;e.Ercyrillic=1056;e.Ereversed=398;e.Ereversedcyrillic=1069;e.Escyrillic=1057;e.Esdescendercyrillic=1194;e.Esh=425;e.Esmall=63333;e.Eta=919;e.Etarmenian=1336;e.Etatonos=905;e.Eth=208;e.Ethsmall=63472;e.Etilde=7868;e.Etildebelow=7706;e.Euro=8364;e.Ezh=439;e.Ezhcaron=494;e.Ezhreversed=440;e.F=70;e.Fcircle=9403;e.Fdotaccent=7710;e.Feharmenian=1366;e.Feicoptic=996;e.Fhook=401;e.Fitacyrillic=1138;e.Fiveroman=8548;e.Fmonospace=65318;e.Fourroman=8547;e.Fsmall=63334;e.G=71;e.GBsquare=13191;e.Gacute=500;e.Gamma=915;e.Gammaafrican=404;e.Gangiacoptic=1002;e.Gbreve=286;e.Gcaron=486;e.Gcedilla=290;e.Gcircle=9404;e.Gcircumflex=284;e.Gcommaaccent=290;e.Gdot=288;e.Gdotaccent=288;e.Gecyrillic=1043;e.Ghadarmenian=1346;e.Ghemiddlehookcyrillic=1172;e.Ghestrokecyrillic=1170;e.Gheupturncyrillic=1168;e.Ghook=403;e.Gimarmenian=1331;e.Gjecyrillic=1027;e.Gmacron=7712;e.Gmonospace=65319;e.Grave=63182;e.Gravesmall=63328;e.Gsmall=63335;e.Gsmallhook=667;e.Gstroke=484;e.H=72;e.H18533=9679;e.H18543=9642;e.H18551=9643;e.H22073=9633;e.HPsquare=13259;e.Haabkhasiancyrillic=1192;e.Hadescendercyrillic=1202;e.Hardsigncyrillic=1066;e.Hbar=294;e.Hbrevebelow=7722;e.Hcedilla=7720;e.Hcircle=9405;e.Hcircumflex=292;e.Hdieresis=7718;e.Hdotaccent=7714;e.Hdotbelow=7716;e.Hmonospace=65320;e.Hoarmenian=1344;e.Horicoptic=1e3;e.Hsmall=63336;e.Hungarumlaut=63183;e.Hungarumlautsmall=63224;e.Hzsquare=13200;e.I=73;e.IAcyrillic=1071;e.IJ=306;e.IUcyrillic=1070;e.Iacute=205;e.Iacutesmall=63469;e.Ibreve=300;e.Icaron=463;e.Icircle=9406;e.Icircumflex=206;e.Icircumflexsmall=63470;e.Icyrillic=1030;e.Idblgrave=520;e.Idieresis=207;e.Idieresisacute=7726;e.Idieresiscyrillic=1252;e.Idieresissmall=63471;e.Idot=304;e.Idotaccent=304;e.Idotbelow=7882;e.Iebrevecyrillic=1238;e.Iecyrillic=1045;e.Ifraktur=8465;e.Igrave=204;e.Igravesmall=63468;e.Ihookabove=7880;e.Iicyrillic=1048;e.Iinvertedbreve=522;e.Iishortcyrillic=1049;e.Imacron=298;e.Imacroncyrillic=1250;e.Imonospace=65321;e.Iniarmenian=1339;e.Iocyrillic=1025;e.Iogonek=302;e.Iota=921;e.Iotaafrican=406;e.Iotadieresis=938;e.Iotatonos=906;e.Ismall=63337;e.Istroke=407;e.Itilde=296;e.Itildebelow=7724;e.Izhitsacyrillic=1140;e.Izhitsadblgravecyrillic=1142;e.J=74;e.Jaarmenian=1345;e.Jcircle=9407;e.Jcircumflex=308;e.Jecyrillic=1032;e.Jheharmenian=1355;e.Jmonospace=65322;e.Jsmall=63338;e.K=75;e.KBsquare=13189;e.KKsquare=13261;e.Kabashkircyrillic=1184;e.Kacute=7728;e.Kacyrillic=1050;e.Kadescendercyrillic=1178;e.Kahookcyrillic=1219;e.Kappa=922;e.Kastrokecyrillic=1182;e.Kaverticalstrokecyrillic=1180;e.Kcaron=488;e.Kcedilla=310;e.Kcircle=9408;e.Kcommaaccent=310;e.Kdotbelow=7730;e.Keharmenian=1364;e.Kenarmenian=1343;e.Khacyrillic=1061;e.Kheicoptic=998;e.Khook=408;e.Kjecyrillic=1036;e.Klinebelow=7732;e.Kmonospace=65323;e.Koppacyrillic=1152;e.Koppagreek=990;e.Ksicyrillic=1134;e.Ksmall=63339;e.L=76;e.LJ=455;e.LL=63167;e.Lacute=313;e.Lambda=923;e.Lcaron=317;e.Lcedilla=315;e.Lcircle=9409;e.Lcircumflexbelow=7740;e.Lcommaaccent=315;e.Ldot=319;e.Ldotaccent=319;e.Ldotbelow=7734;e.Ldotbelowmacron=7736;e.Liwnarmenian=1340;e.Lj=456;e.Ljecyrillic=1033;e.Llinebelow=7738;e.Lmonospace=65324;e.Lslash=321;e.Lslashsmall=63225;e.Lsmall=63340;e.M=77;e.MBsquare=13190;e.Macron=63184;e.Macronsmall=63407;e.Macute=7742;e.Mcircle=9410;e.Mdotaccent=7744;e.Mdotbelow=7746;e.Menarmenian=1348;e.Mmonospace=65325;e.Msmall=63341;e.Mturned=412;e.Mu=924;e.N=78;e.NJ=458;e.Nacute=323;e.Ncaron=327;e.Ncedilla=325;e.Ncircle=9411;e.Ncircumflexbelow=7754;e.Ncommaaccent=325;e.Ndotaccent=7748;e.Ndotbelow=7750;e.Nhookleft=413;e.Nineroman=8552;e.Nj=459;e.Njecyrillic=1034;e.Nlinebelow=7752;e.Nmonospace=65326;e.Nowarmenian=1350;e.Nsmall=63342;e.Ntilde=209;e.Ntildesmall=63473;e.Nu=925;e.O=79;e.OE=338;e.OEsmall=63226;e.Oacute=211;e.Oacutesmall=63475;e.Obarredcyrillic=1256;e.Obarreddieresiscyrillic=1258;e.Obreve=334;e.Ocaron=465;e.Ocenteredtilde=415;e.Ocircle=9412;e.Ocircumflex=212;e.Ocircumflexacute=7888;e.Ocircumflexdotbelow=7896;e.Ocircumflexgrave=7890;e.Ocircumflexhookabove=7892;e.Ocircumflexsmall=63476;e.Ocircumflextilde=7894;e.Ocyrillic=1054;e.Odblacute=336;e.Odblgrave=524;e.Odieresis=214;e.Odieresiscyrillic=1254;e.Odieresissmall=63478;e.Odotbelow=7884;e.Ogoneksmall=63227;e.Ograve=210;e.Ogravesmall=63474;e.Oharmenian=1365;e.Ohm=8486;e.Ohookabove=7886;e.Ohorn=416;e.Ohornacute=7898;e.Ohorndotbelow=7906;e.Ohorngrave=7900;e.Ohornhookabove=7902;e.Ohorntilde=7904;e.Ohungarumlaut=336;e.Oi=418;e.Oinvertedbreve=526;e.Omacron=332;e.Omacronacute=7762;e.Omacrongrave=7760;e.Omega=8486;e.Omegacyrillic=1120;e.Omegagreek=937;e.Omegaroundcyrillic=1146;e.Omegatitlocyrillic=1148;e.Omegatonos=911;e.Omicron=927;e.Omicrontonos=908;e.Omonospace=65327;e.Oneroman=8544;e.Oogonek=490;e.Oogonekmacron=492;e.Oopen=390;e.Oslash=216;e.Oslashacute=510;e.Oslashsmall=63480;e.Osmall=63343;e.Ostrokeacute=510;e.Otcyrillic=1150;e.Otilde=213;e.Otildeacute=7756;e.Otildedieresis=7758;e.Otildesmall=63477;e.P=80;e.Pacute=7764;e.Pcircle=9413;e.Pdotaccent=7766;e.Pecyrillic=1055;e.Peharmenian=1354;e.Pemiddlehookcyrillic=1190;e.Phi=934;e.Phook=420;e.Pi=928;e.Piwrarmenian=1363;e.Pmonospace=65328;e.Psi=936;e.Psicyrillic=1136;e.Psmall=63344;e.Q=81;e.Qcircle=9414;e.Qmonospace=65329;e.Qsmall=63345;e.R=82;e.Raarmenian=1356;e.Racute=340;e.Rcaron=344;e.Rcedilla=342;e.Rcircle=9415;e.Rcommaaccent=342;e.Rdblgrave=528;e.Rdotaccent=7768;e.Rdotbelow=7770;e.Rdotbelowmacron=7772;e.Reharmenian=1360;e.Rfraktur=8476;e.Rho=929;e.Ringsmall=63228;e.Rinvertedbreve=530;e.Rlinebelow=7774;e.Rmonospace=65330;e.Rsmall=63346;e.Rsmallinverted=641;e.Rsmallinvertedsuperior=694;e.S=83;e.SF010000=9484;e.SF020000=9492;e.SF030000=9488;e.SF040000=9496;e.SF050000=9532;e.SF060000=9516;e.SF070000=9524;e.SF080000=9500;e.SF090000=9508;e.SF100000=9472;e.SF110000=9474;e.SF190000=9569;e.SF200000=9570;e.SF210000=9558;e.SF220000=9557;e.SF230000=9571;e.SF240000=9553;e.SF250000=9559;e.SF260000=9565;e.SF270000=9564;e.SF280000=9563;e.SF360000=9566;e.SF370000=9567;e.SF380000=9562;e.SF390000=9556;e.SF400000=9577;e.SF410000=9574;e.SF420000=9568;e.SF430000=9552;e.SF440000=9580;e.SF450000=9575;e.SF460000=9576;e.SF470000=9572;e.SF480000=9573;e.SF490000=9561;e.SF500000=9560;e.SF510000=9554;e.SF520000=9555;e.SF530000=9579;e.SF540000=9578;e.Sacute=346;e.Sacutedotaccent=7780;e.Sampigreek=992;e.Scaron=352;e.Scarondotaccent=7782;e.Scaronsmall=63229;e.Scedilla=350;e.Schwa=399;e.Schwacyrillic=1240;e.Schwadieresiscyrillic=1242;e.Scircle=9416;e.Scircumflex=348;e.Scommaaccent=536;e.Sdotaccent=7776;e.Sdotbelow=7778;e.Sdotbelowdotaccent=7784;e.Seharmenian=1357;e.Sevenroman=8550;e.Shaarmenian=1351;e.Shacyrillic=1064;e.Shchacyrillic=1065;e.Sheicoptic=994;e.Shhacyrillic=1210;e.Shimacoptic=1004;e.Sigma=931;e.Sixroman=8549;e.Smonospace=65331;e.Softsigncyrillic=1068;e.Ssmall=63347;e.Stigmagreek=986;e.T=84;e.Tau=932;e.Tbar=358;e.Tcaron=356;e.Tcedilla=354;e.Tcircle=9417;e.Tcircumflexbelow=7792;e.Tcommaaccent=354;e.Tdotaccent=7786;e.Tdotbelow=7788;e.Tecyrillic=1058;e.Tedescendercyrillic=1196;e.Tenroman=8553;e.Tetsecyrillic=1204;e.Theta=920;e.Thook=428;e.Thorn=222;e.Thornsmall=63486;e.Threeroman=8546;e.Tildesmall=63230;e.Tiwnarmenian=1359;e.Tlinebelow=7790;e.Tmonospace=65332;e.Toarmenian=1337;e.Tonefive=444;e.Tonesix=388;e.Tonetwo=423;e.Tretroflexhook=430;e.Tsecyrillic=1062;e.Tshecyrillic=1035;e.Tsmall=63348;e.Twelveroman=8555;e.Tworoman=8545;e.U=85;e.Uacute=218;e.Uacutesmall=63482;e.Ubreve=364;e.Ucaron=467;e.Ucircle=9418;e.Ucircumflex=219;e.Ucircumflexbelow=7798;e.Ucircumflexsmall=63483;e.Ucyrillic=1059;e.Udblacute=368;e.Udblgrave=532;e.Udieresis=220;e.Udieresisacute=471;e.Udieresisbelow=7794;e.Udieresiscaron=473;e.Udieresiscyrillic=1264;e.Udieresisgrave=475;e.Udieresismacron=469;e.Udieresissmall=63484;e.Udotbelow=7908;e.Ugrave=217;e.Ugravesmall=63481;e.Uhookabove=7910;e.Uhorn=431;e.Uhornacute=7912;e.Uhorndotbelow=7920;e.Uhorngrave=7914;e.Uhornhookabove=7916;e.Uhorntilde=7918;e.Uhungarumlaut=368;e.Uhungarumlautcyrillic=1266;e.Uinvertedbreve=534;e.Ukcyrillic=1144;e.Umacron=362;e.Umacroncyrillic=1262;e.Umacrondieresis=7802;e.Umonospace=65333;e.Uogonek=370;e.Upsilon=933;e.Upsilon1=978;e.Upsilonacutehooksymbolgreek=979;e.Upsilonafrican=433;e.Upsilondieresis=939;e.Upsilondieresishooksymbolgreek=980;e.Upsilonhooksymbol=978;e.Upsilontonos=910;e.Uring=366;e.Ushortcyrillic=1038;e.Usmall=63349;e.Ustraightcyrillic=1198;e.Ustraightstrokecyrillic=1200;e.Utilde=360;e.Utildeacute=7800;e.Utildebelow=7796;e.V=86;e.Vcircle=9419;e.Vdotbelow=7806;e.Vecyrillic=1042;e.Vewarmenian=1358;e.Vhook=434;e.Vmonospace=65334;e.Voarmenian=1352;e.Vsmall=63350;e.Vtilde=7804;e.W=87;e.Wacute=7810;e.Wcircle=9420;e.Wcircumflex=372;e.Wdieresis=7812;e.Wdotaccent=7814;e.Wdotbelow=7816;e.Wgrave=7808;e.Wmonospace=65335;e.Wsmall=63351;e.X=88;e.Xcircle=9421;e.Xdieresis=7820;e.Xdotaccent=7818;e.Xeharmenian=1341;e.Xi=926;e.Xmonospace=65336;e.Xsmall=63352;e.Y=89;e.Yacute=221;e.Yacutesmall=63485;e.Yatcyrillic=1122;e.Ycircle=9422;e.Ycircumflex=374;e.Ydieresis=376;e.Ydieresissmall=63487;e.Ydotaccent=7822;e.Ydotbelow=7924;e.Yericyrillic=1067;e.Yerudieresiscyrillic=1272;e.Ygrave=7922;e.Yhook=435;e.Yhookabove=7926;e.Yiarmenian=1349;e.Yicyrillic=1031;e.Yiwnarmenian=1362;e.Ymonospace=65337;e.Ysmall=63353;e.Ytilde=7928;e.Yusbigcyrillic=1130;e.Yusbigiotifiedcyrillic=1132;e.Yuslittlecyrillic=1126;e.Yuslittleiotifiedcyrillic=1128;e.Z=90;e.Zaarmenian=1334;e.Zacute=377;e.Zcaron=381;e.Zcaronsmall=63231;e.Zcircle=9423;e.Zcircumflex=7824;e.Zdot=379;e.Zdotaccent=379;e.Zdotbelow=7826;e.Zecyrillic=1047;e.Zedescendercyrillic=1176;e.Zedieresiscyrillic=1246;e.Zeta=918;e.Zhearmenian=1338;e.Zhebrevecyrillic=1217;e.Zhecyrillic=1046;e.Zhedescendercyrillic=1174;e.Zhedieresiscyrillic=1244;e.Zlinebelow=7828;e.Zmonospace=65338;e.Zsmall=63354;e.Zstroke=437;e.a=97;e.aabengali=2438;e.aacute=225;e.aadeva=2310;e.aagujarati=2694;e.aagurmukhi=2566;e.aamatragurmukhi=2622;e.aarusquare=13059;e.aavowelsignbengali=2494;e.aavowelsigndeva=2366;e.aavowelsigngujarati=2750;e.abbreviationmarkarmenian=1375;e.abbreviationsigndeva=2416;e.abengali=2437;e.abopomofo=12570;e.abreve=259;e.abreveacute=7855;e.abrevecyrillic=1233;e.abrevedotbelow=7863;e.abrevegrave=7857;e.abrevehookabove=7859;e.abrevetilde=7861;e.acaron=462;e.acircle=9424;e.acircumflex=226;e.acircumflexacute=7845;e.acircumflexdotbelow=7853;e.acircumflexgrave=7847;e.acircumflexhookabove=7849;e.acircumflextilde=7851;e.acute=180;e.acutebelowcmb=791;e.acutecmb=769;e.acutecomb=769;e.acutedeva=2388;e.acutelowmod=719;e.acutetonecmb=833;e.acyrillic=1072;e.adblgrave=513;e.addakgurmukhi=2673;e.adeva=2309;e.adieresis=228;e.adieresiscyrillic=1235;e.adieresismacron=479;e.adotbelow=7841;e.adotmacron=481;e.ae=230;e.aeacute=509;e.aekorean=12624;e.aemacron=483;e.afii00208=8213;e.afii08941=8356;e.afii10017=1040;e.afii10018=1041;e.afii10019=1042;e.afii10020=1043;e.afii10021=1044;e.afii10022=1045;e.afii10023=1025;e.afii10024=1046;e.afii10025=1047;e.afii10026=1048;e.afii10027=1049;e.afii10028=1050;e.afii10029=1051;e.afii10030=1052;e.afii10031=1053;e.afii10032=1054;e.afii10033=1055;e.afii10034=1056;e.afii10035=1057;e.afii10036=1058;e.afii10037=1059;e.afii10038=1060;e.afii10039=1061;e.afii10040=1062;e.afii10041=1063;e.afii10042=1064;e.afii10043=1065;e.afii10044=1066;e.afii10045=1067;e.afii10046=1068;e.afii10047=1069;e.afii10048=1070;e.afii10049=1071;e.afii10050=1168;e.afii10051=1026;e.afii10052=1027;e.afii10053=1028;e.afii10054=1029;e.afii10055=1030;e.afii10056=1031;e.afii10057=1032;e.afii10058=1033;e.afii10059=1034;e.afii10060=1035;e.afii10061=1036;e.afii10062=1038;e.afii10063=63172;e.afii10064=63173;e.afii10065=1072;e.afii10066=1073;e.afii10067=1074;e.afii10068=1075;e.afii10069=1076;e.afii10070=1077;e.afii10071=1105;e.afii10072=1078;e.afii10073=1079;e.afii10074=1080;e.afii10075=1081;e.afii10076=1082;e.afii10077=1083;e.afii10078=1084;e.afii10079=1085;e.afii10080=1086;e.afii10081=1087;e.afii10082=1088;e.afii10083=1089;e.afii10084=1090;e.afii10085=1091;e.afii10086=1092;e.afii10087=1093;e.afii10088=1094;e.afii10089=1095;e.afii10090=1096;e.afii10091=1097;e.afii10092=1098;e.afii10093=1099;e.afii10094=1100;e.afii10095=1101;e.afii10096=1102;e.afii10097=1103;e.afii10098=1169;e.afii10099=1106;e.afii10100=1107;e.afii10101=1108;e.afii10102=1109;e.afii10103=1110;e.afii10104=1111;e.afii10105=1112;e.afii10106=1113;e.afii10107=1114;e.afii10108=1115;e.afii10109=1116;e.afii10110=1118;e.afii10145=1039;e.afii10146=1122;e.afii10147=1138;e.afii10148=1140;e.afii10192=63174;e.afii10193=1119;e.afii10194=1123;e.afii10195=1139;e.afii10196=1141;e.afii10831=63175;e.afii10832=63176;e.afii10846=1241;e.afii299=8206;e.afii300=8207;e.afii301=8205;e.afii57381=1642;e.afii57388=1548;e.afii57392=1632;e.afii57393=1633;e.afii57394=1634;e.afii57395=1635;e.afii57396=1636;e.afii57397=1637;e.afii57398=1638;e.afii57399=1639;e.afii57400=1640;e.afii57401=1641;e.afii57403=1563;e.afii57407=1567;e.afii57409=1569;e.afii57410=1570;e.afii57411=1571;e.afii57412=1572;e.afii57413=1573;e.afii57414=1574;e.afii57415=1575;e.afii57416=1576;e.afii57417=1577;e.afii57418=1578;e.afii57419=1579;e.afii57420=1580;e.afii57421=1581;e.afii57422=1582;e.afii57423=1583;e.afii57424=1584;e.afii57425=1585;e.afii57426=1586;e.afii57427=1587;e.afii57428=1588;e.afii57429=1589;e.afii57430=1590;e.afii57431=1591;e.afii57432=1592;e.afii57433=1593;e.afii57434=1594;e.afii57440=1600;e.afii57441=1601;e.afii57442=1602;e.afii57443=1603;e.afii57444=1604;e.afii57445=1605;e.afii57446=1606;e.afii57448=1608;e.afii57449=1609;e.afii57450=1610;e.afii57451=1611;e.afii57452=1612;e.afii57453=1613;e.afii57454=1614;e.afii57455=1615;e.afii57456=1616;e.afii57457=1617;e.afii57458=1618;e.afii57470=1607;e.afii57505=1700;e.afii57506=1662;e.afii57507=1670;e.afii57508=1688;e.afii57509=1711;e.afii57511=1657;e.afii57512=1672;e.afii57513=1681;e.afii57514=1722;e.afii57519=1746;e.afii57534=1749;e.afii57636=8362;e.afii57645=1470;e.afii57658=1475;e.afii57664=1488;e.afii57665=1489;e.afii57666=1490;e.afii57667=1491;e.afii57668=1492;e.afii57669=1493;e.afii57670=1494;e.afii57671=1495;e.afii57672=1496;e.afii57673=1497;e.afii57674=1498;e.afii57675=1499;e.afii57676=1500;e.afii57677=1501;e.afii57678=1502;e.afii57679=1503;e.afii57680=1504;e.afii57681=1505;e.afii57682=1506;e.afii57683=1507;e.afii57684=1508;e.afii57685=1509;e.afii57686=1510;e.afii57687=1511;e.afii57688=1512;e.afii57689=1513;e.afii57690=1514;e.afii57694=64298;e.afii57695=64299;e.afii57700=64331;e.afii57705=64287;e.afii57716=1520;e.afii57717=1521;e.afii57718=1522;e.afii57723=64309;e.afii57793=1460;e.afii57794=1461;e.afii57795=1462;e.afii57796=1467;e.afii57797=1464;e.afii57798=1463;e.afii57799=1456;e.afii57800=1458;e.afii57801=1457;e.afii57802=1459;e.afii57803=1474;e.afii57804=1473;e.afii57806=1465;e.afii57807=1468;e.afii57839=1469;e.afii57841=1471;e.afii57842=1472;e.afii57929=700;e.afii61248=8453;e.afii61289=8467;e.afii61352=8470;e.afii61573=8236;e.afii61574=8237;e.afii61575=8238;e.afii61664=8204;e.afii63167=1645;e.afii64937=701;e.agrave=224;e.agujarati=2693;e.agurmukhi=2565;e.ahiragana=12354;e.ahookabove=7843;e.aibengali=2448;e.aibopomofo=12574;e.aideva=2320;e.aiecyrillic=1237;e.aigujarati=2704;e.aigurmukhi=2576;e.aimatragurmukhi=2632;e.ainarabic=1593;e.ainfinalarabic=65226;e.aininitialarabic=65227;e.ainmedialarabic=65228;e.ainvertedbreve=515;e.aivowelsignbengali=2504;e.aivowelsigndeva=2376;e.aivowelsigngujarati=2760;e.akatakana=12450;e.akatakanahalfwidth=65393;e.akorean=12623;e.alef=1488;e.alefarabic=1575;e.alefdageshhebrew=64304;e.aleffinalarabic=65166;e.alefhamzaabovearabic=1571;e.alefhamzaabovefinalarabic=65156;e.alefhamzabelowarabic=1573;e.alefhamzabelowfinalarabic=65160;e.alefhebrew=1488;e.aleflamedhebrew=64335;e.alefmaddaabovearabic=1570;e.alefmaddaabovefinalarabic=65154;e.alefmaksuraarabic=1609;e.alefmaksurafinalarabic=65264;e.alefmaksurainitialarabic=65267;e.alefmaksuramedialarabic=65268;e.alefpatahhebrew=64302;e.alefqamatshebrew=64303;e.aleph=8501;e.allequal=8780;e.alpha=945;e.alphatonos=940;e.amacron=257;e.amonospace=65345;e.ampersand=38;e.ampersandmonospace=65286;e.ampersandsmall=63270;e.amsquare=13250;e.anbopomofo=12578;e.angbopomofo=12580;e.angbracketleft=12296;e.angbracketright=12297;e.angkhankhuthai=3674;e.angle=8736;e.anglebracketleft=12296;e.anglebracketleftvertical=65087;e.anglebracketright=12297;e.anglebracketrightvertical=65088;e.angleleft=9001;e.angleright=9002;e.angstrom=8491;e.anoteleia=903;e.anudattadeva=2386;e.anusvarabengali=2434;e.anusvaradeva=2306;e.anusvaragujarati=2690;e.aogonek=261;e.apaatosquare=13056;e.aparen=9372;e.apostrophearmenian=1370;e.apostrophemod=700;e.apple=63743;e.approaches=8784;e.approxequal=8776;e.approxequalorimage=8786;e.approximatelyequal=8773;e.araeaekorean=12686;e.araeakorean=12685;e.arc=8978;e.arighthalfring=7834;e.aring=229;e.aringacute=507;e.aringbelow=7681;e.arrowboth=8596;e.arrowdashdown=8675;e.arrowdashleft=8672;e.arrowdashright=8674;e.arrowdashup=8673;e.arrowdblboth=8660;e.arrowdbldown=8659;e.arrowdblleft=8656;e.arrowdblright=8658;e.arrowdblup=8657;e.arrowdown=8595;e.arrowdownleft=8601;e.arrowdownright=8600;e.arrowdownwhite=8681;e.arrowheaddownmod=709;e.arrowheadleftmod=706;e.arrowheadrightmod=707;e.arrowheadupmod=708;e.arrowhorizex=63719;e.arrowleft=8592;e.arrowleftdbl=8656;e.arrowleftdblstroke=8653;e.arrowleftoverright=8646;e.arrowleftwhite=8678;e.arrowright=8594;e.arrowrightdblstroke=8655;e.arrowrightheavy=10142;e.arrowrightoverleft=8644;e.arrowrightwhite=8680;e.arrowtableft=8676;e.arrowtabright=8677;e.arrowup=8593;e.arrowupdn=8597;e.arrowupdnbse=8616;e.arrowupdownbase=8616;e.arrowupleft=8598;e.arrowupleftofdown=8645;e.arrowupright=8599;e.arrowupwhite=8679;e.arrowvertex=63718;e.asciicircum=94;e.asciicircummonospace=65342;e.asciitilde=126;e.asciitildemonospace=65374;e.ascript=593;e.ascriptturned=594;e.asmallhiragana=12353;e.asmallkatakana=12449;e.asmallkatakanahalfwidth=65383;e.asterisk=42;e.asteriskaltonearabic=1645;e.asteriskarabic=1645;e.asteriskmath=8727;e.asteriskmonospace=65290;e.asterisksmall=65121;e.asterism=8258;e.asuperior=63209;e.asymptoticallyequal=8771;e.at=64;e.atilde=227;e.atmonospace=65312;e.atsmall=65131;e.aturned=592;e.aubengali=2452;e.aubopomofo=12576;e.audeva=2324;e.augujarati=2708;e.augurmukhi=2580;e.aulengthmarkbengali=2519;e.aumatragurmukhi=2636;e.auvowelsignbengali=2508;e.auvowelsigndeva=2380;e.auvowelsigngujarati=2764;e.avagrahadeva=2365;e.aybarmenian=1377;e.ayin=1506;e.ayinaltonehebrew=64288;e.ayinhebrew=1506;e.b=98;e.babengali=2476;e.backslash=92;e.backslashmonospace=65340;e.badeva=2348;e.bagujarati=2732;e.bagurmukhi=2604;e.bahiragana=12400;e.bahtthai=3647;e.bakatakana=12496;e.bar=124;e.barmonospace=65372;e.bbopomofo=12549;e.bcircle=9425;e.bdotaccent=7683;e.bdotbelow=7685;e.beamedsixteenthnotes=9836;e.because=8757;e.becyrillic=1073;e.beharabic=1576;e.behfinalarabic=65168;e.behinitialarabic=65169;e.behiragana=12409;e.behmedialarabic=65170;e.behmeeminitialarabic=64671;e.behmeemisolatedarabic=64520;e.behnoonfinalarabic=64621;e.bekatakana=12505;e.benarmenian=1378;e.bet=1489;e.beta=946;e.betasymbolgreek=976;e.betdagesh=64305;e.betdageshhebrew=64305;e.bethebrew=1489;e.betrafehebrew=64332;e.bhabengali=2477;e.bhadeva=2349;e.bhagujarati=2733;e.bhagurmukhi=2605;e.bhook=595;e.bihiragana=12403;e.bikatakana=12499;e.bilabialclick=664;e.bindigurmukhi=2562;e.birusquare=13105;e.blackcircle=9679;e.blackdiamond=9670;e.blackdownpointingtriangle=9660;e.blackleftpointingpointer=9668;e.blackleftpointingtriangle=9664;e.blacklenticularbracketleft=12304;e.blacklenticularbracketleftvertical=65083;e.blacklenticularbracketright=12305;e.blacklenticularbracketrightvertical=65084;e.blacklowerlefttriangle=9699;e.blacklowerrighttriangle=9698;e.blackrectangle=9644;e.blackrightpointingpointer=9658;e.blackrightpointingtriangle=9654;e.blacksmallsquare=9642;e.blacksmilingface=9787;e.blacksquare=9632;e.blackstar=9733;e.blackupperlefttriangle=9700;e.blackupperrighttriangle=9701;e.blackuppointingsmalltriangle=9652;e.blackuppointingtriangle=9650;e.blank=9251;e.blinebelow=7687;e.block=9608;e.bmonospace=65346;e.bobaimaithai=3610;e.bohiragana=12412;e.bokatakana=12508;e.bparen=9373;e.bqsquare=13251;e.braceex=63732;e.braceleft=123;e.braceleftbt=63731;e.braceleftmid=63730;e.braceleftmonospace=65371;e.braceleftsmall=65115;e.bracelefttp=63729;e.braceleftvertical=65079;e.braceright=125;e.bracerightbt=63742;e.bracerightmid=63741;e.bracerightmonospace=65373;e.bracerightsmall=65116;e.bracerighttp=63740;e.bracerightvertical=65080;e.bracketleft=91;e.bracketleftbt=63728;e.bracketleftex=63727;e.bracketleftmonospace=65339;e.bracketlefttp=63726;e.bracketright=93;e.bracketrightbt=63739;e.bracketrightex=63738;e.bracketrightmonospace=65341;e.bracketrighttp=63737;e.breve=728;e.brevebelowcmb=814;e.brevecmb=774;e.breveinvertedbelowcmb=815;e.breveinvertedcmb=785;e.breveinverteddoublecmb=865;e.bridgebelowcmb=810;e.bridgeinvertedbelowcmb=826;e.brokenbar=166;e.bstroke=384;e.bsuperior=63210;e.btopbar=387;e.buhiragana=12406;e.bukatakana=12502;e.bullet=8226;e.bulletinverse=9688;e.bulletoperator=8729;e.bullseye=9678;e.c=99;e.caarmenian=1390;e.cabengali=2458;e.cacute=263;e.cadeva=2330;e.cagujarati=2714;e.cagurmukhi=2586;e.calsquare=13192;e.candrabindubengali=2433;e.candrabinducmb=784;e.candrabindudeva=2305;e.candrabindugujarati=2689;e.capslock=8682;e.careof=8453;e.caron=711;e.caronbelowcmb=812;e.caroncmb=780;e.carriagereturn=8629;e.cbopomofo=12568;e.ccaron=269;e.ccedilla=231;e.ccedillaacute=7689;e.ccircle=9426;e.ccircumflex=265;e.ccurl=597;e.cdot=267;e.cdotaccent=267;e.cdsquare=13253;e.cedilla=184;e.cedillacmb=807;e.cent=162;e.centigrade=8451;e.centinferior=63199;e.centmonospace=65504;e.centoldstyle=63394;e.centsuperior=63200;e.chaarmenian=1401;e.chabengali=2459;e.chadeva=2331;e.chagujarati=2715;e.chagurmukhi=2587;e.chbopomofo=12564;e.cheabkhasiancyrillic=1213;e.checkmark=10003;e.checyrillic=1095;e.chedescenderabkhasiancyrillic=1215;e.chedescendercyrillic=1207;e.chedieresiscyrillic=1269;e.cheharmenian=1395;e.chekhakassiancyrillic=1228;e.cheverticalstrokecyrillic=1209;e.chi=967;e.chieuchacirclekorean=12919;e.chieuchaparenkorean=12823;e.chieuchcirclekorean=12905;e.chieuchkorean=12618;e.chieuchparenkorean=12809;e.chochangthai=3594;e.chochanthai=3592;e.chochingthai=3593;e.chochoethai=3596;e.chook=392;e.cieucacirclekorean=12918;e.cieucaparenkorean=12822;e.cieuccirclekorean=12904;e.cieuckorean=12616;e.cieucparenkorean=12808;e.cieucuparenkorean=12828;e.circle=9675;e.circlecopyrt=169;e.circlemultiply=8855;e.circleot=8857;e.circleplus=8853;e.circlepostalmark=12342;e.circlewithlefthalfblack=9680;e.circlewithrighthalfblack=9681;e.circumflex=710;e.circumflexbelowcmb=813;e.circumflexcmb=770;e.clear=8999;e.clickalveolar=450;e.clickdental=448;e.clicklateral=449;e.clickretroflex=451;e.club=9827;e.clubsuitblack=9827;e.clubsuitwhite=9831;e.cmcubedsquare=13220;e.cmonospace=65347;e.cmsquaredsquare=13216;e.coarmenian=1409;e.colon=58;e.colonmonetary=8353;e.colonmonospace=65306;e.colonsign=8353;e.colonsmall=65109;e.colontriangularhalfmod=721;e.colontriangularmod=720;e.comma=44;e.commaabovecmb=787;e.commaaboverightcmb=789;e.commaaccent=63171;e.commaarabic=1548;e.commaarmenian=1373;e.commainferior=63201;e.commamonospace=65292;e.commareversedabovecmb=788;e.commareversedmod=701;e.commasmall=65104;e.commasuperior=63202;e.commaturnedabovecmb=786;e.commaturnedmod=699;e.compass=9788;e.congruent=8773;e.contourintegral=8750;e.control=8963;e.controlACK=6;e.controlBEL=7;e.controlBS=8;e.controlCAN=24;e.controlCR=13;e.controlDC1=17;e.controlDC2=18;e.controlDC3=19;e.controlDC4=20;e.controlDEL=127;e.controlDLE=16;e.controlEM=25;e.controlENQ=5;e.controlEOT=4;e.controlESC=27;e.controlETB=23;e.controlETX=3;e.controlFF=12;e.controlFS=28;e.controlGS=29;e.controlHT=9;e.controlLF=10;e.controlNAK=21;e.controlNULL=0;e.controlRS=30;e.controlSI=15;e.controlSO=14;e.controlSOT=2;e.controlSTX=1;e.controlSUB=26;e.controlSYN=22;e.controlUS=31;e.controlVT=11;e.copyright=169;e.copyrightsans=63721;e.copyrightserif=63193;e.cornerbracketleft=12300;e.cornerbracketlefthalfwidth=65378;e.cornerbracketleftvertical=65089;e.cornerbracketright=12301;e.cornerbracketrighthalfwidth=65379;e.cornerbracketrightvertical=65090;e.corporationsquare=13183;e.cosquare=13255;e.coverkgsquare=13254;e.cparen=9374;e.cruzeiro=8354;e.cstretched=663;e.curlyand=8911;e.curlyor=8910;e.currency=164;e.cyrBreve=63185;e.cyrFlex=63186;e.cyrbreve=63188;e.cyrflex=63189;e.d=100;e.daarmenian=1380;e.dabengali=2470;e.dadarabic=1590;e.dadeva=2342;e.dadfinalarabic=65214;e.dadinitialarabic=65215;e.dadmedialarabic=65216;e.dagesh=1468;e.dageshhebrew=1468;e.dagger=8224;e.daggerdbl=8225;e.dagujarati=2726;e.dagurmukhi=2598;e.dahiragana=12384;e.dakatakana=12480;e.dalarabic=1583;e.dalet=1491;e.daletdagesh=64307;e.daletdageshhebrew=64307;e.dalethebrew=1491;e.dalfinalarabic=65194;e.dammaarabic=1615;e.dammalowarabic=1615;e.dammatanaltonearabic=1612;e.dammatanarabic=1612;e.danda=2404;e.dargahebrew=1447;e.dargalefthebrew=1447;e.dasiapneumatacyrilliccmb=1157;e.dblGrave=63187;e.dblanglebracketleft=12298;e.dblanglebracketleftvertical=65085;e.dblanglebracketright=12299;e.dblanglebracketrightvertical=65086;e.dblarchinvertedbelowcmb=811;e.dblarrowleft=8660;e.dblarrowright=8658;e.dbldanda=2405;e.dblgrave=63190;e.dblgravecmb=783;e.dblintegral=8748;e.dbllowline=8215;e.dbllowlinecmb=819;e.dbloverlinecmb=831;e.dblprimemod=698;e.dblverticalbar=8214;e.dblverticallineabovecmb=782;e.dbopomofo=12553;e.dbsquare=13256;e.dcaron=271;e.dcedilla=7697;e.dcircle=9427;e.dcircumflexbelow=7699;e.dcroat=273;e.ddabengali=2465;e.ddadeva=2337;e.ddagujarati=2721;e.ddagurmukhi=2593;e.ddalarabic=1672;e.ddalfinalarabic=64393;e.dddhadeva=2396;e.ddhabengali=2466;e.ddhadeva=2338;e.ddhagujarati=2722;e.ddhagurmukhi=2594;e.ddotaccent=7691;e.ddotbelow=7693;e.decimalseparatorarabic=1643;e.decimalseparatorpersian=1643;e.decyrillic=1076;e.degree=176;e.dehihebrew=1453;e.dehiragana=12391;e.deicoptic=1007;e.dekatakana=12487;e.deleteleft=9003;e.deleteright=8998;e.delta=948;e.deltaturned=397;e.denominatorminusonenumeratorbengali=2552;e.dezh=676;e.dhabengali=2471;e.dhadeva=2343;e.dhagujarati=2727;e.dhagurmukhi=2599;e.dhook=599;e.dialytikatonos=901;e.dialytikatonoscmb=836;e.diamond=9830;e.diamondsuitwhite=9826;e.dieresis=168;e.dieresisacute=63191;e.dieresisbelowcmb=804;e.dieresiscmb=776;e.dieresisgrave=63192;e.dieresistonos=901;e.dihiragana=12386;e.dikatakana=12482;e.dittomark=12291;e.divide=247;e.divides=8739;e.divisionslash=8725;e.djecyrillic=1106;e.dkshade=9619;e.dlinebelow=7695;e.dlsquare=13207;e.dmacron=273;e.dmonospace=65348;e.dnblock=9604;e.dochadathai=3598;e.dodekthai=3604;e.dohiragana=12393;e.dokatakana=12489;e.dollar=36;e.dollarinferior=63203;e.dollarmonospace=65284;e.dollaroldstyle=63268;e.dollarsmall=65129;e.dollarsuperior=63204;e.dong=8363;e.dorusquare=13094;e.dotaccent=729;e.dotaccentcmb=775;e.dotbelowcmb=803;e.dotbelowcomb=803;e.dotkatakana=12539;e.dotlessi=305;e.dotlessj=63166;e.dotlessjstrokehook=644;e.dotmath=8901;e.dottedcircle=9676;e.doubleyodpatah=64287;e.doubleyodpatahhebrew=64287;e.downtackbelowcmb=798;e.downtackmod=725;e.dparen=9375;e.dsuperior=63211;e.dtail=598;e.dtopbar=396;e.duhiragana=12389;e.dukatakana=12485;e.dz=499;e.dzaltone=675;e.dzcaron=454;e.dzcurl=677;e.dzeabkhasiancyrillic=1249;e.dzecyrillic=1109;e.dzhecyrillic=1119;e.e=101;e.eacute=233;e.earth=9793;e.ebengali=2447;e.ebopomofo=12572;e.ebreve=277;e.ecandradeva=2317;e.ecandragujarati=2701;e.ecandravowelsigndeva=2373;e.ecandravowelsigngujarati=2757;e.ecaron=283;e.ecedillabreve=7709;e.echarmenian=1381;e.echyiwnarmenian=1415;e.ecircle=9428;e.ecircumflex=234;e.ecircumflexacute=7871;e.ecircumflexbelow=7705;e.ecircumflexdotbelow=7879;e.ecircumflexgrave=7873;e.ecircumflexhookabove=7875;e.ecircumflextilde=7877;e.ecyrillic=1108;e.edblgrave=517;e.edeva=2319;e.edieresis=235;e.edot=279;e.edotaccent=279;e.edotbelow=7865;e.eegurmukhi=2575;e.eematragurmukhi=2631;e.efcyrillic=1092;e.egrave=232;e.egujarati=2703;e.eharmenian=1383;e.ehbopomofo=12573;e.ehiragana=12360;e.ehookabove=7867;e.eibopomofo=12575;e.eight=56;e.eightarabic=1640;e.eightbengali=2542;e.eightcircle=9319;e.eightcircleinversesansserif=10129;e.eightdeva=2414;e.eighteencircle=9329;e.eighteenparen=9349;e.eighteenperiod=9369;e.eightgujarati=2798;e.eightgurmukhi=2670;e.eighthackarabic=1640;e.eighthangzhou=12328;e.eighthnotebeamed=9835;e.eightideographicparen=12839;e.eightinferior=8328;e.eightmonospace=65304;e.eightoldstyle=63288;e.eightparen=9339;e.eightperiod=9359;e.eightpersian=1784;e.eightroman=8567;e.eightsuperior=8312;e.eightthai=3672;e.einvertedbreve=519;e.eiotifiedcyrillic=1125;e.ekatakana=12456;e.ekatakanahalfwidth=65396;e.ekonkargurmukhi=2676;e.ekorean=12628;e.elcyrillic=1083;e.element=8712;e.elevencircle=9322;e.elevenparen=9342;e.elevenperiod=9362;e.elevenroman=8570;e.ellipsis=8230;e.ellipsisvertical=8942;e.emacron=275;e.emacronacute=7703;e.emacrongrave=7701;e.emcyrillic=1084;e.emdash=8212;e.emdashvertical=65073;e.emonospace=65349;e.emphasismarkarmenian=1371;e.emptyset=8709;e.enbopomofo=12579;e.encyrillic=1085;e.endash=8211;e.endashvertical=65074;e.endescendercyrillic=1187;e.eng=331;e.engbopomofo=12581;e.enghecyrillic=1189;e.enhookcyrillic=1224;e.enspace=8194;e.eogonek=281;e.eokorean=12627;e.eopen=603;e.eopenclosed=666;e.eopenreversed=604;e.eopenreversedclosed=606;e.eopenreversedhook=605;e.eparen=9376;e.epsilon=949;e.epsilontonos=941;e.equal=61;e.equalmonospace=65309;e.equalsmall=65126;e.equalsuperior=8316;e.equivalence=8801;e.erbopomofo=12582;e.ercyrillic=1088;e.ereversed=600;e.ereversedcyrillic=1101;e.escyrillic=1089;e.esdescendercyrillic=1195;e.esh=643;e.eshcurl=646;e.eshortdeva=2318;e.eshortvowelsigndeva=2374;e.eshreversedloop=426;e.eshsquatreversed=645;e.esmallhiragana=12359;e.esmallkatakana=12455;e.esmallkatakanahalfwidth=65386;e.estimated=8494;e.esuperior=63212;e.eta=951;e.etarmenian=1384;e.etatonos=942;e.eth=240;e.etilde=7869;e.etildebelow=7707;e.etnahtafoukhhebrew=1425;e.etnahtafoukhlefthebrew=1425;e.etnahtahebrew=1425;e.etnahtalefthebrew=1425;e.eturned=477;e.eukorean=12641;e.euro=8364;e.evowelsignbengali=2503;e.evowelsigndeva=2375;e.evowelsigngujarati=2759;e.exclam=33;e.exclamarmenian=1372;e.exclamdbl=8252;e.exclamdown=161;e.exclamdownsmall=63393;e.exclammonospace=65281;e.exclamsmall=63265;e.existential=8707;e.ezh=658;e.ezhcaron=495;e.ezhcurl=659;e.ezhreversed=441;e.ezhtail=442;e.f=102;e.fadeva=2398;e.fagurmukhi=2654;e.fahrenheit=8457;e.fathaarabic=1614;e.fathalowarabic=1614;e.fathatanarabic=1611;e.fbopomofo=12552;e.fcircle=9429;e.fdotaccent=7711;e.feharabic=1601;e.feharmenian=1414;e.fehfinalarabic=65234;e.fehinitialarabic=65235;e.fehmedialarabic=65236;e.feicoptic=997;e.female=9792;e.ff=64256;e.f_f=64256;e.ffi=64259;e.f_f_i=64259;e.ffl=64260;e.f_f_l=64260;e.fi=64257;e.f_i=64257;e.fifteencircle=9326;e.fifteenparen=9346;e.fifteenperiod=9366;e.figuredash=8210;e.filledbox=9632;e.filledrect=9644;e.finalkaf=1498;e.finalkafdagesh=64314;e.finalkafdageshhebrew=64314;e.finalkafhebrew=1498;e.finalmem=1501;e.finalmemhebrew=1501;e.finalnun=1503;e.finalnunhebrew=1503;e.finalpe=1507;e.finalpehebrew=1507;e.finaltsadi=1509;e.finaltsadihebrew=1509;e.firsttonechinese=713;e.fisheye=9673;e.fitacyrillic=1139;e.five=53;e.fivearabic=1637;e.fivebengali=2539;e.fivecircle=9316;e.fivecircleinversesansserif=10126;e.fivedeva=2411;e.fiveeighths=8541;e.fivegujarati=2795;e.fivegurmukhi=2667;e.fivehackarabic=1637;e.fivehangzhou=12325;e.fiveideographicparen=12836;e.fiveinferior=8325;e.fivemonospace=65301;e.fiveoldstyle=63285;e.fiveparen=9336;e.fiveperiod=9356;e.fivepersian=1781;e.fiveroman=8564;e.fivesuperior=8309;e.fivethai=3669;e.fl=64258;e.f_l=64258;e.florin=402;e.fmonospace=65350;e.fmsquare=13209;e.fofanthai=3615;e.fofathai=3613;e.fongmanthai=3663;e.forall=8704;e.four=52;e.fourarabic=1636;e.fourbengali=2538;e.fourcircle=9315;e.fourcircleinversesansserif=10125;e.fourdeva=2410;e.fourgujarati=2794;e.fourgurmukhi=2666;e.fourhackarabic=1636;e.fourhangzhou=12324;e.fourideographicparen=12835;e.fourinferior=8324;e.fourmonospace=65300;e.fournumeratorbengali=2551;e.fouroldstyle=63284;e.fourparen=9335;e.fourperiod=9355;e.fourpersian=1780;e.fourroman=8563;e.foursuperior=8308;e.fourteencircle=9325;e.fourteenparen=9345;e.fourteenperiod=9365;e.fourthai=3668;e.fourthtonechinese=715;e.fparen=9377;e.fraction=8260;e.franc=8355;e.g=103;e.gabengali=2455;e.gacute=501;e.gadeva=2327;e.gafarabic=1711;e.gaffinalarabic=64403;e.gafinitialarabic=64404;e.gafmedialarabic=64405;e.gagujarati=2711;e.gagurmukhi=2583;e.gahiragana=12364;e.gakatakana=12460;e.gamma=947;e.gammalatinsmall=611;e.gammasuperior=736;e.gangiacoptic=1003;e.gbopomofo=12557;e.gbreve=287;e.gcaron=487;e.gcedilla=291;e.gcircle=9430;e.gcircumflex=285;e.gcommaaccent=291;e.gdot=289;e.gdotaccent=289;e.gecyrillic=1075;e.gehiragana=12370;e.gekatakana=12466;e.geometricallyequal=8785;e.gereshaccenthebrew=1436;e.gereshhebrew=1523;e.gereshmuqdamhebrew=1437;e.germandbls=223;e.gershayimaccenthebrew=1438;e.gershayimhebrew=1524;e.getamark=12307;e.ghabengali=2456;e.ghadarmenian=1394;e.ghadeva=2328;e.ghagujarati=2712;e.ghagurmukhi=2584;e.ghainarabic=1594;e.ghainfinalarabic=65230;e.ghaininitialarabic=65231;e.ghainmedialarabic=65232;e.ghemiddlehookcyrillic=1173;e.ghestrokecyrillic=1171;e.gheupturncyrillic=1169;e.ghhadeva=2394;e.ghhagurmukhi=2650;e.ghook=608;e.ghzsquare=13203;e.gihiragana=12366;e.gikatakana=12462;e.gimarmenian=1379;e.gimel=1490;e.gimeldagesh=64306;e.gimeldageshhebrew=64306;e.gimelhebrew=1490;e.gjecyrillic=1107;e.glottalinvertedstroke=446;e.glottalstop=660;e.glottalstopinverted=662;e.glottalstopmod=704;e.glottalstopreversed=661;e.glottalstopreversedmod=705;e.glottalstopreversedsuperior=740;e.glottalstopstroke=673;e.glottalstopstrokereversed=674;e.gmacron=7713;e.gmonospace=65351;e.gohiragana=12372;e.gokatakana=12468;e.gparen=9378;e.gpasquare=13228;e.gradient=8711;e.grave=96;e.gravebelowcmb=790;e.gravecmb=768;e.gravecomb=768;e.gravedeva=2387;e.gravelowmod=718;e.gravemonospace=65344;e.gravetonecmb=832;e.greater=62;e.greaterequal=8805;e.greaterequalorless=8923;e.greatermonospace=65310;e.greaterorequivalent=8819;e.greaterorless=8823;e.greateroverequal=8807;e.greatersmall=65125;e.gscript=609;e.gstroke=485;e.guhiragana=12368;e.guillemotleft=171;e.guillemotright=187;e.guilsinglleft=8249;e.guilsinglright=8250;e.gukatakana=12464;e.guramusquare=13080;e.gysquare=13257;e.h=104;e.haabkhasiancyrillic=1193;e.haaltonearabic=1729;e.habengali=2489;e.hadescendercyrillic=1203;e.hadeva=2361;e.hagujarati=2745;e.hagurmukhi=2617;e.haharabic=1581;e.hahfinalarabic=65186;e.hahinitialarabic=65187;e.hahiragana=12399;e.hahmedialarabic=65188;e.haitusquare=13098;e.hakatakana=12495;e.hakatakanahalfwidth=65418;e.halantgurmukhi=2637;e.hamzaarabic=1569;e.hamzalowarabic=1569;e.hangulfiller=12644;e.hardsigncyrillic=1098;e.harpoonleftbarbup=8636;e.harpoonrightbarbup=8640;e.hasquare=13258;e.hatafpatah=1458;e.hatafpatah16=1458;e.hatafpatah23=1458;e.hatafpatah2f=1458;e.hatafpatahhebrew=1458;e.hatafpatahnarrowhebrew=1458;e.hatafpatahquarterhebrew=1458;e.hatafpatahwidehebrew=1458;e.hatafqamats=1459;e.hatafqamats1b=1459;e.hatafqamats28=1459;e.hatafqamats34=1459;e.hatafqamatshebrew=1459;e.hatafqamatsnarrowhebrew=1459;e.hatafqamatsquarterhebrew=1459;e.hatafqamatswidehebrew=1459;e.hatafsegol=1457;e.hatafsegol17=1457;e.hatafsegol24=1457;e.hatafsegol30=1457;e.hatafsegolhebrew=1457;e.hatafsegolnarrowhebrew=1457;e.hatafsegolquarterhebrew=1457;e.hatafsegolwidehebrew=1457;e.hbar=295;e.hbopomofo=12559;e.hbrevebelow=7723;e.hcedilla=7721;e.hcircle=9431;e.hcircumflex=293;e.hdieresis=7719;e.hdotaccent=7715;e.hdotbelow=7717;e.he=1492;e.heart=9829;e.heartsuitblack=9829;e.heartsuitwhite=9825;e.hedagesh=64308;e.hedageshhebrew=64308;e.hehaltonearabic=1729;e.heharabic=1607;e.hehebrew=1492;e.hehfinalaltonearabic=64423;e.hehfinalalttwoarabic=65258;e.hehfinalarabic=65258;e.hehhamzaabovefinalarabic=64421;e.hehhamzaaboveisolatedarabic=64420;e.hehinitialaltonearabic=64424;e.hehinitialarabic=65259;e.hehiragana=12408;e.hehmedialaltonearabic=64425;e.hehmedialarabic=65260;e.heiseierasquare=13179;e.hekatakana=12504;e.hekatakanahalfwidth=65421;e.hekutaarusquare=13110;e.henghook=615;e.herutusquare=13113;e.het=1495;e.hethebrew=1495;e.hhook=614;e.hhooksuperior=689;e.hieuhacirclekorean=12923;e.hieuhaparenkorean=12827;e.hieuhcirclekorean=12909;e.hieuhkorean=12622;e.hieuhparenkorean=12813;e.hihiragana=12402;e.hikatakana=12498;e.hikatakanahalfwidth=65419;e.hiriq=1460;e.hiriq14=1460;e.hiriq21=1460;e.hiriq2d=1460;e.hiriqhebrew=1460;e.hiriqnarrowhebrew=1460;e.hiriqquarterhebrew=1460;e.hiriqwidehebrew=1460;e.hlinebelow=7830;e.hmonospace=65352;e.hoarmenian=1392;e.hohipthai=3627;e.hohiragana=12411;e.hokatakana=12507;e.hokatakanahalfwidth=65422;e.holam=1465;e.holam19=1465;e.holam26=1465;e.holam32=1465;e.holamhebrew=1465;e.holamnarrowhebrew=1465;e.holamquarterhebrew=1465;e.holamwidehebrew=1465;e.honokhukthai=3630;e.hookabovecomb=777;e.hookcmb=777;e.hookpalatalizedbelowcmb=801;e.hookretroflexbelowcmb=802;e.hoonsquare=13122;e.horicoptic=1001;e.horizontalbar=8213;e.horncmb=795;e.hotsprings=9832;e.house=8962;e.hparen=9379;e.hsuperior=688;e.hturned=613;e.huhiragana=12405;e.huiitosquare=13107;e.hukatakana=12501;e.hukatakanahalfwidth=65420;e.hungarumlaut=733;e.hungarumlautcmb=779;e.hv=405;e.hyphen=45;e.hypheninferior=63205;e.hyphenmonospace=65293;e.hyphensmall=65123;e.hyphensuperior=63206;e.hyphentwo=8208;e.i=105;e.iacute=237;e.iacyrillic=1103;e.ibengali=2439;e.ibopomofo=12583;e.ibreve=301;e.icaron=464;e.icircle=9432;e.icircumflex=238;e.icyrillic=1110;e.idblgrave=521;e.ideographearthcircle=12943;e.ideographfirecircle=12939;e.ideographicallianceparen=12863;e.ideographiccallparen=12858;e.ideographiccentrecircle=12965;e.ideographicclose=12294;e.ideographiccomma=12289;e.ideographiccommaleft=65380;e.ideographiccongratulationparen=12855;e.ideographiccorrectcircle=12963;e.ideographicearthparen=12847;e.ideographicenterpriseparen=12861;e.ideographicexcellentcircle=12957;e.ideographicfestivalparen=12864;e.ideographicfinancialcircle=12950;e.ideographicfinancialparen=12854;e.ideographicfireparen=12843;e.ideographichaveparen=12850;e.ideographichighcircle=12964;e.ideographiciterationmark=12293;e.ideographiclaborcircle=12952;e.ideographiclaborparen=12856;e.ideographicleftcircle=12967;e.ideographiclowcircle=12966;e.ideographicmedicinecircle=12969;e.ideographicmetalparen=12846;e.ideographicmoonparen=12842;e.ideographicnameparen=12852;e.ideographicperiod=12290;e.ideographicprintcircle=12958;e.ideographicreachparen=12867;e.ideographicrepresentparen=12857;e.ideographicresourceparen=12862;e.ideographicrightcircle=12968;e.ideographicsecretcircle=12953;e.ideographicselfparen=12866;e.ideographicsocietyparen=12851;e.ideographicspace=12288;e.ideographicspecialparen=12853;e.ideographicstockparen=12849;e.ideographicstudyparen=12859;e.ideographicsunparen=12848;e.ideographicsuperviseparen=12860;e.ideographicwaterparen=12844;e.ideographicwoodparen=12845;e.ideographiczero=12295;e.ideographmetalcircle=12942;e.ideographmooncircle=12938;e.ideographnamecircle=12948;e.ideographsuncircle=12944;e.ideographwatercircle=12940;e.ideographwoodcircle=12941;e.ideva=2311;e.idieresis=239;e.idieresisacute=7727;e.idieresiscyrillic=1253;e.idotbelow=7883;e.iebrevecyrillic=1239;e.iecyrillic=1077;e.ieungacirclekorean=12917;e.ieungaparenkorean=12821;e.ieungcirclekorean=12903;e.ieungkorean=12615;e.ieungparenkorean=12807;e.igrave=236;e.igujarati=2695;e.igurmukhi=2567;e.ihiragana=12356;e.ihookabove=7881;e.iibengali=2440;e.iicyrillic=1080;e.iideva=2312;e.iigujarati=2696;e.iigurmukhi=2568;e.iimatragurmukhi=2624;e.iinvertedbreve=523;e.iishortcyrillic=1081;e.iivowelsignbengali=2496;e.iivowelsigndeva=2368;e.iivowelsigngujarati=2752;e.ij=307;e.ikatakana=12452;e.ikatakanahalfwidth=65394;e.ikorean=12643;e.ilde=732;e.iluyhebrew=1452;e.imacron=299;e.imacroncyrillic=1251;e.imageorapproximatelyequal=8787;e.imatragurmukhi=2623;e.imonospace=65353;e.increment=8710;e.infinity=8734;e.iniarmenian=1387;e.integral=8747;e.integralbottom=8993;e.integralbt=8993;e.integralex=63733;e.integraltop=8992;e.integraltp=8992;e.intersection=8745;e.intisquare=13061;e.invbullet=9688;e.invcircle=9689;e.invsmileface=9787;e.iocyrillic=1105;e.iogonek=303;e.iota=953;e.iotadieresis=970;e.iotadieresistonos=912;e.iotalatin=617;e.iotatonos=943;e.iparen=9380;e.irigurmukhi=2674;e.ismallhiragana=12355;e.ismallkatakana=12451;e.ismallkatakanahalfwidth=65384;e.issharbengali=2554;e.istroke=616;e.isuperior=63213;e.iterationhiragana=12445;e.iterationkatakana=12541;e.itilde=297;e.itildebelow=7725;e.iubopomofo=12585;e.iucyrillic=1102;e.ivowelsignbengali=2495;e.ivowelsigndeva=2367;e.ivowelsigngujarati=2751;e.izhitsacyrillic=1141;e.izhitsadblgravecyrillic=1143;e.j=106;e.jaarmenian=1393;e.jabengali=2460;e.jadeva=2332;e.jagujarati=2716;e.jagurmukhi=2588;e.jbopomofo=12560;e.jcaron=496;e.jcircle=9433;e.jcircumflex=309;e.jcrossedtail=669;e.jdotlessstroke=607;e.jecyrillic=1112;e.jeemarabic=1580;e.jeemfinalarabic=65182;e.jeeminitialarabic=65183;e.jeemmedialarabic=65184;e.jeharabic=1688;e.jehfinalarabic=64395;e.jhabengali=2461;e.jhadeva=2333;e.jhagujarati=2717;e.jhagurmukhi=2589;e.jheharmenian=1403;e.jis=12292;e.jmonospace=65354;e.jparen=9381;e.jsuperior=690;e.k=107;e.kabashkircyrillic=1185;e.kabengali=2453;e.kacute=7729;e.kacyrillic=1082;e.kadescendercyrillic=1179;e.kadeva=2325;e.kaf=1499;e.kafarabic=1603;e.kafdagesh=64315;e.kafdageshhebrew=64315;e.kaffinalarabic=65242;e.kafhebrew=1499;e.kafinitialarabic=65243;e.kafmedialarabic=65244;e.kafrafehebrew=64333;e.kagujarati=2709;e.kagurmukhi=2581;e.kahiragana=12363;e.kahookcyrillic=1220;e.kakatakana=12459;e.kakatakanahalfwidth=65398;e.kappa=954;e.kappasymbolgreek=1008;e.kapyeounmieumkorean=12657;e.kapyeounphieuphkorean=12676;e.kapyeounpieupkorean=12664;e.kapyeounssangpieupkorean=12665;e.karoriisquare=13069;e.kashidaautoarabic=1600;e.kashidaautonosidebearingarabic=1600;e.kasmallkatakana=12533;e.kasquare=13188;e.kasraarabic=1616;e.kasratanarabic=1613;e.kastrokecyrillic=1183;e.katahiraprolongmarkhalfwidth=65392;e.kaverticalstrokecyrillic=1181;e.kbopomofo=12558;e.kcalsquare=13193;e.kcaron=489;e.kcedilla=311;e.kcircle=9434;e.kcommaaccent=311;e.kdotbelow=7731;e.keharmenian=1412;e.kehiragana=12369;e.kekatakana=12465;e.kekatakanahalfwidth=65401;e.kenarmenian=1391;e.kesmallkatakana=12534;e.kgreenlandic=312;e.khabengali=2454;e.khacyrillic=1093;e.khadeva=2326;e.khagujarati=2710;e.khagurmukhi=2582;e.khaharabic=1582;e.khahfinalarabic=65190;e.khahinitialarabic=65191;e.khahmedialarabic=65192;e.kheicoptic=999;e.khhadeva=2393;e.khhagurmukhi=2649;e.khieukhacirclekorean=12920;e.khieukhaparenkorean=12824;e.khieukhcirclekorean=12906;e.khieukhkorean=12619;e.khieukhparenkorean=12810;e.khokhaithai=3586;e.khokhonthai=3589;e.khokhuatthai=3587;e.khokhwaithai=3588;e.khomutthai=3675;e.khook=409;e.khorakhangthai=3590;e.khzsquare=13201;e.kihiragana=12365;e.kikatakana=12461;e.kikatakanahalfwidth=65399;e.kiroguramusquare=13077;e.kiromeetorusquare=13078;e.kirosquare=13076;e.kiyeokacirclekorean=12910;e.kiyeokaparenkorean=12814;e.kiyeokcirclekorean=12896;e.kiyeokkorean=12593;e.kiyeokparenkorean=12800;e.kiyeoksioskorean=12595;e.kjecyrillic=1116;e.klinebelow=7733;e.klsquare=13208;e.kmcubedsquare=13222;e.kmonospace=65355;e.kmsquaredsquare=13218;e.kohiragana=12371;e.kohmsquare=13248;e.kokaithai=3585;e.kokatakana=12467;e.kokatakanahalfwidth=65402;e.kooposquare=13086;e.koppacyrillic=1153;e.koreanstandardsymbol=12927;e.koroniscmb=835;e.kparen=9382;e.kpasquare=13226;e.ksicyrillic=1135;e.ktsquare=13263;e.kturned=670;e.kuhiragana=12367;e.kukatakana=12463;e.kukatakanahalfwidth=65400;e.kvsquare=13240;e.kwsquare=13246;e.l=108;e.labengali=2482;e.lacute=314;e.ladeva=2354;e.lagujarati=2738;e.lagurmukhi=2610;e.lakkhangyaothai=3653;e.lamaleffinalarabic=65276;e.lamalefhamzaabovefinalarabic=65272;e.lamalefhamzaaboveisolatedarabic=65271;e.lamalefhamzabelowfinalarabic=65274;e.lamalefhamzabelowisolatedarabic=65273;e.lamalefisolatedarabic=65275;e.lamalefmaddaabovefinalarabic=65270;e.lamalefmaddaaboveisolatedarabic=65269;e.lamarabic=1604;e.lambda=955;e.lambdastroke=411;e.lamed=1500;e.lameddagesh=64316;e.lameddageshhebrew=64316;e.lamedhebrew=1500;e.lamfinalarabic=65246;e.lamhahinitialarabic=64714;e.laminitialarabic=65247;e.lamjeeminitialarabic=64713;e.lamkhahinitialarabic=64715;e.lamlamhehisolatedarabic=65010;e.lammedialarabic=65248;e.lammeemhahinitialarabic=64904;e.lammeeminitialarabic=64716;e.largecircle=9711;e.lbar=410;e.lbelt=620;e.lbopomofo=12556;e.lcaron=318;e.lcedilla=316;e.lcircle=9435;e.lcircumflexbelow=7741;e.lcommaaccent=316;e.ldot=320;e.ldotaccent=320;e.ldotbelow=7735;e.ldotbelowmacron=7737;e.leftangleabovecmb=794;e.lefttackbelowcmb=792;e.less=60;e.lessequal=8804;e.lessequalorgreater=8922;e.lessmonospace=65308;e.lessorequivalent=8818;e.lessorgreater=8822;e.lessoverequal=8806;e.lesssmall=65124;e.lezh=622;e.lfblock=9612;e.lhookretroflex=621;e.lira=8356;e.liwnarmenian=1388;e.lj=457;e.ljecyrillic=1113;e.ll=63168;e.lladeva=2355;e.llagujarati=2739;e.llinebelow=7739;e.llladeva=2356;e.llvocalicbengali=2529;e.llvocalicdeva=2401;e.llvocalicvowelsignbengali=2531;e.llvocalicvowelsigndeva=2403;e.lmiddletilde=619;e.lmonospace=65356;e.lmsquare=13264;e.lochulathai=3628;e.logicaland=8743;e.logicalnot=172;e.logicalnotreversed=8976;e.logicalor=8744;e.lolingthai=3621;e.longs=383;e.lowlinecenterline=65102;e.lowlinecmb=818;e.lowlinedashed=65101;e.lozenge=9674;e.lparen=9383;e.lslash=322;e.lsquare=8467;e.lsuperior=63214;e.ltshade=9617;e.luthai=3622;e.lvocalicbengali=2444;e.lvocalicdeva=2316;e.lvocalicvowelsignbengali=2530;e.lvocalicvowelsigndeva=2402;e.lxsquare=13267;e.m=109;e.mabengali=2478;e.macron=175;e.macronbelowcmb=817;e.macroncmb=772;e.macronlowmod=717;e.macronmonospace=65507;e.macute=7743;e.madeva=2350;e.magujarati=2734;e.magurmukhi=2606;e.mahapakhhebrew=1444;e.mahapakhlefthebrew=1444;e.mahiragana=12414;e.maichattawalowleftthai=63637;e.maichattawalowrightthai=63636;e.maichattawathai=3659;e.maichattawaupperleftthai=63635;e.maieklowleftthai=63628;e.maieklowrightthai=63627;e.maiekthai=3656;e.maiekupperleftthai=63626;e.maihanakatleftthai=63620;e.maihanakatthai=3633;e.maitaikhuleftthai=63625;e.maitaikhuthai=3655;e.maitholowleftthai=63631;e.maitholowrightthai=63630;e.maithothai=3657;e.maithoupperleftthai=63629;e.maitrilowleftthai=63634;e.maitrilowrightthai=63633;e.maitrithai=3658;e.maitriupperleftthai=63632;e.maiyamokthai=3654;e.makatakana=12510;e.makatakanahalfwidth=65423;e.male=9794;e.mansyonsquare=13127;e.maqafhebrew=1470;e.mars=9794;e.masoracirclehebrew=1455;e.masquare=13187;e.mbopomofo=12551;e.mbsquare=13268;e.mcircle=9436;e.mcubedsquare=13221;e.mdotaccent=7745;e.mdotbelow=7747;e.meemarabic=1605;e.meemfinalarabic=65250;e.meeminitialarabic=65251;e.meemmedialarabic=65252;e.meemmeeminitialarabic=64721;e.meemmeemisolatedarabic=64584;e.meetorusquare=13133;e.mehiragana=12417;e.meizierasquare=13182;e.mekatakana=12513;e.mekatakanahalfwidth=65426;e.mem=1502;e.memdagesh=64318;e.memdageshhebrew=64318;e.memhebrew=1502;e.menarmenian=1396;e.merkhahebrew=1445;e.merkhakefulahebrew=1446;e.merkhakefulalefthebrew=1446;e.merkhalefthebrew=1445;e.mhook=625;e.mhzsquare=13202;e.middledotkatakanahalfwidth=65381;e.middot=183;e.mieumacirclekorean=12914;e.mieumaparenkorean=12818;e.mieumcirclekorean=12900;e.mieumkorean=12609;e.mieumpansioskorean=12656;e.mieumparenkorean=12804;e.mieumpieupkorean=12654;e.mieumsioskorean=12655;e.mihiragana=12415;e.mikatakana=12511;e.mikatakanahalfwidth=65424;e.minus=8722;e.minusbelowcmb=800;e.minuscircle=8854;e.minusmod=727;e.minusplus=8723;e.minute=8242;e.miribaarusquare=13130;e.mirisquare=13129;e.mlonglegturned=624;e.mlsquare=13206;e.mmcubedsquare=13219;e.mmonospace=65357;e.mmsquaredsquare=13215;e.mohiragana=12418;e.mohmsquare=13249;e.mokatakana=12514;e.mokatakanahalfwidth=65427;e.molsquare=13270;e.momathai=3617;e.moverssquare=13223;e.moverssquaredsquare=13224;e.mparen=9384;e.mpasquare=13227;e.mssquare=13235;e.msuperior=63215;e.mturned=623;e.mu=181;e.mu1=181;e.muasquare=13186;e.muchgreater=8811;e.muchless=8810;e.mufsquare=13196;e.mugreek=956;e.mugsquare=13197;e.muhiragana=12416;e.mukatakana=12512;e.mukatakanahalfwidth=65425;e.mulsquare=13205;e.multiply=215;e.mumsquare=13211;e.munahhebrew=1443;e.munahlefthebrew=1443;e.musicalnote=9834;e.musicalnotedbl=9835;e.musicflatsign=9837;e.musicsharpsign=9839;e.mussquare=13234;e.muvsquare=13238;e.muwsquare=13244;e.mvmegasquare=13241;e.mvsquare=13239;e.mwmegasquare=13247;e.mwsquare=13245;e.n=110;e.nabengali=2472;e.nabla=8711;e.nacute=324;e.nadeva=2344;e.nagujarati=2728;e.nagurmukhi=2600;e.nahiragana=12394;e.nakatakana=12490;e.nakatakanahalfwidth=65413;e.napostrophe=329;e.nasquare=13185;e.nbopomofo=12555;e.nbspace=160;e.ncaron=328;e.ncedilla=326;e.ncircle=9437;e.ncircumflexbelow=7755;e.ncommaaccent=326;e.ndotaccent=7749;e.ndotbelow=7751;e.nehiragana=12397;e.nekatakana=12493;e.nekatakanahalfwidth=65416;e.newsheqelsign=8362;e.nfsquare=13195;e.ngabengali=2457;e.ngadeva=2329;e.ngagujarati=2713;e.ngagurmukhi=2585;e.ngonguthai=3591;e.nhiragana=12435;e.nhookleft=626;e.nhookretroflex=627;e.nieunacirclekorean=12911;e.nieunaparenkorean=12815;e.nieuncieuckorean=12597;e.nieuncirclekorean=12897;e.nieunhieuhkorean=12598;e.nieunkorean=12596;e.nieunpansioskorean=12648;e.nieunparenkorean=12801;e.nieunsioskorean=12647;e.nieuntikeutkorean=12646;e.nihiragana=12395;e.nikatakana=12491;e.nikatakanahalfwidth=65414;e.nikhahitleftthai=63641;e.nikhahitthai=3661;e.nine=57;e.ninearabic=1641;e.ninebengali=2543;e.ninecircle=9320;e.ninecircleinversesansserif=10130;e.ninedeva=2415;e.ninegujarati=2799;e.ninegurmukhi=2671;e.ninehackarabic=1641;e.ninehangzhou=12329;e.nineideographicparen=12840;e.nineinferior=8329;e.ninemonospace=65305;e.nineoldstyle=63289;e.nineparen=9340;e.nineperiod=9360;e.ninepersian=1785;e.nineroman=8568;e.ninesuperior=8313;e.nineteencircle=9330;e.nineteenparen=9350;e.nineteenperiod=9370;e.ninethai=3673;e.nj=460;e.njecyrillic=1114;e.nkatakana=12531;e.nkatakanahalfwidth=65437;e.nlegrightlong=414;e.nlinebelow=7753;e.nmonospace=65358;e.nmsquare=13210;e.nnabengali=2467;e.nnadeva=2339;e.nnagujarati=2723;e.nnagurmukhi=2595;e.nnnadeva=2345;e.nohiragana=12398;e.nokatakana=12494;e.nokatakanahalfwidth=65417;e.nonbreakingspace=160;e.nonenthai=3603;e.nonuthai=3609;e.noonarabic=1606;e.noonfinalarabic=65254;e.noonghunnaarabic=1722;e.noonghunnafinalarabic=64415;e.nooninitialarabic=65255;e.noonjeeminitialarabic=64722;e.noonjeemisolatedarabic=64587;e.noonmedialarabic=65256;e.noonmeeminitialarabic=64725;e.noonmeemisolatedarabic=64590;e.noonnoonfinalarabic=64653;e.notcontains=8716;e.notelement=8713;e.notelementof=8713;e.notequal=8800;e.notgreater=8815;e.notgreaternorequal=8817;e.notgreaternorless=8825;e.notidentical=8802;e.notless=8814;e.notlessnorequal=8816;e.notparallel=8742;e.notprecedes=8832;e.notsubset=8836;e.notsucceeds=8833;e.notsuperset=8837;e.nowarmenian=1398;e.nparen=9385;e.nssquare=13233;e.nsuperior=8319;e.ntilde=241;e.nu=957;e.nuhiragana=12396;e.nukatakana=12492;e.nukatakanahalfwidth=65415;e.nuktabengali=2492;e.nuktadeva=2364;e.nuktagujarati=2748;e.nuktagurmukhi=2620;e.numbersign=35;e.numbersignmonospace=65283;e.numbersignsmall=65119;e.numeralsigngreek=884;e.numeralsignlowergreek=885;e.numero=8470;e.nun=1504;e.nundagesh=64320;e.nundageshhebrew=64320;e.nunhebrew=1504;e.nvsquare=13237;e.nwsquare=13243;e.nyabengali=2462;e.nyadeva=2334;e.nyagujarati=2718;e.nyagurmukhi=2590;e.o=111;e.oacute=243;e.oangthai=3629;e.obarred=629;e.obarredcyrillic=1257;e.obarreddieresiscyrillic=1259;e.obengali=2451;e.obopomofo=12571;e.obreve=335;e.ocandradeva=2321;e.ocandragujarati=2705;e.ocandravowelsigndeva=2377;e.ocandravowelsigngujarati=2761;e.ocaron=466;e.ocircle=9438;e.ocircumflex=244;e.ocircumflexacute=7889;e.ocircumflexdotbelow=7897;e.ocircumflexgrave=7891;e.ocircumflexhookabove=7893;e.ocircumflextilde=7895;e.ocyrillic=1086;e.odblacute=337;e.odblgrave=525;e.odeva=2323;e.odieresis=246;e.odieresiscyrillic=1255;e.odotbelow=7885;e.oe=339;e.oekorean=12634;e.ogonek=731;e.ogonekcmb=808;e.ograve=242;e.ogujarati=2707;e.oharmenian=1413;e.ohiragana=12362;e.ohookabove=7887;e.ohorn=417;e.ohornacute=7899;e.ohorndotbelow=7907;e.ohorngrave=7901;e.ohornhookabove=7903;e.ohorntilde=7905;e.ohungarumlaut=337;e.oi=419;e.oinvertedbreve=527;e.okatakana=12458;e.okatakanahalfwidth=65397;e.okorean=12631;e.olehebrew=1451;e.omacron=333;e.omacronacute=7763;e.omacrongrave=7761;e.omdeva=2384;e.omega=969;e.omega1=982;e.omegacyrillic=1121;e.omegalatinclosed=631;e.omegaroundcyrillic=1147;e.omegatitlocyrillic=1149;e.omegatonos=974;e.omgujarati=2768;e.omicron=959;e.omicrontonos=972;e.omonospace=65359;e.one=49;e.onearabic=1633;e.onebengali=2535;e.onecircle=9312;e.onecircleinversesansserif=10122;e.onedeva=2407;e.onedotenleader=8228;e.oneeighth=8539;e.onefitted=63196;e.onegujarati=2791;e.onegurmukhi=2663;e.onehackarabic=1633;e.onehalf=189;e.onehangzhou=12321;e.oneideographicparen=12832;e.oneinferior=8321;e.onemonospace=65297;e.onenumeratorbengali=2548;e.oneoldstyle=63281;e.oneparen=9332;e.oneperiod=9352;e.onepersian=1777;e.onequarter=188;e.oneroman=8560;e.onesuperior=185;e.onethai=3665;e.onethird=8531;e.oogonek=491;e.oogonekmacron=493;e.oogurmukhi=2579;e.oomatragurmukhi=2635;e.oopen=596;e.oparen=9386;e.openbullet=9702;e.option=8997;e.ordfeminine=170;e.ordmasculine=186;e.orthogonal=8735;e.oshortdeva=2322;e.oshortvowelsigndeva=2378;e.oslash=248;e.oslashacute=511;e.osmallhiragana=12361;e.osmallkatakana=12457;e.osmallkatakanahalfwidth=65387;e.ostrokeacute=511;e.osuperior=63216;e.otcyrillic=1151;e.otilde=245;e.otildeacute=7757;e.otildedieresis=7759;e.oubopomofo=12577;e.overline=8254;e.overlinecenterline=65098;e.overlinecmb=773;e.overlinedashed=65097;e.overlinedblwavy=65100;e.overlinewavy=65099;e.overscore=175;e.ovowelsignbengali=2507;e.ovowelsigndeva=2379;e.ovowelsigngujarati=2763;e.p=112;e.paampssquare=13184;e.paasentosquare=13099;e.pabengali=2474;e.pacute=7765;e.padeva=2346;e.pagedown=8671;e.pageup=8670;e.pagujarati=2730;e.pagurmukhi=2602;e.pahiragana=12401;e.paiyannoithai=3631;e.pakatakana=12497;e.palatalizationcyrilliccmb=1156;e.palochkacyrillic=1216;e.pansioskorean=12671;e.paragraph=182;e.parallel=8741;e.parenleft=40;e.parenleftaltonearabic=64830;e.parenleftbt=63725;e.parenleftex=63724;e.parenleftinferior=8333;e.parenleftmonospace=65288;e.parenleftsmall=65113;e.parenleftsuperior=8317;e.parenlefttp=63723;e.parenleftvertical=65077;e.parenright=41;e.parenrightaltonearabic=64831;e.parenrightbt=63736;e.parenrightex=63735;e.parenrightinferior=8334;e.parenrightmonospace=65289;e.parenrightsmall=65114;e.parenrightsuperior=8318;e.parenrighttp=63734;e.parenrightvertical=65078;e.partialdiff=8706;e.paseqhebrew=1472;e.pashtahebrew=1433;e.pasquare=13225;e.patah=1463;e.patah11=1463;e.patah1d=1463;e.patah2a=1463;e.patahhebrew=1463;e.patahnarrowhebrew=1463;e.patahquarterhebrew=1463;e.patahwidehebrew=1463;e.pazerhebrew=1441;e.pbopomofo=12550;e.pcircle=9439;e.pdotaccent=7767;e.pe=1508;e.pecyrillic=1087;e.pedagesh=64324;e.pedageshhebrew=64324;e.peezisquare=13115;e.pefinaldageshhebrew=64323;e.peharabic=1662;e.peharmenian=1402;e.pehebrew=1508;e.pehfinalarabic=64343;e.pehinitialarabic=64344;e.pehiragana=12410;e.pehmedialarabic=64345;e.pekatakana=12506;e.pemiddlehookcyrillic=1191;e.perafehebrew=64334;e.percent=37;e.percentarabic=1642;e.percentmonospace=65285;e.percentsmall=65130;e.period=46;e.periodarmenian=1417;e.periodcentered=183;e.periodhalfwidth=65377;e.periodinferior=63207;e.periodmonospace=65294;e.periodsmall=65106;e.periodsuperior=63208;e.perispomenigreekcmb=834;e.perpendicular=8869;e.perthousand=8240;e.peseta=8359;e.pfsquare=13194;e.phabengali=2475;e.phadeva=2347;e.phagujarati=2731;e.phagurmukhi=2603;e.phi=966;e.phi1=981;e.phieuphacirclekorean=12922;e.phieuphaparenkorean=12826;e.phieuphcirclekorean=12908;e.phieuphkorean=12621;e.phieuphparenkorean=12812;e.philatin=632;e.phinthuthai=3642;e.phisymbolgreek=981;e.phook=421;e.phophanthai=3614;e.phophungthai=3612;e.phosamphaothai=3616;e.pi=960;e.pieupacirclekorean=12915;e.pieupaparenkorean=12819;e.pieupcieuckorean=12662;e.pieupcirclekorean=12901;e.pieupkiyeokkorean=12658;e.pieupkorean=12610;e.pieupparenkorean=12805;e.pieupsioskiyeokkorean=12660;e.pieupsioskorean=12612;e.pieupsiostikeutkorean=12661;e.pieupthieuthkorean=12663;e.pieuptikeutkorean=12659;e.pihiragana=12404;e.pikatakana=12500;e.pisymbolgreek=982;e.piwrarmenian=1411;e.planckover2pi=8463;e.planckover2pi1=8463;e.plus=43;e.plusbelowcmb=799;e.pluscircle=8853;e.plusminus=177;e.plusmod=726;e.plusmonospace=65291;e.plussmall=65122;e.plussuperior=8314;e.pmonospace=65360;e.pmsquare=13272;e.pohiragana=12413;e.pointingindexdownwhite=9759;e.pointingindexleftwhite=9756;e.pointingindexrightwhite=9758;e.pointingindexupwhite=9757;e.pokatakana=12509;e.poplathai=3611;e.postalmark=12306;e.postalmarkface=12320;e.pparen=9387;e.precedes=8826;e.prescription=8478;e.primemod=697;e.primereversed=8245;e.product=8719;e.projective=8965;e.prolongedkana=12540;e.propellor=8984;e.propersubset=8834;e.propersuperset=8835;e.proportion=8759;e.proportional=8733;e.psi=968;e.psicyrillic=1137;e.psilipneumatacyrilliccmb=1158;e.pssquare=13232;e.puhiragana=12407;e.pukatakana=12503;e.pvsquare=13236;e.pwsquare=13242;e.q=113;e.qadeva=2392;e.qadmahebrew=1448;e.qafarabic=1602;e.qaffinalarabic=65238;e.qafinitialarabic=65239;e.qafmedialarabic=65240;e.qamats=1464;e.qamats10=1464;e.qamats1a=1464;e.qamats1c=1464;e.qamats27=1464;e.qamats29=1464;e.qamats33=1464;e.qamatsde=1464;e.qamatshebrew=1464;e.qamatsnarrowhebrew=1464;e.qamatsqatanhebrew=1464;e.qamatsqatannarrowhebrew=1464;e.qamatsqatanquarterhebrew=1464;e.qamatsqatanwidehebrew=1464;e.qamatsquarterhebrew=1464;e.qamatswidehebrew=1464;e.qarneyparahebrew=1439;e.qbopomofo=12561;e.qcircle=9440;e.qhook=672;e.qmonospace=65361;e.qof=1511;e.qofdagesh=64327;e.qofdageshhebrew=64327;e.qofhebrew=1511;e.qparen=9388;e.quarternote=9833;e.qubuts=1467;e.qubuts18=1467;e.qubuts25=1467;e.qubuts31=1467;e.qubutshebrew=1467;e.qubutsnarrowhebrew=1467;e.qubutsquarterhebrew=1467;e.qubutswidehebrew=1467;e.question=63;e.questionarabic=1567;e.questionarmenian=1374;e.questiondown=191;e.questiondownsmall=63423;e.questiongreek=894;e.questionmonospace=65311;e.questionsmall=63295;e.quotedbl=34;e.quotedblbase=8222;e.quotedblleft=8220;e.quotedblmonospace=65282;e.quotedblprime=12318;e.quotedblprimereversed=12317;e.quotedblright=8221;e.quoteleft=8216;e.quoteleftreversed=8219;e.quotereversed=8219;e.quoteright=8217;e.quoterightn=329;e.quotesinglbase=8218;e.quotesingle=39;e.quotesinglemonospace=65287;e.r=114;e.raarmenian=1404;e.rabengali=2480;e.racute=341;e.radeva=2352;e.radical=8730;e.radicalex=63717;e.radoverssquare=13230;e.radoverssquaredsquare=13231;e.radsquare=13229;e.rafe=1471;e.rafehebrew=1471;e.ragujarati=2736;e.ragurmukhi=2608;e.rahiragana=12425;e.rakatakana=12521;e.rakatakanahalfwidth=65431;e.ralowerdiagonalbengali=2545;e.ramiddlediagonalbengali=2544;e.ramshorn=612;e.ratio=8758;e.rbopomofo=12566;e.rcaron=345;e.rcedilla=343;e.rcircle=9441;e.rcommaaccent=343;e.rdblgrave=529;e.rdotaccent=7769;e.rdotbelow=7771;e.rdotbelowmacron=7773;e.referencemark=8251;e.reflexsubset=8838;e.reflexsuperset=8839;e.registered=174;e.registersans=63720;e.registerserif=63194;e.reharabic=1585;e.reharmenian=1408;e.rehfinalarabic=65198;e.rehiragana=12428;e.rekatakana=12524;e.rekatakanahalfwidth=65434;e.resh=1512;e.reshdageshhebrew=64328;e.reshhebrew=1512;e.reversedtilde=8765;e.reviahebrew=1431;e.reviamugrashhebrew=1431;e.revlogicalnot=8976;e.rfishhook=638;e.rfishhookreversed=639;e.rhabengali=2525;e.rhadeva=2397;e.rho=961;e.rhook=637;e.rhookturned=635;e.rhookturnedsuperior=693;e.rhosymbolgreek=1009;e.rhotichookmod=734;e.rieulacirclekorean=12913;e.rieulaparenkorean=12817;e.rieulcirclekorean=12899;e.rieulhieuhkorean=12608;e.rieulkiyeokkorean=12602;e.rieulkiyeoksioskorean=12649;e.rieulkorean=12601;e.rieulmieumkorean=12603;e.rieulpansioskorean=12652;e.rieulparenkorean=12803;e.rieulphieuphkorean=12607;e.rieulpieupkorean=12604;e.rieulpieupsioskorean=12651;e.rieulsioskorean=12605;e.rieulthieuthkorean=12606;e.rieultikeutkorean=12650;e.rieulyeorinhieuhkorean=12653;e.rightangle=8735;e.righttackbelowcmb=793;e.righttriangle=8895;e.rihiragana=12426;e.rikatakana=12522;e.rikatakanahalfwidth=65432;e.ring=730;e.ringbelowcmb=805;e.ringcmb=778;e.ringhalfleft=703;e.ringhalfleftarmenian=1369;e.ringhalfleftbelowcmb=796;e.ringhalfleftcentered=723;e.ringhalfright=702;e.ringhalfrightbelowcmb=825;e.ringhalfrightcentered=722;e.rinvertedbreve=531;e.rittorusquare=13137;e.rlinebelow=7775;e.rlongleg=636;e.rlonglegturned=634;e.rmonospace=65362;e.rohiragana=12429;e.rokatakana=12525;e.rokatakanahalfwidth=65435;e.roruathai=3619;e.rparen=9389;e.rrabengali=2524;e.rradeva=2353;e.rragurmukhi=2652;e.rreharabic=1681;e.rrehfinalarabic=64397;e.rrvocalicbengali=2528;e.rrvocalicdeva=2400;e.rrvocalicgujarati=2784;e.rrvocalicvowelsignbengali=2500;e.rrvocalicvowelsigndeva=2372;e.rrvocalicvowelsigngujarati=2756;e.rsuperior=63217;e.rtblock=9616;e.rturned=633;e.rturnedsuperior=692;e.ruhiragana=12427;e.rukatakana=12523;e.rukatakanahalfwidth=65433;e.rupeemarkbengali=2546;e.rupeesignbengali=2547;e.rupiah=63197;e.ruthai=3620;e.rvocalicbengali=2443;e.rvocalicdeva=2315;e.rvocalicgujarati=2699;e.rvocalicvowelsignbengali=2499;e.rvocalicvowelsigndeva=2371;e.rvocalicvowelsigngujarati=2755;e.s=115;e.sabengali=2488;e.sacute=347;e.sacutedotaccent=7781;e.sadarabic=1589;e.sadeva=2360;e.sadfinalarabic=65210;e.sadinitialarabic=65211;e.sadmedialarabic=65212;e.sagujarati=2744;e.sagurmukhi=2616;e.sahiragana=12373;e.sakatakana=12469;e.sakatakanahalfwidth=65403;e.sallallahoualayhewasallamarabic=65018;e.samekh=1505;e.samekhdagesh=64321;e.samekhdageshhebrew=64321;e.samekhhebrew=1505;e.saraaathai=3634;e.saraaethai=3649;e.saraaimaimalaithai=3652;e.saraaimaimuanthai=3651;e.saraamthai=3635;e.saraathai=3632;e.saraethai=3648;e.saraiileftthai=63622;e.saraiithai=3637;e.saraileftthai=63621;e.saraithai=3636;e.saraothai=3650;e.saraueeleftthai=63624;e.saraueethai=3639;e.saraueleftthai=63623;e.sarauethai=3638;e.sarauthai=3640;e.sarauuthai=3641;e.sbopomofo=12569;e.scaron=353;e.scarondotaccent=7783;e.scedilla=351;e.schwa=601;e.schwacyrillic=1241;e.schwadieresiscyrillic=1243;e.schwahook=602;e.scircle=9442;e.scircumflex=349;e.scommaaccent=537;e.sdotaccent=7777;e.sdotbelow=7779;e.sdotbelowdotaccent=7785;e.seagullbelowcmb=828;e.second=8243;e.secondtonechinese=714;e.section=167;e.seenarabic=1587;e.seenfinalarabic=65202;e.seeninitialarabic=65203;e.seenmedialarabic=65204;e.segol=1462;e.segol13=1462;e.segol1f=1462;e.segol2c=1462;e.segolhebrew=1462;e.segolnarrowhebrew=1462;e.segolquarterhebrew=1462;e.segoltahebrew=1426;e.segolwidehebrew=1462;e.seharmenian=1405;e.sehiragana=12379;e.sekatakana=12475;e.sekatakanahalfwidth=65406;e.semicolon=59;e.semicolonarabic=1563;e.semicolonmonospace=65307;e.semicolonsmall=65108;e.semivoicedmarkkana=12444;e.semivoicedmarkkanahalfwidth=65439;e.sentisquare=13090;e.sentosquare=13091;e.seven=55;e.sevenarabic=1639;e.sevenbengali=2541;e.sevencircle=9318;e.sevencircleinversesansserif=10128;e.sevendeva=2413;e.seveneighths=8542;e.sevengujarati=2797;e.sevengurmukhi=2669;e.sevenhackarabic=1639;e.sevenhangzhou=12327;e.sevenideographicparen=12838;e.seveninferior=8327;e.sevenmonospace=65303;e.sevenoldstyle=63287;e.sevenparen=9338;e.sevenperiod=9358;e.sevenpersian=1783;e.sevenroman=8566;e.sevensuperior=8311;e.seventeencircle=9328;e.seventeenparen=9348;e.seventeenperiod=9368;e.seventhai=3671;e.sfthyphen=173;e.shaarmenian=1399;e.shabengali=2486;e.shacyrillic=1096;e.shaddaarabic=1617;e.shaddadammaarabic=64609;e.shaddadammatanarabic=64606;e.shaddafathaarabic=64608;e.shaddakasraarabic=64610;e.shaddakasratanarabic=64607;e.shade=9618;e.shadedark=9619;e.shadelight=9617;e.shademedium=9618;e.shadeva=2358;e.shagujarati=2742;e.shagurmukhi=2614;e.shalshelethebrew=1427;e.shbopomofo=12565;e.shchacyrillic=1097;e.sheenarabic=1588;e.sheenfinalarabic=65206;e.sheeninitialarabic=65207;e.sheenmedialarabic=65208;e.sheicoptic=995;e.sheqel=8362;e.sheqelhebrew=8362;e.sheva=1456;e.sheva115=1456;e.sheva15=1456;e.sheva22=1456;e.sheva2e=1456;e.shevahebrew=1456;e.shevanarrowhebrew=1456;e.shevaquarterhebrew=1456;e.shevawidehebrew=1456;e.shhacyrillic=1211;e.shimacoptic=1005;e.shin=1513;e.shindagesh=64329;e.shindageshhebrew=64329;e.shindageshshindot=64300;e.shindageshshindothebrew=64300;e.shindageshsindot=64301;e.shindageshsindothebrew=64301;e.shindothebrew=1473;e.shinhebrew=1513;e.shinshindot=64298;e.shinshindothebrew=64298;e.shinsindot=64299;e.shinsindothebrew=64299;e.shook=642;e.sigma=963;e.sigma1=962;e.sigmafinal=962;e.sigmalunatesymbolgreek=1010;e.sihiragana=12375;e.sikatakana=12471;e.sikatakanahalfwidth=65404;e.siluqhebrew=1469;e.siluqlefthebrew=1469;e.similar=8764;e.sindothebrew=1474;e.siosacirclekorean=12916;e.siosaparenkorean=12820;e.sioscieuckorean=12670;e.sioscirclekorean=12902;e.sioskiyeokkorean=12666;e.sioskorean=12613;e.siosnieunkorean=12667;e.siosparenkorean=12806;e.siospieupkorean=12669;e.siostikeutkorean=12668;e.six=54;e.sixarabic=1638;e.sixbengali=2540;e.sixcircle=9317;e.sixcircleinversesansserif=10127;e.sixdeva=2412;e.sixgujarati=2796;e.sixgurmukhi=2668;e.sixhackarabic=1638;e.sixhangzhou=12326;e.sixideographicparen=12837;e.sixinferior=8326;e.sixmonospace=65302;e.sixoldstyle=63286;e.sixparen=9337;e.sixperiod=9357;e.sixpersian=1782;e.sixroman=8565;e.sixsuperior=8310;e.sixteencircle=9327;e.sixteencurrencydenominatorbengali=2553;e.sixteenparen=9347;e.sixteenperiod=9367;e.sixthai=3670;e.slash=47;e.slashmonospace=65295;e.slong=383;e.slongdotaccent=7835;e.smileface=9786;e.smonospace=65363;e.sofpasuqhebrew=1475;e.softhyphen=173;e.softsigncyrillic=1100;e.sohiragana=12381;e.sokatakana=12477;e.sokatakanahalfwidth=65407;e.soliduslongoverlaycmb=824;e.solidusshortoverlaycmb=823;e.sorusithai=3625;e.sosalathai=3624;e.sosothai=3595;e.sosuathai=3626;e.space=32;e.spacehackarabic=32;e.spade=9824;e.spadesuitblack=9824;e.spadesuitwhite=9828;e.sparen=9390;e.squarebelowcmb=827;e.squarecc=13252;e.squarecm=13213;e.squarediagonalcrosshatchfill=9641;e.squarehorizontalfill=9636;e.squarekg=13199;e.squarekm=13214;e.squarekmcapital=13262;e.squareln=13265;e.squarelog=13266;e.squaremg=13198;e.squaremil=13269;e.squaremm=13212;e.squaremsquared=13217;e.squareorthogonalcrosshatchfill=9638;e.squareupperlefttolowerrightfill=9639;e.squareupperrighttolowerleftfill=9640;e.squareverticalfill=9637;e.squarewhitewithsmallblack=9635;e.srsquare=13275;e.ssabengali=2487;e.ssadeva=2359;e.ssagujarati=2743;e.ssangcieuckorean=12617;e.ssanghieuhkorean=12677;e.ssangieungkorean=12672;e.ssangkiyeokkorean=12594;e.ssangnieunkorean=12645;e.ssangpieupkorean=12611;e.ssangsioskorean=12614;e.ssangtikeutkorean=12600;e.ssuperior=63218;e.sterling=163;e.sterlingmonospace=65505;e.strokelongoverlaycmb=822;e.strokeshortoverlaycmb=821;e.subset=8834;e.subsetnotequal=8842;e.subsetorequal=8838;e.succeeds=8827;e.suchthat=8715;e.suhiragana=12377;e.sukatakana=12473;e.sukatakanahalfwidth=65405;e.sukunarabic=1618;e.summation=8721;e.sun=9788;e.superset=8835;e.supersetnotequal=8843;e.supersetorequal=8839;e.svsquare=13276;e.syouwaerasquare=13180;e.t=116;e.tabengali=2468;e.tackdown=8868;e.tackleft=8867;e.tadeva=2340;e.tagujarati=2724;e.tagurmukhi=2596;e.taharabic=1591;e.tahfinalarabic=65218;e.tahinitialarabic=65219;e.tahiragana=12383;e.tahmedialarabic=65220;e.taisyouerasquare=13181;e.takatakana=12479;e.takatakanahalfwidth=65408;e.tatweelarabic=1600;e.tau=964;e.tav=1514;e.tavdages=64330;e.tavdagesh=64330;e.tavdageshhebrew=64330;e.tavhebrew=1514;e.tbar=359;e.tbopomofo=12554;e.tcaron=357;e.tccurl=680;e.tcedilla=355;e.tcheharabic=1670;e.tchehfinalarabic=64379;e.tchehinitialarabic=64380;e.tchehmedialarabic=64381;e.tcircle=9443;e.tcircumflexbelow=7793;e.tcommaaccent=355;e.tdieresis=7831;e.tdotaccent=7787;e.tdotbelow=7789;e.tecyrillic=1090;e.tedescendercyrillic=1197;e.teharabic=1578;e.tehfinalarabic=65174;e.tehhahinitialarabic=64674;e.tehhahisolatedarabic=64524;e.tehinitialarabic=65175;e.tehiragana=12390;e.tehjeeminitialarabic=64673;e.tehjeemisolatedarabic=64523;e.tehmarbutaarabic=1577;e.tehmarbutafinalarabic=65172;e.tehmedialarabic=65176;e.tehmeeminitialarabic=64676;e.tehmeemisolatedarabic=64526;e.tehnoonfinalarabic=64627;e.tekatakana=12486;e.tekatakanahalfwidth=65411;e.telephone=8481;e.telephoneblack=9742;e.telishagedolahebrew=1440;e.telishaqetanahebrew=1449;e.tencircle=9321;e.tenideographicparen=12841;e.tenparen=9341;e.tenperiod=9361;e.tenroman=8569;e.tesh=679;e.tet=1496;e.tetdagesh=64312;e.tetdageshhebrew=64312;e.tethebrew=1496;e.tetsecyrillic=1205;e.tevirhebrew=1435;e.tevirlefthebrew=1435;e.thabengali=2469;e.thadeva=2341;e.thagujarati=2725;e.thagurmukhi=2597;e.thalarabic=1584;e.thalfinalarabic=65196;e.thanthakhatlowleftthai=63640;e.thanthakhatlowrightthai=63639;e.thanthakhatthai=3660;e.thanthakhatupperleftthai=63638;e.theharabic=1579;e.thehfinalarabic=65178;e.thehinitialarabic=65179;e.thehmedialarabic=65180;e.thereexists=8707;e.therefore=8756;e.theta=952;e.theta1=977;e.thetasymbolgreek=977;e.thieuthacirclekorean=12921;e.thieuthaparenkorean=12825;e.thieuthcirclekorean=12907;e.thieuthkorean=12620;e.thieuthparenkorean=12811;e.thirteencircle=9324;e.thirteenparen=9344;e.thirteenperiod=9364;e.thonangmonthothai=3601;e.thook=429;e.thophuthaothai=3602;e.thorn=254;e.thothahanthai=3607;e.thothanthai=3600;e.thothongthai=3608;e.thothungthai=3606;e.thousandcyrillic=1154;e.thousandsseparatorarabic=1644;e.thousandsseparatorpersian=1644;e.three=51;e.threearabic=1635;e.threebengali=2537;e.threecircle=9314;e.threecircleinversesansserif=10124;e.threedeva=2409;e.threeeighths=8540;e.threegujarati=2793;e.threegurmukhi=2665;e.threehackarabic=1635;e.threehangzhou=12323;e.threeideographicparen=12834;e.threeinferior=8323;e.threemonospace=65299;e.threenumeratorbengali=2550;e.threeoldstyle=63283;e.threeparen=9334;e.threeperiod=9354;e.threepersian=1779;e.threequarters=190;e.threequartersemdash=63198;e.threeroman=8562;e.threesuperior=179;e.threethai=3667;e.thzsquare=13204;e.tihiragana=12385;e.tikatakana=12481;e.tikatakanahalfwidth=65409;e.tikeutacirclekorean=12912;e.tikeutaparenkorean=12816;e.tikeutcirclekorean=12898;e.tikeutkorean=12599;e.tikeutparenkorean=12802;e.tilde=732;e.tildebelowcmb=816;e.tildecmb=771;e.tildecomb=771;e.tildedoublecmb=864;e.tildeoperator=8764;e.tildeoverlaycmb=820;e.tildeverticalcmb=830;e.timescircle=8855;e.tipehahebrew=1430;e.tipehalefthebrew=1430;e.tippigurmukhi=2672;e.titlocyrilliccmb=1155;e.tiwnarmenian=1407;e.tlinebelow=7791;e.tmonospace=65364;e.toarmenian=1385;e.tohiragana=12392;e.tokatakana=12488;e.tokatakanahalfwidth=65412;e.tonebarextrahighmod=741;e.tonebarextralowmod=745;e.tonebarhighmod=742;e.tonebarlowmod=744;e.tonebarmidmod=743;e.tonefive=445;e.tonesix=389;e.tonetwo=424;e.tonos=900;e.tonsquare=13095;e.topatakthai=3599;e.tortoiseshellbracketleft=12308;e.tortoiseshellbracketleftsmall=65117;e.tortoiseshellbracketleftvertical=65081;e.tortoiseshellbracketright=12309;e.tortoiseshellbracketrightsmall=65118;e.tortoiseshellbracketrightvertical=65082;e.totaothai=3605;e.tpalatalhook=427;e.tparen=9391;e.trademark=8482;e.trademarksans=63722;e.trademarkserif=63195;e.tretroflexhook=648;e.triagdn=9660;e.triaglf=9668;e.triagrt=9658;e.triagup=9650;e.ts=678;e.tsadi=1510;e.tsadidagesh=64326;e.tsadidageshhebrew=64326;e.tsadihebrew=1510;e.tsecyrillic=1094;e.tsere=1461;e.tsere12=1461;e.tsere1e=1461;e.tsere2b=1461;e.tserehebrew=1461;e.tserenarrowhebrew=1461;e.tserequarterhebrew=1461;e.tserewidehebrew=1461;e.tshecyrillic=1115;e.tsuperior=63219;e.ttabengali=2463;e.ttadeva=2335;e.ttagujarati=2719;e.ttagurmukhi=2591;e.tteharabic=1657;e.ttehfinalarabic=64359;e.ttehinitialarabic=64360;e.ttehmedialarabic=64361;e.tthabengali=2464;e.tthadeva=2336;e.tthagujarati=2720;e.tthagurmukhi=2592;e.tturned=647;e.tuhiragana=12388;e.tukatakana=12484;e.tukatakanahalfwidth=65410;e.tusmallhiragana=12387;e.tusmallkatakana=12483;e.tusmallkatakanahalfwidth=65391;e.twelvecircle=9323;e.twelveparen=9343;e.twelveperiod=9363;e.twelveroman=8571;e.twentycircle=9331;e.twentyhangzhou=21316;e.twentyparen=9351;e.twentyperiod=9371;e.two=50;e.twoarabic=1634;e.twobengali=2536;e.twocircle=9313;e.twocircleinversesansserif=10123;e.twodeva=2408;e.twodotenleader=8229;e.twodotleader=8229;e.twodotleadervertical=65072;e.twogujarati=2792;e.twogurmukhi=2664;e.twohackarabic=1634;e.twohangzhou=12322;e.twoideographicparen=12833;e.twoinferior=8322;e.twomonospace=65298;e.twonumeratorbengali=2549;e.twooldstyle=63282;e.twoparen=9333;e.twoperiod=9353;e.twopersian=1778;e.tworoman=8561;e.twostroke=443;e.twosuperior=178;e.twothai=3666;e.twothirds=8532;e.u=117;e.uacute=250;e.ubar=649;e.ubengali=2441;e.ubopomofo=12584;e.ubreve=365;e.ucaron=468;e.ucircle=9444;e.ucircumflex=251;e.ucircumflexbelow=7799;e.ucyrillic=1091;e.udattadeva=2385;e.udblacute=369;e.udblgrave=533;e.udeva=2313;e.udieresis=252;e.udieresisacute=472;e.udieresisbelow=7795;e.udieresiscaron=474;e.udieresiscyrillic=1265;e.udieresisgrave=476;e.udieresismacron=470;e.udotbelow=7909;e.ugrave=249;e.ugujarati=2697;e.ugurmukhi=2569;e.uhiragana=12358;e.uhookabove=7911;e.uhorn=432;e.uhornacute=7913;e.uhorndotbelow=7921;e.uhorngrave=7915;e.uhornhookabove=7917;e.uhorntilde=7919;e.uhungarumlaut=369;e.uhungarumlautcyrillic=1267;e.uinvertedbreve=535;e.ukatakana=12454;e.ukatakanahalfwidth=65395;e.ukcyrillic=1145;e.ukorean=12636;e.umacron=363;e.umacroncyrillic=1263;e.umacrondieresis=7803;e.umatragurmukhi=2625;e.umonospace=65365;e.underscore=95;e.underscoredbl=8215;e.underscoremonospace=65343;e.underscorevertical=65075;e.underscorewavy=65103;e.union=8746;e.universal=8704;e.uogonek=371;e.uparen=9392;e.upblock=9600;e.upperdothebrew=1476;e.upsilon=965;e.upsilondieresis=971;e.upsilondieresistonos=944;e.upsilonlatin=650;e.upsilontonos=973;e.uptackbelowcmb=797;e.uptackmod=724;e.uragurmukhi=2675;e.uring=367;e.ushortcyrillic=1118;e.usmallhiragana=12357;e.usmallkatakana=12453;e.usmallkatakanahalfwidth=65385;e.ustraightcyrillic=1199;e.ustraightstrokecyrillic=1201;e.utilde=361;e.utildeacute=7801;e.utildebelow=7797;e.uubengali=2442;e.uudeva=2314;e.uugujarati=2698;e.uugurmukhi=2570;e.uumatragurmukhi=2626;e.uuvowelsignbengali=2498;e.uuvowelsigndeva=2370;e.uuvowelsigngujarati=2754;e.uvowelsignbengali=2497;e.uvowelsigndeva=2369;e.uvowelsigngujarati=2753;e.v=118;e.vadeva=2357;e.vagujarati=2741;e.vagurmukhi=2613;e.vakatakana=12535;e.vav=1493;e.vavdagesh=64309;e.vavdagesh65=64309;e.vavdageshhebrew=64309;e.vavhebrew=1493;e.vavholam=64331;e.vavholamhebrew=64331;e.vavvavhebrew=1520;e.vavyodhebrew=1521;e.vcircle=9445;e.vdotbelow=7807;e.vecyrillic=1074;e.veharabic=1700;e.vehfinalarabic=64363;e.vehinitialarabic=64364;e.vehmedialarabic=64365;e.vekatakana=12537;e.venus=9792;e.verticalbar=124;e.verticallineabovecmb=781;e.verticallinebelowcmb=809;e.verticallinelowmod=716;e.verticallinemod=712;e.vewarmenian=1406;e.vhook=651;e.vikatakana=12536;e.viramabengali=2509;e.viramadeva=2381;e.viramagujarati=2765;e.visargabengali=2435;e.visargadeva=2307;e.visargagujarati=2691;e.vmonospace=65366;e.voarmenian=1400;e.voicediterationhiragana=12446;e.voicediterationkatakana=12542;e.voicedmarkkana=12443;e.voicedmarkkanahalfwidth=65438;e.vokatakana=12538;e.vparen=9393;e.vtilde=7805;e.vturned=652;e.vuhiragana=12436;e.vukatakana=12532;e.w=119;e.wacute=7811;e.waekorean=12633;e.wahiragana=12431;e.wakatakana=12527;e.wakatakanahalfwidth=65436;e.wakorean=12632;e.wasmallhiragana=12430;e.wasmallkatakana=12526;e.wattosquare=13143;e.wavedash=12316;e.wavyunderscorevertical=65076;e.wawarabic=1608;e.wawfinalarabic=65262;e.wawhamzaabovearabic=1572;e.wawhamzaabovefinalarabic=65158;e.wbsquare=13277;e.wcircle=9446;e.wcircumflex=373;e.wdieresis=7813;e.wdotaccent=7815;e.wdotbelow=7817;e.wehiragana=12433;e.weierstrass=8472;e.wekatakana=12529;e.wekorean=12638;e.weokorean=12637;e.wgrave=7809;e.whitebullet=9702;e.whitecircle=9675;e.whitecircleinverse=9689;e.whitecornerbracketleft=12302;e.whitecornerbracketleftvertical=65091;e.whitecornerbracketright=12303;e.whitecornerbracketrightvertical=65092;e.whitediamond=9671;e.whitediamondcontainingblacksmalldiamond=9672;e.whitedownpointingsmalltriangle=9663;e.whitedownpointingtriangle=9661;e.whiteleftpointingsmalltriangle=9667;e.whiteleftpointingtriangle=9665;e.whitelenticularbracketleft=12310;e.whitelenticularbracketright=12311;e.whiterightpointingsmalltriangle=9657;e.whiterightpointingtriangle=9655;e.whitesmallsquare=9643;e.whitesmilingface=9786;e.whitesquare=9633;e.whitestar=9734;e.whitetelephone=9743;e.whitetortoiseshellbracketleft=12312;e.whitetortoiseshellbracketright=12313;e.whiteuppointingsmalltriangle=9653;e.whiteuppointingtriangle=9651;e.wihiragana=12432;e.wikatakana=12528;e.wikorean=12639;e.wmonospace=65367;e.wohiragana=12434;e.wokatakana=12530;e.wokatakanahalfwidth=65382;e.won=8361;e.wonmonospace=65510;e.wowaenthai=3623;e.wparen=9394;e.wring=7832;e.wsuperior=695;e.wturned=653;e.wynn=447;e.x=120;e.xabovecmb=829;e.xbopomofo=12562;e.xcircle=9447;e.xdieresis=7821;e.xdotaccent=7819;e.xeharmenian=1389;e.xi=958;e.xmonospace=65368;e.xparen=9395;e.xsuperior=739;e.y=121;e.yaadosquare=13134;e.yabengali=2479;e.yacute=253;e.yadeva=2351;e.yaekorean=12626;e.yagujarati=2735;e.yagurmukhi=2607;e.yahiragana=12420;e.yakatakana=12516;e.yakatakanahalfwidth=65428;e.yakorean=12625;e.yamakkanthai=3662;e.yasmallhiragana=12419;e.yasmallkatakana=12515;e.yasmallkatakanahalfwidth=65388;e.yatcyrillic=1123;e.ycircle=9448;e.ycircumflex=375;e.ydieresis=255;e.ydotaccent=7823;e.ydotbelow=7925;e.yeharabic=1610;e.yehbarreearabic=1746;e.yehbarreefinalarabic=64431;e.yehfinalarabic=65266;e.yehhamzaabovearabic=1574;e.yehhamzaabovefinalarabic=65162;e.yehhamzaaboveinitialarabic=65163;e.yehhamzaabovemedialarabic=65164;e.yehinitialarabic=65267;e.yehmedialarabic=65268;e.yehmeeminitialarabic=64733;e.yehmeemisolatedarabic=64600;e.yehnoonfinalarabic=64660;e.yehthreedotsbelowarabic=1745;e.yekorean=12630;e.yen=165;e.yenmonospace=65509;e.yeokorean=12629;e.yeorinhieuhkorean=12678;e.yerahbenyomohebrew=1450;e.yerahbenyomolefthebrew=1450;e.yericyrillic=1099;e.yerudieresiscyrillic=1273;e.yesieungkorean=12673;e.yesieungpansioskorean=12675;e.yesieungsioskorean=12674;e.yetivhebrew=1434;e.ygrave=7923;e.yhook=436;e.yhookabove=7927;e.yiarmenian=1397;e.yicyrillic=1111;e.yikorean=12642;e.yinyang=9775;e.yiwnarmenian=1410;e.ymonospace=65369;e.yod=1497;e.yoddagesh=64313;e.yoddageshhebrew=64313;e.yodhebrew=1497;e.yodyodhebrew=1522;e.yodyodpatahhebrew=64287;e.yohiragana=12424;e.yoikorean=12681;e.yokatakana=12520;e.yokatakanahalfwidth=65430;e.yokorean=12635;e.yosmallhiragana=12423;e.yosmallkatakana=12519;e.yosmallkatakanahalfwidth=65390;e.yotgreek=1011;e.yoyaekorean=12680;e.yoyakorean=12679;e.yoyakthai=3618;e.yoyingthai=3597;e.yparen=9396;e.ypogegrammeni=890;e.ypogegrammenigreekcmb=837;e.yr=422;e.yring=7833;e.ysuperior=696;e.ytilde=7929;e.yturned=654;e.yuhiragana=12422;e.yuikorean=12684;e.yukatakana=12518;e.yukatakanahalfwidth=65429;e.yukorean=12640;e.yusbigcyrillic=1131;e.yusbigiotifiedcyrillic=1133;e.yuslittlecyrillic=1127;e.yuslittleiotifiedcyrillic=1129;e.yusmallhiragana=12421;e.yusmallkatakana=12517;e.yusmallkatakanahalfwidth=65389;e.yuyekorean=12683;e.yuyeokorean=12682;e.yyabengali=2527;e.yyadeva=2399;e.z=122;e.zaarmenian=1382;e.zacute=378;e.zadeva=2395;e.zagurmukhi=2651;e.zaharabic=1592;e.zahfinalarabic=65222;e.zahinitialarabic=65223;e.zahiragana=12374;e.zahmedialarabic=65224;e.zainarabic=1586;e.zainfinalarabic=65200;e.zakatakana=12470;e.zaqefgadolhebrew=1429;e.zaqefqatanhebrew=1428;e.zarqahebrew=1432;e.zayin=1494;e.zayindagesh=64310;e.zayindageshhebrew=64310;e.zayinhebrew=1494;e.zbopomofo=12567;e.zcaron=382;e.zcircle=9449;e.zcircumflex=7825;e.zcurl=657;e.zdot=380;e.zdotaccent=380;e.zdotbelow=7827;e.zecyrillic=1079;e.zedescendercyrillic=1177;e.zedieresiscyrillic=1247;e.zehiragana=12380;e.zekatakana=12476;e.zero=48;e.zeroarabic=1632;e.zerobengali=2534;e.zerodeva=2406;e.zerogujarati=2790;e.zerogurmukhi=2662;e.zerohackarabic=1632;e.zeroinferior=8320;e.zeromonospace=65296;e.zerooldstyle=63280;e.zeropersian=1776;e.zerosuperior=8304;e.zerothai=3664;e.zerowidthjoiner=65279;e.zerowidthnonjoiner=8204;e.zerowidthspace=8203;e.zeta=950;e.zhbopomofo=12563;e.zhearmenian=1386;e.zhebrevecyrillic=1218;e.zhecyrillic=1078;e.zhedescendercyrillic=1175;e.zhedieresiscyrillic=1245;e.zihiragana=12376;e.zikatakana=12472;e.zinorhebrew=1454;e.zlinebelow=7829;e.zmonospace=65370;e.zohiragana=12382;e.zokatakana=12478;e.zparen=9397;e.zretroflexhook=656;e.zstroke=438;e.zuhiragana=12378;e.zukatakana=12474;e[".notdef"]=0;e.angbracketleftbig=9001;e.angbracketleftBig=9001;e.angbracketleftbigg=9001;e.angbracketleftBigg=9001;e.angbracketrightBig=9002;e.angbracketrightbig=9002;e.angbracketrightBigg=9002;e.angbracketrightbigg=9002;e.arrowhookleft=8618;e.arrowhookright=8617;e.arrowlefttophalf=8636;e.arrowleftbothalf=8637;e.arrownortheast=8599;e.arrownorthwest=8598;e.arrowrighttophalf=8640;e.arrowrightbothalf=8641;e.arrowsoutheast=8600;e.arrowsouthwest=8601;e.backslashbig=8726;e.backslashBig=8726;e.backslashBigg=8726;e.backslashbigg=8726;e.bardbl=8214;e.bracehtipdownleft=65079;e.bracehtipdownright=65079;e.bracehtipupleft=65080;e.bracehtipupright=65080;e.braceleftBig=123;e.braceleftbig=123;e.braceleftbigg=123;e.braceleftBigg=123;e.bracerightBig=125;e.bracerightbig=125;e.bracerightbigg=125;e.bracerightBigg=125;e.bracketleftbig=91;e.bracketleftBig=91;e.bracketleftbigg=91;e.bracketleftBigg=91;e.bracketrightBig=93;e.bracketrightbig=93;e.bracketrightbigg=93;e.bracketrightBigg=93;e.ceilingleftbig=8968;e.ceilingleftBig=8968;e.ceilingleftBigg=8968;e.ceilingleftbigg=8968;e.ceilingrightbig=8969;e.ceilingrightBig=8969;e.ceilingrightbigg=8969;e.ceilingrightBigg=8969;e.circledotdisplay=8857;e.circledottext=8857;e.circlemultiplydisplay=8855;e.circlemultiplytext=8855;e.circleplusdisplay=8853;e.circleplustext=8853;e.contintegraldisplay=8750;e.contintegraltext=8750;e.coproductdisplay=8720;e.coproducttext=8720;e.floorleftBig=8970;e.floorleftbig=8970;e.floorleftbigg=8970;e.floorleftBigg=8970;e.floorrightbig=8971;e.floorrightBig=8971;e.floorrightBigg=8971;e.floorrightbigg=8971;e.hatwide=770;e.hatwider=770;e.hatwidest=770;e.intercal=7488;e.integraldisplay=8747;e.integraltext=8747;e.intersectiondisplay=8898;e.intersectiontext=8898;e.logicalanddisplay=8743;e.logicalandtext=8743;e.logicalordisplay=8744;e.logicalortext=8744;e.parenleftBig=40;e.parenleftbig=40;e.parenleftBigg=40;e.parenleftbigg=40;e.parenrightBig=41;e.parenrightbig=41;e.parenrightBigg=41;e.parenrightbigg=41;e.prime=8242;e.productdisplay=8719;e.producttext=8719;e.radicalbig=8730;e.radicalBig=8730;e.radicalBigg=8730;e.radicalbigg=8730;e.radicalbt=8730;e.radicaltp=8730;e.radicalvertex=8730;e.slashbig=47;e.slashBig=47;e.slashBigg=47;e.slashbigg=47;e.summationdisplay=8721;e.summationtext=8721;e.tildewide=732;e.tildewider=732;e.tildewidest=732;e.uniondisplay=8899;e.unionmultidisplay=8846;e.unionmultitext=8846;e.unionsqdisplay=8852;e.unionsqtext=8852;e.uniontext=8899;e.vextenddouble=8741;e.vextendsingle=8739}),gr=getLookupTableFactory(function(e){e.space=32;e.a1=9985;e.a2=9986;e.a202=9987;e.a3=9988;e.a4=9742;e.a5=9990;e.a119=9991;e.a118=9992;e.a117=9993;e.a11=9755;e.a12=9758;e.a13=9996;e.a14=9997;e.a15=9998;e.a16=9999;e.a105=1e4;e.a17=10001;e.a18=10002;e.a19=10003;e.a20=10004;e.a21=10005;e.a22=10006;e.a23=10007;e.a24=10008;e.a25=10009;e.a26=10010;e.a27=10011;e.a28=10012;e.a6=10013;e.a7=10014;e.a8=10015;e.a9=10016;e.a10=10017;e.a29=10018;e.a30=10019;e.a31=10020;e.a32=10021;e.a33=10022;e.a34=10023;e.a35=9733;e.a36=10025;e.a37=10026;e.a38=10027;e.a39=10028;e.a40=10029;e.a41=10030;e.a42=10031;e.a43=10032;e.a44=10033;e.a45=10034;e.a46=10035;e.a47=10036;e.a48=10037;e.a49=10038;e.a50=10039;e.a51=10040;e.a52=10041;e.a53=10042;e.a54=10043;e.a55=10044;e.a56=10045;e.a57=10046;e.a58=10047;e.a59=10048;e.a60=10049;e.a61=10050;e.a62=10051;e.a63=10052;e.a64=10053;e.a65=10054;e.a66=10055;e.a67=10056;e.a68=10057;e.a69=10058;e.a70=10059;e.a71=9679;e.a72=10061;e.a73=9632;e.a74=10063;e.a203=10064;e.a75=10065;e.a204=10066;e.a76=9650;e.a77=9660;e.a78=9670;e.a79=10070;e.a81=9687;e.a82=10072;e.a83=10073;e.a84=10074;e.a97=10075;e.a98=10076;e.a99=10077;e.a100=10078;e.a101=10081;e.a102=10082;e.a103=10083;e.a104=10084;e.a106=10085;e.a107=10086;e.a108=10087;e.a112=9827;e.a111=9830;e.a110=9829;e.a109=9824;e.a120=9312;e.a121=9313;e.a122=9314;e.a123=9315;e.a124=9316;e.a125=9317;e.a126=9318;e.a127=9319;e.a128=9320;e.a129=9321;e.a130=10102;e.a131=10103;e.a132=10104;e.a133=10105;e.a134=10106;e.a135=10107;e.a136=10108;e.a137=10109;e.a138=10110;e.a139=10111;e.a140=10112;e.a141=10113;e.a142=10114;e.a143=10115;e.a144=10116;e.a145=10117;e.a146=10118;e.a147=10119;e.a148=10120;e.a149=10121;e.a150=10122;e.a151=10123;e.a152=10124;e.a153=10125;e.a154=10126;e.a155=10127;e.a156=10128;e.a157=10129;e.a158=10130;e.a159=10131;e.a160=10132;e.a161=8594;e.a163=8596;e.a164=8597;e.a196=10136;e.a165=10137;e.a192=10138;e.a166=10139;e.a167=10140;e.a168=10141;e.a169=10142;e.a170=10143;e.a171=10144;e.a172=10145;e.a173=10146;e.a162=10147;e.a174=10148;e.a175=10149;e.a176=10150;e.a177=10151;e.a178=10152;e.a179=10153;e.a193=10154;e.a180=10155;e.a199=10156;e.a181=10157;e.a200=10158;e.a182=10159;e.a201=10161;e.a183=10162;e.a184=10163;e.a197=10164;e.a185=10165;e.a194=10166;e.a198=10167;e.a186=10168;e.a195=10169;e.a187=10170;e.a188=10171;e.a189=10172;e.a190=10173;e.a191=10174;e.a89=10088;e.a90=10089;e.a93=10090;e.a94=10091;e.a91=10092;e.a92=10093;e.a205=10094;e.a85=10095;e.a206=10096;e.a86=10097;e.a87=10098;e.a88=10099;e.a95=10100;e.a96=10101;e[".notdef"]=0}),pr=getLookupTableFactory(function(e){e[63721]=169;e[63193]=169;e[63720]=174;e[63194]=174;e[63722]=8482;e[63195]=8482;e[63729]=9127;e[63730]=9128;e[63731]=9129;e[63740]=9131;e[63741]=9132;e[63742]=9133;e[63726]=9121;e[63727]=9122;e[63728]=9123;e[63737]=9124;e[63738]=9125;e[63739]=9126;e[63723]=9115;e[63724]=9116;e[63725]=9117;e[63734]=9118;e[63735]=9119;e[63736]=9120});function getUnicodeForGlyph(e,t){let a=t[e];if(void 0!==a)return a;if(!e)return-1;if("u"===e[0]){const t=e.length;let r;if(7===t&&"n"===e[1]&&"i"===e[2])r=e.substring(3);else{if(!(t>=5&&t<=7))return-1;r=e.substring(1)}if(r===r.toUpperCase()){a=parseInt(r,16);if(a>=0)return a}}return-1}const mr=[[0,127],[128,255],[256,383],[384,591],[592,687,7424,7551,7552,7615],[688,767,42752,42783],[768,879,7616,7679],[880,1023],[11392,11519],[1024,1279,1280,1327,11744,11775,42560,42655],[1328,1423],[1424,1535],[42240,42559],[1536,1791,1872,1919],[1984,2047],[2304,2431],[2432,2559],[2560,2687],[2688,2815],[2816,2943],[2944,3071],[3072,3199],[3200,3327],[3328,3455],[3584,3711],[3712,3839],[4256,4351,11520,11567],[6912,7039],[4352,4607],[7680,7935,11360,11391,42784,43007],[7936,8191],[8192,8303,11776,11903],[8304,8351],[8352,8399],[8400,8447],[8448,8527],[8528,8591],[8592,8703,10224,10239,10496,10623,11008,11263],[8704,8959,10752,11007,10176,10223,10624,10751],[8960,9215],[9216,9279],[9280,9311],[9312,9471],[9472,9599],[9600,9631],[9632,9727],[9728,9983],[9984,10175],[12288,12351],[12352,12447],[12448,12543,12784,12799],[12544,12591,12704,12735],[12592,12687],[43072,43135],[12800,13055],[13056,13311],[44032,55215],[55296,57343],[67840,67871],[19968,40959,11904,12031,12032,12255,12272,12287,13312,19903,131072,173791,12688,12703],[57344,63743],[12736,12783,63744,64255,194560,195103],[64256,64335],[64336,65023],[65056,65071],[65040,65055],[65104,65135],[65136,65279],[65280,65519],[65520,65535],[3840,4095],[1792,1871],[1920,1983],[3456,3583],[4096,4255],[4608,4991,4992,5023,11648,11743],[5024,5119],[5120,5759],[5760,5791],[5792,5887],[6016,6143],[6144,6319],[10240,10495],[40960,42127],[5888,5919,5920,5951,5952,5983,5984,6015],[66304,66351],[66352,66383],[66560,66639],[118784,119039,119040,119295,119296,119375],[119808,120831],[1044480,1048573],[65024,65039,917760,917999],[917504,917631],[6400,6479],[6480,6527],[6528,6623],[6656,6687],[11264,11359],[11568,11647],[19904,19967],[43008,43055],[65536,65663,65664,65791,65792,65855],[65856,65935],[66432,66463],[66464,66527],[66640,66687],[66688,66735],[67584,67647],[68096,68191],[119552,119647],[73728,74751,74752,74879],[119648,119679],[7040,7103],[7168,7247],[7248,7295],[43136,43231],[43264,43311],[43312,43359],[43520,43615],[65936,65999],[66e3,66047],[66208,66271,66176,66207,67872,67903],[127024,127135,126976,127023]];function getUnicodeRangeFor(e,t=-1){if(-1!==t){const a=mr[t];for(let r=0,i=a.length;r=a[r]&&e<=a[r+1])return t}for(let t=0,a=mr.length;t=a[r]&&e<=a[r+1])return t}return-1}const br=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),yr=new Map;const wr=!0,xr=1,Sr=2,Ar=4,kr=32,Cr=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(e,t){if(void 0!==t[e])return e;const a=getUnicodeForGlyph(e,t);if(-1!==a)for(const e in t)if(t[e]===a)return e;info("Unable to recover a standard glyph name for: "+e);return e}function type1FontGlyphMapping(e,t,a){const r=Object.create(null);let i,n,s;const o=!!(e.flags&Ar);if(e.isInternalFont){s=t;for(n=0;n=0?i:0}}else if(e.baseEncodingName){s=getEncoding(e.baseEncodingName);for(n=0;n=0?i:0}}else if(o)for(n in t)r[n]=t[n];else{s=lr;for(n=0;n=0?i:0}}const c=e.differences;let l;if(c)for(n in c){const e=c[n];i=a.indexOf(e);if(-1===i){l||(l=fr());const t=recoverGlyphName(e,l);t!==e&&(i=a.indexOf(t))}r[n]=i>=0?i:0}return r}function normalizeFontName(e){return e.replaceAll(/[,_]/g,"-").replaceAll(/\s/g,"")}const vr=getLookupTableFactory(e=>{e[8211]=65074;e[8212]=65073;e[8229]=65072;e[8230]=65049;e[12289]=65041;e[12290]=65042;e[12296]=65087;e[12297]=65088;e[12298]=65085;e[12299]=65086;e[12300]=65089;e[12301]=65090;e[12302]=65091;e[12303]=65092;e[12304]=65083;e[12305]=65084;e[12308]=65081;e[12309]=65082;e[12310]=65047;e[12311]=65048;e[65103]=65076;e[65281]=65045;e[65288]=65077;e[65289]=65078;e[65292]=65040;e[65306]=65043;e[65307]=65044;e[65311]=65046;e[65339]=65095;e[65341]=65096;e[65343]=65075;e[65371]=65079;e[65373]=65080});const Fr=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],Ir=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],Tr=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],Or=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],Mr=391,Dr=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],Rr=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]+e[t-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]-e[t-1]}},{id:"div",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]/e[t-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(e,t){e[t-1]=-e[t-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(e,t){e[t-2]=e[t-2]*e[t-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(e,t,a){this.bytes=e.getBytes();this.properties=t;this.seacAnalysisEnabled=!!a}parse(){const e=this.properties,t=new CFF;this.cff=t;const a=this.parseHeader(),r=this.parseIndex(a.endPos),i=this.parseIndex(r.endPos),n=this.parseIndex(i.endPos),s=this.parseIndex(n.endPos),o=this.parseDict(i.obj.get(0)),c=this.createDict(CFFTopDict,o,t.strings);t.header=a.obj;t.names=this.parseNameIndex(r.obj);t.strings=this.parseStringIndex(n.obj);t.topDict=c;t.globalSubrIndex=s.obj;this.parsePrivateDict(t.topDict);t.isCIDFont=c.hasName("ROS");const l=c.getByName("CharStrings"),h=this.parseIndex(l).obj,u=c.getByName("FontMatrix");u&&(e.fontMatrix=u);const d=c.getByName("FontBBox");if(d){e.ascent=Math.max(d[3],d[1]);e.descent=Math.min(d[1],d[3]);e.ascentScaled=!0}let f,g;if(t.isCIDFont){const e=this.parseIndex(c.getByName("FDArray")).obj;for(let a=0,r=e.count;a=t)throw new FormatError("Invalid CFF header");if(0!==a){info("cff data is shifted");e=e.subarray(a);this.bytes=e}const r=e[0],i=e[1],n=e[2],s=e[3];return{obj:new CFFHeader(r,i,n,s),endPos:n}}parseDict(e){let t=0;function parseOperand(){let a=e[t++];if(30===a)return function parseFloatOperand(){let a="";const r=15,i=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],n=e.length;for(;t>4,o=15&n;if(s===r)break;a+=i[s];if(o===r)break;a+=i[o]}return parseFloat(a)}();if(28===a){a=readInt16(e,t);t+=2;return a}if(29===a){a=e[t++];a=a<<8|e[t++];a=a<<8|e[t++];a=a<<8|e[t++];return a}if(a>=32&&a<=246)return a-139;if(a>=247&&a<=250)return 256*(a-247)+e[t++]+108;if(a>=251&&a<=254)return-256*(a-251)-e[t++]-108;warn('CFFParser_parseDict: "'+a+'" is a reserved command.');return NaN}let a=[];const r=[];t=0;const i=e.length;for(;t10)return!1;let i=e.stackSize;const n=e.stack;let s=t.length;for(let o=0;o=4){i-=4;if(this.seacAnalysisEnabled){e.seac=n.slice(i,i+4);return!1}}l=Dr[c]}else if(c>=32&&c<=246){n[i]=c-139;i++}else if(c>=247&&c<=254){n[i]=c<251?(c-247<<8)+t[o]+108:-(c-251<<8)-t[o]-108;o++;i++}else if(255===c){n[i]=(t[o]<<24|t[o+1]<<16|t[o+2]<<8|t[o+3])/65536;o+=4;i++}else if(19===c||20===c){e.hints+=i>>1;if(0===e.hints){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}o+=e.hints+7>>3;i%=2;l=Dr[c]}else{if(10===c||29===c){const t=10===c?a:r;if(!t){l=Dr[c];warn("Missing subrsIndex for "+l.id);return!1}let s=32768;t.count<1240?s=107:t.count<33900&&(s=1131);const o=n[--i]+s;if(o<0||o>=t.count||isNaN(o)){l=Dr[c];warn("Out of bounds subrIndex for "+l.id);return!1}e.stackSize=i;e.callDepth++;if(!this.parseCharString(e,t.get(o),a,r))return!1;e.callDepth--;i=e.stackSize;continue}if(11===c){e.stackSize=i;return!0}if(0===c&&o===t.length){t[o-1]=14;l=Dr[14]}else{if(9===c){t.copyWithin(o-1,o,-1);o-=1;s-=1;continue}l=Dr[c]}}if(l){if(l.stem){e.hints+=i>>1;if(3===c||23===c)e.hasVStems=!0;else if(e.hasVStems&&(1===c||18===c)){warn("CFF stem hints are in wrong order");t[o-1]=1===c?3:23}}if("min"in l&&!e.undefStack&&i=2&&l.stem?i%=2:i>1&&warn("Found too many parameters for stack-clearing command");i>0&&(e.width=n[i-1])}if("stackDelta"in l){"stackFn"in l&&l.stackFn(n,i);i+=l.stackDelta}else if(l.stackClearing)i=0;else if(l.resetStack){i=0;e.undefStack=!1}else if(l.undefStack){i=0;e.undefStack=!0;e.firstStackClearing=!1}}}s=i.length){warn("Invalid fd index for glyph index.");u=!1}if(u){f=i[e].privateDict;d=f.subrsIndex}}else t&&(d=t);u&&(u=this.parseCharString(h,c,d,a));if(null!==h.width){const e=f.getByName("nominalWidthX");o[l]=e+h.width}else{const e=f.getByName("defaultWidthX");o[l]=e}null!==h.seac&&(s[l]=h.seac);u||e.set(l,new Uint8Array([14]))}return{charStrings:e,seacs:s,widths:o}}emptyPrivateDictionary(e){const t=this.createDict(CFFPrivateDict,[],e.strings);e.setByKey(18,[0,0]);e.privateDict=t}parsePrivateDict(e){if(!e.hasName("Private")){this.emptyPrivateDictionary(e);return}const t=e.getByName("Private");if(!Array.isArray(t)||2!==t.length){e.removeByName("Private");return}const a=t[0],r=t[1];if(0===a||r>=this.bytes.length){this.emptyPrivateDictionary(e);return}const i=r+a,n=this.bytes.subarray(r,i),s=this.parseDict(n),o=this.createDict(CFFPrivateDict,s,e.strings);e.privateDict=o;0===o.getByName("ExpansionFactor")&&o.setByName("ExpansionFactor",.06);if(!o.getByName("Subrs"))return;const c=o.getByName("Subrs"),l=r+c;if(0===c||l>=this.bytes.length){this.emptyPrivateDictionary(e);return}const h=this.parseIndex(l);o.subrsIndex=h.obj}parseCharsets(e,t,a,r){if(0===e)return new CFFCharset(!0,Pr.ISO_ADOBE,Fr);if(1===e)return new CFFCharset(!0,Pr.EXPERT,Ir);if(2===e)return new CFFCharset(!0,Pr.EXPERT_SUBSET,Tr);const i=this.bytes,n=e,s=i[e++],o=[r?0:".notdef"];let c,l,h;t-=1;switch(s){case 0:for(h=0;h=65535){warn("Not enough space in charstrings to duplicate first glyph.");return}const e=this.charStrings.get(0);this.charStrings.add(e);this.isCIDFont&&this.fdSelect.fdSelect.push(this.fdSelect.fdSelect[0])}hasGlyphId(e){if(e<0||e>=this.charStrings.count)return!1;return this.charStrings.get(e).length>0}}class CFFHeader{constructor(e,t,a,r){this.major=e;this.minor=t;this.hdrSize=a;this.offSize=r}}class CFFStrings{constructor(){this.strings=[]}get(e){return e>=0&&e<=390?Or[e]:e-Mr<=this.strings.length?this.strings[e-Mr]:Or[0]}getSID(e){let t=Or.indexOf(e);if(-1!==t)return t;t=this.strings.indexOf(e);return-1!==t?t+Mr:-1}add(e){this.strings.push(e)}get count(){return this.strings.length}}class CFFIndex{constructor(){this.objects=[];this.length=0}add(e){this.length+=e.length;this.objects.push(e)}set(e,t){this.length+=t.length-this.objects[e].length;this.objects[e]=t}get(e){return this.objects[e]}get count(){return this.objects.length}}class CFFDict{constructor(e,t){this.keyToNameMap=e.keyToNameMap;this.nameToKeyMap=e.nameToKeyMap;this.defaults=e.defaults;this.types=e.types;this.opcodes=e.opcodes;this.order=e.order;this.strings=t;this.values=Object.create(null)}setByKey(e,t){if(!(e in this.keyToNameMap))return!1;if(0===t.length)return!0;for(const a of t)if(isNaN(a)){warn(`Invalid CFFDict value: "${t}" for key "${e}".`);return!0}const a=this.types[e];"num"!==a&&"sid"!==a&&"offset"!==a||(t=t[0]);this.values[e]=t;return!0}setByName(e,t){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name "${e}"`);this.values[this.nameToKeyMap[e]]=t}hasName(e){return this.nameToKeyMap[e]in this.values}getByName(e){if(!(e in this.nameToKeyMap))throw new FormatError(`Invalid dictionary name ${e}"`);const t=this.nameToKeyMap[e];return t in this.values?this.values[t]:this.defaults[t]}removeByName(e){delete this.values[this.nameToKeyMap[e]]}static createTables(e){const t={keyToNameMap:{},nameToKeyMap:{},defaults:{},types:{},opcodes:{},order:[]};for(const a of e){const e=Array.isArray(a[0])?(a[0][0]<<8)+a[0][1]:a[0];t.keyToNameMap[e]=a[1];t.nameToKeyMap[a[1]]=e;t.types[e]=a[2];t.defaults[e]=a[3];t.opcodes[e]=Array.isArray(a[0])?a[0]:[a[0]];t.order.push(e)}return t}}const Nr=[[[12,30],"ROS",["sid","sid","num"],null],[[12,20],"SyntheticBase","num",null],[0,"version","sid",null],[1,"Notice","sid",null],[[12,0],"Copyright","sid",null],[2,"FullName","sid",null],[3,"FamilyName","sid",null],[4,"Weight","sid",null],[[12,1],"isFixedPitch","num",0],[[12,2],"ItalicAngle","num",0],[[12,3],"UnderlinePosition","num",-100],[[12,4],"UnderlineThickness","num",50],[[12,5],"PaintType","num",0],[[12,6],"CharstringType","num",2],[[12,7],"FontMatrix",["num","num","num","num","num","num"],[.001,0,0,.001,0,0]],[13,"UniqueID","num",null],[5,"FontBBox",["num","num","num","num"],[0,0,0,0]],[[12,8],"StrokeWidth","num",0],[14,"XUID","array",null],[15,"charset","offset",0],[16,"Encoding","offset",0],[17,"CharStrings","offset",0],[18,"Private",["offset","offset"],null],[[12,21],"PostScript","sid",null],[[12,22],"BaseFontName","sid",null],[[12,23],"BaseFontBlend","delta",null],[[12,31],"CIDFontVersion","num",0],[[12,32],"CIDFontRevision","num",0],[[12,33],"CIDFontType","num",0],[[12,34],"CIDCount","num",8720],[[12,35],"UIDBase","num",null],[[12,37],"FDSelect","offset",null],[[12,36],"FDArray","offset",null],[[12,38],"FontName","sid",null]];class CFFTopDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(Nr))}constructor(e){super(CFFTopDict.tables,e);this.privateDict=null}}const Er=[[6,"BlueValues","delta",null],[7,"OtherBlues","delta",null],[8,"FamilyBlues","delta",null],[9,"FamilyOtherBlues","delta",null],[[12,9],"BlueScale","num",.039625],[[12,10],"BlueShift","num",7],[[12,11],"BlueFuzz","num",1],[10,"StdHW","num",null],[11,"StdVW","num",null],[[12,12],"StemSnapH","delta",null],[[12,13],"StemSnapV","delta",null],[[12,14],"ForceBold","num",0],[[12,17],"LanguageGroup","num",0],[[12,18],"ExpansionFactor","num",.06],[[12,19],"initialRandomSeed","num",0],[20,"defaultWidthX","num",0],[21,"nominalWidthX","num",0],[19,"Subrs","offset",null]];class CFFPrivateDict extends CFFDict{static get tables(){return shadow(this,"tables",this.createTables(Er))}constructor(e){super(CFFPrivateDict.tables,e);this.subrsIndex=null}}const Pr={ISO_ADOBE:0,EXPERT:1,EXPERT_SUBSET:2};class CFFCharset{constructor(e,t,a,r){this.predefined=e;this.format=t;this.charset=a;this.raw=r}}class CFFEncoding{constructor(e,t,a,r){this.predefined=e;this.format=t;this.encoding=a;this.raw=r}}class CFFFDSelect{constructor(e,t){this.format=e;this.fdSelect=t}getFDIndex(e){return e<0||e>=this.fdSelect.length?-1:this.fdSelect[e]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(e){return e in this.offsets}track(e,t){if(e in this.offsets)throw new FormatError(`Already tracking location of ${e}`);this.offsets[e]=t}offset(e){for(const t in this.offsets)this.offsets[t]+=e}setEntryLocation(e,t,a){if(!(e in this.offsets))throw new FormatError(`Not tracking location of ${e}`);const r=a.data,i=this.offsets[e];for(let e=0,a=t.length;e>24&255;r[s]=l>>16&255;r[o]=l>>8&255;r[c]=255&l}}}class CFFCompiler{constructor(e){this.cff=e}compile(){const e=this.cff,t={data:[],length:0,add(e){try{this.data.push(...e)}catch{this.data=this.data.concat(e)}this.length=this.data.length}},a=this.compileHeader(e.header);t.add(a);const r=this.compileNameIndex(e.names);t.add(r);if(e.isCIDFont&&e.topDict.hasName("FontMatrix")){const t=e.topDict.getByName("FontMatrix");e.topDict.removeByName("FontMatrix");for(const a of e.fdArray){let e=t.slice(0);a.hasName("FontMatrix")&&(e=Util.transform(e,a.getByName("FontMatrix")));a.setByName("FontMatrix",e)}}const i=e.topDict.getByName("XUID");i?.length>16&&e.topDict.removeByName("XUID");e.topDict.setByName("charset",0);let n=this.compileTopDicts([e.topDict],t.length,e.isCIDFont);t.add(n.output);const s=n.trackers[0],o=this.compileStringIndex(e.strings.strings);t.add(o);const c=this.compileIndex(e.globalSubrIndex);t.add(c);if(e.encoding&&e.topDict.hasName("Encoding"))if(e.encoding.predefined)s.setEntryLocation("Encoding",[e.encoding.format],t);else{const a=this.compileEncoding(e.encoding);s.setEntryLocation("Encoding",[t.length],t);t.add(a)}const l=this.compileCharset(e.charset,e.charStrings.count,e.strings,e.isCIDFont);s.setEntryLocation("charset",[t.length],t);t.add(l);const h=this.compileCharStrings(e.charStrings);s.setEntryLocation("CharStrings",[t.length],t);t.add(h);if(e.isCIDFont){s.setEntryLocation("FDSelect",[t.length],t);const a=this.compileFDSelect(e.fdSelect);t.add(a);n=this.compileTopDicts(e.fdArray,t.length,!0);s.setEntryLocation("FDArray",[t.length],t);t.add(n.output);const r=n.trackers;this.compilePrivateDicts(e.fdArray,r,t)}this.compilePrivateDicts([e.topDict],[s],t);t.add([0]);return t.data}encodeNumber(e){return Number.isInteger(e)?this.encodeInteger(e):this.encodeFloat(e)}static get EncodeFloatRegExp(){return shadow(this,"EncodeFloatRegExp",/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/)}encodeFloat(e){let t=e.toString();const a=CFFCompiler.EncodeFloatRegExp.exec(t);if(a){const r=parseFloat("1e"+((a[2]?+a[2]:0)+a[1].length));t=(Math.round(e*r)/r).toString()}let r,i,n="";for(r=0,i=t.length;r=-107&&e<=107?[e+139]:e>=108&&e<=1131?[247+((e-=108)>>8),255&e]:e>=-1131&&e<=-108?[251+((e=-e-108)>>8),255&e]:e>=-32768&&e<=32767?[28,e>>8&255,255&e]:[29,e>>24&255,e>>16&255,e>>8&255,255&e];return t}compileHeader(e){return[e.major,e.minor,4,e.offSize]}compileNameIndex(e){const t=new CFFIndex;for(const a of e){const e=Math.min(a.length,127);let r=new Array(e);for(let t=0;t"~"||"["===e||"]"===e||"("===e||")"===e||"{"===e||"}"===e||"<"===e||">"===e||"/"===e||"%"===e)&&(e="_");r[t]=e}r=r.join("");""===r&&(r="Bad_Font_Name");t.add(stringToBytes(r))}return this.compileIndex(t)}compileTopDicts(e,t,a){const r=[];let i=new CFFIndex;for(const n of e){if(a){n.removeByName("CIDFontVersion");n.removeByName("CIDFontRevision");n.removeByName("CIDFontType");n.removeByName("CIDCount");n.removeByName("UIDBase")}const e=new CFFOffsetTracker,s=this.compileDict(n,e);r.push(e);i.add(s);e.offset(t)}i=this.compileIndex(i,r);return{trackers:r,output:i}}compilePrivateDicts(e,t,a){for(let r=0,i=e.length;r>8&255,255&e])}else{i=new Uint8Array(1+2*n);i[0]=0;let t=0;const r=e.charset.length;let s=!1;for(let n=1;n>8&255;i[n+1]=255&o}}return this.compileTypedArray(i)}compileEncoding(e){return this.compileTypedArray(e.raw)}compileFDSelect(e){const t=e.format;let a,r;switch(t){case 0:a=new Uint8Array(1+e.fdSelect.length);a[0]=t;for(r=0;r>8&255,255&i,n];for(r=1;r>8&255,255&r,t);n=t}}const o=(s.length-3)/3;s[1]=o>>8&255;s[2]=255&o;s.push(r>>8&255,255&r);a=new Uint8Array(s)}return this.compileTypedArray(a)}compileTypedArray(e){return Array.from(e)}compileIndex(e,t=[]){const a=e.objects,r=a.length;if(0===r)return[0,0];const i=[r>>8&255,255&r];let n,s,o=1;for(n=0;n>8&255,255&c):3===s?i.push(c>>16&255,c>>8&255,255&c):i.push(c>>>24&255,c>>16&255,c>>8&255,255&c);a[n]&&(c+=a[n].length)}for(n=0;n=this.firstChar&&e<=this.lastChar?e:-1}amend(e){unreachable("Should not call amend()")}}class CFFFont{constructor(e,t){this.properties=t;const a=new CFFParser(e,t,wr);this.cff=a.parse();this.cff.duplicateFirstGlyph();const r=new CFFCompiler(this.cff);this.seacs=this.cff.seacs;try{this.data=r.compile()}catch{warn("Failed to compile font "+t.loadedName);this.data=e}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){const e=this.cff,t=this.properties,{cidToGidMap:a,cMap:r}=t,i=e.charset.charset;let n,s;if(t.composite){let t,o;if(a?.length>0){t=Object.create(null);for(let e=0,r=a.length;e=0){const r=a[t];r&&(i[e]=r)}}i.length>0&&(this.properties.builtInEncoding=i)}}function getFloat214(e,t){return readInt16(e,t)/16384}function getSubroutineBias(e){const t=e.length;let a=32768;t<1240?a=107:t<33900&&(a=1131);return a}function parseCmap(e,t,a){const r=1===readUint16(e,t+2)?readUint32(e,t+8):readUint32(e,t+16),i=readUint16(e,t+r);let n,s,o;if(4===i){readUint16(e,t+r+2);const a=readUint16(e,t+r+6)>>1;s=t+r+14;n=[];for(o=0;o>1;a0;)h.push({flags:n})}for(a=0;a>1;y=!0;break;case 4:s+=i.pop();moveTo(n,s);y=!0;break;case 5:for(;i.length>0;){n+=i.shift();s+=i.shift();lineTo(n,s)}break;case 6:for(;i.length>0;){n+=i.shift();lineTo(n,s);if(0===i.length)break;s+=i.shift();lineTo(n,s)}break;case 7:for(;i.length>0;){s+=i.shift();lineTo(n,s);if(0===i.length)break;n+=i.shift();lineTo(n,s)}break;case 8:for(;i.length>0;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 10:m=i.pop();b=null;if(a.isCFFCIDFont){const e=a.fdSelect.getFDIndex(r);if(e>=0&&eMath.abs(s-t)?n+=i.shift():s+=i.shift();bezierCurveTo(l,u,h,d,n,s);break;default:throw new FormatError(`unknown operator: 12 ${w}`)}break;case 14:if(i.length>=4){const e=i.pop(),r=i.pop();s=i.pop();n=i.pop();t.save();t.translate(n,s);let o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[e]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId);t.restore();o=lookupCmap(a.cmap,String.fromCharCode(a.glyphNameMap[lr[r]]));compileCharString(a.glyphs[o.glyphId],t,a,o.glyphId)}return;case 19:case 20:o+=i.length>>1;c+=o+7>>3;y=!0;break;case 21:s+=i.pop();n+=i.pop();moveTo(n,s);y=!0;break;case 22:n+=i.pop();moveTo(n,s);y=!0;break;case 24:for(;i.length>2;){l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}n+=i.shift();s+=i.shift();lineTo(n,s);break;case 25:for(;i.length>6;){n+=i.shift();s+=i.shift();lineTo(n,s)}l=n+i.shift();u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+i.shift();bezierCurveTo(l,u,h,d,n,s);break;case 26:i.length%2&&(n+=i.shift());for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h;s=d+i.shift();bezierCurveTo(l,u,h,d,n,s)}break;case 27:i.length%2&&(s+=i.shift());for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d;bezierCurveTo(l,u,h,d,n,s)}break;case 28:i.push(readInt16(e,c));c+=2;break;case 29:m=i.pop()+a.gsubrsBias;b=a.gsubrs[m];b&&parse(b);break;case 30:for(;i.length>0;){l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;case 31:for(;i.length>0;){l=n+i.shift();u=s;h=l+i.shift();d=u+i.shift();s=d+i.shift();n=h+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s);if(0===i.length)break;l=n;u=s+i.shift();h=l+i.shift();d=u+i.shift();n=h+i.shift();s=d+(1===i.length?i.shift():0);bezierCurveTo(l,u,h,d,n,s)}break;default:if(w<32)throw new FormatError(`unknown operator: ${w}`);if(w<247)i.push(w-139);else if(w<251)i.push(256*(w-247)+e[c++]+108);else if(w<255)i.push(256*-(w-251)-e[c++]-108);else{i.push((e[c]<<24|e[c+1]<<16|e[c+2]<<8|e[c+3])/65536);c+=4}}y&&(i.length=0)}}(e)}class Commands{cmds=[];transformStack=[];currentTransform=[1,0,0,1,0,0];add(e,t){if(t){const{currentTransform:a}=this;for(let e=0,r=t.length;e=0&&e2*readUint16(e,t)}const n=[];let s=i(t,0);for(let a=r;ae.getSize()+3&-4))}write(){const e=this.getSize(),t=new DataView(new ArrayBuffer(e)),a=e>131070,r=a?4:2,i=new DataView(new ArrayBuffer((this.glyphs.length+1)*r));a?i.setUint32(0,0):i.setUint16(0,0);let n=0,s=0;for(const e of this.glyphs){n+=e.write(n,t);n=n+3&-4;s+=r;a?i.setUint32(s,n):i.setUint16(s,n>>1)}return{isLocationLong:a,loca:new Uint8Array(i.buffer),glyf:new Uint8Array(t.buffer)}}scale(e){for(let t=0,a=this.glyphs.length;te.getSize()));return this.header.getSize()+e}write(e,t){if(!this.header)return 0;const a=e;e+=this.header.write(e,t);if(this.simple)e+=this.simple.write(e,t);else for(const a of this.composites)e+=a.write(e,t);return e-a}scale(e){if(!this.header)return;const t=(this.header.xMin+this.header.xMax)/2;this.header.scale(t,e);if(this.simple)this.simple.scale(t,e);else for(const a of this.composites)a.scale(t,e)}}class GlyphHeader{constructor({numberOfContours:e,xMin:t,yMin:a,xMax:r,yMax:i}){this.numberOfContours=e;this.xMin=t;this.yMin=a;this.xMax=r;this.yMax=i}static parse(e,t){return[10,new GlyphHeader({numberOfContours:t.getInt16(e),xMin:t.getInt16(e+2),yMin:t.getInt16(e+4),xMax:t.getInt16(e+6),yMax:t.getInt16(e+8)})]}getSize(){return 10}write(e,t){t.setInt16(e,this.numberOfContours);t.setInt16(e+2,this.xMin);t.setInt16(e+4,this.yMin);t.setInt16(e+6,this.xMax);t.setInt16(e+8,this.yMax);return 10}scale(e,t){this.xMin=Math.round(e+(this.xMin-e)*t);this.xMax=Math.round(e+(this.xMax-e)*t)}}class Contour{constructor({flags:e,xCoordinates:t,yCoordinates:a}){this.xCoordinates=t;this.yCoordinates=a;this.flags=e}}class SimpleGlyph{constructor({contours:e,instructions:t}){this.contours=e;this.instructions=t}static parse(e,t,a){const r=[];for(let i=0;i255?e+=2:o>0&&(e+=1);t=n;o=Math.abs(s-a);o>255?e+=2:o>0&&(e+=1);a=s}}return e}write(e,t){const a=e,r=[],i=[],n=[];let s=0,o=0;for(const a of this.contours){for(let e=0,t=a.xCoordinates.length;e=0?18:2;r.push(e)}else r.push(l)}s=c;const h=a.yCoordinates[e];l=h-o;if(0===l){t|=32;i.push(0)}else{const e=Math.abs(l);if(e<=255){t|=l>=0?36:4;i.push(e)}else i.push(l)}o=h;n.push(t)}t.setUint16(e,r.length-1);e+=2}t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}for(const a of n)t.setUint8(e++,a);for(let a=0,i=r.length;a=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(e+=2):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(e+=2);return e}write(e,t){const a=e;2&this.flags?this.argument1>=-128&&this.argument1<=127&&this.argument2>=-128&&this.argument2<=127||(this.flags|=1):this.argument1>=0&&this.argument1<=255&&this.argument2>=0&&this.argument2<=255||(this.flags|=1);t.setUint16(e,this.flags);t.setUint16(e+2,this.glyphIndex);e+=4;if(1&this.flags){if(2&this.flags){t.setInt16(e,this.argument1);t.setInt16(e+2,this.argument2)}else{t.setUint16(e,this.argument1);t.setUint16(e+2,this.argument2)}e+=4}else{t.setUint8(e,this.argument1);t.setUint8(e+1,this.argument2);e+=2}if(256&this.flags){t.setUint16(e,this.instructions.length);e+=2;if(this.instructions.length){new Uint8Array(t.buffer,0,t.buffer.byteLength).set(this.instructions,e);e+=this.instructions.length}}return e-a}scale(e,t){}}function writeInt16(e,t,a){e[t]=a>>8&255;e[t+1]=255&a}function writeInt32(e,t,a){e[t]=a>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}function writeData(e,t,a){if(a instanceof Uint8Array)e.set(a,t);else if("string"==typeof a)for(let r=0,i=a.length;ra;){a<<=1;r++}const i=a*t;return{range:i,entry:r,rangeShift:t*e-i}}toArray(){let e=this.sfnt;const t=this.tables,a=Object.keys(t);a.sort();const r=a.length;let i,n,s,o,c,l=12+16*r;const h=[l];for(i=0;i>>0;h.push(l)}const u=new Uint8Array(l);for(i=0;i>>0}writeInt32(u,l+4,e);writeInt32(u,l+8,h[i]);writeInt32(u,l+12,t[c].length);l+=16}return u}addTable(e,t){if(e in this.tables)throw new Error("Table "+e+" already exists");this.tables[e]=t}}const $r=[4],Vr=[5],Kr=[6],Jr=[7],Yr=[8],Zr=[12,35],Qr=[14],ei=[21],ti=[22],ai=[30],ri=[31];class Type1CharString{constructor(){this.width=0;this.lsb=0;this.flexing=!1;this.output=[];this.stack=[]}convert(e,t,a){const r=e.length;let i,n,s,o=!1;for(let c=0;cr)return!0;const i=r-e;for(let e=i;e>8&255,255&t);else{t=65536*t|0;this.output.push(255,t>>24&255,t>>16&255,t>>8&255,255&t)}}this.output.push(...t);a?this.stack.splice(i,e):this.stack.length=0;return!1}}function isHexDigit(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function decrypt(e,t,a){if(a>=e.length)return new Uint8Array(0);let r,i,n=0|t;for(r=0;r>8;n=52845*(t+n)+22719&65535}return o}function isSpecial(e){return 47===e||91===e||93===e||123===e||125===e||40===e||41===e}class Type1Parser{constructor(e,t,a){if(t){const t=e.getBytes(),a=!((isHexDigit(t[0])||isWhiteSpace(t[0]))&&isHexDigit(t[1])&&isHexDigit(t[2])&&isHexDigit(t[3])&&isHexDigit(t[4])&&isHexDigit(t[5])&&isHexDigit(t[6])&&isHexDigit(t[7]));e=new Stream(a?decrypt(t,55665,4):function decryptAscii(e,t,a){let r=0|t;const i=e.length,n=new Uint8Array(i>>>1);let s,o;for(s=0,o=0;s>8;r=52845*(e+r)+22719&65535}}return n.slice(a,o)}(t,55665,4))}this.seacAnalysisEnabled=!!a;this.stream=e;this.nextChar()}readNumberArray(){this.getToken();const e=[];for(;;){const t=this.getToken();if(null===t||"]"===t||"}"===t)break;e.push(parseFloat(t||0))}return e}readNumber(){const e=this.getToken();return parseFloat(e||0)}readInt(){const e=this.getToken();return 0|parseInt(e||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){this.stream.skip(-2);return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(-1===t)return null;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}if(isSpecial(t)){this.nextChar();return String.fromCharCode(t)}let a="";do{a+=String.fromCharCode(t);t=this.nextChar()}while(t>=0&&!isWhiteSpace(t)&&!isSpecial(t));return a}readCharStrings(e,t){return-1===t?e:decrypt(e,4330,t)}extractFontProgram(e){const t=this.stream,a=[],r=[],i=Object.create(null);i.lenIV=4;const n={subrs:[],charstrings:[],properties:{privateData:i}};let s,o,c,l;for(;null!==(s=this.getToken());)if("/"===s){s=this.getToken();switch(s){case"CharStrings":this.getToken();this.getToken();this.getToken();this.getToken();for(;;){s=this.getToken();if(null===s||"end"===s)break;if("/"!==s)continue;const e=this.getToken();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const a=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s?this.getToken():"/"===s&&this.prevChar();r.push({glyph:e,encoded:a})}break;case"Subrs":this.readInt();this.getToken();for(;"dup"===this.getToken();){const e=this.readInt();o=this.readInt();this.getToken();c=o>0?t.getBytes(o):new Uint8Array(0);l=n.properties.privateData.lenIV;const r=this.readCharStrings(c,l);this.nextChar();s=this.getToken();"noaccess"===s&&this.getToken();a[e]=r}break;case"BlueValues":case"OtherBlues":case"FamilyBlues":case"FamilyOtherBlues":const e=this.readNumberArray();e.length>0&&e.length,0;break;case"StemSnapH":case"StemSnapV":n.properties.privateData[s]=this.readNumberArray();break;case"StdHW":case"StdVW":n.properties.privateData[s]=this.readNumberArray()[0];break;case"BlueShift":case"lenIV":case"BlueFuzz":case"BlueScale":case"LanguageGroup":n.properties.privateData[s]=this.readNumber();break;case"ExpansionFactor":n.properties.privateData[s]=this.readNumber()||.06;break;case"ForceBold":n.properties.privateData[s]=this.readBoolean()}}for(const{encoded:t,glyph:i}of r){const r=new Type1CharString,s=r.convert(t,a,this.seacAnalysisEnabled);let o=r.output;s&&(o=[14]);const c={glyphName:i,charstring:o,width:r.width,lsb:r.lsb,seac:r.seac};".notdef"===i?n.charstrings.unshift(c):n.charstrings.push(c);if(e.builtInEncoding){const t=e.builtInEncoding.indexOf(i);t>-1&&void 0===e.widths[t]&&t>=e.firstChar&&t<=e.lastChar&&(e.widths[t]=r.width)}}return n}extractFontHeader(e){let t;for(;null!==(t=this.getToken());)if("/"===t){t=this.getToken();switch(t){case"FontMatrix":const a=this.readNumberArray();e.fontMatrix=a;break;case"Encoding":const r=this.getToken();let i;if(/^\d+$/.test(r)){i=[];const e=0|parseInt(r,10);this.getToken();for(let a=0;a=i){s+=a;for(;s=0&&(r[e]=i)}}return type1FontGlyphMapping(e,r,a)}hasGlyphId(e){if(e<0||e>=this.numGlyphs)return!1;if(0===e)return!0;return this.charstrings[e-1].charstring.length>0}getSeacs(e){const t=[];for(let a=0,r=e.length;a0;e--)t[e]-=t[e-1];f.setByName(e,t)}n.topDict.privateDict=f;const p=new CFFIndex;for(h=0,u=r.length;h0&&e.toUnicode.amend(t)}class fonts_Glyph{constructor(e,t,a,r,i,n,s,o,c){this.originalCharCode=e;this.fontChar=t;this.unicode=a;this.accent=r;this.width=i;this.vmetric=n;this.operatorListId=s;this.isSpace=o;this.isInFont=c}get category(){return shadow(this,"category",function getCharUnicodeCategory(e){const t=yr.get(e);if(t)return t;const a=e.match(br),r={isWhitespace:!!a?.[1],isZeroWidthDiacritic:!!a?.[2],isInvisibleFormatMark:!!a?.[3]};yr.set(e,r);return r}(this.unicode),!0)}}function int16(e,t){return(e<<8)+t}function writeSignedInt16(e,t,a){e[t+1]=a;e[t]=a>>>8}function signedInt16(e,t){const a=(e<<8)+t;return 32768&a?a-65536:a}function string16(e){return String.fromCharCode(e>>8&255,255&e)}function safeString16(e){e>32767?e=32767:e<-32768&&(e=-32768);return String.fromCharCode(e>>8&255,255&e)}function isTrueTypeCollectionFile(e){return"ttcf"===bytesToString(e.peekBytes(4))}function getFontFileType(e,{type:t,subtype:a,composite:r}){let i,n;if(function isTrueTypeFile(e){const t=e.peekBytes(4);return 65536===readUint32(t,0)||"true"===bytesToString(t)}(e)||isTrueTypeCollectionFile(e))i=r?"CIDFontType2":"TrueType";else if(function isOpenTypeFile(e){return"OTTO"===bytesToString(e.peekBytes(4))}(e))i=r?"CIDFontType2":"OpenType";else if(function isType1File(e){const t=e.peekBytes(2);return 37===t[0]&&33===t[1]||128===t[0]&&1===t[1]}(e))i=r?"CIDFontType0":"MMType1"===t?"MMType1":"Type1";else if(function isCFFFile(e){const t=e.peekBytes(4);return t[0]>=1&&t[3]>=1&&t[3]<=4}(e))if(r){i="CIDFontType0";n="CIDFontType0C"}else{i="MMType1"===t?"MMType1":"Type1";n="Type1C"}else{warn("getFontFileType: Unable to detect correct font file Type/Subtype.");i=t;n=a}return[i,n]}function applyStandardFontGlyphMap(e,t){for(const a in t)e[+a]=t[a]}function buildToFontChar(e,t,a){const r=[];let i;for(let a=0,n=e.length;aii[0][0]<=e&&e<=ii[0][1]||ii[1][0]<=e&&e<=ii[1][1];let u=null;for(const d in e){let f=e[d];if(!t(f))continue;if(l>h){c++;if(c>=ii.length){warn("Ran out of space in font private use area.");break}l=ii[c][0];h=ii[c][1]}const g=l++;0===f&&(f=a);let p=r.get(d);if("string"==typeof p)if(1===p.length)p=p.codePointAt(0);else{if(!u){u=new Map;for(let e=64256;e<=64335;e++){const t=String.fromCharCode(e).normalize("NFKD");t.length>1&&u.set(t,e)}}p=u.get(p)||p.codePointAt(0)}if(p&&!isInPrivateArea(p)&&!o.has(f)){n.set(p,f);o.add(f)}i[g]=f;s[d]=g}return{toFontChar:s,charCodeToGlyphId:i,toUnicodeExtraMap:n,nextAvailableFontCharCode:l}}function createCmapTable(e,t,a){const r=function getRanges(e,t,a){const r=[];for(const t in e)e[t]>=a||r.push({fontCharCode:0|t,glyphId:e[t]});if(t)for(const[e,i]of t)i>=a||r.push({fontCharCode:e,glyphId:i});0===r.length&&r.push({fontCharCode:0,glyphId:0});r.sort((e,t)=>e.fontCharCode-t.fontCharCode);const i=[],n=r.length;for(let e=0;e65535?2:1;let n,s,o,c,l="\0\0"+string16(i)+"\0\0"+string32(4+8*i);for(n=r.length-1;n>=0&&!(r[n][0]<=65535);--n);const h=n+1;r[n][0]<65535&&65535===r[n][1]&&(r[n][1]=65534);const u=r[n][1]<65535?1:0,d=h+u,f=OpenTypeFileBuilder.getSearchParams(d,2);let g,p,m,b,y="",w="",x="",S="",k="",C=0;for(n=0,s=h;n0){w+="ÿÿ";y+="ÿÿ";x+="\0";S+="\0\0"}const v="\0\0"+string16(2*d)+string16(f.range)+string16(f.entry)+string16(f.rangeShift)+w+"\0\0"+y+x+S+k;let F="",T="";if(i>1){l+="\0\0\n"+string32(4+8*i+4+v.length);F="";for(n=0,s=r.length;ne||!o)&&(o=e);c 123 are reserved for internal usage");s|=1<65535&&(c=65535)}else{o=0;c=255}const h=e.bbox||[0,0,0,0],u=a.unitsPerEm||(e.fontMatrix?1/Math.max(...e.fontMatrix.slice(0,4).map(Math.abs)):1e3),d=e.ascentScaled?1:u/ni,f=a.ascent||Math.round(d*(e.ascent||h[3]));let g=a.descent||Math.round(d*(e.descent||h[1]));g>0&&e.descent>0&&h[1]<0&&(g=-g);const p=a.yMax||f,m=-a.yMin||-g;return"\0$ô\0\0\0Š»\0\0\0ŒŠ»\0\0ß\x001\0\0\0\0"+String.fromCharCode(e.fixedPitch?9:0)+"\0\0\0\0\0\0"+string32(r)+string32(i)+string32(n)+string32(s)+"*21*"+string16(e.italicAngle?1:0)+string16(o||e.firstChar)+string16(c||e.lastChar)+string16(f)+string16(g)+"\0d"+string16(p)+string16(m)+"\0\0\0\0\0\0\0\0"+string16(e.xHeight)+string16(e.capHeight)+string16(0)+string16(o||e.firstChar)+"\0"}function createPostTable(e){return"\0\0\0"+string32(Math.floor(65536*e.italicAngle))+"\0\0\0\0"+string32(e.fixedPitch?1:0)+"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}function createPostscriptName(e){return e.replaceAll(/[^\x21-\x7E]|[[\](){}<>/%]/g,"").slice(0,63)}function createNameTable(e,t){t||(t=[[],[]]);const a=[t[0][0]||"Original licence",t[0][1]||e,t[0][2]||"Unknown",t[0][3]||"uniqueID",t[0][4]||e,t[0][5]||"Version 0.11",t[0][6]||createPostscriptName(e),t[0][7]||"Unknown",t[0][8]||"Unknown",t[0][9]||"Unknown"],r=[];let i,n,s,o,c;for(i=0,n=a.length;i0;if((s||o)&&"CIDFontType2"===a&&this.cidEncoding.startsWith("Identity-")){const a=e.cidToGidMap,r=[];applyStandardFontGlyphMap(r,qr());/Arial-?Black/i.test(t)?applyStandardFontGlyphMap(r,Hr()):/Calibri/i.test(t)&&applyStandardFontGlyphMap(r,Wr());if(a){for(const e in r){const t=r[e];void 0!==a[t]&&(r[+e]=a[t])}a.length!==this.toUnicode.length&&e.hasIncludedToUnicodeMap&&this.toUnicode instanceof IdentityToUnicodeMap&&this.toUnicode.forEach(function(e,t){const i=r[e];void 0===a[i]&&(r[+e]=t)})}this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach(function(e,t){r[+e]=t});this.toFontChar=r;this.toUnicode=new ToUnicodeMap(r)}else if(/Symbol/i.test(r))this.toFontChar=buildToFontChar(ur,fr(),this.differences);else if(/Dingbats/i.test(r))this.toFontChar=buildToFontChar(dr,gr(),this.differences);else if(s||o){const e=buildToFontChar(this.defaultEncoding,fr(),this.differences);"CIDFontType2"!==a||this.cidEncoding.startsWith("Identity-")||this.toUnicode instanceof IdentityToUnicodeMap||this.toUnicode.forEach(function(t,a){e[+t]=a});this.toFontChar=e}else{const e=fr(),a=[];this.toUnicode.forEach((t,r)=>{if(!this.composite){const a=getUnicodeForGlyph(this.differences[t]||this.defaultEncoding[t],e);-1!==a&&(r=a)}a[+t]=r});this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(t)&&applyStandardFontGlyphMap(a,qr());this.toFontChar=a}amendFallbackToUnicode(e);this.loadedName=r.split("-",1)[0]}checkAndRepair(e,t,a){const r=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(e,t){const a=Object.create(null);a["OS/2"]=null;a.cmap=null;a.head=null;a.hhea=null;a.hmtx=null;a.maxp=null;a.name=null;a.post=null;for(let i=0;i>>0,r=e.getInt32()>>>0,i=e.getInt32()>>>0,n=e.pos;e.pos=e.start||0;e.skip(r);const s=e.getBytes(i);e.pos=n;if("head"===t){s[8]=s[9]=s[10]=s[11]=0;s[17]|=32}return{tag:t,checksum:a,length:i,offset:r,data:s}}function readOpenTypeHeader(e){return{version:e.getString(4),numTables:e.getUint16(),searchRange:e.getUint16(),entrySelector:e.getUint16(),rangeShift:e.getUint16()}}function sanitizeGlyph(e,t,a,r,i,n){const s={length:0,sizeOfInstructions:0};if(t<0||t>=e.length||a>e.length||a-t<=12)return s;const o=e.subarray(t,a),c=signedInt16(o[2],o[3]),l=signedInt16(o[4],o[5]),h=signedInt16(o[6],o[7]),u=signedInt16(o[8],o[9]);if(c>h){writeSignedInt16(o,2,h);writeSignedInt16(o,6,c)}if(l>u){writeSignedInt16(o,4,u);writeSignedInt16(o,8,l)}const d=signedInt16(o[0],o[1]);if(d<0){if(d<-1)return s;r.set(o,i);s.length=o.length;return s}let f,g=10,p=0;for(f=0;fo.length)return s;if(!n&&b>0){r.set(o.subarray(0,m),i);r.set([0,0],i+m);r.set(o.subarray(y,x),i+m+2);x-=b;o.length-x>3&&(x=x+3&-4);s.length=x;return s}if(o.length-x>3){x=x+3&-4;r.set(o.subarray(0,x),i);s.length=x;return s}r.set(o,i);s.length=o.length;return s}function readNameTable(e){const a=(t.start||0)+e.offset;t.pos=a;const r=[[],[]],i=[],n=e.length,s=a+n;if(0!==t.getUint16()||n<6)return[r,i];const o=t.getUint16(),c=t.getUint16();let l,h;for(l=0;ls)continue;t.pos=n;const o=e.name;if(e.encoding){let a="";for(let r=0,i=e.length;r0&&(l+=e-1)}}else{if(m||y){warn("TT: nested FDEFs not allowed");p=!0}m=!0;u=l;s=d.pop();t.functionsDefined[s]={data:c,i:l}}else if(!m&&!y){s=d.at(-1);if(isNaN(s))info("TT: CALL empty stack (or invalid entry).");else{t.functionsUsed[s]=!0;if(s in t.functionsStackDeltas){const e=d.length+t.functionsStackDeltas[s];if(e<0){warn("TT: CALL invalid functions stack delta.");t.hintsValid=!1;return}d.length=e}else if(s in t.functionsDefined&&!g.includes(s)){f.push({data:c,i:l,stackTop:d.length-1});g.push(s);o=t.functionsDefined[s];if(!o){warn("TT: CALL non-existent function");t.hintsValid=!1;return}c=o.data;l=o.i}}}if(!m&&!y){let t=0;e<=142?t=i[e]:e>=192&&e<=223?t=-1:e>=224&&(t=-2);if(e>=113&&e<=117){r=d.pop();isNaN(r)||(t=2*-r)}for(;t<0&&d.length>0;){d.pop();t++}for(;t>0;){d.push(NaN);t--}}}t.tooComplexToFollowFunctions=p;const w=[c];l>c.length&&w.push(new Uint8Array(l-c.length));if(u>h){warn("TT: complementing a missing function tail");w.push(new Uint8Array([34,45]))}!function foldTTTable(e,t){if(t.length>1){let a,r,i=0;for(a=0,r=t.length;a>>0,n=[];for(let t=0;t>>0);const s={ttcTag:t,majorVersion:a,minorVersion:r,numFonts:i,offsetTable:n};switch(a){case 1:return s;case 2:s.dsigTag=e.getInt32()>>>0;s.dsigLength=e.getInt32()>>>0;s.dsigOffset=e.getInt32()>>>0;return s}throw new FormatError(`Invalid TrueType Collection majorVersion: ${a}.`)}(e),i=t.split("+");let n;for(let s=0;s0||!(a.cMap instanceof IdentityCMap));if("OTTO"===n.version&&!t||!s.head||!s.hhea||!s.maxp||!s.post){c=new Stream(s["CFF "].data);o=new CFFFont(c,a);return this.convert(e,o,a)}delete s.glyf;delete s.loca;delete s.fpgm;delete s.prep;delete s["cvt "];this.isOpenType=!0}if(!s.maxp)throw new FormatError('Required "maxp" table is not found');t.pos=(t.start||0)+s.maxp.offset;let h=t.getInt32();const u=t.getUint16();if(65536!==h&&20480!==h){if(6===s.maxp.length)h=20480;else{if(!(s.maxp.length>=32))throw new FormatError('"maxp" table has a wrong version number');h=65536}!function writeUint32(e,t,a){e[t+3]=255&a;e[t+2]=a>>>8;e[t+1]=a>>>16;e[t]=a>>>24}(s.maxp.data,0,h)}if(a.scaleFactors?.length===u&&l){const{scaleFactors:e}=a,t=int16(s.head.data[50],s.head.data[51]),r=new GlyfTable({glyfTable:s.glyf.data,isGlyphLocationsLong:t,locaTable:s.loca.data,numGlyphs:u});r.scale(e);const{glyf:i,loca:n,isLocationLong:o}=r.write();s.glyf.data=i;s.loca.data=n;if(o!==!!t){s.head.data[50]=0;s.head.data[51]=o?1:0}const c=s.hmtx.data;for(let t=0;t>8&255;c[a+1]=255&r;writeSignedInt16(c,a+2,Math.round(e[t]*signedInt16(c[a+2],c[a+3])))}}let d=u+1,f=!0;if(d>65535){f=!1;d=u;warn("Not enough space in glyfs to duplicate first glyph.")}let g=0,p=0;if(h>=65536&&s.maxp.length>=32){t.pos+=8;if(t.getUint16()>2){s.maxp.data[14]=0;s.maxp.data[15]=2}t.pos+=4;g=t.getUint16();t.pos+=4;p=t.getUint16()}s.maxp.data[4]=d>>8;s.maxp.data[5]=255&d;const m=function sanitizeTTPrograms(e,t,a,r){const i={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};e&&sanitizeTTProgram(e,i);t&&sanitizeTTProgram(t,i);e&&function checkInvalidFunctions(e,t){if(!e.tooComplexToFollowFunctions)if(e.functionsDefined.length>t){warn("TT: more functions defined than expected");e.hintsValid=!1}else for(let a=0,r=e.functionsUsed.length;at){warn("TT: invalid function id: "+a);e.hintsValid=!1;return}if(e.functionsUsed[a]&&!e.functionsDefined[a]){warn("TT: undefined function: "+a);e.hintsValid=!1;return}}}(i,r);if(a&&1&a.length){const e=new Uint8Array(a.length+1);e.set(a.data);a.data=e}return i.hintsValid}(s.fpgm,s.prep,s["cvt "],g);if(!m){delete s.fpgm;delete s.prep;delete s["cvt "]}!function sanitizeMetrics(e,t,a,r,i,n){if(!t){a&&(a.data=null);return}e.pos=(e.start||0)+t.offset;e.pos+=4;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;e.pos+=2;const s=e.getUint16();e.pos+=8;e.pos+=2;let o=e.getUint16();if(0!==s){if(!(2&int16(r.data[44],r.data[45]))){t.data[22]=0;t.data[23]=0}}if(o>i){info(`The numOfMetrics (${o}) should not be greater than the numGlyphs (${i}).`);o=i;t.data[34]=(65280&o)>>8;t.data[35]=255&o}const c=i-o-(a.length-4*o>>1);if(c>0){const e=new Uint8Array(a.length+2*c);e.set(a.data);if(n){e[a.length]=a.data[2];e[a.length+1]=a.data[3]}a.data=e}}(t,s.hhea,s.hmtx,s.head,d,f);if(!s.head)throw new FormatError('Required "head" table is not found');!function sanitizeHead(e,t,a){const r=e.data,i=function int32(e,t,a,r){return(e<<24)+(t<<16)+(a<<8)+r}(r[0],r[1],r[2],r[3]);if(i>>16!=1){info("Attempting to fix invalid version in head table: "+i);r[0]=0;r[1]=1;r[2]=0;r[3]=0}const n=int16(r[50],r[51]);if(n<0||n>1){info("Attempting to fix invalid indexToLocFormat in head table: "+n);const e=t+1;if(a===e<<1){r[50]=0;r[51]=0}else{if(a!==e<<2)throw new FormatError("Could not fix indexToLocFormat: "+n);r[50]=0;r[51]=1}}}(s.head,u,l?s.loca.length:0);let b=Object.create(null);if(l){const e=int16(s.head.data[50],s.head.data[51]),t=function sanitizeGlyphLocations(e,t,a,r,i,n,s){let o,c,l;if(r){o=4;c=function fontItemDecodeLong(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]};l=function fontItemEncodeLong(e,t,a){e[t]=a>>>24&255;e[t+1]=a>>16&255;e[t+2]=a>>8&255;e[t+3]=255&a}}else{o=2;c=function fontItemDecode(e,t){return e[t]<<9|e[t+1]<<1};l=function fontItemEncode(e,t,a){e[t]=a>>9&255;e[t+1]=a>>1&255}}const h=n?a+1:a,u=o*(1+h),d=new Uint8Array(u);d.set(e.data.subarray(0,u));e.data=d;const f=t.data,g=f.length,p=new Uint8Array(g);let m,b;const y=[];for(m=0,b=0;mg&&(e=g);y.push({index:m,offset:e,endOffset:0})}y.sort((e,t)=>e.offset-t.offset);for(m=0;me.index-t.index);for(m=0;ms&&(s=e.sizeOfInstructions);S+=t;l(d,b,S)}if(0===S){const e=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(m=0,b=o;ma+S)t.data=p.subarray(0,a+S);else{t.data=new Uint8Array(a+S);t.data.set(p.subarray(0,S))}t.data.set(p.subarray(0,a),S);l(e.data,d.length-o,S+a)}else t.data=p.subarray(0,S);return{missingGlyphs:x,maxSizeOfInstructions:s}}(s.loca,s.glyf,u,e,m,f,p);b=t.missingGlyphs;if(h>=65536&&s.maxp.length>=32){s.maxp.data[26]=t.maxSizeOfInstructions>>8;s.maxp.data[27]=255&t.maxSizeOfInstructions}}if(!s.hhea)throw new FormatError('Required "hhea" table is not found');if(0===s.hhea.data[10]&&0===s.hhea.data[11]){s.hhea.data[10]=255;s.hhea.data[11]=255}const y={unitsPerEm:int16(s.head.data[18],s.head.data[19]),yMax:signedInt16(s.head.data[42],s.head.data[43]),yMin:signedInt16(s.head.data[38],s.head.data[39]),ascent:signedInt16(s.hhea.data[4],s.hhea.data[5]),descent:signedInt16(s.hhea.data[6],s.hhea.data[7]),lineGap:signedInt16(s.hhea.data[8],s.hhea.data[9])};this.ascent=y.ascent/y.unitsPerEm;this.descent=y.descent/y.unitsPerEm;this.lineGap=y.lineGap/y.unitsPerEm;if(this.cssFontInfo?.lineHeight){this.lineHeight=this.cssFontInfo.metrics.lineHeight;this.lineGap=this.cssFontInfo.metrics.lineGap}else this.lineHeight=this.ascent-this.descent+this.lineGap;s.post&&function readPostScriptTable(e,a,r){const i=(t.start||0)+e.offset;t.pos=i;const n=i+e.length,s=t.getInt32();t.skip(28);let o,c,l=!0;switch(s){case 65536:o=Cr;break;case 131072:const e=t.getUint16();if(e!==r){l=!1;break}const i=[];for(c=0;c=32768){l=!1;break}i.push(e)}if(!l)break;const h=[],u=[];for(;t.pos65535)throw new FormatError("Max size of CID is 65,535");let i=-1;t?i=r:void 0!==e[r]&&(i=e[r]);i>=0&&i>>0;let h=!1;if(o?.platformId!==i||o?.encodingId!==n){if(0!==i||0!==n&&1!==n&&3!==n)if(1===i&&0===n)h=!0;else if(3!==i||1!==n||!r&&o){if(a&&3===i&&0===n){h=!0;let a=!0;if(e>3;e.push(r);a=Math.max(r,a)}const r=[];for(let e=0;e<=a;e++)r.push({firstCode:t.getUint16(),entryCount:t.getUint16(),idDelta:signedInt16(t.getByte(),t.getByte()),idRangePos:t.pos+t.getUint16()});for(let a=0;a<256;a++)if(0===e[a]){t.pos=r[0].idRangePos+2*a;f=t.getUint16();u.push({charCode:a,glyphId:f})}else{const i=r[e[a]];for(d=0;d>1;t.skip(6);const a=[];let r;for(r=0;r>1)-(e-r);i.offsetIndex=s;o=Math.max(o,s+i.end-i.start+1)}else i.offsetIndex=-1}const c=[];for(d=0;d>>0;for(d=0;d>>0,a=t.getInt32()>>>0;let r=t.getInt32()>>>0;for(let t=e;t<=a;t++)u.push({charCode:t,glyphId:r++})}}}u.sort((e,t)=>e.charCode-t.charCode);const g=[],p=new Set;for(const e of u){const{charCode:t}=e;if(!p.has(t)){p.add(t);g.push(e)}}return{platformId:o.platformId,encodingId:o.encodingId,mappings:g,hasShortCmap:h}}(s.cmap,t,this.isSymbolicFont,a.hasEncoding),r=e.platformId,i=e.encodingId,n=e.mappings;let o=[],c=!1;!a.hasEncoding||"MacRomanEncoding"!==a.baseEncodingName&&"WinAnsiEncoding"!==a.baseEncodingName||(o=getEncoding(a.baseEncodingName));if(a.hasEncoding&&!this.isSymbolicFont&&(3===r&&1===i||1===r&&0===i)){const e=fr();for(let t=0;t<256;t++){let s;s=void 0!==this.differences[t]?this.differences[t]:o.length&&""!==o[t]?o[t]:lr[t];if(!s)continue;const c=recoverGlyphName(s,e);let l;3===r&&1===i?l=e[c]:1===r&&0===i&&(l=cr.indexOf(c));if(void 0===l){if(!a.glyphNames&&a.hasIncludedToUnicodeMap&&!(this.toUnicode instanceof IdentityToUnicodeMap)){const e=this.toUnicode.get(t);e&&(l=e.codePointAt(0))}if(void 0===l)continue}for(const e of n)if(e.charCode===l){w[t]=e.glyphId;break}}}else if(0===r){for(const e of n)w[e.charCode]=e.glyphId;c=!0}else if(3===r&&0===i)for(const e of n){let t=e.charCode;t>=61440&&t<=61695&&(t&=255);w[t]=e.glyphId}else for(const e of n)w[e.charCode]=e.glyphId;if(a.glyphNames&&(o.length||this.differences.length))for(let e=0;e<256;++e){if(!c&&void 0!==w[e])continue;const t=this.differences[e]||o[e];if(!t)continue;const r=a.glyphNames.indexOf(t);r>0&&hasGlyph(r)&&(w[e]=r)}}0===w.length&&(w[0]=0);let x=d-1;f||(x=0);if(!a.cssFontInfo){const e=adjustMapping(w,hasGlyph,x,this.toUnicode);this.toFontChar=e.toFontChar;s.cmap={tag:"cmap",data:createCmapTable(e.charCodeToGlyphId,e.toUnicodeExtraMap,d)};s["OS/2"]&&function validateOS2Table(e,t){t.pos=(t.start||0)+e.offset;const a=t.getUint16();t.skip(60);const r=t.getUint16();if(a<4&&768&r)return!1;if(t.getUint16()>t.getUint16())return!1;t.skip(6);if(0===t.getUint16())return!1;e.data[8]=e.data[9]=0;return!0}(s["OS/2"],t)||(s["OS/2"]={tag:"OS/2",data:createOS2Table(a,e.charCodeToGlyphId,y)})}if(!l)try{c=new Stream(s["CFF "].data);o=new CFFParser(c,a,wr).parse();o.duplicateFirstGlyph();const e=new CFFCompiler(o);s["CFF "].data=e.compile()}catch{warn("Failed to compile font "+a.loadedName)}if(s.name){const[t,r]=readNameTable(s.name);s.name.data=createNameTable(e,t);this.psName=t[0][6]||null;a.composite||function adjustTrueTypeToUnicode(e,t,a){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(e.hasEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;if(!t)return;if(0===a.length)return;if(e.defaultEncoding===hr)return;for(const e of a)if(!isWinNameRecord(e))return;const r=hr,i=[],n=fr();for(const e in r){const t=r[e];if(""===t)continue;const a=n[t];void 0!==a&&(i[e]=String.fromCharCode(a))}i.length>0&&e.toUnicode.amend(i)}(a,this.isSymbolicFont,r)}else s.name={tag:"name",data:createNameTable(this.name)};const S=new OpenTypeFileBuilder(n.version);for(const e in s)S.addTable(e,s[e].data);return S.toArray()}convert(e,a,r){r.fixedPitch=!1;r.builtInEncoding&&function adjustType1ToUnicode(e,t){if(e.isInternalFont)return;if(e.hasIncludedToUnicodeMap)return;if(t===e.defaultEncoding)return;if(e.toUnicode instanceof IdentityToUnicodeMap)return;const a=[],r=fr();for(const i in t){if(e.hasEncoding&&(e.baseEncodingName||void 0!==e.differences[i]))continue;const n=getUnicodeForGlyph(t[i],r);-1!==n&&(a[i]=String.fromCharCode(n))}a.length>0&&e.toUnicode.amend(a)}(r,r.builtInEncoding);let i=1;a instanceof CFFFont&&(i=a.numGlyphs-1);const n=a.getGlyphMapping(r);let s=null,o=n,c=null;if(!r.cssFontInfo){s=adjustMapping(n,a.hasGlyphId.bind(a),i,this.toUnicode);this.toFontChar=s.toFontChar;o=s.charCodeToGlyphId;c=s.toUnicodeExtraMap}const l=a.numGlyphs;function getCharCodes(e,t){let a=null;for(const r in e)t===e[r]&&(a||=[]).push(0|r);return a}function createCharCode(e,t){for(const a in e)if(t===e[a])return 0|a;s.charCodeToGlyphId[s.nextAvailableFontCharCode]=t;return s.nextAvailableFontCharCode++}const h=a.seacs;if(s&&h?.length){const e=r.fontMatrix||t,i=a.getCharset(),o=Object.create(null);for(let t in h){t|=0;const a=h[t],r=lr[a[2]],c=lr[a[3]],l=i.indexOf(r),u=i.indexOf(c);if(l<0||u<0)continue;const d={x:a[0]*e[0]+a[1]*e[2]+e[4],y:a[0]*e[1]+a[1]*e[3]+e[5]},f=getCharCodes(n,t);if(f)for(const e of f){const t=s.charCodeToGlyphId,a=createCharCode(t,l),r=createCharCode(t,u);o[e]={baseFontCharCode:a,accentFontCharCode:r,accentOffset:d}}}r.seacMap=o}const u=r.fontMatrix?1/Math.max(...r.fontMatrix.slice(0,4).map(Math.abs)):1e3,d=new OpenTypeFileBuilder("OTTO");d.addTable("CFF ",a.data);d.addTable("OS/2",createOS2Table(r,o));d.addTable("cmap",createCmapTable(o,c,l));d.addTable("head","\0\0\0\0\0\0\0\0\0\0_<õ\0\0"+safeString16(u)+"\0\0\0\0ž\v~'\0\0\0\0ž\v~'\0\0"+safeString16(r.descent)+"ÿ"+safeString16(r.ascent)+string16(r.italicAngle?2:0)+"\0\0\0\0\0\0\0");d.addTable("hhea","\0\0\0"+safeString16(r.ascent)+safeString16(r.descent)+"\0\0ÿÿ\0\0\0\0\0\0"+safeString16(r.capHeight)+safeString16(Math.tan(r.italicAngle)*r.xHeight)+"\0\0\0\0\0\0\0\0\0\0\0\0"+string16(l));d.addTable("hmtx",function fontFieldsHmtx(){const e=a.charstrings,t=a.cff?a.cff.widths:null;let r="\0\0\0\0";for(let a=1,i=l;a=65520&&e<=65535?0:e>=62976&&e<=63743?pr()[e]||e:173===e?45:e}(a)}this.isType3Font&&(i=a);let h=null;if(this.seacMap?.[e]){l=!0;const t=this.seacMap[e];a=t.baseFontCharCode;h={fontChar:String.fromCodePoint(t.accentFontCharCode),offset:t.accentOffset}}let u="";"number"==typeof a&&(a<=1114111?u=String.fromCodePoint(a):warn(`charToGlyph - invalid fontCharCode: ${a}`));if(this.missingFile&&this.vertical&&1===u.length){const e=vr()[u.charCodeAt(0)];e&&(u=c=String.fromCharCode(e))}n=new fonts_Glyph(e,u,c,h,r,o,i,t,l);return this._glyphCache[e]=n}charsToGlyphs(e){let t=this._charsCache[e];if(t)return t;t=[];if(this.cMap){const a=Object.create(null),r=e.length;let i=0;for(;it.length%2==1,r=this.toUnicode instanceof IdentityToUnicodeMap?e=>this.toUnicode.charCodeOf(e):e=>this.toUnicode.charCodeOf(String.fromCodePoint(e));for(let i=0,n=e.length;i55295&&(n<57344||n>65533)&&i++;if(this.toUnicode){const e=r(n);if(-1!==e){if(hasCurrentBufErrors()){t.push(a.join(""));a.length=0}for(let t=(this.cMap?this.cMap.getCharCodeLength(e):1)-1;t>=0;t--)a.push(String.fromCharCode(e>>8*t&255));continue}}if(!hasCurrentBufErrors()){t.push(a.join(""));a.length=0}a.push(String.fromCodePoint(n))}t.push(a.join(""));return t}}class ErrorFont{constructor(e){this.error=e;this.loadedName="g_font_error";this.missingFile=!0}charsToGlyphs(){return[]}encodeString(e){return[e]}exportData(){return{error:this.error}}}class CssFontInfo{#E;#H;#W;static strings=["fontFamily","fontWeight","italicAngle"];static write(e){const t=new TextEncoder,a={};let r=0;for(const i of CssFontInfo.strings){const n=t.encode(e[i]);a[i]=n;r+=4+n.length}const i=new ArrayBuffer(r),n=new Uint8Array(i),s=new DataView(i);let o=0;for(const e of CssFontInfo.strings){const t=a[e],r=t.length;s.setUint32(o,r);n.set(t,o+4);o+=4+r}assert(o===i.byteLength,"CssFontInfo.write: Buffer overflow");return i}constructor(e){this.#E=e;this.#H=new DataView(this.#E);this.#W=new TextDecoder}#G(e){assert(e>a&3;return 0===r?void 0:2===r}get black(){return this.#Y(0)}get bold(){return this.#Y(1)}get disableFontFace(){return this.#Y(2)}get fontExtraProperties(){return this.#Y(3)}get isInvalidPDFjsFont(){return this.#Y(4)}get isType3Font(){return this.#Y(5)}get italic(){return this.#Y(6)}get missingFile(){return this.#Y(7)}get remeasure(){return this.#Y(8)}get vertical(){return this.#Y(9)}#Z(e){assert(e0){let e=l[0],a=l[0],r=l[1],i=l[1];for(let t=0;tn?n:e;r=r>s?s:r;a=a"boolean"==typeof e)})(f,2)&&([u,d]=f);if(!(this.shadingType!==li||u&&d)){const[e,t,a,r,i,n]=this.coordsArr,s=Math.hypot(e-r,t-i);a<=n+s&&n<=a+s&&warn("Unsupported radial gradient.")}this.extendStart=u;this.extendEnd=d;const g=e.getRaw("Function"),p=r.create(g,!0),m=(l-c)/840,b=this.colorStops=[];if(c>=l||m<=0){info("Bad shading domain.");return}const y=new Float32Array(o.numComps),w=new Float32Array(1);let x=0;w[0]=c;p(w,0,y,0);const S=new Uint8ClampedArray(3);o.getRgb(y,0,S);let[k,C,v]=S;b.push([0,Util.makeHexColor(k,C,v)]);let F=1;w[0]=c+m;p(w,0,y,0);o.getRgb(y,0,S);let[T,O,M]=S,D=T-k+1,R=O-C+1,N=M-v+1,E=T-k-1,L=O-C-1,_=M-v-1;for(let e=2;e<840;e++){w[0]=c+e*m;p(w,0,y,0);o.getRgb(y,0,S);const[t,a,r]=S,i=e-x;D=Math.min(D,(t-k+1)/i);R=Math.min(R,(a-C+1)/i);N=Math.min(N,(r-v+1)/i);E=Math.max(E,(t-k-1)/i);L=Math.max(L,(a-C-1)/i);_=Math.max(_,(r-v-1)/i);if(!(E<=D&&L<=R&&_<=N)){const e=Util.makeHexColor(T,O,M);b.push([F/840,e]);D=t-T+1;R=a-O+1;N=r-M+1;E=t-T-1;L=a-O-1;_=r-M-1;x=F;k=T;C=O;v=M}F=e;T=t;O=a;M=r}b.push([1,Util.makeHexColor(T,O,M)]);let U="transparent";e.has("Background")&&(U=o.getRgbHex(e.get("Background"),0));if(!u){b.unshift([0,U]);b[1][0]+=BaseShading.SMALL_NUMBER}if(!d){b.at(-1)[0]-=BaseShading.SMALL_NUMBER;b.push([1,U])}this.colorStops=b}getIR(){const{coordsArr:e,shadingType:t}=this;let a,r,i,n,s;if(t===ci){r=[e[0],e[1]];i=[e[2],e[3]];n=null;s=null;a="axial"}else if(t===li){r=[e[0],e[1]];i=[e[3],e[4]];n=e[2];s=e[5];a="radial"}else unreachable(`getPattern type unknown: ${t}`);return["RadialAxial",a,this.bbox,this.colorStops,r,i,n,s]}}class MeshStreamReader{constructor(e,t){this.stream=e;this.context=t;this.buffer=0;this.bufferLength=0;const a=t.numComps;this.tmpCompsBuf=new Float32Array(a);const r=t.colorSpace.numComps;this.tmpCsCompsBuf=t.colorFn?new Float32Array(r):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos0)return!0;const e=this.stream.getByte();if(e<0)return!1;this.buffer=e;this.bufferLength=8;return!0}readBits(e){const{stream:t}=this;let{buffer:a,bufferLength:r}=this;if(32===e){if(0===r)return t.getInt32()>>>0;a=a<<24|t.getByte()<<16|t.getByte()<<8|t.getByte();const e=t.getByte();this.buffer=e&(1<>r)>>>0}if(8===e&&0===r)return t.getByte();for(;r>r}align(){this.buffer=0;this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){const{bitsPerCoordinate:e,decode:t}=this.context,a=this.readBits(e),r=this.readBits(e),i=e<32?1/((1<n?n:e;t=t>s?s:t;a=ae*i[t]):a;let s,o=-2;const c=[];for(const[e,t]of r.map((e,t)=>[e,t]).sort(([e],[t])=>e-t))if(-1!==e)if(e===o+1){s.push(n[t]);o+=1}else{o=e;s=[n[t]];c.push(e,s)}return c}(e),a=new Dict(null);a.set("BaseFont",Name.get(e));a.set("Type",Name.get("Font"));a.set("Subtype",Name.get("CIDFontType2"));a.set("Encoding",Name.get("Identity-H"));a.set("CIDToGIDMap",Name.get("Identity"));a.set("W",t);a.set("FirstChar",t[0]);a.set("LastChar",t.at(-2)+t.at(-1).length-1);const r=new Dict(null);a.set("FontDescriptor",r);const i=new Dict(null);i.set("Ordering","Identity");i.set("Registry","Adobe");i.set("Supplement",0);a.set("CIDSystemInfo",i);return a}class PostScriptParser{constructor(e){this.lexer=e;this.operators=[];this.token=null;this.prev=null}nextToken(){this.prev=this.token;this.token=this.lexer.getToken()}accept(e){if(this.token.type===e){this.nextToken();return!0}return!1}expect(e){if(this.accept(e))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${e}.`)}parse(){this.nextToken();this.expect(nn.LBRACE);this.parseBlock();this.expect(nn.RBRACE);return this.operators}parseBlock(){for(;;)if(this.accept(nn.NUMBER))this.operators.push(this.prev.value);else if(this.accept(nn.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(nn.LBRACE))return;this.parseCondition()}}parseCondition(){const e=this.operators.length;this.operators.push(null,null);this.parseBlock();this.expect(nn.RBRACE);if(this.accept(nn.IF)){this.operators[e]=this.operators.length;this.operators[e+1]="jz"}else{if(!this.accept(nn.LBRACE))throw new FormatError("PS Function: error parsing conditional.");{const t=this.operators.length;this.operators.push(null,null);const a=this.operators.length;this.parseBlock();this.expect(nn.RBRACE);this.expect(nn.IFELSE);this.operators[t]=this.operators.length;this.operators[t+1]="j";this.operators[e]=a;this.operators[e+1]="jz"}}}}const nn={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(e,t){this.type=e;this.value=t}static getOperator(e){return PostScriptToken.opCache[e]||=new PostScriptToken(nn.OPERATOR,e)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(nn.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(nn.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(nn.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(nn.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(e){this.stream=e;this.nextChar();this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let e=!1,t=this.currentChar;for(;;){if(t<0)return sa;if(e)10!==t&&13!==t||(e=!1);else if(37===t)e=!0;else if(!isWhiteSpace(t))break;t=this.nextChar()}switch(0|t){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(nn.NUMBER,this.getNumber());case 123:this.nextChar();return PostScriptToken.LBRACE;case 125:this.nextChar();return PostScriptToken.RBRACE}const a=this.strBuf;a.length=0;a[0]=String.fromCharCode(t);for(;(t=this.nextChar())>=0&&(t>=65&&t<=90||t>=97&&t<=122);)a.push(String.fromCharCode(t));const r=a.join("");switch(r.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(r)}}getNumber(){let e=this.currentChar;const t=this.strBuf;t.length=0;t[0]=String.fromCharCode(e);for(;(e=this.nextChar())>=0&&(e>=48&&e<=57||45===e||46===e);)t.push(String.fromCharCode(e));const a=parseFloat(t.join(""));if(isNaN(a))throw new FormatError(`Invalid floating point number: ${a}`);return a}}class BaseLocalCache{constructor(e){this._onlyRefs=!0===e?.onlyRefs;if(!this._onlyRefs){this._nameRefMap=new Map;this._imageMap=new Map}this._imageCache=new RefSetCache}getByName(e){this._onlyRefs&&unreachable("Should not call `getByName` method.");const t=this._nameRefMap.get(e);return t?this.getByRef(t):this._imageMap.get(e)||null}getByRef(e){return this._imageCache.get(e)||null}set(e,t,a){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalImageCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalColorSpaceCache extends BaseLocalCache{set(e=null,t=null,a){if("string"!=typeof e&&!t)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(t){if(this._imageCache.has(t))return;null!==e&&this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalFunctionCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class LocalGStateCache extends BaseLocalCache{set(e,t=null,a){if("string"!=typeof e)throw new Error('LocalGStateCache.set - expected "name" argument.');if(t){if(this._imageCache.has(t))return;this._nameRefMap.set(e,t);this._imageCache.put(t,a)}else this._imageMap.has(e)||this._imageMap.set(e,a)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class RegionalImageCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}}class GlobalColorSpaceCache extends BaseLocalCache{constructor(e){super({onlyRefs:!0})}set(e=null,t,a){if(!t)throw new Error('GlobalColorSpaceCache.set - expected "ref" argument.');this._imageCache.has(t)||this._imageCache.put(t,a)}clear(){this._imageCache.clear()}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5e7;#oe=new RefSet;constructor(){this._refCache=new RefSetCache;this._imageCache=new RefSetCache}get#ce(){let e=0;for(const t of this._imageCache)e+=t.byteSize;return e}get#le(){return!(this._imageCache.size+e):null}class PDFFunction{static getSampleArray(e,t,a,r){let i,n,s=1;for(i=0,n=e.length;i>c)*h;l&=(1<0&&(d=n[u-1]);let f=a[1];u>1,c=r.length>>1,l=new PostScriptEvaluator(s),h=Object.create(null);let u=8192;const d=new Float32Array(c);return function constructPostScriptFn(e,t,a,r){let n,s,f="";const g=d;for(n=0;ne&&(s=e)}m[n]=s}if(u>0){u--;h[f]=m}a.set(m,r)}}}function isPDFFunction(e){let t;if(e instanceof Dict)t=e;else{if(!(e instanceof BaseStream))return!1;t=e.dict}return t.has("FunctionType")}class PostScriptStack{static MAX_STACK_SIZE=100;constructor(e){this.stack=e?Array.from(e):[]}push(e){if(this.stack.length>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(e)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(e){if(this.stack.length+e>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");const t=this.stack;for(let a=t.length-e,r=e-1;r>=0;r--,a++)t.push(t[a])}index(e){this.push(this.stack[this.stack.length-e-1])}roll(e,t){const a=this.stack,r=a.length-e,i=a.length-1,n=r+(t-Math.floor(t/e)*e);for(let e=r,t=i;e0?t.push(s<>o);break;case"ceiling":s=t.pop();t.push(Math.ceil(s));break;case"copy":s=t.pop();t.copy(s);break;case"cos":s=t.pop();t.push(Math.cos(s%360/180*Math.PI));break;case"cvi":s=0|t.pop();t.push(s);break;case"cvr":break;case"div":o=t.pop();s=t.pop();t.push(s/o);break;case"dup":t.copy(1);break;case"eq":o=t.pop();s=t.pop();t.push(s===o);break;case"exch":t.roll(2,1);break;case"exp":o=t.pop();s=t.pop();t.push(s**o);break;case"false":t.push(!1);break;case"floor":s=t.pop();t.push(Math.floor(s));break;case"ge":o=t.pop();s=t.pop();t.push(s>=o);break;case"gt":o=t.pop();s=t.pop();t.push(s>o);break;case"idiv":o=t.pop();s=t.pop();t.push(s/o|0);break;case"index":s=t.pop();t.index(s);break;case"le":o=t.pop();s=t.pop();t.push(s<=o);break;case"ln":s=t.pop();t.push(Math.log(s));break;case"log":s=t.pop();t.push(Math.log10(s));break;case"lt":o=t.pop();s=t.pop();t.push(s=t?new AstLiteral(t):e.max<=t?e:new AstMin(e,t)}class PostScriptCompiler{compile(e,t,a){const r=[],i=[],n=t.length>>1,s=a.length>>1;let o,c,l,h,u,d,f,g,p=0;for(let e=0;et.min){o.unshift("Math.max(",n,", ");o.push(")")}if(s4){r=!0;t=0}else{r=!1;t=1}const c=[];for(n=0;n=0&&"ET"===ln[e];--e)ln[e]="EN";for(let e=n+1;e0&&(t=ln[n-1]);let a=u;e+1g&&isOdd(g)&&(m=g)}for(g=p;g>=m;--g){let e=-1;for(n=0,s=c.length;n=0){reverseValues(cn,e,n);e=-1}}else e<0&&(e=n);e>=0&&reverseValues(cn,e,c.length)}for(n=0,s=cn.length;n"!==e||(cn[n]="")}return createBidiText(cn.join(""),r)}const hn={style:"normal",weight:"normal"},un={style:"normal",weight:"bold"},dn={style:"italic",weight:"normal"},fn={style:"italic",weight:"bold"},gn=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","PT Astra Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:hn,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:un,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:dn,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:fn,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:hn,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:un,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:dn,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:fn,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:hn,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:un,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:dn,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:fn,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:hn,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:un,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:dn,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:fn,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:hn,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:un,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:dn,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:fn,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:hn}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),pn=new Map([["Arial-Black","ArialBlack"]]);function getFamilyName(e){const t=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return e.split(/[- ,+]+/g).filter(e=>!t.has(e.toLowerCase())).join(" ")}function generateFont({alias:e,local:t,path:a,fallback:r,style:i,ultimate:n},s,o,c=!0,l=!0,h=""){const u={style:null,ultimate:null};if(t){const e=h?` ${h}`:"";for(const a of t)s.push(`local(${a}${e})`)}if(e){const t=gn.get(e),n=h||function getStyleToAppend(e){switch(e){case un:return"Bold";case dn:return"Italic";case fn:return"Bold Italic";default:if("bold"===e?.weight)return"Bold";if("italic"===e?.style)return"Italic"}return""}(i);Object.assign(u,generateFont(t,s,o,c&&!r,l&&!a,n))}i&&(u.style=i);n&&(u.ultimate=n);if(c&&r){const e=gn.get(r),{ultimate:t}=generateFont(e,s,o,c,l&&!a,h);u.ultimate||=t}l&&a&&o&&s.push(`url(${o}${a})`);return u}function getFontSubstitution(e,t,a,r,i,n){if(r.startsWith("InvalidPDFjsFont_"))return null;"TrueType"!==n&&"Type1"!==n||!/^[A-Z]{6}\+/.test(r)||(r=r.slice(7));const s=r=normalizeFontName(r);let o=e.get(s);if(o)return o;let c=gn.get(r);if(!c)for(const[e,t]of pn)if(r.startsWith(e)){r=`${t}${r.substring(e.length)}`;c=gn.get(r);break}let l=!1;if(!c){c=gn.get(i);l=!0}const h=`${t.getDocId()}_s${t.createFontId()}`;if(!c){if(!validateFontName(r)){warn(`Cannot substitute the font because of its name: ${r}`);e.set(s,null);return null}const t=/bold/gi.test(r),a=/oblique|italic/gi.test(r),i=t&&a&&fn||t&&un||a&&dn||hn;o={css:`"${getFamilyName(r)}",${h}`,guessFallback:!0,loadedName:h,baseFontName:r,src:`local(${r})`,style:i};e.set(s,o);return o}const u=[];l&&validateFontName(r)&&u.push(`local(${r})`);const{style:d,ultimate:f}=generateFont(c,u,a),g=null===f,p=g?"":`,${f}`;o={css:`"${getFamilyName(r)}",${h}${p}`,guessFallback:g,loadedName:h,baseFontName:r,src:u.join(","),style:d};e.set(s,o);return o}const mn=3285377520,bn=4294901760,yn=65535;class MurmurHash3_64{constructor(e){this.h1=e?4294967295&e:mn;this.h2=e?4294967295&e:mn}update(e){let t,a;if("string"==typeof e){t=new Uint8Array(2*e.length);a=0;for(let r=0,i=e.length;r>>8;t[a++]=255&i}}}else{if(!ArrayBuffer.isView(e))throw new Error("Invalid data format, must be a string or TypedArray.");t=e.slice();a=t.byteLength}const r=a>>2,i=a-4*r,n=new Uint32Array(t.buffer,0,r);let s=0,o=0,c=this.h1,l=this.h2;const h=3432918353,u=461845907,d=11601,f=13715;for(let e=0;e>>17;s=s*u&bn|s*f&yn;c^=s;c=c<<13|c>>>19;c=5*c+3864292196}else{o=n[e];o=o*h&bn|o*d&yn;o=o<<15|o>>>17;o=o*u&bn|o*f&yn;l^=o;l=l<<13|l>>>19;l=5*l+3864292196}s=0;switch(i){case 3:s^=t[4*r+2]<<16;case 2:s^=t[4*r+1]<<8;case 1:s^=t[4*r];s=s*h&bn|s*d&yn;s=s<<15|s>>>17;s=s*u&bn|s*f&yn;1&r?c^=s:l^=s}this.h1=c;this.h2=l}hexdigest(){let e=this.h1,t=this.h2;e^=t>>>1;e=3981806797*e&bn|36045*e&yn;t=4283543511*t&bn|(2950163797*(t<<16|e>>>16)&bn)>>>16;e^=t>>>1;e=444984403*e&bn|60499*e&yn;t=3301882366*t&bn|(3120437893*(t<<16|e>>>16)&bn)>>>16;e^=t>>>1;return(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}function resizeImageMask(e,t,a,r,i,n){const s=i*n;let o;o=t<=8?new Uint8Array(s):t<=16?new Uint16Array(s):new Uint32Array(s);const c=a/i,l=r/n;let h,u,d,f,g=0;const p=new Uint16Array(i),m=a;for(h=0;h0&&Number.isInteger(a.height)&&a.height>0&&(a.width!==f||a.height!==g)){warn("PDFImage - using the Width/Height of the image data, rather than the image dictionary.");f=a.width;g=a.height}else{const e="number"==typeof f&&f>0,t="number"==typeof g&&g>0;if(!e||!t){if(!a.fallbackDims)throw new FormatError(`Invalid image width: ${f} or height: ${g}`);warn("PDFImage - using the Width/Height of the parent image, for SMask/Mask data.");e||(f=a.fallbackDims.width);t||(g=a.fallbackDims.height)}}this.width=f;this.height=g;this.interpolate=h.get("I","Interpolate");this.imageMask=h.get("IM","ImageMask")||!1;this.matte=h.get("Matte")||!1;let p=a.bitsPerComponent;if(!p){p=h.get("BPC","BitsPerComponent");if(!p){if(!this.imageMask)throw new FormatError(`Bits per component missing in image: ${this.imageMask}`);p=1}}this.bpc=p;if(!this.imageMask){let i=h.getRaw("CS")||h.getRaw("ColorSpace");const n=!!i;if(n)this.jpxDecoderOptions?.smaskInData&&(i=Name.get("DeviceRGBA"));else if(this.jpxDecoderOptions)i=Name.get("DeviceRGBA");else switch(a.numComps){case 1:i=Name.get("DeviceGray");break;case 3:i=Name.get("DeviceRGB");break;case 4:i=Name.get("DeviceCMYK");break;default:throw new Error(`Images with ${a.numComps} color components not supported.`)}this.colorSpace=ColorSpaceUtils.parse({cs:i,xref:e,resources:r?t:null,pdfFunctionFactory:o,globalColorSpaceCache:c,localColorSpaceCache:l});this.numComps=this.colorSpace.numComps;if(this.jpxDecoderOptions){this.jpxDecoderOptions.numComponents=n?this.numComps:0;this.jpxDecoderOptions.isIndexedColormap="Indexed"===this.colorSpace.name}}this.decode=h.getArray("D","Decode");this.needsDecode=!1;if(this.decode&&(this.colorSpace&&!this.colorSpace.isDefaultDecode(this.decode,p)||s&&!ColorSpace.isDefaultDecode(this.decode,1))){this.needsDecode=!0;const e=(1<0,c=(r+7>>3)*i,l=e.getBytes(c),h=1===r&&1===i&&o===(0===l.length||!!(128&l[0]));if(h)return{isSingleOpaquePixel:h};if(t){if(ImageResizer.needsToBeResized(r,i)){const e=new Uint8ClampedArray(r*i*4);convertBlackAndWhiteToRGBA({src:l,dest:e,width:r,height:i,nonBlackColor:0,inverseDecode:o});return ImageResizer.createImage({kind:O,data:e,width:r,height:i,interpolate:n})}const e=new OffscreenCanvas(r,i),t=e.getContext("2d"),a=t.createImageData(r,i);convertBlackAndWhiteToRGBA({src:l,dest:a.data,width:r,height:i,nonBlackColor:0,inverseDecode:o});t.putImageData(a,0,0);return{data:null,width:r,height:i,interpolate:n,bitmap:e.transferToImageBitmap()}}const u=l.byteLength;let d;if(e instanceof DecodeStream&&(!o||c===u))d=l;else if(o){d=new Uint8Array(c);d.set(l);d.fill(255,u)}else d=new Uint8Array(l);if(o)for(let e=0;e>7&1;s[d+1]=u>>6&1;s[d+2]=u>>5&1;s[d+3]=u>>4&1;s[d+4]=u>>3&1;s[d+5]=u>>2&1;s[d+6]=u>>1&1;s[d+7]=1&u;d+=8}if(d>=1}}}}else{let a=0;u=0;for(d=0,h=n;d>r;i<0?i=0:i>l&&(i=l);s[d]=i;u&=(1<s[r+1]){t=255;break}}o[h]=t}}}if(o)for(h=0,d=3,u=t*r;h>3,h=t&&ImageResizer.needsToBeResized(a,r);if(!this.smask&&!this.mask&&"DeviceRGBA"===this.colorSpace.name){i.kind=O;const e=i.data=await this.getImageBytes(o*s*4,{});return t?h?ImageResizer.createImage(i,!1):this.createBitmap(O,a,r,e):i}if(!e){let e;"DeviceGray"===this.colorSpace.name&&1===c?e=F:"DeviceRGB"!==this.colorSpace.name||8!==c||this.needsDecode||(e=T);if(e&&!this.smask&&!this.mask&&a===s&&r===o){const n=await this.#he(s,o);if(n)return n;const c=await this.getImageBytes(o*l,{});if(t)return h?ImageResizer.createImage({data:c,kind:e,width:a,height:r,interpolate:this.interpolate},this.needsDecode):this.createBitmap(e,s,o,c);i.kind=e;i.data=c;if(this.needsDecode){assert(e===F,"PDFImage.createImageData: The image must be grayscale.");const t=i.data;for(let e=0,a=t.length;e>3,s=await this.getImageBytes(r*n,{internal:!0}),o=this.getComponents(s);let c,l;if(1===i){l=a*r;if(this.needsDecode)for(c=0;c0&&r[0].count++}class TimeSlotManager{static TIME_SLOT_DURATION_MS=20;static CHECK_TIME_EVERY=100;constructor(){this.reset()}check(){if(++this.checkedo){const e="Image exceeded maximum allowed size and was removed.";if(!c)throw new Error(e);warn(e);return}let g;h.has("OC")&&(g=await this.parseMarkedContentProps(h.get("OC"),e));let p,m,b;if(h.get("IM","ImageMask")||!1){p=await PDFImage.createMask({image:t,isOffscreenCanvasSupported:l&&!this.parsingType3Font});if(p.isSingleOpaquePixel){m=Xt;b=[];r.addImageOps(m,b,g);if(i){const e={fn:m,args:b,optionalContent:g};n.set(i,u,e);u&&this._regionalImageCache.set(null,u,e)}return}if(this.parsingType3Font){b=function compileType3Glyph({data:e,width:t,height:a}){if(t>1e3||a>1e3)return null;const r=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1,n=new Uint8Array(i*(a+1));let s,o,c;const l=t+7&-8,h=new Uint8Array(l*a);let u=0;for(const t of e){let e=128;for(;e>0;){h[u++]=t&e?0:255;e>>=1}}let d=0;u=0;if(0!==h[u]){n[0]=1;++d}for(o=1;o>2)+(h[u+1]?4:0)+(h[u-l+1]?8:0);if(r[e]){n[c+o]=r[e];++d}u++}if(h[u-l]!==h[u]){n[c+o]=h[u]?2:4;++d}if(d>1e3)return null}u=l*(a-1);c=s*i;if(0!==h[u]){n[c]=8;++d}for(o=1;o1e3)return null;const f=new Int32Array([0,i,-1,0,-i,0,0,0,1]),g=[],{a:p,b:m,c:b,d:y,e:w,f:x}=(new DOMMatrix).scaleSelf(1/t,-1/a).translateSelf(0,-a);for(s=0;d&&s<=a;s++){let e=s*i;const a=e+t;for(;e>4;n[e]&=l>>2|l<<2}r=e%i;o=e/i|0;g.push($t,p*r+b*o+w,m*r+y*o+x);n[e]||--d}while(c!==e);--s}return[Gt,[new Float32Array(g)],new Float32Array([0,0,t,a])]}(p);if(b){r.addImageOps(qt,b,g);return}warn("Cannot compile Type3 glyph.");r.addImageOps(Nt,[p],g);return}const e=`mask_${this.idFactory.createObjId()}`;r.addDependency(e);p.dataLen=p.bitmap?p.width*p.height*4:p.data.length;this._sendImgData(e,p);m=Nt;b=[{data:e,width:p.width,height:p.height,interpolate:p.interpolate,count:1}];r.addImageOps(m,b,g);if(i){const t={objId:e,fn:m,args:b,optionalContent:g};n.set(i,u,t);u&&this._regionalImageCache.set(null,u,t)}return}const y=h.has("SMask")||h.has("Mask");if(a&&d+f<200&&!y){try{const i=new PDFImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:s});p=await i.createImageData(!0,!1);r.addImageOps(Lt,[p],g)}catch(e){const t=`Unable to decode inline image: "${e}".`;if(!c)throw new Error(t);warn(t)}return}let w=`img_${this.idFactory.createObjId()}`,x=!1,S=null;if(this.parsingType3Font)w=`${this.idFactory.getDocId()}_type3_${w}`;else if(i&&u){x=this.globalImageCache.shouldCache(u,this.pageIndex);if(x){assert(!a,"Cannot cache an inline image globally.");w=`${this.idFactory.getDocId()}_${w}`}}r.addDependency(w);m=Pt;b=[w,d,f];r.addImageOps(m,b,g,y);if(x){S={objId:w,fn:m,args:b,optionalContent:g,hasMask:y,byteSize:0};if(this.globalImageCache.hasDecodeFailed(u)){this.globalImageCache.setData(u,S);this._sendImgData(w,null,x);return}if(d*f>25e4||y){const e=await this.handler.sendWithPromise("commonobj",[w,"CopyLocalImage",{imageRef:u}]);if(e){this.globalImageCache.setData(u,S);this.globalImageCache.addByteSize(u,e);return}}}PDFImage.buildImage({xref:this.xref,res:e,image:t,isInline:a,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:s}).then(async e=>{p=await e.createImageData(!1,l);p.dataLen=p.bitmap?p.width*p.height*4:p.data.length;p.ref=u;x&&this.globalImageCache.addByteSize(u,p.dataLen);return this._sendImgData(w,p,x)}).catch(e=>{warn(`Unable to decode image "${w}": "${e}".`);u&&this.globalImageCache.addDecodeFailed(u);return this._sendImgData(w,null,x)});if(i){const e={objId:w,fn:m,args:b,optionalContent:g,hasMask:y};n.set(i,u,e);if(u){this._regionalImageCache.set(null,u,e);if(x){assert(S,"The global cache-data must be available.");this.globalImageCache.setData(u,S)}}}}handleSMask(e,t,a,r,i,n,s){const o=e.get("G"),c={subtype:e.get("S").name,backdrop:e.get("BC")},l=e.get("TR");if(isPDFFunction(l)){const e=this._pdfFunctionFactory.create(l),t=new Uint8Array(256),a=new Float32Array(1);for(let r=0;r<256;r++){a[0]=r/255;e(a,0,a,0);t[r]=255*a[0]|0}c.transferMap=t}return this.buildFormXObject(t,o,c,a,r,i.state.clone({newPath:!0}),n,s)}handleTransferFunction(e){let t;if(Array.isArray(e))t=e;else{if(!isPDFFunction(e))return null;t=[e]}const a=[];let r=0,i=0;for(const e of t){const t=this.xref.fetchIfRef(e);r++;if(isName(t,"Identity")){a.push(null);continue}if(!isPDFFunction(t))return null;const n=this._pdfFunctionFactory.create(t),s=new Uint8Array(256),o=new Float32Array(1);for(let e=0;e<256;e++){o[0]=e/255;n(o,0,o,0);s[e]=255*o[0]|0}a.push(s);i++}return 1!==r&&4!==r||0===i?null:a}handleTilingType(e,t,a,r,i,n,s,o){const c=new OperatorList,l=Dict.merge({xref:this.xref,dictArray:[i.get("Resources"),a]});return this.getOperatorList({stream:r,task:s,resources:l,operatorList:c}).then(function(){const a=c.getIR(),r=getTilingPatternIR(a,i,t);n.addDependencies(c.dependencies);n.addOp(e,r);i.objId&&o.set(null,i.objId,{operatorListIR:a,dict:i})}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`handleTilingType - ignoring pattern: "${e}".`)}})}async handleSetFont(e,t,a,r,i,n,s=null,o=null){const c=t?.[0]instanceof Name?t[0].name:null,l=await this.loadFont(c,a,e,i,s,o);l.font.isType3Font&&r.addDependencies(l.type3Dependencies);n.font=l.font;l.send(this.handler);return l.loadedName}handleText(e,t){const a=t.font,r=a.charsToGlyphs(e);if(a.data){(!!(t.textRenderingMode&v)||"Pattern"===t.fillColorSpace.name||a.disableFontFace)&&PartialEvaluator.buildFontPaths(a,r,this.handler,this.options)}return r}ensureStateFont(e){if(e.font)return;const t=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw t;warn(`ensureStateFont: "${t}".`)}async setGState({resources:e,gState:t,operatorList:a,cacheKey:r,task:i,stateManager:n,localGStateCache:s,localColorSpaceCache:o,seenRefs:c}){const l=t.objId;let h=!0;const u=[];let d=Promise.resolve();for(const[r,s]of t)switch(r){case"Type":break;case"LW":if("number"!=typeof s){warn(`Invalid LW (line width): ${s}`);break}u.push([r,Math.abs(s)]);break;case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":u.push([r,s]);break;case"Font":h=!1;d=d.then(()=>this.handleSetFont(e,null,s[0],a,i,n.state).then(function(e){a.addDependency(e);u.push([r,[e,s[1]]])}));break;case"BM":u.push([r,normalizeBlendMode(s)]);break;case"SMask":if(isName(s,"None")){u.push([r,!1]);break}if(s instanceof Dict){h=!1;d=d.then(()=>this.handleSMask(s,e,a,i,n,o,c));u.push([r,!0])}else warn("Unsupported SMask type");break;case"TR":const t=this.handleTransferFunction(s);u.push([r,t]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+r);break;default:info("Unknown graphic state operator "+r)}await d;u.length>0&&a.addOp(be,[u]);h&&s.set(r,l,u)}loadFont(e,t,a,r,i=null,n=null){const errorFont=async()=>new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${e}" is not available.`),dict:t});let s;if(t)t instanceof Ref&&(s=t);else{const t=a.get("Font");t&&(s=t.getRaw(e))}if(s){if(this.type3FontRefs?.has(s))return errorFont();if(this.fontCache.has(s))return this.fontCache.get(s);try{t=this.xref.fetchIfRef(s)}catch(e){warn(`loadFont - lookup failed: "${e}".`)}}if(!(t instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font){warn(`Font "${e}" is not available.`);return errorFont()}warn(`Font "${e}" is not available -- attempting to fallback to a default font.`);t=i||PartialEvaluator.fallbackFontDict}if(t.cacheKey&&this.fontCache.has(t.cacheKey))return this.fontCache.get(t.cacheKey);const{promise:o,resolve:c}=Promise.withResolvers();let l;try{l=this.preEvaluateFont(t);l.cssFontInfo=n}catch(e){warn(`loadFont - preEvaluateFont failed: "${e}".`);return errorFont()}const{descriptor:h,hash:u}=l,d=s instanceof Ref;let f;if(u&&h instanceof Dict){const e=h.fontAliases||=Object.create(null);if(e[u]){const t=e[u].aliasRef;if(d&&t&&this.fontCache.has(t)){this.fontCache.putAlias(s,t);return this.fontCache.get(s)}}else e[u]={fontID:this.idFactory.createFontId()};d&&(e[u].aliasRef=s);f=e[u].fontID}else f=this.idFactory.createFontId();assert(f?.startsWith("f"),'The "fontID" must be (correctly) defined.');if(d)this.fontCache.put(s,o);else{t.cacheKey=`cacheKey_${f}`;this.fontCache.put(t.cacheKey,o)}t.loadedName=`${this.idFactory.getDocId()}_${f}`;this.translateFont(l).then(async e=>{const i=new TranslatedFont({loadedName:t.loadedName,font:e,dict:t});if(e.isType3Font)try{await i.loadType3Data(this,a,r)}catch(e){throw new Error(`Type3 font load error: ${e}`)}c(i)}).catch(e=>{warn(`loadFont - translateFont failed: "${e}".`);c(new TranslatedFont({loadedName:t.loadedName,font:new ErrorFont(e?.message),dict:t}))});return o}buildPath(e,t,a){const{pathMinMax:r,pathBuffer:i}=a;switch(0|e){case Ie:{const e=a.currentPointX=t[0],n=a.currentPointY=t[1],s=t[2],o=t[3],c=e+s,l=n+o;0===s||0===o?i.push(zt,e,n,$t,c,l,Jt):i.push(zt,e,n,$t,c,n,$t,c,l,$t,e,l,Jt);Util.rectBoundingBox(e,n,c,l,r);break}case Se:{const e=a.currentPointX=t[0],n=a.currentPointY=t[1];i.push(zt,e,n);Util.pointBoundingBox(e,n,r);break}case Ae:{const e=a.currentPointX=t[0],n=a.currentPointY=t[1];i.push($t,e,n);Util.pointBoundingBox(e,n,r);break}case ke:{const e=a.currentPointX,n=a.currentPointY,[s,o,c,l,h,u]=t;a.currentPointX=h;a.currentPointY=u;i.push(Vt,s,o,c,l,h,u);Util.bezierBoundingBox(e,n,s,o,c,l,h,u,r);break}case Ce:{const e=a.currentPointX,n=a.currentPointY,[s,o,c,l]=t;a.currentPointX=c;a.currentPointY=l;i.push(Vt,e,n,s,o,c,l);Util.bezierBoundingBox(e,n,e,n,s,o,c,l,r);break}case ve:{const e=a.currentPointX,n=a.currentPointY,[s,o,c,l]=t;a.currentPointX=c;a.currentPointY=l;i.push(Vt,s,o,c,l,c,l);Util.bezierBoundingBox(e,n,s,o,c,l,c,l,r);break}case Fe:i.push(Jt)}}_getColorSpace(e,t,a){return ColorSpaceUtils.parse({cs:e,xref:this.xref,resources:t,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:a,asyncIfNotCached:!0})}async _handleColorSpace(e){try{return await e}catch(e){if(e instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`_handleColorSpace - ignoring ColorSpace: "${e}".`);return null}throw e}}parseShading({shading:e,resources:t,localColorSpaceCache:a,localShadingPatternCache:r}){let i,n=r.get(e);if(n)return n;try{i=Pattern.parseShading(e,this.xref,t,this._pdfFunctionFactory,this.globalColorSpaceCache,a).getIR()}catch(t){if(t instanceof AbortException)return null;if(this.options.ignoreErrors){warn(`parseShading - ignoring shading: "${t}".`);r.set(e,null);return null}throw t}n=`pattern_${this.idFactory.createObjId()}`;this.parsingType3Font&&(n=`${this.idFactory.getDocId()}_type3_${n}`);r.set(e,n);if(this.parsingType3Font){const e=[],t=PatternInfo.write(i);e.push(t);this.handler.send("commonobj",[n,"Pattern",t],e)}else this.handler.send("obj",[n,this.pageIndex,"Pattern",i]);return n}handleColorN(e,t,a,r,i,n,s,o,c,l){const h=a.pop();if(h instanceof Name){const u=i.getRaw(h.name),d=u instanceof Ref&&c.getByRef(u);if(d)try{const i=r.base?r.base.getRgbHex(a,0):null,n=getTilingPatternIR(d.operatorListIR,d.dict,i);e.addOp(t,n);return}catch{}const f=this.xref.fetchIfRef(u);if(f){const i=f instanceof BaseStream?f.dict:f,h=i.get("PatternType");if(h===xn){const o=r.base?r.base.getRgbHex(a,0):null;return this.handleTilingType(t,o,n,f,i,e,s,c)}if(h===Sn){const a=i.get("Shading"),r=this.parseShading({shading:a,resources:n,localColorSpaceCache:o,localShadingPatternCache:l});if(r){const a=lookupMatrix(i.getArray("Matrix"),null);e.addOp(t,["Shading",r,a])}return}throw new FormatError(`Unknown PatternType: ${h}`)}}throw new FormatError(`Unknown PatternName: ${h}`)}_parseVisibilityExpression(e,t,a){if(++t>10){warn("Visibility expression is too deeply nested");return}const r=e.length,i=this.xref.fetchIfRef(e[0]);if(!(r<2)&&i instanceof Name){switch(i.name){case"And":case"Or":case"Not":a.push(i.name);break;default:warn(`Invalid operator ${i.name} in visibility expression`);return}for(let i=1;i0)return{type:"OCMD",expression:t}}const t=a.get("OCGs");if(Array.isArray(t)||t instanceof Dict){const e=[];if(Array.isArray(t))for(const a of t)e.push(a.toString());else e.push(t.objId);return{type:r,ids:e,policy:a.get("P")instanceof Name?a.get("P").name:null,expression:null}}if(t instanceof Ref)return{type:r,id:t.toString()}}return null}getOperatorList({stream:e,task:t,resources:a,operatorList:r,initialState:i=null,fallbackFontDict:n=null,prevRefs:s=null}){const o=e.dict?.objId,c=new RefSet(s);if(o){if(s?.has(o))throw new Error(`getOperatorList - ignoring circular reference: ${o}`);c.put(o)}a||=Dict.empty;i||=new EvalState;if(!r)throw new Error('getOperatorList: missing "operatorList" parameter');const l=this,h=this.xref,u=new LocalImageCache,d=new LocalColorSpaceCache,f=new LocalGStateCache,g=new LocalTilingPatternCache,p=new Map,m=a.get("XObject")||Dict.empty,b=a.get("Pattern")||Dict.empty,y=new StateManager(i),w=new EvaluatorPreprocessor(e,h,y),x=new TimeSlotManager;function closePendingRestoreOPS(e){for(let e=0,t=w.savedStatesDepth;e{y.state.fillColorSpace=e||ColorSpaceUtils.gray}));return}case it:{const t=l._getColorSpace(e[0],a,d);if(t instanceof ColorSpace){y.state.strokeColorSpace=t;continue}next(l._handleColorSpace(t).then(e=>{y.state.strokeColorSpace=e||ColorSpaceUtils.gray}));return}case ct:C=y.state.fillColorSpace;e=[C.getRgbHex(e,0)];i=ft;break;case st:C=y.state.strokeColorSpace;e=[C.getRgbHex(e,0)];i=dt;break;case ut:y.state.fillColorSpace=ColorSpaceUtils.gray;e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=ft;break;case ht:y.state.strokeColorSpace=ColorSpaceUtils.gray;e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=dt;break;case pt:y.state.fillColorSpace=ColorSpaceUtils.cmyk;e=[ColorSpaceUtils.cmyk.getRgbHex(e,0)];i=ft;break;case gt:y.state.strokeColorSpace=ColorSpaceUtils.cmyk;e=[ColorSpaceUtils.cmyk.getRgbHex(e,0)];i=dt;break;case ft:y.state.fillColorSpace=ColorSpaceUtils.rgb;e=[ColorSpaceUtils.rgb.getRgbHex(e,0)];break;case dt:y.state.strokeColorSpace=ColorSpaceUtils.rgb;e=[ColorSpaceUtils.rgb.getRgbHex(e,0)];break;case lt:C=y.state.patternFillColorSpace;if(!C){if(isNumberArray(e,null)){e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=ft;break}e=[];i=Wt;break}if("Pattern"===C.name){next(l.handleColorN(r,lt,e,C,b,a,t,d,g,p));return}e=[C.getRgbHex(e,0)];i=ft;break;case ot:C=y.state.patternStrokeColorSpace;if(!C){if(isNumberArray(e,null)){e=[ColorSpaceUtils.gray.getRgbHex(e,0)];i=dt;break}e=[];i=Ht;break}if("Pattern"===C.name){next(l.handleColorN(r,ot,e,C,b,a,t,d,g,p));return}e=[C.getRgbHex(e,0)];i=dt;break;case mt:let T;try{const t=a.get("Shading");if(!t)throw new FormatError("No shading resource found");T=t.get(e[0].name);if(!T)throw new FormatError("No shading object found")}catch(e){if(e instanceof AbortException)continue;if(l.options.ignoreErrors){warn(`getOperatorList - ignoring Shading: "${e}".`);continue}throw e}const O=l.parseShading({shading:T,resources:a,localColorSpaceCache:d,localShadingPatternCache:p});if(!O)continue;e=[O];i=mt;break;case be:F=e[0]instanceof Name;v=e[0].name;if(F){const t=f.getByName(v);if(t){t.length>0&&r.addOp(be,[t]);e=null;continue}}next(new Promise(function(e,i){if(!F)throw new FormatError("GState must be referred to by name.");const n=a.get("ExtGState");if(!(n instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const s=n.get(v);if(!(s instanceof Dict))throw new FormatError("GState should be a dictionary.");l.setGState({resources:a,gState:s,operatorList:r,cacheKey:v,task:t,stateManager:y,localGStateCache:f,localColorSpaceCache:d,seenRefs:c}).then(e,i)}).catch(function(e){if(!(e instanceof AbortException)){if(!l.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring ExtGState: "${e}".`)}}));return;case he:{const[t]=e;if("number"!=typeof t){warn(`Invalid setLineWidth: ${t}`);continue}e[0]=Math.abs(t);break}case ge:{const t=e[1];if("number"!=typeof t){warn(`Invalid setDash: ${t}`);continue}const a=e[0];if(!Array.isArray(a)){warn(`Invalid setDash: ${a}`);continue}a.some(e=>"number"!=typeof e)&&(e[0]=a.filter(e=>"number"==typeof e));break}case Se:case Ae:case ke:case Ce:case ve:case Fe:case Ie:l.buildPath(i,e,y.state);continue;case Te:case Oe:case Me:case De:case Be:case Re:case Ne:case Ee:case Pe:{const{state:{pathBuffer:e,pathMinMax:t}}=y;i!==Oe&&i!==Ne&&i!==Ee||e.push(Jt);if(0===e.length)r.addOp(qt,[i,[null],null]);else{r.addOp(qt,[i,[new Float32Array(e)],t.slice()]);e.length=0;t.set([1/0,1/0,-1/0,-1/0],0)}continue}case Je:r.addOp(i,[new Float32Array(e)]);continue;case St:case At:case Ft:case It:continue;case Ct:if(!(e[0]instanceof Name)){warn(`Expected name for beginMarkedContentProps arg0=${e[0]}`);r.addOp(Ct,["OC",null]);continue}if("OC"===e[0].name){next(l.parseMarkedContentProps(e[1],a).then(e=>{r.addOp(Ct,["OC",e])}).catch(e=>{if(!(e instanceof AbortException)){if(!l.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring beginMarkedContentProps: "${e}".`);r.addOp(Ct,["OC",null])}}));return}e=[e[0].name,e[1]instanceof Dict?e[1].get("MCID"):null];break;default:if(null!==e){for(S=0,k=e.length;S{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getOperatorList - ignoring errors during "${t.name}" task: "${e}".`);closePendingRestoreOPS()}})}getTextContent({stream:e,task:a,resources:r,stateManager:i=null,includeMarkedContent:n=!1,sink:s,seenStyles:o=new Set,viewBox:c,lang:l=null,markedContentData:h=null,disableNormalization:u=!1,keepWhiteSpace:d=!1,prevRefs:f=null,intersector:g=null}){const p=e.dict?.objId,m=new RefSet(f);if(p){if(f?.has(p))throw new Error(`getTextContent - ignoring circular reference: ${p}`);m.put(p)}r||=Dict.empty;i||=new StateManager(new TextState);n&&(h||={level:0});const b={items:[],styles:Object.create(null),lang:l},y={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},w=[" "," "];let x=0;function saveLastChar(e){const t=(x+1)%2,a=" "!==w[x]&&" "===w[t];w[x]=e;x=t;return!d&&a}function shouldAddWhitepsace(){return!d&&" "!==w[x]&&" "===w[(x+1)%2]}function resetLastChars(){w[0]=w[1]=" ";x=0}const S=this,k=this.xref,C=[];let v=null;const F=new LocalImageCache,T=new LocalGStateCache,O=new EvaluatorPreprocessor(e,k,i);let M;function pushWhitespace({width:e=0,height:t=0,transform:a=y.prevTransform,fontName:r=y.fontName}){g?.addExtraChar(" ");b.items.push({str:" ",dir:"ltr",width:e,height:t,transform:a,fontName:r,hasEOL:!1})}function getCurrentTextTransform(){const e=M.font,a=[M.fontSize*M.textHScale,0,0,M.fontSize,0,M.textRise];if(e.isType3Font&&(M.fontSize<=1||e.isCharBBox)&&!isArrayEqual(M.fontMatrix,t)){const t=e.bbox[3]-e.bbox[1];t>0&&(a[3]*=t*M.fontMatrix[3])}return Util.transform(M.ctm,Util.transform(M.textMatrix,a))}function ensureTextContentItem(){if(y.initialized)return y;const{font:e,loadedName:t}=M;if(!o.has(t)){o.add(t);b.styles[t]={fontFamily:e.fallbackName,ascent:e.ascent,descent:e.descent,vertical:e.vertical};if(S.options.fontExtraProperties&&e.systemFontInfo){const a=b.styles[t];a.fontSubstitution=e.systemFontInfo.css;a.fontSubstitutionLoadedName=e.systemFontInfo.loadedName}}y.fontName=t;const a=y.transform=getCurrentTextTransform();if(e.vertical){y.width=y.totalWidth=Math.hypot(a[0],a[1]);y.height=y.totalHeight=0;y.vertical=!0}else{y.width=y.totalWidth=0;y.height=y.totalHeight=Math.hypot(a[2],a[3]);y.vertical=!1}const r=Math.hypot(M.textLineMatrix[0],M.textLineMatrix[1]),i=Math.hypot(M.ctm[0],M.ctm[1]);y.textAdvanceScale=i*r;const{fontSize:n}=M;y.trackingSpaceMin=.102*n;y.notASpace=.03*n;y.negativeSpaceMax=-.2*n;y.spaceInFlowMin=.102*n;y.spaceInFlowMax=.6*n;y.hasEOL=!1;y.initialized=!0;return y}function updateAdvanceScale(){if(!y.initialized)return;const e=Math.hypot(M.textLineMatrix[0],M.textLineMatrix[1]),t=Math.hypot(M.ctm[0],M.ctm[1])*e;if(t!==y.textAdvanceScale){if(y.vertical){y.totalHeight+=y.height*y.textAdvanceScale;y.height=0}else{y.totalWidth+=y.width*y.textAdvanceScale;y.width=0}y.textAdvanceScale=t}}function runBidiTransform(e){let t=e.str.join("");u||(t=function normalizeUnicode(e){if(!ra){ra=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu;ia=new Map([["ſt","ſt"]])}return e.replaceAll(ra,(e,t,a)=>t?t.normalize("NFKC"):ia.get(a))}(t));const a=bidi(t,-1,e.vertical);return{str:a.str,dir:a.dir,width:Math.abs(e.totalWidth),height:Math.abs(e.totalHeight),transform:e.transform,fontName:e.fontName,hasEOL:e.hasEOL}}async function handleSetFont(e,i){const n=await S.loadFont(e,i,r,a);M.loadedName=n.loadedName;M.font=n.font;M.fontMatrix=n.font.fontMatrix||t}function applyInverseRotation(e,t,a){const r=Math.hypot(a[0],a[1]);return[(a[0]*e+a[1]*t)/r,(a[2]*e+a[3]*t)/r]}function compareWithLastPosition(e){const t=getCurrentTextTransform();let a=t[4],r=t[5];if(M.font?.vertical){if(ac[2]||r+ec[3])return!1}else if(a+ec[2]||rc[3])return!1;if(!M.font||!y.prevTransform)return!0;let i=y.prevTransform[4],n=y.prevTransform[5];if(i===a&&n===r)return!0;let s=-1;t[0]&&0===t[1]&&0===t[2]?s=t[0]>0?0:180:t[1]&&0===t[0]&&0===t[3]&&(s=t[1]>0?90:270);switch(s){case 0:break;case 90:[a,r]=[r,a];[i,n]=[n,i];break;case 180:[a,r,i,n]=[-a,-r,-i,-n];break;case 270:[a,r]=[-r,-a];[i,n]=[-n,-i];break;default:[a,r]=applyInverseRotation(a,r,t);[i,n]=applyInverseRotation(i,n,y.prevTransform)}if(M.font.vertical){const e=(n-r)/y.textAdvanceScale,t=a-i,s=Math.sign(y.height);if(e.5*y.width){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(t)>y.width){appendEOL();return!0}e<=s*y.notASpace&&resetLastChars();if(e<=s*y.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({height:Math.abs(e)})}else y.height+=e;else if(!addFakeSpaces(e,y.prevTransform,s))if(0===y.str.length){resetLastChars();pushWhitespace({height:Math.abs(e)})}else y.height+=e;Math.abs(t)>.25*y.width&&flushTextContentItem();return!0}const o=(a-i)/y.textAdvanceScale,l=r-n,h=Math.sign(y.width);if(o.5*y.height){appendEOL();return!0}resetLastChars();flushTextContentItem();return!0}if(Math.abs(l)>y.height){appendEOL();return!0}o<=h*y.notASpace&&resetLastChars();if(o<=h*y.trackingSpaceMin)if(shouldAddWhitepsace()){resetLastChars();flushTextContentItem();pushWhitespace({width:Math.abs(o)})}else y.width+=o;else if(!addFakeSpaces(o,y.prevTransform,h))if(0===y.str.length){resetLastChars();pushWhitespace({width:Math.abs(o)})}else y.width+=o;Math.abs(l)>.25*y.height&&flushTextContentItem();return!0}function buildTextContentItem({chars:e,extraSpacing:t}){const a=M.font;if(!e){const e=M.charSpacing+t;e&&(a.vertical?M.translateTextMatrix(0,-e):M.translateTextMatrix(e*M.textHScale,0));d&&compareWithLastPosition(0);return}const r=a.charsToGlyphs(e),i=M.fontMatrix[0]*M.fontSize;for(let e=0,n=r.length;e0){const e=C.join("");C.length=0;buildTextContentItem({chars:e,extraSpacing:0})}break;case Ze:if(!i.state.font){S.ensureStateFont(i.state);continue}buildTextContentItem({chars:w[0],extraSpacing:0});break;case et:if(!i.state.font){S.ensureStateFont(i.state);continue}M.carriageReturn();buildTextContentItem({chars:w[0],extraSpacing:0});break;case tt:if(!i.state.font){S.ensureStateFont(i.state);continue}M.wordSpacing=w[0];M.charSpacing=w[1];M.carriageReturn();buildTextContentItem({chars:w[2],extraSpacing:0});break;case xt:flushTextContentItem();v??=r.get("XObject")||Dict.empty;y=w[0]instanceof Name;p=w[0].name;if(y&&F.getByName(p))break;next(new Promise(function(e,t){if(!y)throw new FormatError("XObject must be referred to by name.");let f=v.getRaw(p);if(f instanceof Ref){if(F.getByRef(f)){e();return}if(S.globalImageCache.getData(f,S.pageIndex)){e();return}f=k.fetch(f)}if(!(f instanceof BaseStream))throw new FormatError("XObject should be a stream");const{dict:g}=f,b=g.get("Subtype");if(!(b instanceof Name))throw new FormatError("XObject should have a Name subtype");if("Form"!==b.name){F.set(p,g.objId,!0);e();return}const w=i.state.clone(),x=new StateManager(w),C=lookupMatrix(g.getArray("Matrix"),null);C&&x.transform(C);const T=g.get("Resources");enqueueChunk();const O={enqueueInvoked:!1,enqueue(e,t){this.enqueueInvoked=!0;s.enqueue(e,t)},get desiredSize(){return s.desiredSize??0},get ready(){return s.ready}};S.getTextContent({stream:f,task:a,resources:T instanceof Dict?T:r,stateManager:x,includeMarkedContent:n,sink:s&&O,seenStyles:o,viewBox:c,lang:l,markedContentData:h,disableNormalization:u,keepWhiteSpace:d,prevRefs:m}).then(function(){O.enqueueInvoked||F.set(p,g.objId,!0);e()},t)}).catch(function(e){if(!(e instanceof AbortException)){if(!S.options.ignoreErrors)throw e;warn(`getTextContent - ignoring XObject: "${e}".`)}}));return;case be:y=w[0]instanceof Name;p=w[0].name;if(y&&T.getByName(p))break;next(new Promise(function(e,t){if(!y)throw new FormatError("GState must be referred to by name.");const a=r.get("ExtGState");if(!(a instanceof Dict))throw new FormatError("ExtGState should be a dictionary.");const i=a.get(p);if(!(i instanceof Dict))throw new FormatError("GState should be a dictionary.");const n=i.get("Font");if(n){flushTextContentItem();M.fontName=null;M.fontSize=n[1];handleSetFont(null,n[0]).then(e,t)}else{T.set(p,i.objId,!0);e()}}).catch(function(e){if(!(e instanceof AbortException)){if(!S.options.ignoreErrors)throw e;warn(`getTextContent - ignoring ExtGState: "${e}".`)}}));return;case kt:flushTextContentItem();if(n){h.level++;b.items.push({type:"beginMarkedContent",tag:w[0]instanceof Name?w[0].name:null})}break;case Ct:flushTextContentItem();if(n){h.level++;let e=null;w[1]instanceof Dict&&(e=w[1].get("MCID"));b.items.push({type:"beginMarkedContentProps",id:Number.isInteger(e)?`${S.idFactory.getPageObjId()}_mc${e}`:null,tag:w[0]instanceof Name?w[0].name:null})}break;case vt:flushTextContentItem();if(n){if(0===h.level)break;h.level--;b.items.push({type:"endMarkedContent"})}break;case we:!e||e.font===M.font&&e.fontSize===M.fontSize&&e.fontName===M.fontName||flushTextContentItem()}if(b.items.length>=(s?.desiredSize??1)){g=!0;break}}if(g)next(An);else{flushTextContentItem();enqueueChunk();e()}}).catch(e=>{if(!(e instanceof AbortException)){if(!this.options.ignoreErrors)throw e;warn(`getTextContent - ignoring errors during "${a.name}" task: "${e}".`);flushTextContentItem();enqueueChunk()}})}async extractDataStructures(e,t){const a=this.xref;let r;const i=this.readToUnicode(t.toUnicode);if(t.composite){const a=e.get("CIDSystemInfo");a instanceof Dict&&(t.cidSystemInfo={registry:stringToPDFString(a.get("Registry")),ordering:stringToPDFString(a.get("Ordering")),supplement:a.get("Supplement")});try{const t=e.get("CIDToGIDMap");t instanceof BaseStream&&(r=t.getBytes())}catch(e){if(!this.options.ignoreErrors)throw e;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${e}".`)}}const n=[];let s,o=null;if(e.has("Encoding")){s=e.get("Encoding");if(s instanceof Dict){o=s.get("BaseEncoding");o=o instanceof Name?o.name:null;if(s.has("Differences")){const e=s.get("Differences");let t=0;for(const r of e){const e=a.fetchIfRef(r);if("number"==typeof e)t=e;else{if(!(e instanceof Name))throw new FormatError(`Invalid entry in 'Differences' array: ${e}`);n[t++]=e.name}}}}else if(s instanceof Name)o=s.name;else{const e="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(e);warn(e)}"MacRomanEncoding"!==o&&"MacExpertEncoding"!==o&&"WinAnsiEncoding"!==o&&(o=null)}const c=!t.file||t.isInternalFont,l=Xr()[t.name];o&&c&&l&&(o=null);if(o)t.defaultEncoding=getEncoding(o);else{let e=!!(t.flags&Ar);const a=!!(t.flags&kr);if("TrueType"===t.type&&e&&a&&0!==n.length){t.flags&=~Ar;e=!1}s=lr;"TrueType"!==t.type||a||(s=hr);if(e||l){s=cr;c&&(/Symbol/i.test(t.name)?s=ur:/Dingbats/i.test(t.name)?s=dr:/Wingdings/i.test(t.name)&&(s=hr))}t.defaultEncoding=s}t.differences=n;t.baseEncodingName=o;t.hasEncoding=!!o||n.length>0;t.dict=e;t.toUnicode=await i;const h=await this.buildToUnicode(t);t.toUnicode=h;r&&(t.cidToGidMap=this.readCidToGidMap(r,h));return t}_simpleFontToUnicode(e,t=!1){assert(!e.composite,"Must be a simple font.");const a=[],r=e.defaultEncoding.slice(),i=e.baseEncodingName,n=e.differences;for(const e in n){const t=n[e];".notdef"!==t&&(r[e]=t)}const s=fr();for(const n in r){let o=r[n];if(""===o)continue;let c=s[o];if(void 0!==c){a[n]=String.fromCharCode(c);continue}let l=0;switch(o[0]){case"G":3===o.length&&(l=parseInt(o.substring(1),16));break;case"g":5===o.length&&(l=parseInt(o.substring(1),16));break;case"C":case"c":if(o.length>=3&&o.length<=4){const a=o.substring(1);if(t){l=parseInt(a,16);break}l=+a;if(Number.isNaN(l)&&Number.isInteger(parseInt(a,16)))return this._simpleFontToUnicode(e,!0)}break;case"u":c=getUnicodeForGlyph(o,s);-1!==c&&(l=c);break;default:switch(o){case"f_h":case"f_t":case"T_h":a[n]=o.replaceAll("_","");continue}}if(l>0&&l<=1114111&&Number.isInteger(l)){if(i&&l===+n){const e=getEncoding(i);if(e&&(o=e[n])){a[n]=String.fromCharCode(s[o]);continue}}a[n]=String.fromCodePoint(l)}}return a}async buildToUnicode(e){e.hasIncludedToUnicodeMap=e.toUnicode?.length>0;if(e.hasIncludedToUnicodeMap){!e.composite&&e.hasEncoding&&(e.fallbackToUnicode=this._simpleFontToUnicode(e));return e.toUnicode}if(!e.composite)return new ToUnicodeMap(this._simpleFontToUnicode(e));if(e.composite&&(e.cMap.builtInCMap&&!(e.cMap instanceof IdentityCMap)||"Adobe"===e.cidSystemInfo?.registry&&("GB1"===e.cidSystemInfo.ordering||"CNS1"===e.cidSystemInfo.ordering||"Japan1"===e.cidSystemInfo.ordering||"Korea1"===e.cidSystemInfo.ordering))){const{registry:t,ordering:a}=e.cidSystemInfo,r=Name.get(`${t}-${a}-UCS2`),i=await CMapFactory.create({encoding:r,fetchBuiltInCMap:this._fetchBuiltInCMapBound,useCMap:null}),n=[],s=[];e.cMap.forEach(function(e,t){if(t>65535)throw new FormatError("Max size of CID is 65,535");const a=i.lookup(t);if(a){s.length=0;for(let e=0,t=a.length;e>1;(0!==i||t.has(n))&&(a[n]=i)}return a}extractWidths(e,t,a){const r=this.xref;let i=[],n=0;const s=[];let o;if(a.composite){const t=e.get("DW");n="number"==typeof t?Math.ceil(t):1e3;const c=e.get("W");if(Array.isArray(c))for(let e=0,t=c.length;e{const t=c.get(e),r=new OperatorList;return n.getOperatorList({stream:t,task:a,resources:l,operatorList:r}).then(()=>{switch(r.fnArray[0]){case rt:this.#fe(r,b);break;case at:b||this.#ge(r)}h[e]=r.getIR();for(const e of r.dependencies)i.add(e)}).catch(function(t){warn(`Type3 font resource "${e}" is not available.`);const a=new OperatorList;h[e]=a.getIR()})});this.#de=o.then(()=>{r.charProcOperatorList=h;if(this._bbox){r.isCharBBox=!0;r.bbox=this._bbox}});return this.#de}#fe(e,t=NaN){const a=Util.normalizeRect(e.argsArray[0].slice(2)),r=a[2]-a[0],i=a[3]-a[1],n=Math.hypot(r,i);if(0===r||0===i){e.fnArray.splice(0,1);e.argsArray.splice(0,1)}else if(0===t||Math.round(n/t)>=10){this._bbox??=[1/0,1/0,-1/0,-1/0];Util.rectBoundingBox(...a,this._bbox)}let s=0,o=e.length;for(;s=Se&&n<=Pe;if(i.variableArgs)o>s&&info(`Command ${r}: expected [0, ${s}] args, but received ${o} args.`);else{if(o!==s){const e=this.nonProcessedArgs;for(;o>s;){e.push(t.shift());o--}for(;oEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError(`Invalid ${e}`);warn(`Skipping ${e}`);null!==t&&(t.length=0);continue}}this.preprocessCommand(n,t);e.fn=n;e.args=t;return!0}if(a===sa)return!1;if(null!==a){null===t&&(t=[]);t.push(a);if(t.length>33)throw new FormatError("Too many arguments")}}}preprocessCommand(e,t){switch(0|e){case ye:this.stateManager.save();break;case we:this.stateManager.restore();break;case xe:this.stateManager.transform(t)}}}class DefaultAppearanceEvaluator extends EvaluatorPreprocessor{constructor(e){super(new StringStream(e))}parse(){const e={fn:0,args:[]},t={fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3)};try{for(;;){e.args.length=0;if(!this.read(e))break;if(0!==this.savedStatesDepth)continue;const{fn:a,args:r}=e;switch(0|a){case Ge:const[e,a]=r;e instanceof Name&&(t.fontName=e.name);"number"==typeof a&&a>0&&(t.fontSize=a);break;case ft:ColorSpaceUtils.rgb.getRgbItem(r,0,t.fontColor,0);break;case ut:ColorSpaceUtils.gray.getRgbItem(r,0,t.fontColor,0);break;case pt:ColorSpaceUtils.cmyk.getRgbItem(r,0,t.fontColor,0)}}}catch(e){warn(`parseDefaultAppearance - ignoring errors: "${e}".`)}return t}}function parseDefaultAppearance(e){return new DefaultAppearanceEvaluator(e).parse()}class AppearanceStreamEvaluator extends EvaluatorPreprocessor{constructor(e,t,a,r){super(e);this.stream=e;this.evaluatorOptions=t;this.xref=a;this.globalColorSpaceCache=r;this.resources=e.dict?.get("Resources")}parse(){const e={fn:0,args:[]};let t={scaleFactor:1,fontSize:0,fontName:"",fontColor:new Uint8ClampedArray(3),fillColorSpace:ColorSpaceUtils.gray},a=!1;const r=[];try{for(;;){e.args.length=0;if(a||!this.read(e))break;const{fn:i,args:n}=e;switch(0|i){case ye:r.push({scaleFactor:t.scaleFactor,fontSize:t.fontSize,fontName:t.fontName,fontColor:t.fontColor.slice(),fillColorSpace:t.fillColorSpace});break;case we:t=r.pop()||t;break;case Je:t.scaleFactor*=Math.hypot(n[0],n[1]);break;case Ge:const[e,i]=n;e instanceof Name&&(t.fontName=e.name);"number"==typeof i&&i>0&&(t.fontSize=i*t.scaleFactor);break;case nt:t.fillColorSpace=ColorSpaceUtils.parse({cs:n[0],xref:this.xref,resources:this.resources,pdfFunctionFactory:this._pdfFunctionFactory,globalColorSpaceCache:this.globalColorSpaceCache,localColorSpaceCache:this._localColorSpaceCache});break;case ct:t.fillColorSpace.getRgbItem(n,0,t.fontColor,0);break;case ft:ColorSpaceUtils.rgb.getRgbItem(n,0,t.fontColor,0);break;case ut:ColorSpaceUtils.gray.getRgbItem(n,0,t.fontColor,0);break;case pt:ColorSpaceUtils.cmyk.getRgbItem(n,0,t.fontColor,0);break;case Ze:case Qe:case et:case tt:a=!0}}}catch(e){warn(`parseAppearanceStream - ignoring errors: "${e}".`)}this.stream.reset();delete t.scaleFactor;delete t.fillColorSpace;return t}get _localColorSpaceCache(){return shadow(this,"_localColorSpaceCache",new LocalColorSpaceCache)}get _pdfFunctionFactory(){return shadow(this,"_pdfFunctionFactory",new PDFFunctionFactory({xref:this.xref,isEvalSupported:this.evaluatorOptions.isEvalSupported}))}}function getPdfColor(e,t){if(e[0]===e[1]&&e[1]===e[2]){return`${numberToString(e[0]/255)} ${t?"g":"G"}`}return Array.from(e,e=>numberToString(e/255)).join(" ")+" "+(t?"rg":"RG")}class FakeUnicodeFont{constructor(e,t){this.xref=e;this.widths=null;this.firstChar=1/0;this.lastChar=-1/0;this.fontFamily=t;const a=new OffscreenCanvas(1,1);this.ctxMeasure=a.getContext("2d",{willReadFrequently:!0});FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1);this.fontName=Name.get(`InvalidPDFjsFont_${t}_${FakeUnicodeFont._fontNameId++}`)}get fontDescriptorRef(){if(!FakeUnicodeFont._fontDescriptorRef){const e=new Dict(this.xref);e.setIfName("Type","FontDescriptor");e.set("FontName",this.fontName);e.set("FontFamily","MyriadPro Regular");e.set("FontBBox",[0,0,0,0]);e.setIfName("FontStretch","Normal");e.set("FontWeight",400);e.set("ItalicAngle",0);FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(e)}return FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.setIfName("Type","Font");e.setIfName("Subtype","CIDFontType0");e.setIfName("CIDToGIDMap","Identity");e.set("FirstChar",this.firstChar);e.set("LastChar",this.lastChar);e.set("FontDescriptor",this.fontDescriptorRef);e.set("DW",1e3);const t=[],a=[...this.widths.entries()].sort();let r=null,i=null;for(const[e,n]of a)if(r)if(e===r+i.length)i.push(n);else{t.push(r,i);r=e;i=[n]}else{r=e;i=[n]}r&&t.push(r,i);e.set("W",t);const n=new Dict(this.xref);n.set("Ordering","Identity");n.set("Registry","Adobe");n.set("Supplement",0);e.set("CIDSystemInfo",n);return this.xref.getNewPersistentRef(e)}get baseFontRef(){const e=new Dict(this.xref);e.set("BaseFont",this.fontName);e.setIfName("Type","Font");e.setIfName("Subtype","Type0");e.setIfName("Encoding","Identity-H");e.set("DescendantFonts",[this.descendantFontRef]);e.setIfName("ToUnicode","Identity-H");return this.xref.getNewPersistentRef(e)}get resources(){const e=new Dict(this.xref),t=new Dict(this.xref);t.set(this.fontName.name,this.baseFontRef);e.set("Font",t);return e}_createContext(){this.widths=new Map;this.ctxMeasure.font=`1000px ${this.fontFamily}`;return this.ctxMeasure}createFontResources(e){const t=this._createContext();for(const a of e.split(/\r\n?|\n/))for(const e of a.split("")){const a=e.charCodeAt(0);if(this.widths.has(a))continue;const r=t.measureText(e),i=Math.ceil(r.width);this.widths.set(a,i);this.firstChar=Math.min(a,this.firstChar);this.lastChar=Math.max(a,this.lastChar)}return this.resources}static getFirstPositionInfo(e,t,i){const[n,s,o,c]=e;let l=o-n,h=c-s;t%180!=0&&([l,h]=[h,l]);const u=a*i;return{coords:[0,h+r*i-u],bbox:[0,0,l,h],matrix:0!==t?getRotationMatrix(t,h,u):void 0}}createAppearance(e,t,i,n,s,o){const c=this._createContext(),l=[];let h=-1/0;for(const t of e.split(/\r\n?|\n/)){l.push(t);const e=c.measureText(t).width;h=Math.max(h,e);for(const e of codePointIter(t)){const t=String.fromCodePoint(e);let a=this.widths.get(e);if(void 0===a){const r=c.measureText(t);a=Math.ceil(r.width);this.widths.set(e,a);this.firstChar=Math.min(e,this.firstChar);this.lastChar=Math.max(e,this.lastChar)}}}h*=n/1e3;const[u,d,f,g]=t;let p=f-u,m=g-d;i%180!=0&&([p,m]=[m,p]);let b=1;h>p&&(b=p/h);let y=1;const w=a*n,x=r*n,S=w*l.length;S>m&&(y=m/S);const k=n*Math.min(b,y),C=["q",`0 0 ${numberToString(p)} ${numberToString(m)} re W n`,"BT",`1 0 0 1 0 ${numberToString(m+x)} Tm 0 Tc ${getPdfColor(s,!0)}`,`/${this.fontName.name} ${numberToString(k)} Tf`],{resources:v}=this;if(1!==(o="number"==typeof o&&o>=0&&o<=1?o:1)){C.push("/R0 gs");const e=new Dict(this.xref),t=new Dict(this.xref);t.set("ca",o);t.set("CA",o);t.setIfName("Type","ExtGState");e.set("R0",t);v.set("ExtGState",e)}const F=numberToString(w);for(const e of l)C.push(`0 -${F} Td <${stringToUTF16HexString(e)}> Tj`);C.push("ET","Q");const T=C.join("\n"),O=new Dict(this.xref);O.setIfName("Subtype","Form");O.setIfName("Type","XObject");O.set("BBox",[0,0,p,m]);O.set("Length",T.length);O.set("Resources",v);if(i){const e=getRotationMatrix(i,p,m);O.set("Matrix",e)}const M=new StringStream(T);M.dict=O;return M}}const kn=["m/d","m/d/yy","mm/dd/yy","mm/yy","d-mmm","d-mmm-yy","dd-mmm-yy","yy-mm-dd","mmm-yy","mmmm-yy","mmm d, yyyy","mmmm d, yyyy","m/d/yy h:MM tt","m/d/yy HH:MM"],Cn=["HH:MM","h:MM tt","HH:MM:ss","h:MM:ss tt"];class NameOrNumberTree{constructor(e,t,a){this.root=e;this.xref=t;this._type=a}getAll(){const e=new Map;if(!this.root)return e;const t=this.xref,a=new RefSet;a.put(this.root);const r=[this.root];for(;r.length>0;){const i=t.fetchIfRef(r.shift());if(!(i instanceof Dict))continue;if(i.has("Kids")){const e=i.get("Kids");if(!Array.isArray(e))continue;for(const t of e){if(a.has(t))throw new FormatError(`Duplicate entry in "${this._type}" tree.`);r.push(t);a.put(t)}continue}const n=i.get(this._type);if(Array.isArray(n))for(let a=0,r=n.length;a10){warn(`Search depth limit reached for "${this._type}" tree.`);return null}const i=a.get("Kids");if(!Array.isArray(i))return null;let n=0,s=i.length-1;for(;n<=s;){const r=n+s>>1,o=t.fetchIfRef(i[r]),c=o.get("Limits");if(et.fetchIfRef(c[1]))){a=o;break}n=r+1}}if(n>s)return null}const i=a.get(this._type);if(Array.isArray(i)){let a=0,r=i.length-2;for(;a<=r;){const n=a+r>>1,s=n+(1&n),o=t.fetchIfRef(i[s]);if(eo))return i[s+1];a=s+2}}}return null}get(e){return this.xref.fetchIfRef(this.getRaw(e))}}class NameTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Names")}}class NumberTree extends NameOrNumberTree{constructor(e,t){super(e,t,"Nums")}}function clearGlobalCaches(){!function clearPatternCaches(){gi=Object.create(null)}();!function clearPrimitiveCaches(){oa=Object.create(null);ca=Object.create(null);la=Object.create(null)}();!function clearUnicodeCaches(){yr.clear()}();JpxImage.cleanup()}function pickPlatformItem(e){return e instanceof Dict?e.has("UF")?e.get("UF"):e.has("F")?e.get("F"):e.has("Unix")?e.get("Unix"):e.has("Mac")?e.get("Mac"):e.has("DOS")?e.get("DOS"):null:null}class FileSpec{#pe=!1;constructor(e,t,a=!1){if(e instanceof Dict){this.xref=t;this.root=e;e.has("FS")&&(this.fs=e.get("FS"));e.has("RF")&&warn("Related file specifications are not supported");a||(e.has("EF")?this.#pe=!0:warn("Non-embedded file specifications are not supported"))}}get filename(){let e="";const t=pickPlatformItem(this.root);t&&"string"==typeof t&&(e=stringToPDFString(t,!0).replaceAll("\\\\","\\").replaceAll("\\/","/").replaceAll("\\","/"));return shadow(this,"filename",e||"unnamed")}get content(){if(!this.#pe)return null;this._contentRef||=pickPlatformItem(this.root?.get("EF"));let e=null;if(this._contentRef){const t=this.xref.fetchIfRef(this._contentRef);t instanceof BaseStream?e=t.getBytes():warn("Embedded file specification points to non-existing/invalid content")}else warn("Embedded file specification does not have any content");return e}get description(){let e="";const t=this.root?.get("Desc");t&&"string"==typeof t&&(e=stringToPDFString(t));return shadow(this,"description",e)}get serializable(){return{rawFilename:this.filename,filename:(e=this.filename,e.substring(e.lastIndexOf("/")+1)),content:this.content,description:this.description};var e}}const vn=0,Fn=-2,In=-3,Tn=-4,On=-5,Mn=-6,Dn=-9;function isWhitespace(e,t){const a=e[t];return" "===a||"\n"===a||"\r"===a||"\t"===a}class XMLParserBase{_resolveEntities(e){return e.replaceAll(/&([^;]+);/g,(e,t)=>{if("#x"===t.substring(0,2))return String.fromCodePoint(parseInt(t.substring(2),16));if("#"===t.substring(0,1))return String.fromCodePoint(parseInt(t.substring(1),10));switch(t){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(t)})}_parseContent(e,t){const a=[];let r=t;function skipWs(){for(;r"!==e[r]&&"/"!==e[r];)++r;const i=e.substring(t,r);skipWs();for(;r"!==e[r]&&"/"!==e[r]&&"?"!==e[r];){skipWs();let t="",i="";for(;r"!==e[a]&&"?"!==e[a]&&"/"!==e[a];)++a;const r=e.substring(t,a);!function skipWs(){for(;a"!==e[a+1]);)++a;return{name:r,value:e.substring(i,a),parsed:a-t}}parseXml(e){let t=0;for(;t",a);if(t<0){this.onError(Dn);return}this.onEndElement(e.substring(a,t));a=t+1;break;case"?":++a;const r=this._parseProcessingInstruction(e,a);if("?>"!==e.substring(a+r.parsed,a+r.parsed+2)){this.onError(In);return}this.onPi(r.name,r.value);a+=r.parsed+2;break;case"!":if("--"===e.substring(a+1,a+3)){t=e.indexOf("--\x3e",a+3);if(t<0){this.onError(On);return}this.onComment(e.substring(a+3,t));a=t+3}else if("[CDATA["===e.substring(a+1,a+8)){t=e.indexOf("]]>",a+8);if(t<0){this.onError(Fn);return}this.onCdata(e.substring(a+8,t));a=t+3}else{if("DOCTYPE"!==e.substring(a+1,a+8)){this.onError(Mn);return}{const r=e.indexOf("[",a+8);let i=!1;t=e.indexOf(">",a+8);if(t<0){this.onError(Tn);return}if(r>0&&t>r){t=e.indexOf("]>",a+8);if(t<0){this.onError(Tn);return}i=!0}const n=e.substring(a+8,t+(i?1:0));this.onDoctype(n);a=t+(i?2:1)}}break;default:const i=this._parseContent(e,a);if(null===i){this.onError(Mn);return}let n=!1;if("/>"===e.substring(a+i.parsed,a+i.parsed+2))n=!0;else if(">"!==e.substring(a+i.parsed,a+i.parsed+1)){this.onError(Dn);return}this.onBeginElement(i.name,i.attributes,n);a+=i.parsed+(n?2:1)}}else{for(;ae.textContent).join(""):this.nodeValue||""}get children(){return this.childNodes||[]}hasChildNodes(){return this.childNodes?.length>0}searchNode(e,t){if(t>=e.length)return this;const a=e[t];if(a.name.startsWith("#")&&t0){r.push([i,0]);i=i.childNodes[0]}else{if(0===r.length)return null;for(;0!==r.length;){const[e,t]=r.pop(),a=t+1;if(a");for(const t of this.childNodes)t.dump(e);e.push(``)}else this.nodeValue?e.push(`>${encodeToXmlString(this.nodeValue)}`):e.push("/>")}else e.push(encodeToXmlString(this.nodeValue))}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes:e=!1,lowerCaseName:t=!1}){super();this._currentFragment=null;this._stack=null;this._errorCode=vn;this._hasAttributes=e;this._lowerCaseName=t}parseFromString(e){this._currentFragment=[];this._stack=[];this._errorCode=vn;this.parseXml(e);if(this._errorCode!==vn)return;const[t]=this._currentFragment;return t?{documentElement:t}:void 0}onText(e){if(function isWhitespaceString(e){for(let t=0,a=e.length;t\\376\\377([^<]+)/g,function(e,t){const a=t.replaceAll(/\\([0-3])([0-7])([0-7])/g,function(e,t,a,r){return String.fromCharCode(64*t+8*a+1*r)}).replaceAll(/&(amp|apos|gt|lt|quot);/g,function(e,t){switch(t){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${t} isn't defined.`)}),r=[">"];for(let e=0,t=a.length;e=32&&t<127&&60!==t&&62!==t&&38!==t?r.push(String.fromCharCode(t)):r.push("&#x"+(65536+t).toString(16).substring(1)+";")}return r.join("")})}_getSequence(e){const t=e.nodeName;return"rdf:bag"!==t&&"rdf:seq"!==t&&"rdf:alt"!==t?null:e.childNodes.filter(e=>"rdf:li"===e.nodeName)}_parseArray(e){if(!e.hasChildNodes())return;const[t]=e.childNodes,a=this._getSequence(t)||[];this._metadataMap.set(e.nodeName,a.map(e=>e.textContent.trim()))}_parse(e){let t=e.documentElement;if("rdf:rdf"!==t.nodeName){t=t.firstChild;for(;t&&"rdf:rdf"!==t.nodeName;)t=t.nextSibling}if(t&&"rdf:rdf"===t.nodeName&&t.hasChildNodes())for(const e of t.childNodes)if("rdf:description"===e.nodeName)for(const t of e.childNodes){const e=t.nodeName;switch(e){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(t);continue}this._metadataMap.set(e,t.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const Bn=1,Rn=2,Nn=3,En=4,Pn=5;class StructTreeRoot{constructor(e,t,a){this.xref=e;this.dict=t;this.ref=a instanceof Ref?a:null;this.roleMap=new Map;this.structParentIds=null;this.kidRefToPosition=void 0}getKidPosition(e){if(void 0===this.kidRefToPosition){const e=this.dict.get("K");if(Array.isArray(e)){const t=this.kidRefToPosition=new Map;for(let a=0,r=e.length;a=0||(e.parentTreeId=a++);s=!1}}if(s){for(const e of t.values())for(const t of e){delete t.parentTreeId;delete t.structTreeParent}return!1}return!0}async updateStructureTree({newAnnotationsByPage:e,pdfManager:t,changes:a}){const{ref:r,xref:i}=this,n=this.dict.clone(),s=new RefSetCache;s.put(r,n);let o,c=n.getRaw("ParentTree");if(c instanceof Ref)o=i.fetch(c);else{o=c;c=i.getNewTemporaryRef();n.set("ParentTree",c)}o=o.clone();s.put(c,o);let l=o.getRaw("Nums"),h=null;if(l instanceof Ref){h=l;l=i.fetch(h)}l=l.slice();h||o.set("Nums",l);const u=await StructTreeRoot.#be({newAnnotationsByPage:e,structTreeRootRef:r,structTreeRoot:this,kids:null,nums:l,xref:i,pdfManager:t,changes:a,cache:s});if(-1!==u){n.set("ParentTreeNextKey",u);h&&s.put(h,l);for(const[e,t]of s.items())a.put(e,{data:t})}}static async#be({newAnnotationsByPage:e,structTreeRootRef:t,structTreeRoot:a,kids:r,nums:i,xref:n,pdfManager:s,changes:o,cache:c}){const l=Name.get("OBJR");let h,u=-1;for(const[d,f]of e){const e=await s.getPage(d),{ref:g}=e,p=g instanceof Ref;for(const{accessibilityData:s,ref:m,parentTreeId:b,structTreeParent:y}of f){if(!s?.type)continue;const{structParent:f}=s;if(a&&Number.isInteger(f)&&f>=0){let t=(h||=new Map).get(d);if(void 0===t){t=new StructTreePage(a,e.pageDict).collectObjects(g);h.set(d,t)}const r=t?.get(f);if(r){const e=n.fetch(r).clone();StructTreeRoot.#we(e,s);o.put(r,{data:e});continue}}u=Math.max(u,b);const w=n.getNewTemporaryRef(),x=new Dict(n);StructTreeRoot.#we(x,s);await this.#xe({structTreeParent:y,tagDict:x,newTagRef:w,structTreeRootRef:t,fallbackKids:r,xref:n,cache:c});const S=new Dict(n);x.set("K",S);S.set("Type",l);p&&S.set("Pg",g);S.set("Obj",m);c.put(w,x);i.push(b,w)}}return u+1}static#we(e,{type:t,title:a,lang:r,alt:i,expanded:n,actualText:s}){e.set("S",Name.get(t));a&&e.set("T",stringToAsciiOrUTF16BE(a));r&&e.set("Lang",stringToAsciiOrUTF16BE(r));i&&e.set("Alt",stringToAsciiOrUTF16BE(i));n&&e.set("E",stringToAsciiOrUTF16BE(n));s&&e.set("ActualText",stringToAsciiOrUTF16BE(s))}static#ye({elements:e,xref:t,pageDict:a,numberTree:r}){const i=new Map;for(const t of e)if(t.structTreeParentId){const e=parseInt(t.structTreeParentId.split("_mc")[1],10);let a=i.get(e);if(!a){a=[];i.set(e,a)}a.push(t)}const n=a.get("StructParents");if(!Number.isInteger(n))return;const s=r.get(n),updateElement=(e,a,r)=>{const n=i.get(e);if(n){const e=a.getRaw("P"),i=t.fetchIfRef(e);if(e instanceof Ref&&i instanceof Dict){const e={ref:r,dict:a};for(const t of n)t.structTreeParent=e}return!0}return!1};for(const e of s){if(!(e instanceof Ref))continue;const a=t.fetch(e),r=a.get("K");if(Number.isInteger(r))updateElement(r,a,e);else if(Array.isArray(r))for(let i of r){i=t.fetchIfRef(i);if(Number.isInteger(i)&&updateElement(i,a,e))break;if(!(i instanceof Dict))continue;if(!isName(i.get("Type"),"MCR"))break;const r=i.get("MCID");if(Number.isInteger(r)&&updateElement(r,a,e))break}}}static async#xe({structTreeParent:e,tagDict:t,newTagRef:a,structTreeRootRef:r,fallbackKids:i,xref:n,cache:s}){let o,c=null;if(e){({ref:c}=e);o=e.dict.getRaw("P")||r}else o=r;t.set("P",o);const l=n.fetchIfRef(o);if(!l){i.push(a);return}let h=s.get(o);if(!h){h=l.clone();s.put(o,h)}const u=h.getRaw("K");let d=u instanceof Ref?s.get(u):null;if(!d){d=n.fetchIfRef(u);d=Array.isArray(d)?d.slice():[u];const e=n.getNewTemporaryRef();h.set("K",e);s.put(e,d)}const f=d.indexOf(c);d.splice(f>=0?f+1:d.length,0,a)}}class StructElementNode{constructor(e,t){this.tree=e;this.xref=e.xref;this.dict=t;this.kids=[];this.parseKids()}get role(){const e=this.dict.get("S"),t=e instanceof Name?e.name:"",{root:a}=this.tree;return a.roleMap.get(t)??t}get mathML(){let e=this.dict.get("AF")||[];Array.isArray(e)||(e=[e]);for(let t of e){t=this.xref.fetchIfRef(t);if(!(t instanceof Dict))continue;if(!isName(t.get("Type"),"Filespec"))continue;if(!isName(t.get("AFRelationship"),"Supplement"))continue;const e=t.get("EF");if(!(e instanceof Dict))continue;const a=e.get("UF")||e.get("F");if(a instanceof BaseStream&&(isName(a.dict.get("Type"),"EmbeddedFile")&&isName(a.dict.get("Subtype"),"application/mathml+xml")))return stringToUTF8String(a.getString())}const t=this.dict.get("A");if(t instanceof Dict){if(isName(t.get("O"),"MSFT_Office")){const e=t.get("MSFT_MathML");return e?stringToPDFString(e):null}}return null}parseKids(){let e=null;const t=this.dict.getRaw("Pg");t instanceof Ref&&(e=t.toString());const a=this.dict.get("K");if(Array.isArray(a))for(const t of a){const a=this.parseKid(e,this.xref.fetchIfRef(t));a&&this.kids.push(a)}else{const t=this.parseKid(e,a);t&&this.kids.push(t)}}parseKid(e,t){if(Number.isInteger(t))return this.tree.pageDict.objId!==e?null:new StructElement({type:Bn,mcid:t,pageObjId:e});if(!(t instanceof Dict))return null;const a=t.getRaw("Pg");a instanceof Ref&&(e=a.toString());const r=t.get("Type")instanceof Name?t.get("Type").name:null;if("MCR"===r){if(this.tree.pageDict.objId!==e)return null;const a=t.getRaw("Stm");return new StructElement({type:Rn,refObjId:a instanceof Ref?a.toString():null,pageObjId:e,mcid:t.get("MCID")})}if("OBJR"===r){if(this.tree.pageDict.objId!==e)return null;const a=t.getRaw("Obj");return new StructElement({type:Nn,refObjId:a instanceof Ref?a.toString():null,pageObjId:e})}return new StructElement({type:Pn,dict:t})}}class StructElement{constructor({type:e,dict:t=null,mcid:a=null,pageObjId:r=null,refObjId:i=null}){this.type=e;this.dict=t;this.mcid=a;this.pageObjId=r;this.refObjId=i;this.parentNode=null}}class StructTreePage{constructor(e,t){this.root=e;this.xref=e?.xref??null;this.rootDict=e?.dict??null;this.pageDict=t;this.nodes=[]}collectObjects(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return null;const t=this.rootDict.get("ParentTree");if(!t)return null;const a=this.root.structParentIds?.get(e);if(!a)return null;const r=new Map,i=new NumberTree(t,this.xref);for(const[e]of a){const t=i.getRaw(e);t instanceof Ref&&r.set(e,t)}return r}parse(e){if(!(this.root&&this.rootDict&&e instanceof Ref))return;const t=this.rootDict.get("ParentTree");if(!t)return;const a=this.pageDict.get("StructParents"),r=this.root.structParentIds?.get(e);if(!Number.isInteger(a)&&!r)return;const i=new Map,n=new NumberTree(t,this.xref);if(Number.isInteger(a)){const e=n.get(a);if(Array.isArray(e))for(const t of e)t instanceof Ref&&this.addNode(this.xref.fetch(t),i)}if(r)for(const[e,t]of r){const a=n.get(e);if(a){const e=this.addNode(this.xref.fetchIfRef(a),i);1===e?.kids?.length&&e.kids[0].type===Nn&&(e.kids[0].type=t)}}}addNode(e,t,a=0){if(a>40){warn("StructTree MAX_DEPTH reached.");return null}if(!(e instanceof Dict))return null;if(t.has(e))return t.get(e);const r=new StructElementNode(this,e);t.set(e,r);switch(r.role){case"L":case"LBody":case"LI":case"Table":case"THead":case"TBody":case"TFoot":case"TR":for(const e of r.kids)e.type===Pn&&this.addNode(e.dict,t,a-1)}const i=e.get("P");if(!(i instanceof Dict)||isName(i.get("Type"),"StructTreeRoot")){this.addTopLevelNode(e,r)||t.delete(e);return r}const n=this.addNode(i,t,a+1);if(!n)return r;let s=!1;for(const t of n.kids)if(t.type===Pn&&t.dict===e){t.parentNode=r;s=!0}s||t.delete(e);return r}addTopLevelNode(e,t){const a=this.root.getKidPosition(e.objId);if(isNaN(a))return!1;-1!==a&&(this.nodes[a]=t);return!0}get serializable(){function nodeToSerializable(e,t,a=0){if(a>40){warn("StructTree too deep to be fully serialized.");return}const r=Object.create(null);r.role=e.role;r.children=[];t.children.push(r);let i=e.dict.get("Alt");"string"!=typeof i&&(i=e.dict.get("ActualText"));"string"==typeof i&&(r.alt=stringToPDFString(i));if("Formula"===r.role){const{mathML:t}=e;t&&(r.mathML=t)}const n=e.dict.get("A");if(n instanceof Dict){const e=lookupNormalRect(n.getArray("BBox"),null);if(e)r.bbox=e;else{const e=n.get("Width"),t=n.get("Height");"number"==typeof e&&e>0&&"number"==typeof t&&t>0&&(r.bbox=[0,0,e,t])}}const s=e.dict.get("Lang");"string"==typeof s&&(r.lang=stringToPDFString(s));for(const t of e.kids){const e=t.type===Pn?t.parentNode:null;e?nodeToSerializable(e,r,a+1):t.type===Bn||t.type===Rn?r.children.push({type:"content",id:`p${t.pageObjId}_mc${t.mcid}`}):t.type===Nn?r.children.push({type:"object",id:t.refObjId}):t.type===En&&r.children.push({type:"annotation",id:`pdfjs_internal_id_${t.refObjId}`})}}const e=Object.create(null);e.children=[];e.role="Root";for(const t of this.nodes)t&&nodeToSerializable(t,e);return e}}const Ln=function _isValidExplicitDest(e,t,a){if(!Array.isArray(a)||a.length<2)return!1;const[r,i,...n]=a;if(!e(r)&&!Number.isInteger(r))return!1;if(!t(i))return!1;const s=n.length;let o=!0;switch(i.name){case"XYZ":if(s<2||s>3)return!1;break;case"Fit":case"FitB":return 0===s;case"FitH":case"FitBH":case"FitV":case"FitBV":if(s>1)return!1;break;case"FitR":if(4!==s)return!1;o=!1;break;default:return!1}for(const e of n)if(!("number"==typeof e||o&&null===e))return!1;return!0}.bind(null,e=>e instanceof Ref,isName);function fetchDest(e){e instanceof Dict&&(e=e.get("D"));return Ln(e)?e:null}function fetchRemoteDest(e){let t=e.get("D");if(t){t instanceof Name&&(t=t.name);if("string"==typeof t)return stringToPDFString(t,!0);if(Ln(t))return JSON.stringify(t)}return null}class Catalog{#Se=null;#Ae=null;builtInCMapCache=new Map;fontCache=new RefSetCache;globalColorSpaceCache=new GlobalColorSpaceCache;globalImageCache=new GlobalImageCache;nonBlendModesSet=new RefSet;pageDictCache=new RefSetCache;pageIndexCache=new RefSetCache;pageKidsCountCache=new RefSetCache;standardFontDataCache=new Map;systemFontCache=new Map;constructor(e,t){this.pdfManager=e;this.xref=t;this.#Ae=t.getCatalogObj();if(!(this.#Ae instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict}cloneDict(){return this.#Ae.clone()}get version(){const e=this.#Ae.get("Version");if(e instanceof Name){if(ua.test(e.name))return shadow(this,"version",e.name);warn(`Invalid PDF catalog version: ${e.name}`)}return shadow(this,"version",null)}get lang(){const e=this.#Ae.get("Lang");return shadow(this,"lang",e&&"string"==typeof e?stringToPDFString(e):null)}get needsRendering(){const e=this.#Ae.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof e&&e)}get collection(){let e=null;try{const t=this.#Ae.get("Collection");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch Collection entry; assuming no collection is present.")}return shadow(this,"collection",e)}get acroForm(){let e=null;try{const t=this.#Ae.get("AcroForm");t instanceof Dict&&t.size>0&&(e=t)}catch(e){if(e instanceof MissingDataException)throw e;info("Cannot fetch AcroForm entry; assuming no forms are present.")}return shadow(this,"acroForm",e)}get acroFormRef(){const e=this.#Ae.getRaw("AcroForm");return shadow(this,"acroFormRef",e instanceof Ref?e:null)}get metadata(){const e=this.#Ae.getRaw("Metadata");if(!(e instanceof Ref))return shadow(this,"metadata",null);let t=null;try{const a=this.xref.fetch(e,!this.xref.encrypt?.encryptMetadata);if(a instanceof BaseStream&&a.dict instanceof Dict){const e=a.dict.get("Type"),r=a.dict.get("Subtype");if(isName(e,"Metadata")&&isName(r,"XML")){const e=stringToUTF8String(a.getString());e&&(t=new MetadataParser(e).serializable)}}}catch(e){if(e instanceof MissingDataException)throw e;info(`Skipping invalid Metadata: "${e}".`)}return shadow(this,"metadata",t)}get markInfo(){let e=null;try{e=this.#ke()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read mark info.")}return shadow(this,"markInfo",e)}#ke(){const e=this.#Ae.get("MarkInfo");if(!(e instanceof Dict))return null;const t={Marked:!1,UserProperties:!1,Suspects:!1};for(const a in t){const r=e.get(a);"boolean"==typeof r&&(t[a]=r)}return t}get structTreeRoot(){let e=null;try{e=this.#Ce()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable read to structTreeRoot info.")}return shadow(this,"structTreeRoot",e)}#Ce(){const e=this.#Ae.getRaw("StructTreeRoot"),t=this.xref.fetchIfRef(e);if(!(t instanceof Dict))return null;const a=new StructTreeRoot(this.xref,t,e);a.init();return a}get toplevelPagesDict(){const e=this.#Ae.get("Pages");if(!(e instanceof Dict))throw new FormatError("Invalid top-level pages dictionary.");return shadow(this,"toplevelPagesDict",e)}get documentOutline(){let e=null;try{e=this.#ve()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read document outline.")}return shadow(this,"documentOutline",e)}#ve(){let e=this.#Ae.get("Outlines");if(!(e instanceof Dict))return null;e=e.getRaw("First");if(!(e instanceof Ref))return null;const t={items:[]},a=[{obj:e,parent:t}],r=new RefSet;r.put(e);const i=this.xref,n=new Uint8ClampedArray(3);for(;a.length>0;){const t=a.shift(),s=i.fetchIfRef(t.obj);if(null===s)continue;s.has("Title")||warn("Invalid outline item encountered.");const o={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:s,resultObj:o,docBaseUrl:this.baseUrl,docAttachments:this.attachments});const c=s.get("Title"),l=s.get("F")||0,h=s.getArray("C"),u=s.get("Count");let d=n;!isNumberArray(h,3)||0===h[0]&&0===h[1]&&0===h[2]||(d=ColorSpaceUtils.rgb.getRgb(h,0));const f={action:o.action,attachment:o.attachment,dest:o.dest,url:o.url,unsafeUrl:o.unsafeUrl,newWindow:o.newWindow,setOCGState:o.setOCGState,title:"string"==typeof c?stringToPDFString(c):"",color:d,count:Number.isInteger(u)?u:void 0,bold:!!(2&l),italic:!!(1&l),items:[]};t.parent.items.push(f);e=s.getRaw("First");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:f});r.put(e)}e=s.getRaw("Next");if(e instanceof Ref&&!r.has(e)){a.push({obj:e,parent:t.parent});r.put(e)}}return t.items.length>0?t.items:null}get permissions(){let e=null;try{e=this.#Fe()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read permissions.")}return shadow(this,"permissions",e)}#Fe(){const e=this.xref.trailer.get("Encrypt");if(!(e instanceof Dict))return null;let t=e.get("P");if("number"!=typeof t)return null;t+=2**32;const a=[];for(const e in w){const r=w[e];t&r&&a.push(r)}return a}get optionalContentConfig(){let e=null;try{const t=this.#Ae.get("OCProperties");if(!t)return shadow(this,"optionalContentConfig",null);const a=t.get("D");if(!a)return shadow(this,"optionalContentConfig",null);const r=t.get("OCGs");if(!Array.isArray(r))return shadow(this,"optionalContentConfig",null);const i=new RefSetCache;for(const e of r)e instanceof Ref&&!i.has(e)&&i.put(e,this.#Ie(e));e=this.#Te(a,i)}catch(e){if(e instanceof MissingDataException)throw e;warn(`Unable to read optional content config: ${e}`)}return shadow(this,"optionalContentConfig",e)}#Ie(e){const t=this.xref.fetch(e),a={id:e.toString(),name:null,intent:null,usage:{print:null,view:null},rbGroups:[]},r=t.get("Name");"string"==typeof r&&(a.name=stringToPDFString(r));let i=t.getArray("Intent");Array.isArray(i)||(i=[i]);i.every(e=>e instanceof Name)&&(a.intent=i.map(e=>e.name));const n=t.get("Usage");if(!(n instanceof Dict))return a;const s=a.usage,o=n.get("Print");if(o instanceof Dict){const e=o.get("PrintState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.print={printState:e.name}}}const c=n.get("View");if(c instanceof Dict){const e=c.get("ViewState");if(e instanceof Name)switch(e.name){case"ON":case"OFF":s.view={viewState:e.name}}}return a}#Te(e,t){function parseOnOff(e){const a=[];if(Array.isArray(e))for(const r of e)r instanceof Ref&&t.has(r)&&a.push(r.toString());return a}function parseOrder(e,a=0){if(!Array.isArray(e))return null;const i=[];for(const n of e){if(n instanceof Ref&&t.has(n)){r.put(n);i.push(n.toString());continue}const e=parseNestedOrder(n,a);e&&i.push(e)}if(a>0)return i;const n=[];for(const[e]of t.items())r.has(e)||n.push(e.toString());n.length&&i.push({name:null,order:n});return i}function parseNestedOrder(e,t){if(++t>i){warn("parseNestedOrder - reached MAX_NESTED_LEVELS.");return null}const r=a.fetchIfRef(e);if(!Array.isArray(r))return null;const n=a.fetchIfRef(r[0]);if("string"!=typeof n)return null;const s=parseOrder(r.slice(1),t);return s?.length?{name:stringToPDFString(n),order:s}:null}const a=this.xref,r=new RefSet,i=10;!function parseRBGroups(e){if(Array.isArray(e))for(const r of e){const e=a.fetchIfRef(r);if(!Array.isArray(e)||!e.length)continue;const i=new Set;for(const a of e)if(a instanceof Ref&&t.has(a)&&!i.has(a.toString())){i.add(a.toString());t.get(a).rbGroups.push(i)}}}(e.get("RBGroups"));return{name:"string"==typeof e.get("Name")?stringToPDFString(e.get("Name")):null,creator:"string"==typeof e.get("Creator")?stringToPDFString(e.get("Creator")):null,baseState:e.get("BaseState")instanceof Name?e.get("BaseState").name:null,on:parseOnOff(e.get("ON")),off:parseOnOff(e.get("OFF")),order:parseOrder(e.get("Order")),groups:[...t]}}setActualNumPages(e=null){this.#Se=e}get hasActualNumPages(){return null!==this.#Se}get _pagesCount(){const e=this.toplevelPagesDict.get("Count");if(!Number.isInteger(e))throw new FormatError("Page count in top-level pages dictionary is not an integer.");return shadow(this,"_pagesCount",e)}get numPages(){return this.#Se??this._pagesCount}get destinations(){const e=this.#Oe(),t=Object.create(null);for(const a of e)if(a instanceof NameTree)for(const[e,r]of a.getAll()){const a=fetchDest(r);a&&(t[stringToPDFString(e,!0)]=a)}else if(a instanceof Dict)for(const[e,r]of a){const a=fetchDest(r);a&&(t[stringToPDFString(e,!0)]||=a)}return shadow(this,"destinations",t)}getDestination(e){if(this.hasOwnProperty("destinations"))return this.destinations[e]??null;const t=this.#Oe();for(const a of t)if(a instanceof NameTree||a instanceof Dict){const t=fetchDest(a.get(e));if(t)return t}if(t.length){const t=this.destinations[e];if(t)return t}return null}#Oe(){const e=this.#Ae.get("Names"),t=[];e?.has("Dests")&&t.push(new NameTree(e.getRaw("Dests"),this.xref));this.#Ae.has("Dests")&&t.push(this.#Ae.get("Dests"));return t}get pageLabels(){let e=null;try{e=this.#Me()}catch(e){if(e instanceof MissingDataException)throw e;warn("Unable to read page labels.")}return shadow(this,"pageLabels",e)}#Me(){const e=this.#Ae.getRaw("PageLabels");if(!e)return null;const t=new Array(this.numPages);let a=null,r="";const i=new NumberTree(e,this.xref).getAll();let n="",s=1;for(let e=0,o=this.numPages;e=1))throw new FormatError("Invalid start in PageLabel dictionary.");s=e}else s=1}switch(a){case"D":n=s;break;case"R":case"r":n=toRomanNumerals(s,"r"===a);break;case"A":case"a":const e=26,t="a"===a?97:65,r=s-1;n=String.fromCharCode(t+r%e).repeat(Math.floor(r/e)+1);break;default:if(a)throw new FormatError(`Invalid style "${a}" in PageLabel dictionary.`);n=""}t[e]=r+n;s++}return t}get pageLayout(){const e=this.#Ae.get("PageLayout");let t="";if(e instanceof Name)switch(e.name){case"SinglePage":case"OneColumn":case"TwoColumnLeft":case"TwoColumnRight":case"TwoPageLeft":case"TwoPageRight":t=e.name}return shadow(this,"pageLayout",t)}get pageMode(){const e=this.#Ae.get("PageMode");let t="UseNone";if(e instanceof Name)switch(e.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"FullScreen":case"UseOC":case"UseAttachments":t=e.name}return shadow(this,"pageMode",t)}get viewerPreferences(){const e=this.#Ae.get("ViewerPreferences");if(!(e instanceof Dict))return shadow(this,"viewerPreferences",null);let t=null;for(const[a,r]of e){let e;switch(a){case"HideToolbar":case"HideMenubar":case"HideWindowUI":case"FitWindow":case"CenterWindow":case"DisplayDocTitle":case"PickTrayByPDFSize":"boolean"==typeof r&&(e=r);break;case"NonFullScreenPageMode":if(r instanceof Name)switch(r.name){case"UseNone":case"UseOutlines":case"UseThumbs":case"UseOC":e=r.name;break;default:e="UseNone"}break;case"Direction":if(r instanceof Name)switch(r.name){case"L2R":case"R2L":e=r.name;break;default:e="L2R"}break;case"ViewArea":case"ViewClip":case"PrintArea":case"PrintClip":if(r instanceof Name)switch(r.name){case"MediaBox":case"CropBox":case"BleedBox":case"TrimBox":case"ArtBox":e=r.name;break;default:e="CropBox"}break;case"PrintScaling":if(r instanceof Name)switch(r.name){case"None":case"AppDefault":e=r.name;break;default:e="AppDefault"}break;case"Duplex":if(r instanceof Name)switch(r.name){case"Simplex":case"DuplexFlipShortEdge":case"DuplexFlipLongEdge":e=r.name;break;default:e="None"}break;case"PrintPageRange":if(Array.isArray(r)&&r.length%2==0){r.every((e,t,a)=>Number.isInteger(e)&&e>0&&(0===t||e>=a[t-1])&&e<=this.numPages)&&(e=r)}break;case"NumCopies":Number.isInteger(r)&&r>0&&(e=r);break;default:warn(`Ignoring non-standard key in ViewerPreferences: ${a}.`);continue}if(void 0!==e){t??=Object.create(null);t[a]=e}else warn(`Bad value, for key "${a}", in ViewerPreferences: ${r}.`)}return shadow(this,"viewerPreferences",t)}get openAction(){const e=this.#Ae.get("OpenAction"),t=Object.create(null);if(e instanceof Dict){const a=new Dict(this.xref);a.set("A",e);const r={url:null,dest:null,action:null};Catalog.parseDestDictionary({destDict:a,resultObj:r});Array.isArray(r.dest)?t.dest=r.dest:r.action&&(t.action=r.action)}else Ln(e)&&(t.dest=e);return shadow(this,"openAction",objectSize(t)>0?t:null)}get attachments(){const e=this.#Ae.get("Names");let t=null;if(e instanceof Dict&&e.has("EmbeddedFiles")){const a=new NameTree(e.getRaw("EmbeddedFiles"),this.xref);for(const[e,r]of a.getAll()){const a=new FileSpec(r,this.xref);t??=Object.create(null);t[stringToPDFString(e,!0)]=a.serializable}}return shadow(this,"attachments",t)}get xfaImages(){const e=this.#Ae.get("Names");let t=null;if(e instanceof Dict&&e.has("XFAImages")){const a=new NameTree(e.getRaw("XFAImages"),this.xref);for(const[e,r]of a.getAll())if(r instanceof BaseStream){t??=new Map;t.set(stringToPDFString(e,!0),r.getBytes())}}return shadow(this,"xfaImages",t)}#De(){const e=this.#Ae.get("Names");let t=null;function appendIfJavaScriptDict(e,a){if(!(a instanceof Dict))return;if(!isName(a.get("S"),"JavaScript"))return;let r=a.get("JS");if(r instanceof BaseStream)r=r.getString();else if("string"!=typeof r)return;r=stringToPDFString(r,!0).replaceAll("\0","");r&&(t||=new Map).set(e,r)}if(e instanceof Dict&&e.has("JavaScript")){const t=new NameTree(e.getRaw("JavaScript"),this.xref);for(const[e,a]of t.getAll())appendIfJavaScriptDict(stringToPDFString(e,!0),a)}const a=this.#Ae.get("OpenAction");a&&appendIfJavaScriptDict("OpenAction",a);return t}get jsActions(){const e=this.#De();let t=collectActions(this.xref,this.#Ae,ne);if(e){t||=Object.create(null);for(const[a,r]of e)a in t?t[a].push(r):t[a]=[r]}return shadow(this,"jsActions",t)}async cleanup(e=!1){clearGlobalCaches();this.globalColorSpaceCache.clear();this.globalImageCache.clear(e);this.pageKidsCountCache.clear();this.pageIndexCache.clear();this.pageDictCache.clear();this.nonBlendModesSet.clear();for(const{dict:e}of await Promise.all(this.fontCache))delete e.cacheKey;this.fontCache.clear();this.builtInCMapCache.clear();this.standardFontDataCache.clear();this.systemFontCache.clear()}async getPageDict(e){const t=[this.toplevelPagesDict],a=new RefSet,r=this.#Ae.getRaw("Pages");r instanceof Ref&&a.put(r);const i=this.xref,n=this.pageKidsCountCache,s=this.pageIndexCache,o=this.pageDictCache;let c=0;for(;t.length;){const r=t.pop();if(r instanceof Ref){const l=n.get(r);if(l>=0&&c+l<=e){c+=l;continue}if(a.has(r))throw new FormatError("Pages tree contains circular reference.");a.put(r);const h=await(o.get(r)||i.fetchAsync(r));if(h instanceof Dict){let t=h.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!h.has("Kids")){n.has(r)||n.put(r,1);s.has(r)||s.put(r,c);if(c===e)return[h,r];c++;continue}}t.push(h);continue}if(!(r instanceof Dict))throw new FormatError("Page dictionary kid reference points to wrong type of object.");const{objId:l}=r;let h=r.getRaw("Count");h instanceof Ref&&(h=await i.fetchAsync(h));if(Number.isInteger(h)&&h>=0){l&&!n.has(l)&&n.put(l,h);if(c+h<=e){c+=h;continue}}let u=r.getRaw("Kids");u instanceof Ref&&(u=await i.fetchAsync(u));if(!Array.isArray(u)){let t=r.getRaw("Type");t instanceof Ref&&(t=await i.fetchAsync(t));if(isName(t,"Page")||!r.has("Kids")){if(c===e)return[r,null];c++;continue}throw new FormatError("Page dictionary kids object is not an array.")}for(let e=u.length-1;e>=0;e--){const a=u[e];t.push(a);r===this.toplevelPagesDict&&a instanceof Ref&&!o.has(a)&&o.put(a,i.fetchAsync(a))}}throw new Error(`Page index ${e} not found.`)}async getAllPageDicts(e=!1){const{ignoreErrors:t}=this.pdfManager.evaluatorOptions,a=[{currentNode:this.toplevelPagesDict,posInKids:0}],r=new RefSet,i=this.#Ae.getRaw("Pages");i instanceof Ref&&r.put(i);const n=new Map,s=this.xref,o=this.pageIndexCache;let c=0;function addPageDict(e,t){t&&!o.has(t)&&o.put(t,c);n.set(c++,[e,t])}function addPageError(a){if(a instanceof XRefEntryException&&!e)throw a;if(e&&t&&0===c){warn(`getAllPageDicts - Skipping invalid first page: "${a}".`);a=Dict.empty}n.set(c++,[a,null])}for(;a.length>0;){const e=a.at(-1),{currentNode:t,posInKids:i}=e;let n=t.getRaw("Kids");if(n instanceof Ref)try{n=await s.fetchAsync(n)}catch(e){addPageError(e);break}if(!Array.isArray(n)){addPageError(new FormatError("Page dictionary kids object is not an array."));break}if(i>=n.length){a.pop();continue}const o=n[i];let c;if(o instanceof Ref){if(r.has(o)){addPageError(new FormatError("Pages tree contains circular reference."));break}r.put(o);try{c=await s.fetchAsync(o)}catch(e){addPageError(e);break}}else c=o;if(!(c instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let l=c.getRaw("Type");if(l instanceof Ref)try{l=await s.fetchAsync(l)}catch(e){addPageError(e);break}isName(l,"Page")||!c.has("Kids")?addPageDict(c,o instanceof Ref?o:null):a.push({currentNode:c,posInKids:0});e.posInKids++}return n}getPageIndex(e){const t=this.pageIndexCache.get(e);if(void 0!==t)return Promise.resolve(t);const a=this.xref;let r=0;const next=t=>function pagesBeforeRef(t){let r,i=0;return a.fetchAsync(t).then(function(a){if(isRefsEqual(t,e)&&!isDict(a,"Page")&&!(a instanceof Dict&&!a.has("Type")&&a.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!a)return null;if(!(a instanceof Dict))throw new FormatError("Node must be a dictionary.");r=a.getRaw("Parent");return a.getAsync("Parent")}).then(function(e){if(!e)return null;if(!(e instanceof Dict))throw new FormatError("Parent must be a dictionary.");return e.getAsync("Kids")}).then(function(e){if(!e)return null;const n=[];let s=!1;for(const r of e){if(!(r instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(r,t)){s=!0;break}n.push(a.fetchAsync(r).then(function(e){if(!(e instanceof Dict))throw new FormatError("Kid node must be a dictionary.");e.has("Count")?i+=e.get("Count"):i++}))}if(!s)throw new FormatError("Kid reference not found in parent's kids.");return Promise.all(n).then(()=>[i,r])})}(t).then(t=>{if(!t){this.pageIndexCache.put(e,r);return r}const[a,i]=t;r+=a;return next(i)});return next(e)}get baseUrl(){const e=this.#Ae.get("URI");if(e instanceof Dict){const t=e.get("Base");if("string"==typeof t){const e=createValidAbsoluteUrl(t,null,{tryConvertEncoding:!0});if(e)return shadow(this,"baseUrl",e.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict:e,resultObj:t,docBaseUrl:a=null,docAttachments:r=null}){if(!(e instanceof Dict)){warn("parseDestDictionary: `destDict` must be a dictionary.");return}let i,n,s=e.get("A");if(!(s instanceof Dict))if(e.has("Dest"))s=e.get("Dest");else{s=e.get("AA");s instanceof Dict&&(s.has("D")?s=s.get("D"):s.has("U")&&(s=s.get("U")))}if(s instanceof Dict){const e=s.get("S");if(!(e instanceof Name)){warn("parseDestDictionary: Invalid type in Action dictionary.");return}const a=e.name;switch(a){case"ResetForm":const e=s.get("Flags"),o=!(1&("number"==typeof e?e:0)),c=[],l=[];for(const e of s.get("Fields")||[])e instanceof Ref?l.push(e.toString()):"string"==typeof e&&c.push(stringToPDFString(e));t.resetForm={fields:c,refs:l,include:o};break;case"URI":i=s.get("URI");i instanceof Name&&(i="/"+i.name);break;case"GoTo":n=s.get("D");break;case"Launch":case"GoToR":const h=s.get("F");if(h instanceof Dict){const e=new FileSpec(h,null,!0),{rawFilename:t}=e.serializable;i=t}else"string"==typeof h&&(i=h);const u=fetchRemoteDest(s);u&&"string"==typeof i&&(i=i.split("#",1)[0]+"#"+u);const d=s.get("NewWindow");"boolean"==typeof d&&(t.newWindow=d);break;case"GoToE":const f=s.get("T");let g;if(r&&f instanceof Dict){const e=f.get("R"),t=f.get("N");isName(e,"C")&&"string"==typeof t&&(g=r[stringToPDFString(t,!0)])}if(g){t.attachment=g;const e=fetchRemoteDest(s);e&&(t.attachmentDest=e)}else warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":const p=s.get("N");p instanceof Name&&(t.action=p.name);break;case"SetOCGState":const m=s.get("State"),b=s.get("PreserveRB");if(!Array.isArray(m)||0===m.length)break;const y=[];for(const e of m)if(e instanceof Name)switch(e.name){case"ON":case"OFF":case"Toggle":y.push(e.name)}else e instanceof Ref&&y.push(e.toString());if(y.length!==m.length)break;t.setOCGState={state:y,preserveRB:"boolean"!=typeof b||b};break;case"JavaScript":const w=s.get("JS");let x;w instanceof BaseStream?x=w.getString():"string"==typeof w&&(x=w);const S=x&&recoverJsURL(stringToPDFString(x,!0));if(S){i=S.url;t.newWindow=S.newWindow;break}default:if("JavaScript"===a||"SubmitForm"===a)break;warn(`parseDestDictionary - unsupported action: "${a}".`)}}else e.has("Dest")&&(n=e.get("Dest"));if("string"==typeof i){const e=createValidAbsoluteUrl(i,a,{addDefaultProtocol:!0,tryConvertEncoding:!0});e&&(t.url=e.href);t.unsafeUrl=i}if(n){n instanceof Name&&(n=n.name);"string"==typeof n?t.dest=stringToPDFString(n,!0):Ln(n)&&(t.dest=n)}}}function mayHaveChildren(e){return e instanceof Ref||e instanceof Dict||e instanceof BaseStream||Array.isArray(e)}function addChildren(e,t){if(e instanceof Dict)e=e.getRawValues();else if(e instanceof BaseStream)e=e.dict.getRawValues();else if(!Array.isArray(e))return;for(const a of e)mayHaveChildren(a)&&t.push(a)}class ObjectLoader{refSet=new RefSet;constructor(e,t,a){this.dict=e;this.keys=t;this.xref=a}async load(){const{keys:e,dict:t}=this,a=[];for(const r of e){const e=t.getRaw(r);void 0!==e&&a.push(e)}await this.#Be(a);this.refSet=null}async#Be(e){const t=[],a=[];for(;e.length;){let r=e.pop();if(r instanceof Ref){if(this.refSet.has(r))continue;try{this.refSet.put(r);r=this.xref.fetch(r)}catch(e){if(!(e instanceof MissingDataException)){warn(`ObjectLoader.#walk - requesting all data: "${e}".`);await this.xref.stream.manager.requestAllChunks();return}t.push(r);a.push({begin:e.begin,end:e.end})}}if(r instanceof BaseStream){const e=r.getBaseStreams();if(e){let i=!1;for(const t of e)if(!t.isDataLoaded){i=!0;a.push({begin:t.start,end:t.end})}i&&t.push(r)}}addChildren(r,e)}if(a.length){await this.xref.stream.manager.requestRanges(a);for(const e of t)e instanceof Ref&&this.refSet.remove(e);await this.#Be(t)}}static async load(e,t,a){if(a.stream.isDataLoaded)return;const r=new ObjectLoader(e,t,a);await r.load()}}const _n=Symbol(),Un=Symbol(),jn=Symbol(),Xn=Symbol(),qn=Symbol(),Hn=Symbol(),Wn=Symbol(),Gn=Symbol(),zn=Symbol(),$n=Symbol("content"),Vn=Symbol("data"),Kn=Symbol(),Jn=Symbol("extra"),Yn=Symbol(),Zn=Symbol(),Qn=Symbol(),es=Symbol(),ts=Symbol(),as=Symbol(),rs=Symbol(),is=Symbol(),ns=Symbol(),ss=Symbol(),os=Symbol(),cs=Symbol(),ls=Symbol(),hs=Symbol(),us=Symbol(),ds=Symbol(),fs=Symbol(),gs=Symbol(),ps=Symbol(),ms=Symbol(),bs=Symbol(),ys=Symbol(),ws=Symbol(),xs=Symbol(),Ss=Symbol(),As=Symbol(),ks=Symbol(),Cs=Symbol(),vs=Symbol(),Fs=Symbol(),Is=Symbol(),Ts=Symbol(),Os=Symbol("namespaceId"),Ms=Symbol("nodeName"),Ds=Symbol(),Bs=Symbol(),Rs=Symbol(),Ns=Symbol(),Es=Symbol(),Ls=Symbol(),_s=Symbol(),Us=Symbol(),js=Symbol("root"),Xs=Symbol(),qs=Symbol(),Hs=Symbol(),Ws=Symbol(),Gs=Symbol(),zs=Symbol(),$s=Symbol(),Vs=Symbol(),Ks=Symbol(),Js=Symbol(),Ys=Symbol(),Zs=Symbol("uid"),Qs=Symbol(),eo={config:{id:0,check:e=>e.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:e=>"http://ns.adobe.com/xdp/pdf/"===e},signature:{id:6,check:e=>"http://www.w3.org/2000/09/xmldsig#"===e},sourceSet:{id:7,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:e=>"http://www.w3.org/1999/XSL/Transform"===e},template:{id:9,check:e=>e.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:e=>e.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:e=>"http://ns.adobe.com/xdp/"===e},xfdf:{id:12,check:e=>"http://ns.adobe.com/xfdf/"===e},xhtml:{id:13,check:e=>"http://www.w3.org/1999/xhtml"===e},xmpmeta:{id:14,check:e=>"http://ns.adobe.com/xmpmeta/"===e}},to={pt:e=>e,cm:e=>e/2.54*72,mm:e=>e/25.4*72,in:e=>72*e,px:e=>e},ao=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(e){return e.startsWith("'")||e.startsWith('"')?e.slice(1,-1):e}function getInteger({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseInt(e,10);return!isNaN(r)&&a(r)?r:t}function getFloat({data:e,defaultValue:t,validate:a}){if(!e)return t;e=e.trim();const r=parseFloat(e);return!isNaN(r)&&a(r)?r:t}function getKeyword({data:e,defaultValue:t,validate:a}){return e&&a(e=e.trim())?e:t}function getStringOption(e,t){return getKeyword({data:e,defaultValue:t[0],validate:e=>t.includes(e)})}function getMeasurement(e,t="0"){t||="0";if(!e)return getMeasurement(t);const a=e.trim().match(ao);if(!a)return getMeasurement(t);const[,r,i]=a,n=parseFloat(r);if(isNaN(n))return getMeasurement(t);if(0===n)return 0;const s=to[i];return s?s(n):n}function getRatio(e){if(!e)return{num:1,den:1};const t=e.split(":",2).map(e=>parseFloat(e.trim())).filter(e=>!isNaN(e));1===t.length&&t.push(1);if(0===t.length)return{num:1,den:1};const[a,r]=t;return{num:a,den:r}}function getRelevant(e){return e?e.trim().split(/\s+/).map(e=>({excluded:"-"===e[0],viewname:e.substring(1)})):[]}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(e,t,a,r){this.success=e;this.html=t;this.bbox=a;this.breakNode=r}isBreak(){return!!this.breakNode}static breakNode(e){return new HTMLResult(!1,null,null,e)}static success(e,t=null){return new HTMLResult(!0,e,t,null)}}class FontFinder{constructor(e){this.fonts=new Map;this.cache=new Map;this.warned=new Set;this.defaultFont=null;this.add(e)}add(e,t=null){for(const t of e)this.addPdfFont(t);for(const e of this.fonts.values())e.regular||(e.regular=e.italic||e.bold||e.bolditalic);if(!t||0===t.size)return;const a=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const e of t)this.fonts.set(e,a)}addPdfFont(e){const t=e.cssFontInfo,a=t.fontFamily;let r=this.fonts.get(a);if(!r){r=Object.create(null);this.fonts.set(a,r);this.defaultFont||(this.defaultFont=r)}let i="";const n=parseFloat(t.fontWeight);0!==parseFloat(t.italicAngle)?i=n>=700?"bolditalic":"italic":n>=700&&(i="bold");if(!i){(e.name.includes("Bold")||e.psName?.includes("Bold"))&&(i="bold");(e.name.includes("Italic")||e.name.endsWith("It")||e.psName?.includes("Italic")||e.psName?.endsWith("It"))&&(i+="italic")}i||(i="regular");r[i]=e}getDefault(){return this.defaultFont}find(e,t=!0){let a=this.fonts.get(e)||this.cache.get(e);if(a)return a;const r=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let i=e.replaceAll(r,"");a=this.fonts.get(i);if(a){this.cache.set(e,a);return a}i=i.toLowerCase();const n=[];for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t);if(0===n.length)for(const[,e]of this.fonts.entries())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(0===n.length){i=i.replaceAll(/psmt|mt/gi,"");for(const[e,t]of this.fonts.entries())e.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(t)}if(0===n.length)for(const e of this.fonts.values())e.regular.name?.replaceAll(r,"").toLowerCase().startsWith(i)&&n.push(e);if(n.length>=1){1!==n.length&&t&&warn(`XFA - Too many choices to guess the correct font: ${e}`);this.cache.set(e,n[0]);return n[0]}if(t&&!this.warned.has(e)){this.warned.add(e);warn(`XFA - Cannot find the font: ${e}`)}return null}}function selectFont(e,t){return"italic"===e.posture?"bold"===e.weight?t.bolditalic:t.italic:"bold"===e.weight?t.bold:t.regular}class text_FontInfo{constructor(e,t,a,r){this.lineHeight=a;this.paraMargin=t||{top:0,bottom:0,left:0,right:0};if(!e){[this.pdfFont,this.xfaFont]=this.defaultFont(r);return}this.xfaFont={typeface:e.typeface,posture:e.posture,weight:e.weight,size:e.size,letterSpacing:e.letterSpacing};const i=r.find(e.typeface);if(i){this.pdfFont=selectFont(e,i);this.pdfFont||([this.pdfFont,this.xfaFont]=this.defaultFont(r))}else[this.pdfFont,this.xfaFont]=this.defaultFont(r)}defaultFont(e){const t=e.find("Helvetica",!1)||e.find("Myriad Pro",!1)||e.find("Arial",!1)||e.getDefault();if(t?.regular){const e=t.regular;return[e,{typeface:e.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0}]}return[null,{typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0}]}}class FontSelector{constructor(e,t,a,r){this.fontFinder=r;this.stack=[new text_FontInfo(e,t,a,r)]}pushData(e,t,a){const r=this.stack.at(-1);for(const t of["typeface","posture","weight","size","letterSpacing"])e[t]||(e[t]=r.xfaFont[t]);for(const e of["top","bottom","left","right"])isNaN(t[e])&&(t[e]=r.paraMargin[e]);const i=new text_FontInfo(e,t,a||r.lineHeight,this.fontFinder);i.pdfFont||(i.pdfFont=r.pdfFont);this.stack.push(i)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(e,t,a,r){this.glyphs=[];this.fontSelector=new FontSelector(e,t,a,r);this.extraHeight=0}pushData(e,t,a){this.fontSelector.pushData(e,t,a)}popFont(e){return this.fontSelector.popFont()}addPara(){const e=this.fontSelector.topFont();this.extraHeight+=e.paraMargin.top+e.paraMargin.bottom}addString(e){if(!e)return;const t=this.fontSelector.topFont(),a=t.xfaFont.size;if(t.pdfFont){const r=t.xfaFont.letterSpacing,i=t.pdfFont,n=i.lineHeight||1.2,s=t.lineHeight||Math.max(1.2,n)*a,o=n-(void 0===i.lineGap?.2:i.lineGap),c=Math.max(1,o)*a,l=a/1e3,h=i.defaultWidth||i.charsToGlyphs(" ")[0].width;for(const t of e.split(/[\u2029\n]/)){const e=i.encodeString(t).join(""),a=i.charsToGlyphs(e);for(const e of a){const t=e.width||h;this.glyphs.push([t*l+r,s,c,e.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop();return}for(const t of e.split(/[\u2029\n]/)){for(const e of t.split(""))this.glyphs.push([a,1.2*a,a,e,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}compute(e){let t=-1,a=0,r=0,i=0,n=0,s=0,o=!1,c=!0;for(let l=0,h=this.glyphs.length;le){r=Math.max(r,n);n=0;i+=s;s=m;t=-1;a=0;o=!0;c=!1}else{s=Math.max(m,s);a=n;n+=h;t=l}else if(n+h>e){i+=s;s=m;if(-1!==t){l=t;r=Math.max(r,a);n=0;t=-1;a=0}else{r=Math.max(r,n);n=h}o=!0;c=!1}else{n+=h;s=Math.max(m,s)}}r=Math.max(r,n);i+=s+this.extraHeight;return{width:1.02*r,height:i,isBroken:o}}}const ro=/^[^.[]+/,io=/^[^\]]+/,no=0,so=1,oo=2,co=3,lo=4,ho=new Map([["$data",(e,t)=>e.datasets?e.datasets.data:e],["$record",(e,t)=>(e.datasets?e.datasets.data:e)[cs]()[0]],["$template",(e,t)=>e.template],["$connectionSet",(e,t)=>e.connectionSet],["$form",(e,t)=>e.form],["$layout",(e,t)=>e.layout],["$host",(e,t)=>e.host],["$dataWindow",(e,t)=>e.dataWindow],["$event",(e,t)=>e.event],["!",(e,t)=>e.datasets],["$xfa",(e,t)=>e],["xfa",(e,t)=>e],["$",(e,t)=>t]]),uo=new WeakMap;function parseIndex(e){return"*"===(e=e.trim())?1/0:parseInt(e,10)||0}function parseExpression(e,t,a=!0){let r=e.match(ro);if(!r)return null;let[i]=r;const n=[{name:i,cacheName:"."+i,index:0,js:null,formCalc:null,operator:no}];let s=i.length;for(;s0&&h.push(e)}if(0===h.length&&!o&&0===c){const a=t[ds]();if(!(t=a))return null;c=-1;e=[t];continue}e=isFinite(l)?h.filter(e=>le[l]):h.flat()}return 0===e.length?null:e}function createDataNode(e,t,a){const r=parseExpression(a);if(!r)return null;if(r.some(e=>e.operator===so))return null;const i=ho.get(r[0].name);let n=0;if(i){e=i(e,t);n=1}else e=t||e;for(let t=r.length;ne[$s]()).join("")}get[po](){const e=Object.getPrototypeOf(this);if(!e._attributes){const t=e._attributes=new Set;for(const e of Object.getOwnPropertyNames(this)){if(null===this[e]||this[e]instanceof XFAObject||this[e]instanceof XFAObjectArray)break;t.add(e)}}return shadow(this,po,e._attributes)}[As](e){let t=this;for(;t;){if(t===e)return!0;t=t[ds]()}return!1}[ds](){return this[Fo]}[us](){return this[ds]()}[cs](e=null){return e?this[e]:this[mo]}[Kn](){const e=Object.create(null);this[$n]&&(e.$content=this[$n]);for(const t of Object.getOwnPropertyNames(this)){const a=this[t];null!==a&&(a instanceof XFAObject?e[t]=a[Kn]():a instanceof XFAObjectArray?a.isEmpty()||(e[t]=a.dump()):e[t]=a)}return e}[Ys](){return null}[Ks](){return HTMLResult.EMPTY}*[ls](){for(const e of this[cs]())yield e}*[xo](e,t){for(const a of this[ls]())if(!e||t===e.has(a[Ms])){const e=this[ts](),t=a[Ks](e);t.success||(this[Jn].failingNode=a);yield t}}[Zn](){return null}[Un](e,t){this[Jn].children.push(e)}[ts](){}[Xn]({filter:e=null,include:t=!0}){if(this[Jn].generator){const e=this[ts](),t=this[Jn].failingNode[Ks](e);if(!t.success)return t;t.html&&this[Un](t.html,t.bbox);delete this[Jn].failingNode}else this[Jn].generator=this[xo](e,t);for(;;){const e=this[Jn].generator.next();if(e.done)break;const t=e.value;if(!t.success)return t;t.html&&this[Un](t.html,t.bbox)}this[Jn].generator=null;return HTMLResult.EMPTY}[Ws](e){this[Oo]=new Set(Object.keys(e))}[Ao](e){const t=this[po],a=this[Oo];return[...e].filter(e=>t.has(e)&&!a.has(e))}[Xs](e,t=new Set){for(const a of this[mo])a[Io](e,t)}[Io](e,t){const a=this[So](e,t);a?this[fo](a,e,t):this[Xs](e,t)}[So](e,t){const{use:a,usehref:r}=this;if(!a&&!r)return null;let i=null,n=null,s=null,o=a;if(r){o=r;r.startsWith("#som(")&&r.endsWith(")")?n=r.slice(5,-1):r.startsWith(".#som(")&&r.endsWith(")")?n=r.slice(6,-1):r.startsWith("#")?s=r.slice(1):r.startsWith(".#")&&(s=r.slice(2))}else a.startsWith("#")?s=a.slice(1):n=a;this.use=this.usehref="";if(s)i=e.get(s);else{i=searchNode(e.get(js),this,n,!0,!1);i&&(i=i[0])}if(!i){warn(`XFA - Invalid prototype reference: ${o}.`);return null}if(i[Ms]!==this[Ms]){warn(`XFA - Incompatible prototype: ${i[Ms]} !== ${this[Ms]}.`);return null}if(t.has(i)){warn("XFA - Cycle detected in prototypes use.");return null}t.add(i);const c=i[So](e,t);c&&i[fo](c,e,t);i[Xs](e,t);t.delete(i);return i}[fo](e,t,a){if(a.has(e)){warn("XFA - Cycle detected in prototypes use.");return}!this[$n]&&e[$n]&&(this[$n]=e[$n]);new Set(a).add(e);for(const t of this[Ao](e[Oo])){this[t]=e[t];this[Oo]&&this[Oo].add(t)}for(const r of Object.getOwnPropertyNames(this)){if(this[po].has(r))continue;const i=this[r],n=e[r];if(i instanceof XFAObjectArray){for(const e of i[mo])e[Io](t,a);for(let r=i[mo].length,s=n[mo].length;rXFAObject[bo](e)):"object"==typeof e&&null!==e?Object.assign({},e):e}[Gn](){const e=Object.create(Object.getPrototypeOf(this));for(const t of Object.getOwnPropertySymbols(this))try{e[t]=this[t]}catch{shadow(e,t,this[t])}e[Zs]=`${e[Ms]}${Do++}`;e[mo]=[];for(const t of Object.getOwnPropertyNames(this)){if(this[po].has(t)){e[t]=XFAObject[bo](this[t]);continue}const a=this[t];e[t]=a instanceof XFAObjectArray?new XFAObjectArray(a[Co]):null}for(const t of this[mo]){const a=t[Ms],r=t[Gn]();e[mo].push(r);r[Fo]=e;null===e[a]?e[a]=r:e[a][mo].push(r)}return e}[cs](e=null){return e?this[mo].filter(t=>t[Ms]===e):this[mo]}[as](e){return this[e]}[rs](e,t,a=!0){return Array.from(this[is](e,t,a))}*[is](e,t,a=!0){if("parent"!==e){for(const a of this[mo]){a[Ms]===e&&(yield a);a.name===e&&(yield a);(t||a[Fs]())&&(yield*a[is](e,t,!1))}a&&this[po].has(e)&&(yield new XFAAttribute(this,e,this[e]))}else yield this[Fo]}}class XFAObjectArray{constructor(e=1/0){this[Co]=e;this[mo]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(e){if(this[mo].length<=this[Co]){this[mo].push(e);return!0}warn(`XFA - node "${e[Ms]}" accepts no more than ${this[Co]} children`);return!1}isEmpty(){return 0===this[mo].length}dump(){return 1===this[mo].length?this[mo][0][Kn]():this[mo].map(e=>e[Kn]())}[Gn](){const e=new XFAObjectArray(this[Co]);e[mo]=this[mo].map(e=>e[Gn]());return e}get children(){return this[mo]}clear(){this[mo].length=0}}class XFAAttribute{constructor(e,t,a){this[Fo]=e;this[Ms]=t;this[$n]=a;this[zn]=!1;this[Zs]="attribute"+Do++}[ds](){return this[Fo]}[Ss](){return!0}[ns](){return this[$n].trim()}[Gs](e){e=e.value||"";this[$n]=e.toString()}[$s](){return this[$n]}[As](e){return this[Fo]===e||this[Fo][As](e)}}class XmlObject extends XFAObject{constructor(e,t,a={}){super(e,t);this[$n]="";this[yo]=null;if("#text"!==t){const e=new Map;this[go]=e;for(const[t,r]of Object.entries(a))e.set(t,new XFAAttribute(this,t,r));if(a.hasOwnProperty(Ds)){const e=a[Ds].xfa.dataNode;void 0!==e&&("dataGroup"===e?this[yo]=!1:"dataValue"===e&&(this[yo]=!0))}}this[zn]=!1}[Js](e){const t=this[Ms];if("#text"===t){e.push(encodeToXmlString(this[$n]));return}const a=utf8StringToString(t),r=this[Os]===Bo?"xfa:":"";e.push(`<${r}${a}`);for(const[t,a]of this[go].entries()){const r=utf8StringToString(t);e.push(` ${r}="${encodeToXmlString(a[$n])}"`)}null!==this[yo]&&(this[yo]?e.push(' xfa:dataNode="dataValue"'):e.push(' xfa:dataNode="dataGroup"'));if(this[$n]||0!==this[mo].length){e.push(">");if(this[$n])"string"==typeof this[$n]?e.push(encodeToXmlString(this[$n])):this[$n][Js](e);else for(const t of this[mo])t[Js](e);e.push(``)}else e.push("/>")}[Bs](e){if(this[$n]){const e=new XmlObject(this[Os],"#text");this[jn](e);e[$n]=this[$n];this[$n]=""}this[jn](e);return!0}[Ns](e){this[$n]+=e}[Yn](){if(this[$n]&&this[mo].length>0){const e=new XmlObject(this[Os],"#text");this[jn](e);e[$n]=this[$n];delete this[$n]}}[Ks](){return"#text"===this[Ms]?HTMLResult.success({name:"#text",value:this[$n]}):HTMLResult.EMPTY}[cs](e=null){return e?this[mo].filter(t=>t[Ms]===e):this[mo]}[es](){return this[go]}[as](e){const t=this[go].get(e);return void 0!==t?t:this[cs](e)}*[is](e,t){const a=this[go].get(e);a&&(yield a);for(const a of this[mo]){a[Ms]===e&&(yield a);t&&(yield*a[is](e,t))}}*[Qn](e,t){const a=this[go].get(e);!a||t&&a[zn]||(yield a);for(const a of this[mo])yield*a[Qn](e,t)}*[os](e,t,a){for(const r of this[mo]){r[Ms]!==e||a&&r[zn]||(yield r);t&&(yield*r[os](e,t,a))}}[Ss](){return null===this[yo]?0===this[mo].length||this[mo][0][Os]===eo.xhtml.id:this[yo]}[ns](){return null===this[yo]?0===this[mo].length?this[$n].trim():this[mo][0][Os]===eo.xhtml.id?this[mo][0][$s]().trim():null:this[$n].trim()}[Gs](e){e=e.value||"";this[$n]=e.toString()}[Kn](e=!1){const t=Object.create(null);e&&(t.$ns=this[Os]);this[$n]&&(t.$content=this[$n]);t.$name=this[Ms];t.children=[];for(const a of this[mo])t.children.push(a[Kn](e));t.attributes=Object.create(null);for(const[e,a]of this[go])t.attributes[e]=a[$n];return t}}class ContentObject extends XFAObject{constructor(e,t){super(e,t);this[$n]=""}[Ns](e){this[$n]+=e}[Yn](){}}class OptionObject extends ContentObject{constructor(e,t,a){super(e,t);this[vo]=a}[Yn](){this[$n]=getKeyword({data:this[$n],defaultValue:this[vo][0],validate:e=>this[vo].includes(e)})}[qn](e){super[qn](e);delete this[vo]}}class StringObject extends ContentObject{[Yn](){this[$n]=this[$n].trim()}}class IntegerObject extends ContentObject{constructor(e,t,a,r){super(e,t);this[wo]=a;this[Mo]=r}[Yn](){this[$n]=getInteger({data:this[$n],defaultValue:this[wo],validate:this[Mo]})}[qn](e){super[qn](e);delete this[wo];delete this[Mo]}}class Option01 extends IntegerObject{constructor(e,t){super(e,t,0,e=>1===e)}}class Option10 extends IntegerObject{constructor(e,t){super(e,t,1,e=>0===e)}}function measureToString(e){return"string"==typeof e?"0px":Number.isInteger(e)?`${e}px`:`${e.toFixed(2)}px`}const Ro={anchorType(e,t){const a=e[us]();if(a&&(!a.layout||"position"===a.layout)){"transform"in t||(t.transform="");switch(e.anchorType){case"bottomCenter":t.transform+="translate(-50%, -100%)";break;case"bottomLeft":t.transform+="translate(0,-100%)";break;case"bottomRight":t.transform+="translate(-100%,-100%)";break;case"middleCenter":t.transform+="translate(-50%,-50%)";break;case"middleLeft":t.transform+="translate(0,-50%)";break;case"middleRight":t.transform+="translate(-100%,-50%)";break;case"topCenter":t.transform+="translate(-50%,0)";break;case"topRight":t.transform+="translate(-100%,0)"}}},dimensions(e,t){const a=e[us]();let r=e.w;const i=e.h;if(a.layout?.includes("row")){const t=a[Jn],i=e.colSpan;let n;if(-1===i){n=Math.sumPrecise(t.columnWidths.slice(t.currentColumn));t.currentColumn=0}else{n=Math.sumPrecise(t.columnWidths.slice(t.currentColumn,t.currentColumn+i));t.currentColumn=(t.currentColumn+e.colSpan)%t.columnWidths.length}isNaN(n)||(r=e.w=n)}t.width=""!==r?measureToString(r):"auto";t.height=""!==i?measureToString(i):"auto"},position(e,t){const a=e[us]();if(!a?.layout||"position"===a.layout){t.position="absolute";t.left=measureToString(e.x);t.top=measureToString(e.y)}},rotate(e,t){if(e.rotate){"transform"in t||(t.transform="");t.transform+=`rotate(-${e.rotate}deg)`;t.transformOrigin="top left"}},presence(e,t){switch(e.presence){case"invisible":t.visibility="hidden";break;case"hidden":case"inactive":t.display="none"}},hAlign(e,t){if("para"===e[Ms])switch(e.hAlign){case"justifyAll":t.textAlign="justify-all";break;case"radix":t.textAlign="left";break;default:t.textAlign=e.hAlign}else switch(e.hAlign){case"left":t.alignSelf="start";break;case"center":t.alignSelf="center";break;case"right":t.alignSelf="end"}},margin(e,t){e.margin&&(t.margin=e.margin[Ys]().margin)}};function setMinMaxDimensions(e,t){if("position"===e[us]().layout){e.minW>0&&(t.minWidth=measureToString(e.minW));e.maxW>0&&(t.maxWidth=measureToString(e.maxW));e.minH>0&&(t.minHeight=measureToString(e.minH));e.maxH>0&&(t.maxHeight=measureToString(e.maxH))}}function layoutText(e,t,a,r,i,n){const s=new TextMeasure(t,a,r,i);"string"==typeof e?s.addString(e):e[Es](s);return s.compute(n)}function layoutNode(e,t){let a=null,r=null,i=!1;if((!e.w||!e.h)&&e.value){let n=0,s=0;if(e.margin){n=e.margin.leftInset+e.margin.rightInset;s=e.margin.topInset+e.margin.bottomInset}let o=null,c=null;if(e.para){c=Object.create(null);o=""===e.para.lineHeight?null:e.para.lineHeight;c.top=""===e.para.spaceAbove?0:e.para.spaceAbove;c.bottom=""===e.para.spaceBelow?0:e.para.spaceBelow;c.left=""===e.para.marginLeft?0:e.para.marginLeft;c.right=""===e.para.marginRight?0:e.para.marginRight}let l=e.font;if(!l){const t=e[fs]();let a=e[ds]();for(;a&&a!==t;){if(a.font){l=a.font;break}a=a[ds]()}}const h=(e.w||t.width)-n,u=e[gs].fontFinder;if(e.value.exData&&e.value.exData[$n]&&"text/html"===e.value.exData.contentType){const t=layoutText(e.value.exData[$n],l,c,o,u,h);r=t.width;a=t.height;i=t.isBroken}else{const t=e.value[$s]();if(t){const e=layoutText(t,l,c,o,u,h);r=e.width;a=e.height;i=e.isBroken}}null===r||e.w||(r+=n);null===a||e.h||(a+=s)}return{w:r,h:a,isBroken:i}}function computeBbox(e,t,a){let r;if(""!==e.w&&""!==e.h)r=[e.x,e.y,e.w,e.h];else{if(!a)return null;let i=e.w;if(""===i){if(0===e.maxW){const t=e[us]();i="position"===t.layout&&""!==t.w?0:e.minW}else i=Math.min(e.maxW,a.width);t.attributes.style.width=measureToString(i)}let n=e.h;if(""===n){if(0===e.maxH){const t=e[us]();n="position"===t.layout&&""!==t.h?0:e.minH}else n=Math.min(e.maxH,a.height);t.attributes.style.height=measureToString(n)}r=[e.x,e.y,i,n]}return r}function fixDimensions(e){const t=e[us]();if(t.layout?.includes("row")){const a=t[Jn],r=e.colSpan;let i;i=-1===r?Math.sumPrecise(a.columnWidths.slice(a.currentColumn)):Math.sumPrecise(a.columnWidths.slice(a.currentColumn,a.currentColumn+r));isNaN(i)||(e.w=i)}t.layout&&"position"!==t.layout&&(e.x=e.y=0);"table"===e.layout&&""===e.w&&Array.isArray(e.columnWidths)&&(e.w=Math.sumPrecise(e.columnWidths))}function layoutClass(e){switch(e.layout){case"position":default:return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb"}}function toStyle(e,...t){const a=Object.create(null);for(const r of t){const t=e[r];if(null!==t)if(Ro.hasOwnProperty(r))Ro[r](e,a);else if(t instanceof XFAObject){const e=t[Ys]();e?Object.assign(a,e):warn(`(DEBUG) - XFA - style for ${r} not implemented yet`)}}return a}function createWrapper(e,t){const{attributes:a}=t,{style:r}=a,i={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};a.class.push("xfaWrapped");if(e.border){const{widths:a,insets:n}=e.border[Jn];let s,o,c=n[0],l=n[3];const h=n[0]+n[2],u=n[1]+n[3];switch(e.border.hand){case"even":c-=a[0]/2;l-=a[3]/2;s=`calc(100% + ${(a[1]+a[3])/2-u}px)`;o=`calc(100% + ${(a[0]+a[2])/2-h}px)`;break;case"left":c-=a[0];l-=a[3];s=`calc(100% + ${a[1]+a[3]-u}px)`;o=`calc(100% + ${a[0]+a[2]-h}px)`;break;case"right":s=u?`calc(100% - ${u}px)`:"100%";o=h?`calc(100% - ${h}px)`:"100%"}const d=["xfaBorder"];isPrintOnly(e.border)&&d.push("xfaPrintOnly");const f={name:"div",attributes:{class:d,style:{top:`${c}px`,left:`${l}px`,width:s,height:o}},children:[]};for(const e of["border","borderWidth","borderColor","borderRadius","borderStyle"])if(void 0!==r[e]){f.attributes.style[e]=r[e];delete r[e]}i.children.push(f,t)}else i.children.push(t);for(const e of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])if(void 0!==r[e]){i.attributes.style[e]=r[e];delete r[e]}i.attributes.style.position="absolute"===r.position?"absolute":"relative";delete r.position;if(r.alignSelf){i.attributes.style.alignSelf=r.alignSelf;delete r.alignSelf}return i}function fixTextIndent(e){const t=getMeasurement(e.textIndent,"0px");if(t>=0)return;const a="padding"+("left"===("right"===e.textAlign?"right":"left")?"Left":"Right"),r=getMeasurement(e[a],"0px");e[a]=r-t+"px"}function setAccess(e,t){switch(e.access){case"nonInteractive":t.push("xfaNonInteractive");break;case"readOnly":t.push("xfaReadOnly");break;case"protected":t.push("xfaDisabled")}}function isPrintOnly(e){return e.relevant.length>0&&!e.relevant[0].excluded&&"print"===e.relevant[0].viewname}function getCurrentPara(e){const t=e[fs]()[Jn].paraStack;return t.length?t.at(-1):null}function setPara(e,t,a){if(a.attributes.class?.includes("xfaRich")){if(t){""===e.h&&(t.height="auto");""===e.w&&(t.width="auto")}const r=getCurrentPara(e);if(r){const e=a.attributes.style;e.display="flex";e.flexDirection="column";switch(r.vAlign){case"top":e.justifyContent="start";break;case"bottom":e.justifyContent="end";break;case"middle":e.justifyContent="center"}const t=r[Ys]();for(const[a,r]of Object.entries(t))a in e||(e[a]=r)}}}function setFontFamily(e,t,a,r){if(!a){delete r.fontFamily;return}const i=stripQuotes(e.typeface);r.fontFamily=`"${i}"`;const n=a.find(i);if(n){const{fontFamily:a}=n.regular.cssFontInfo;a!==i&&(r.fontFamily=`"${a}"`);const s=getCurrentPara(t);if(s&&""!==s.lineHeight)return;if(r.lineHeight)return;const o=selectFont(e,n);o&&(r.lineHeight=Math.max(1.2,o.lineHeight))}}function fixURL(e){const t=createValidAbsoluteUrl(e,null,{addDefaultProtocol:!0,tryConvertEncoding:!0});return t?t.href:null}function createLine(e,t){return{name:"div",attributes:{class:["lr-tb"===e.layout?"xfaLr":"xfaRl"]},children:t}}function flushHTML(e){if(!e[Jn])return null;const t={name:"div",attributes:e[Jn].attributes,children:e[Jn].children};if(e[Jn].failingNode){const a=e[Jn].failingNode[Zn]();a&&(e.layout.endsWith("-tb")?t.children.push(createLine(e,[a])):t.children.push(a))}return 0===t.children.length?null:t}function addHTML(e,t,a){const r=e[Jn],i=r.availableSpace,[n,s,o,c]=a;switch(e.layout){case"position":r.width=Math.max(r.width,n+o);r.height=Math.max(r.height,s+c);r.children.push(t);break;case"lr-tb":case"rl-tb":if(!r.line||1===r.attempt){r.line=createLine(e,[]);r.children.push(r.line);r.numberInLine=0}r.numberInLine+=1;r.line.children.push(t);if(0===r.attempt){r.currentWidth+=o;r.height=Math.max(r.height,r.prevHeight+c)}else{r.currentWidth=o;r.prevHeight=r.height;r.height+=c;r.attempt=0}r.width=Math.max(r.width,r.currentWidth);break;case"rl-row":case"row":{r.children.push(t);r.width+=o;r.height=Math.max(r.height,c);const e=measureToString(r.height);for(const t of r.children)t.attributes.style.height=e;break}case"table":case"tb":r.width=MathClamp(o,r.width,i.width);r.height+=c;r.children.push(t)}}function getAvailableSpace(e){const t=e[Jn].availableSpace,a=e.margin?e.margin.topInset+e.margin.bottomInset:0,r=e.margin?e.margin.leftInset+e.margin.rightInset:0;switch(e.layout){case"lr-tb":case"rl-tb":return 0===e[Jn].attempt?{width:t.width-r-e[Jn].currentWidth,height:t.height-a-e[Jn].prevHeight}:{width:t.width-r,height:t.height-a-e[Jn].height};case"rl-row":case"row":return{width:Math.sumPrecise(e[Jn].columnWidths.slice(e[Jn].currentColumn)),height:t.height-r};case"table":case"tb":return{width:t.width-r,height:t.height-a-e[Jn].height};default:return t}}function checkDimensions(e,t){if(null===e[fs]()[Jn].firstUnsplittable)return!0;if(0===e.w||0===e.h)return!0;const a=e[us](),r=a[Jn]?.attempt||0,[,i,n,s]=function getTransformedBBox(e){let t,a,r=""===e.w?NaN:e.w,i=""===e.h?NaN:e.h,[n,s]=[0,0];switch(e.anchorType||""){case"bottomCenter":[n,s]=[r/2,i];break;case"bottomLeft":[n,s]=[0,i];break;case"bottomRight":[n,s]=[r,i];break;case"middleCenter":[n,s]=[r/2,i/2];break;case"middleLeft":[n,s]=[0,i/2];break;case"middleRight":[n,s]=[r,i/2];break;case"topCenter":[n,s]=[r/2,0];break;case"topRight":[n,s]=[r,0]}switch(e.rotate||0){case 0:[t,a]=[-n,-s];break;case 90:[t,a]=[-s,n];[r,i]=[i,-r];break;case 180:[t,a]=[n,s];[r,i]=[-r,-i];break;case 270:[t,a]=[s,-n];[r,i]=[-i,r]}return[e.x+t+Math.min(0,r),e.y+a+Math.min(0,i),Math.abs(r),Math.abs(i)]}(e);switch(a.layout){case"lr-tb":case"rl-tb":return 0===r?e[fs]()[Jn].noLayoutFailure?""!==e.w?Math.round(n-t.width)<=2:t.width>2:!(""!==e.h&&Math.round(s-t.height)>2)&&(""!==e.w?Math.round(n-t.width)<=2||0===a[Jn].numberInLine&&t.height>2:t.width>2):!!e[fs]()[Jn].noLayoutFailure||!(""!==e.h&&Math.round(s-t.height)>2)&&((""===e.w||Math.round(n-t.width)<=2||!a[vs]())&&t.height>2);case"table":case"tb":return!!e[fs]()[Jn].noLayoutFailure||(""===e.h||e[Cs]()?(""===e.w||Math.round(n-t.width)<=2||!a[vs]())&&t.height>2:Math.round(s-t.height)<=2);case"position":if(e[fs]()[Jn].noLayoutFailure)return!0;if(""===e.h||Math.round(s+i-t.height)<=2)return!0;return s+i>e[fs]()[Jn].currentContentArea.h;case"rl-row":case"row":return!!e[fs]()[Jn].noLayoutFailure||(""===e.h||Math.round(s-t.height)<=2);default:return!0}}const No=eo.template.id,Eo="http://www.w3.org/2000/svg",Po=/^H(\d+)$/,Lo=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),_o=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(e){if(!e||!e.border)return{w:0,h:0};const t=e.border[ss]();return t?{w:t.widths[0]+t.widths[2]+t.insets[0]+t.insets[2],h:t.widths[1]+t.widths[3]+t.insets[1]+t.insets[3]}:{w:0,h:0}}function hasMargin(e){return e.margin&&(e.margin.topInset||e.margin.rightInset||e.margin.bottomInset||e.margin.leftInset)}function _setValue(e,t){if(!e.value){const t=new Value({});e[jn](t);e.value=t}e.value[Gs](t)}function*getContainedChildren(e){for(const t of e[cs]())t instanceof SubformSet?yield*t[ls]():yield t}function isRequired(e){return"error"===e.validate?.nullTest}function setTabIndex(e){for(;e;){if(!e.traversal){e[zs]=e[ds]()[zs];return}if(e[zs])return;let t=null;for(const a of e.traversal[cs]())if("next"===a.operation){t=a;break}if(!t||!t.ref){e[zs]=e[ds]()[zs];return}const a=e[fs]();e[zs]=++a[zs];const r=a[qs](t.ref,e);if(!r)return;e=r[0]}}function applyAssist(e,t){const a=e.assist;if(a){const e=a[Ks]();e&&(t.title=e);const r=a.role.match(Po);if(r){const e="heading",a=r[1];t.role=e;t["aria-level"]=a}}if("table"===e.layout)t.role="table";else if("row"===e.layout)t.role="row";else{const a=e[ds]();"row"===a.layout&&(t.role="TH"===a.assist?.role?"columnheader":"cell")}}function ariaLabel(e){if(!e.assist)return null;const t=e.assist;return t.speak&&""!==t.speak[$n]?t.speak[$n]:t.toolTip?t.toolTip[$n]:null}function valueToHtml(e){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:e}]})}function setFirstUnsplittable(e){const t=e[fs]();if(null===t[Jn].firstUnsplittable){t[Jn].firstUnsplittable=e;t[Jn].noLayoutFailure=!0}}function unsetFirstUnsplittable(e){const t=e[fs]();t[Jn].firstUnsplittable===e&&(t[Jn].noLayoutFailure=!1)}function handleBreak(e){if(e[Jn])return!1;e[Jn]=Object.create(null);if("auto"===e.targetType)return!1;const t=e[fs]();let a=null;if(e.target){a=t[qs](e.target,e[ds]());if(!a)return!1;a=a[0]}const{currentPageArea:r,currentContentArea:i}=t[Jn];if("pageArea"===e.targetType){a instanceof PageArea||(a=null);if(e.startNew){e[Jn].target=a||r;return!0}if(a&&a!==r){e[Jn].target=a;return!0}return!1}a instanceof ContentArea||(a=null);const n=a&&a[ds]();let s,o=n;if(e.startNew)if(a){const e=n.contentArea.children,t=e.indexOf(i),r=e.indexOf(a);-1!==t&&te;r[Jn].noLayoutFailure=!0;const s=t[Ks](a);e[Un](s.html,s.bbox);r[Jn].noLayoutFailure=i;t[us]=n}class AppearanceFilter extends StringObject{constructor(e){super(No,"appearanceFilter");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Arc extends XFAObject{constructor(e){super(No,"arc",!0);this.circular=getInteger({data:e.circular,defaultValue:0,validate:e=>1===e});this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.startAngle=getFloat({data:e.startAngle,defaultValue:0,validate:e=>!0});this.sweepAngle=getFloat({data:e.sweepAngle,defaultValue:360,validate:e=>!0});this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null;this.fill=null}[Ks](){const e=this.edge||new Edge({}),t=e[Ys](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ys]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;let r;const i={xmlns:Eo,style:{width:"100%",height:"100%",overflow:"visible"}};if(360===this.sweepAngle)r={name:"ellipse",attributes:{xmlns:Eo,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:a}};else{const e=this.startAngle*Math.PI/180,t=this.sweepAngle*Math.PI/180,n=this.sweepAngle>180?1:0,[s,o,c,l]=[50*(1+Math.cos(e)),50*(1-Math.sin(e)),50*(1+Math.cos(e+t)),50*(1-Math.sin(e+t))];r={name:"path",attributes:{xmlns:Eo,d:`M ${s} ${o} A 50 50 0 ${n} 0 ${c} ${l}`,vectorEffect:"non-scaling-stroke",style:a}};Object.assign(i,{viewBox:"0 0 100 100",preserveAspectRatio:"none"})}const n={name:"svg",children:[r],attributes:i};if(hasMargin(this[ds]()[ds]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[n]});n.attributes.style.position="absolute";return HTMLResult.success(n)}}class Area extends XFAObject{constructor(e){super(No,"area",!0);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null;this.area=new XFAObjectArray;this.draw=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[ls](){yield*getContainedChildren(this)}[Fs](){return!0}[xs](){return!0}[Un](e,t){const[a,r,i,n]=t;this[Jn].width=Math.max(this[Jn].width,a+i);this[Jn].height=Math.max(this[Jn].height,r+n);this[Jn].children.push(e)}[ts](){return this[Jn].availableSpace}[Ks](e){const t=toStyle(this,"position"),a={style:t,id:this[Zs],class:["xfaArea"]};isPrintOnly(this)&&a.class.push("xfaPrintOnly");this.name&&(a.xfaName=this.name);const r=[];this[Jn]={children:r,width:0,height:0,availableSpace:e};const i=this[Xn]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0});if(!i.success){if(i.isBreak())return i;delete this[Jn];return HTMLResult.FAILURE}t.width=measureToString(this[Jn].width);t.height=measureToString(this[Jn].height);const n={name:"div",attributes:a,children:r},s=[this.x,this.y,this[Jn].width,this[Jn].height];delete this[Jn];return HTMLResult.success(n,s)}}class Assist extends XFAObject{constructor(e){super(No,"assist",!0);this.id=e.id||"";this.role=e.role||"";this.use=e.use||"";this.usehref=e.usehref||"";this.speak=null;this.toolTip=null}[Ks](){return this.toolTip?.[$n]||null}}class Barcode extends XFAObject{constructor(e){super(No,"barcode",!0);this.charEncoding=getKeyword({data:e.charEncoding?e.charEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.checksum=getStringOption(e.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]);this.dataColumnCount=getInteger({data:e.dataColumnCount,defaultValue:-1,validate:e=>e>=0});this.dataLength=getInteger({data:e.dataLength,defaultValue:-1,validate:e=>e>=0});this.dataPrep=getStringOption(e.dataPrep,["none","flateCompress"]);this.dataRowCount=getInteger({data:e.dataRowCount,defaultValue:-1,validate:e=>e>=0});this.endChar=e.endChar||"";this.errorCorrectionLevel=getInteger({data:e.errorCorrectionLevel,defaultValue:-1,validate:e=>e>=0&&e<=8});this.id=e.id||"";this.moduleHeight=getMeasurement(e.moduleHeight,"5mm");this.moduleWidth=getMeasurement(e.moduleWidth,"0.25mm");this.printCheckDigit=getInteger({data:e.printCheckDigit,defaultValue:0,validate:e=>1===e});this.rowColumnRatio=getRatio(e.rowColumnRatio);this.startChar=e.startChar||"";this.textLocation=getStringOption(e.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]);this.truncate=getInteger({data:e.truncate,defaultValue:0,validate:e=>1===e});this.type=getStringOption(e.type?e.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]);this.upsMode=getStringOption(e.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]);this.use=e.use||"";this.usehref=e.usehref||"";this.wideNarrowRatio=getRatio(e.wideNarrowRatio);this.encrypt=null;this.extras=null}}class Bind extends XFAObject{constructor(e){super(No,"bind",!0);this.match=getStringOption(e.match,["once","dataRef","global","none"]);this.ref=e.ref||"";this.picture=null}}class BindItems extends XFAObject{constructor(e){super(No,"bindItems");this.connection=e.connection||"";this.labelRef=e.labelRef||"";this.ref=e.ref||"";this.valueRef=e.valueRef||""}}class Bookend extends XFAObject{constructor(e){super(No,"bookend");this.id=e.id||"";this.leader=e.leader||"";this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||""}}class BooleanElement extends Option01{constructor(e){super(No,"boolean");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Ks](e){return valueToHtml(1===this[$n]?"1":"0")}}class Border extends XFAObject{constructor(e){super(No,"border",!0);this.break=getStringOption(e.break,["close","open"]);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.extras=null;this.fill=null;this.margin=null}[ss](){if(!this[Jn]){const e=this.edge.children.slice();if(e.length<4){const t=e.at(-1)||new Edge({});for(let a=e.length;a<4;a++)e.push(t)}const t=e.map(e=>e.thickness),a=[0,0,0,0];if(this.margin){a[0]=this.margin.topInset;a[1]=this.margin.rightInset;a[2]=this.margin.bottomInset;a[3]=this.margin.leftInset}this[Jn]={widths:t,insets:a,edges:e}}return this[Jn]}[Ys](){const{edges:e}=this[ss](),t=e.map(e=>{const t=e[Ys]();t.color||="#000000";return t}),a=Object.create(null);this.margin&&Object.assign(a,this.margin[Ys]());"visible"===this.fill?.presence&&Object.assign(a,this.fill[Ys]());if(this.corner.children.some(e=>0!==e.radius)){const e=this.corner.children.map(e=>e[Ys]());if(2===e.length||3===e.length){const t=e.at(-1);for(let a=e.length;a<4;a++)e.push(t)}a.borderRadius=e.map(e=>e.radius).join(" ")}switch(this.presence){case"invisible":case"hidden":a.borderStyle="";break;case"inactive":a.borderStyle="none";break;default:a.borderStyle=t.map(e=>e.style).join(" ")}a.borderWidth=t.map(e=>e.width).join(" ");a.borderColor=t.map(e=>e.color).join(" ");return a}}class Break extends XFAObject{constructor(e){super(No,"break",!0);this.after=getStringOption(e.after,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.afterTarget=e.afterTarget||"";this.before=getStringOption(e.before,["auto","contentArea","pageArea","pageEven","pageOdd"]);this.beforeTarget=e.beforeTarget||"";this.bookendLeader=e.bookendLeader||"";this.bookendTrailer=e.bookendTrailer||"";this.id=e.id||"";this.overflowLeader=e.overflowLeader||"";this.overflowTarget=e.overflowTarget||"";this.overflowTrailer=e.overflowTrailer||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class BreakAfter extends XFAObject{constructor(e){super(No,"breakAfter",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}}class BreakBefore extends XFAObject{constructor(e){super(No,"breakBefore",!0);this.id=e.id||"";this.leader=e.leader||"";this.startNew=getInteger({data:e.startNew,defaultValue:0,validate:e=>1===e});this.target=e.target||"";this.targetType=getStringOption(e.targetType,["auto","contentArea","pageArea"]);this.trailer=e.trailer||"";this.use=e.use||"";this.usehref=e.usehref||"";this.script=null}[Ks](e){this[Jn]={};return HTMLResult.FAILURE}}class Button extends XFAObject{constructor(e){super(No,"button",!0);this.highlight=getStringOption(e.highlight,["inverted","none","outline","push"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ks](e){const t=this[ds]()[ds](),a={name:"button",attributes:{id:this[Zs],class:["xfaButton"],style:{}},children:[]};for(const e of t.event.children){if("click"!==e.activity||!e.script)continue;const t=recoverJsURL(e.script[$n]);if(!t)continue;const r=fixURL(t.url);r&&a.children.push({name:"a",attributes:{id:"link"+this[Zs],href:r,newWindow:t.newWindow,class:["xfaLink"],style:{}},children:[]})}return HTMLResult.success(a)}}class Calculate extends XFAObject{constructor(e){super(No,"calculate",!0);this.id=e.id||"";this.override=getStringOption(e.override,["disabled","error","ignore","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.script=null}}class Caption extends XFAObject{constructor(e){super(No,"caption",!0);this.id=e.id||"";this.placement=getStringOption(e.placement,["left","bottom","inline","right","top"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.reserve=Math.ceil(getMeasurement(e.reserve));this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.font=null;this.margin=null;this.para=null;this.value=null}[Gs](e){_setValue(this,e)}[ss](e){if(!this[Jn]){let{width:t,height:a}=e;switch(this.placement){case"left":case"right":case"inline":t=this.reserve<=0?t:this.reserve;break;case"top":case"bottom":a=this.reserve<=0?a:this.reserve}this[Jn]=layoutNode(this,{width:t,height:a})}return this[Jn]}[Ks](e){if(!this.value)return HTMLResult.EMPTY;this[_s]();const t=this.value[Ks](e).html;if(!t){this[Ls]();return HTMLResult.EMPTY}const a=this.reserve;if(this.reserve<=0){const{w:t,h:a}=this[ss](e);switch(this.placement){case"left":case"right":case"inline":this.reserve=t;break;case"top":case"bottom":this.reserve=a}}const r=[];"string"==typeof t?r.push({name:"#text",value:t}):r.push(t);const i=toStyle(this,"font","margin","visibility");switch(this.placement){case"left":case"right":this.reserve>0&&(i.width=measureToString(this.reserve));break;case"top":case"bottom":this.reserve>0&&(i.height=measureToString(this.reserve))}setPara(this,null,t);this[Ls]();this.reserve=a;return HTMLResult.success({name:"div",attributes:{style:i,class:["xfaCaption"]},children:r})}}class Certificate extends StringObject{constructor(e){super(No,"certificate");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Certificates extends XFAObject{constructor(e){super(No,"certificates",!0);this.credentialServerPolicy=getStringOption(e.credentialServerPolicy,["optional","required"]);this.id=e.id||"";this.url=e.url||"";this.urlPolicy=e.urlPolicy||"";this.use=e.use||"";this.usehref=e.usehref||"";this.encryption=null;this.issuers=null;this.keyUsage=null;this.oids=null;this.signing=null;this.subjectDNs=null}}class CheckButton extends XFAObject{constructor(e){super(No,"checkButton",!0);this.id=e.id||"";this.mark=getStringOption(e.mark,["default","check","circle","cross","diamond","square","star"]);this.shape=getStringOption(e.shape,["square","round"]);this.size=getMeasurement(e.size,"10pt");this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"margin"),a=measureToString(this.size);t.width=t.height=a;let r,i,n;const s=this[ds]()[ds](),o=s.items.children.length&&s.items.children[0][Ks]().html||[],c={on:(void 0!==o[0]?o[0]:"on").toString(),off:(void 0!==o[1]?o[1]:"off").toString()},l=(s.value?.[$s]()||"off")===c.on||void 0,h=s[us](),u=s[Zs];let d;if(h instanceof ExclGroup){n=h[Zs];r="radio";i="xfaRadio";d=h[Vn]?.[Zs]||h[Zs]}else{r="checkbox";i="xfaCheckbox";d=s[Vn]?.[Zs]||s[Zs]}const f={name:"input",attributes:{class:[i],style:t,fieldId:u,dataId:d,type:r,checked:l,xfaOn:c.on,xfaOff:c.off,"aria-label":ariaLabel(s),"aria-required":!1}};n&&(f.attributes.name=n);if(isRequired(s)){f.attributes["aria-required"]=!0;f.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[f]})}}class ChoiceList extends XFAObject{constructor(e){super(No,"choiceList",!0);this.commitOn=getStringOption(e.commitOn,["select","exit"]);this.id=e.id||"";this.open=getStringOption(e.open,["userControl","always","multiSelect","onEntry"]);this.textEntry=getInteger({data:e.textEntry,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","margin"),a=this[ds]()[ds](),r={fontSize:`calc(${a.font?.size||10}px * var(--total-scale-factor))`},i=[];if(a.items.children.length>0){const e=a.items;let t=0,n=0;if(2===e.children.length){t=e.children[0].save;n=1-t}const s=e.children[t][Ks]().html,o=e.children[n][Ks]().html;let c=!1;const l=a.value?.[$s]()||"";for(let e=0,t=s.length;eMathClamp(parseInt(e.trim(),10),0,255)).map(e=>isNaN(e)?0:e);if(n.length<3)return{r:a,g:r,b:i};[a,r,i]=n;return{r:a,g:r,b:i}}(e.value):"";this.extras=null}[ps](){return!1}[Ys](){return this.value?Util.makeHexColor(this.value.r,this.value.g,this.value.b):null}}class Comb extends XFAObject{constructor(e){super(No,"comb");this.id=e.id||"";this.numberOfCells=getInteger({data:e.numberOfCells,defaultValue:0,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||""}}class Connect extends XFAObject{constructor(e){super(No,"connect",!0);this.connection=e.connection||"";this.id=e.id||"";this.ref=e.ref||"";this.usage=getStringOption(e.usage,["exportAndImport","exportOnly","importOnly"]);this.use=e.use||"";this.usehref=e.usehref||"";this.picture=null}}class ContentArea extends XFAObject{constructor(e){super(No,"contentArea",!0);this.h=getMeasurement(e.h);this.id=e.id||"";this.name=e.name||"";this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=getMeasurement(e.w);this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.desc=null;this.extras=null}[Ks](e){const t={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},a=["xfaContentarea"];isPrintOnly(this)&&a.push("xfaPrintOnly");return HTMLResult.success({name:"div",children:[],attributes:{style:t,class:a,id:this[Zs]}})}}class Corner extends XFAObject{constructor(e){super(No,"corner",!0);this.id=e.id||"";this.inverted=getInteger({data:e.inverted,defaultValue:0,validate:e=>1===e});this.join=getStringOption(e.join,["square","round"]);this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.radius=getMeasurement(e.radius);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](){const e=toStyle(this,"visibility");e.radius=measureToString("square"===this.join?0:this.radius);return e}}class DateElement extends ContentObject{constructor(e){super(No,"date");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=this[$n].trim();this[$n]=e?new Date(e):null}[Ks](e){return valueToHtml(this[$n]?this[$n].toString():"")}}class DateTime extends ContentObject{constructor(e){super(No,"dateTime");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=this[$n].trim();this[$n]=e?new Date(e):null}[Ks](e){return valueToHtml(this[$n]?this[$n].toString():"")}}class DateTimeEdit extends XFAObject{constructor(e){super(No,"dateTimeEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.picker=getStringOption(e.picker,["host","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","font","margin"),a=this[ds]()[ds](),r={name:"input",attributes:{type:"text",fieldId:a[Zs],dataId:a[Vn]?.[Zs]||a[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Decimal extends ContentObject{constructor(e){super(No,"decimal");this.fracDigits=getInteger({data:e.fracDigits,defaultValue:2,validate:e=>!0});this.id=e.id||"";this.leadDigits=getInteger({data:e.leadDigits,defaultValue:-1,validate:e=>!0});this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=parseFloat(this[$n].trim());this[$n]=isNaN(e)?null:e}[Ks](e){return valueToHtml(null!==this[$n]?this[$n].toString():"")}}class DefaultUi extends XFAObject{constructor(e){super(No,"defaultUi",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class Desc extends XFAObject{constructor(e){super(No,"desc",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(e){super(No,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class DigestMethods extends XFAObject{constructor(e){super(No,"digestMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(e){super(No,"draw",!0);this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.border=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.value=null;this.setProperty=new XFAObjectArray}[Gs](e){_setValue(this,e)}[Ks](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this);this[_s]();const t=this.w,a=this.h,{w:r,h:i,isBroken:n}=layoutNode(this,e);if(r&&""===this.w){if(n&&this[us]()[vs]()){this[Ls]();return HTMLResult.FAILURE}this.w=r}i&&""===this.h&&(this.h=i);setFirstUnsplittable(this);if(!checkDimensions(this,e)){this.w=t;this.h=a;this[Ls]();return HTMLResult.FAILURE}unsetFirstUnsplittable(this);const s=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin");setMinMaxDimensions(this,s);if(s.margin){s.padding=s.margin;delete s.margin}const o=["xfaDraw"];this.font&&o.push("xfaFont");isPrintOnly(this)&&o.push("xfaPrintOnly");const c={style:s,id:this[Zs],class:o};this.name&&(c.xfaName=this.name);const l={name:"div",attributes:c,children:[]};applyAssist(this,c);const h=computeBbox(this,l,e),u=this.value?this.value[Ks](e).html:null;if(null===u){this.w=t;this.h=a;this[Ls]();return HTMLResult.success(createWrapper(this,l),h)}l.children.push(u);setPara(this,s,u);this.w=t;this.h=a;this[Ls]();return HTMLResult.success(createWrapper(this,l),h)}}class Edge extends XFAObject{constructor(e){super(No,"edge",!0);this.cap=getStringOption(e.cap,["square","butt","round"]);this.id=e.id||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.stroke=getStringOption(e.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]);this.thickness=getMeasurement(e.thickness,"0.5pt");this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](){const e=toStyle(this,"visibility");Object.assign(e,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[Ys]():"#000000",style:""});if("visible"!==this.presence)e.style="none";else switch(this.stroke){case"solid":e.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":e.style="dashed";break;case"dotted":e.style="dotted";break;case"embossed":e.style="ridge";break;case"etched":e.style="groove";break;case"lowered":e.style="inset";break;case"raised":e.style="outset"}return e}}class Encoding extends OptionObject{constructor(e){super(No,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Encodings extends XFAObject{constructor(e){super(No,"encodings",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(e){super(No,"encrypt",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=null}}class EncryptData extends XFAObject{constructor(e){super(No,"encryptData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["encrypt","decrypt"]);this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Encryption extends XFAObject{constructor(e){super(No,"encryption",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(e){super(No,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EncryptionMethods extends XFAObject{constructor(e){super(No,"encryptionMethods",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(e){super(No,"event",!0);this.activity=getStringOption(e.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]);this.id=e.id||"";this.listen=getStringOption(e.listen,["refOnly","refAndDescendents"]);this.name=e.name||"";this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.encryptData=null;this.execute=null;this.script=null;this.signData=null;this.submit=null}}class ExData extends ContentObject{constructor(e){super(No,"exData");this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.maxLength=getInteger({data:e.maxLength,defaultValue:-1,validate:e=>e>=-1});this.name=e.name||"";this.rid=e.rid||"";this.transferEncoding=getStringOption(e.transferEncoding,["none","base64","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[ws](){return"text/html"===this.contentType}[Bs](e){if("text/html"===this.contentType&&e[Os]===eo.xhtml.id){this[$n]=e;return!0}if("text/xml"===this.contentType){this[$n]=e;return!0}return!1}[Ks](e){return"text/html"===this.contentType&&this[$n]?this[$n][Ks](e):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(e){super(No,"exObject",!0);this.archive=e.archive||"";this.classId=e.classId||"";this.codeBase=e.codeBase||"";this.codeType=e.codeType||"";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(e){super(No,"exclGroup",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.accessKey=e.accessKey||"";this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.margin=null;this.para=null;this.traversal=null;this.validate=null;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.field=new XFAObjectArray;this.setProperty=new XFAObjectArray}[xs](){return!0}[ps](){return!0}[Gs](e){for(const t of this.field.children){if(!t.value){const e=new Value({});t[jn](e);t.value=e}t.value[Gs](e)}}[vs](){return this.layout.endsWith("-tb")&&0===this[Jn].attempt&&this[Jn].numberInLine>0||this[ds]()[vs]()}[Cs](){const e=this[us]();if(!e[Cs]())return!1;if(void 0!==this[Jn]._isSplittable)return this[Jn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Jn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Jn].numberInLine)return!1;this[Jn]._isSplittable=!0;return!0}[Zn](){return flushHTML(this)}[Un](e,t){addHTML(this,e,t)}[ts](){return getAvailableSpace(this)}[Ks](e){setTabIndex(this);if("hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Zs],class:[]};setAccess(this,a.class);this[Jn]||=Object.create(null);Object.assign(this[Jn],{children:t,attributes:a,attempt:0,line:null,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[Cs]();r||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const i=new Set(["field"]);if(this.layout.includes("row")){const e=this[us]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Jn].columnWidths=e;this[Jn].currentColumn=0}}const n=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),s=["xfaExclgroup"],o=layoutClass(this);o&&s.push(o);isPrintOnly(this)&&s.push("xfaPrintOnly");a.style=n;a.class=s;this.name&&(a.xfaName=this.name);this[_s]();const c="lr-tb"===this.layout||"rl-tb"===this.layout,l=c?2:1;for(;this[Jn].attempte>=1||-1===e});this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.rotate=getInteger({data:e.rotate,defaultValue:0,validate:e=>e%90==0});this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.border=null;this.calculate=null;this.caption=null;this.desc=null;this.extras=null;this.font=null;this.format=null;this.items=new XFAObjectArray(2);this.keep=null;this.margin=null;this.para=null;this.traversal=null;this.ui=null;this.validate=null;this.value=null;this.bindItems=new XFAObjectArray;this.connect=new XFAObjectArray;this.event=new XFAObjectArray;this.setProperty=new XFAObjectArray}[xs](){return!0}[Gs](e){_setValue(this,e)}[Ks](e){setTabIndex(this);if(!this.ui){this.ui=new Ui({});this.ui[gs]=this[gs];this[jn](this.ui);let e;switch(this.items.children.length){case 0:e=new TextEdit({});this.ui.textEdit=e;break;case 1:e=new CheckButton({});this.ui.checkButton=e;break;case 2:e=new ChoiceList({});this.ui.choiceList=e}this.ui[jn](e)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[Jn];this[_s]();const t=this.caption?this.caption[Ks](e).html:null,a=this.w,r=this.h;let i=0,n=0;if(this.margin){i=this.margin.leftInset+this.margin.rightInset;n=this.margin.topInset+this.margin.bottomInset}let s=null;if(""===this.w||""===this.h){let t=null,a=null,r=0,o=0;if(this.ui.checkButton)r=o=this.ui.checkButton.size;else{const{w:t,h:a}=layoutNode(this,e);if(null!==t){r=t;o=a}else o=function fonts_getMetrics(e,t=!1){let a=null;if(e){const t=stripQuotes(e.typeface),r=e[gs].fontFinder.find(t);a=selectFont(e,r)}if(!a)return{lineHeight:12,lineGap:2,lineNoGap:10};const r=e.size||10,i=a.lineHeight?Math.max(t?0:1.2,a.lineHeight):1.2,n=void 0===a.lineGap?.2:a.lineGap;return{lineHeight:i*r,lineGap:n*r,lineNoGap:Math.max(1,i-n)*r}}(this.font,!0).lineNoGap}s=getBorderDims(this.ui[ss]());r+=s.w;o+=s.h;if(this.caption){const{w:i,h:n,isBroken:s}=this.caption[ss](e);if(s&&this[us]()[vs]()){this[Ls]();return HTMLResult.FAILURE}t=i;a=n;switch(this.caption.placement){case"left":case"right":case"inline":t+=r;break;case"top":case"bottom":a+=o}}else{t=r;a=o}if(t&&""===this.w){t+=i;this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+1e>=1&&e<=5});this.appearanceFilter=null;this.certificates=null;this.digestMethods=null;this.encodings=null;this.encryptionMethods=null;this.handler=null;this.lockDocument=null;this.mdp=null;this.reasons=null;this.timeStamp=null}}class Float extends ContentObject{constructor(e){super(No,"float");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=parseFloat(this[$n].trim());this[$n]=isNaN(e)?null:e}[Ks](e){return valueToHtml(null!==this[$n]?this[$n].toString():"")}}class template_Font extends XFAObject{constructor(e){super(No,"font",!0);this.baselineShift=getMeasurement(e.baselineShift);this.fontHorizontalScale=getFloat({data:e.fontHorizontalScale,defaultValue:100,validate:e=>e>=0});this.fontVerticalScale=getFloat({data:e.fontVerticalScale,defaultValue:100,validate:e=>e>=0});this.id=e.id||"";this.kerningMode=getStringOption(e.kerningMode,["none","pair"]);this.letterSpacing=getMeasurement(e.letterSpacing,"0");this.lineThrough=getInteger({data:e.lineThrough,defaultValue:0,validate:e=>1===e||2===e});this.lineThroughPeriod=getStringOption(e.lineThroughPeriod,["all","word"]);this.overline=getInteger({data:e.overline,defaultValue:0,validate:e=>1===e||2===e});this.overlinePeriod=getStringOption(e.overlinePeriod,["all","word"]);this.posture=getStringOption(e.posture,["normal","italic"]);this.size=getMeasurement(e.size,"10pt");this.typeface=e.typeface||"Courier";this.underline=getInteger({data:e.underline,defaultValue:0,validate:e=>1===e||2===e});this.underlinePeriod=getStringOption(e.underlinePeriod,["all","word"]);this.use=e.use||"";this.usehref=e.usehref||"";this.weight=getStringOption(e.weight,["normal","bold"]);this.extras=null;this.fill=null}[qn](e){super[qn](e);this[gs].usedTypefaces.add(this.typeface)}[Ys](){const e=toStyle(this,"fill"),t=e.color;if(t)if("#000000"===t)delete e.color;else if(!t.startsWith("#")){e.background=t;e.backgroundClip="text";e.color="transparent"}this.baselineShift&&(e.verticalAlign=measureToString(this.baselineShift));e.fontKerning="none"===this.kerningMode?"none":"normal";e.letterSpacing=measureToString(this.letterSpacing);if(0!==this.lineThrough){e.textDecoration="line-through";2===this.lineThrough&&(e.textDecorationStyle="double")}if(0!==this.overline){e.textDecoration="overline";2===this.overline&&(e.textDecorationStyle="double")}e.fontStyle=this.posture;e.fontSize=measureToString(.99*this.size);setFontFamily(this,this,this[gs].fontFinder,e);if(0!==this.underline){e.textDecoration="underline";2===this.underline&&(e.textDecorationStyle="double")}e.fontWeight=this.weight;return e}}class Format extends XFAObject{constructor(e){super(No,"format",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null}}class Handler extends StringObject{constructor(e){super(No,"handler");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Hyphenation extends XFAObject{constructor(e){super(No,"hyphenation");this.excludeAllCaps=getInteger({data:e.excludeAllCaps,defaultValue:0,validate:e=>1===e});this.excludeInitialCap=getInteger({data:e.excludeInitialCap,defaultValue:0,validate:e=>1===e});this.hyphenate=getInteger({data:e.hyphenate,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.pushCharacterCount=getInteger({data:e.pushCharacterCount,defaultValue:3,validate:e=>e>=0});this.remainCharacterCount=getInteger({data:e.remainCharacterCount,defaultValue:3,validate:e=>e>=0});this.use=e.use||"";this.usehref=e.usehref||"";this.wordCharacterCount=getInteger({data:e.wordCharacterCount,defaultValue:7,validate:e=>e>=0})}}class Image extends StringObject{constructor(e){super(No,"image");this.aspect=getStringOption(e.aspect,["fit","actual","height","none","width"]);this.contentType=e.contentType||"";this.href=e.href||"";this.id=e.id||"";this.name=e.name||"";this.transferEncoding=getStringOption(e.transferEncoding,["base64","none","package"]);this.use=e.use||"";this.usehref=e.usehref||""}[Ks](){if(this.contentType&&!Lo.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let e=this[gs].images?.get(this.href);if(!e&&(this.href||!this[$n]))return HTMLResult.EMPTY;e||"base64"!==this.transferEncoding||(e=function fromBase64Util(e){return Uint8Array.fromBase64?Uint8Array.fromBase64(e):stringToBytes(atob(e))}(this[$n]));if(!e)return HTMLResult.EMPTY;if(!this.contentType){for(const[t,a]of _o)if(e.length>t.length&&t.every((t,a)=>t===e[a])){this.contentType=a;break}if(!this.contentType)return HTMLResult.EMPTY}const t=new Blob([e],{type:this.contentType});let a;switch(this.aspect){case"fit":case"actual":break;case"height":a={height:"100%",objectFit:"fill"};break;case"none":a={width:"100%",height:"100%",objectFit:"fill"};break;case"width":a={width:"100%",objectFit:"fill"}}const r=this[ds]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:a,src:URL.createObjectURL(t),alt:r?ariaLabel(r[ds]()):null}})}}class ImageEdit extends XFAObject{constructor(e){super(No,"imageEdit",!0);this.data=getStringOption(e.data,["link","embed"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}[Ks](e){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(e){super(No,"integer");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=parseInt(this[$n].trim(),10);this[$n]=isNaN(e)?null:e}[Ks](e){return valueToHtml(null!==this[$n]?this[$n].toString():"")}}class Issuers extends XFAObject{constructor(e){super(No,"issuers",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(e){super(No,"items",!0);this.id=e.id||"";this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.ref=e.ref||"";this.save=getInteger({data:e.save,defaultValue:0,validate:e=>1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Ks](){const e=[];for(const t of this[cs]())e.push(t[$s]());return HTMLResult.success(e)}}class Keep extends XFAObject{constructor(e){super(No,"keep",!0);this.id=e.id||"";const t=["none","contentArea","pageArea"];this.intact=getStringOption(e.intact,t);this.next=getStringOption(e.next,t);this.previous=getStringOption(e.previous,t);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}}class KeyUsage extends XFAObject{constructor(e){super(No,"keyUsage");const t=["","yes","no"];this.crlSign=getStringOption(e.crlSign,t);this.dataEncipherment=getStringOption(e.dataEncipherment,t);this.decipherOnly=getStringOption(e.decipherOnly,t);this.digitalSignature=getStringOption(e.digitalSignature,t);this.encipherOnly=getStringOption(e.encipherOnly,t);this.id=e.id||"";this.keyAgreement=getStringOption(e.keyAgreement,t);this.keyCertSign=getStringOption(e.keyCertSign,t);this.keyEncipherment=getStringOption(e.keyEncipherment,t);this.nonRepudiation=getStringOption(e.nonRepudiation,t);this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Line extends XFAObject{constructor(e){super(No,"line",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.slope=getStringOption(e.slope,["\\","/"]);this.use=e.use||"";this.usehref=e.usehref||"";this.edge=null}[Ks](){const e=this[ds]()[ds](),t=this.edge||new Edge({}),a=t[Ys](),r=Object.create(null),i="visible"===t.presence?t.thickness:0;r.strokeWidth=measureToString(i);r.stroke=a.color;let n,s,o,c,l="100%",h="100%";if(e.w<=i){[n,s,o,c]=["50%",0,"50%","100%"];l=r.strokeWidth}else if(e.h<=i){[n,s,o,c]=[0,"50%","100%","50%"];h=r.strokeWidth}else"\\"===this.slope?[n,s,o,c]=[0,0,"100%","100%"]:[n,s,o,c]=[0,"100%","100%",0];const u={name:"svg",children:[{name:"line",attributes:{xmlns:Eo,x1:n,y1:s,x2:o,y2:c,style:r}}],attributes:{xmlns:Eo,width:l,height:h,style:{overflow:"visible"}}};if(hasMargin(e))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[u]});u.attributes.style.position="absolute";return HTMLResult.success(u)}}class Linear extends XFAObject{constructor(e){super(No,"linear",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toRight","toBottom","toLeft","toTop"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){e=e?e[Ys]():"#FFFFFF";return`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${e}, ${this.color?this.color[Ys]():"#000000"})`}}class LockDocument extends ContentObject{constructor(e){super(No,"lockDocument");this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){this[$n]=getStringOption(this[$n],["auto","0","1"])}}class Manifest extends XFAObject{constructor(e){super(No,"manifest",!0);this.action=getStringOption(e.action,["include","all","exclude"]);this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(e){super(No,"margin",!0);this.bottomInset=getMeasurement(e.bottomInset,"0");this.id=e.id||"";this.leftInset=getMeasurement(e.leftInset,"0");this.rightInset=getMeasurement(e.rightInset,"0");this.topInset=getMeasurement(e.topInset,"0");this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(e){super(No,"mdp");this.id=e.id||"";this.permissions=getInteger({data:e.permissions,defaultValue:2,validate:e=>1===e||3===e});this.signatureType=getStringOption(e.signatureType,["filler","author"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Medium extends XFAObject{constructor(e){super(No,"medium");this.id=e.id||"";this.imagingBBox=function getBBox(e){const t=-1;if(!e)return{x:t,y:t,width:t,height:t};const a=e.split(",",4).map(e=>getMeasurement(e.trim(),"-1"));if(a.length<4||a[2]<0||a[3]<0)return{x:t,y:t,width:t,height:t};const[r,i,n,s]=a;return{x:r,y:i,width:n,height:s}}(e.imagingBBox);this.long=getMeasurement(e.long);this.orientation=getStringOption(e.orientation,["portrait","landscape"]);this.short=getMeasurement(e.short);this.stock=e.stock||"";this.trayIn=getStringOption(e.trayIn,["auto","delegate","pageFront"]);this.trayOut=getStringOption(e.trayOut,["auto","delegate"]);this.use=e.use||"";this.usehref=e.usehref||""}}class Message extends XFAObject{constructor(e){super(No,"message",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(e){super(No,"numericEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","font","margin"),a=this[ds]()[ds](),r={name:"input",attributes:{type:"text",fieldId:a[Zs],dataId:a[Vn]?.[Zs]||a[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(a),"aria-required":!1}};if(isRequired(a)){r.attributes["aria-required"]=!0;r.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[r]})}}class Occur extends XFAObject{constructor(e){super(No,"occur",!0);this.id=e.id||"";this.initial=""!==e.initial?getInteger({data:e.initial,defaultValue:"",validate:e=>!0}):"";this.max=""!==e.max?getInteger({data:e.max,defaultValue:1,validate:e=>!0}):"";this.min=""!==e.min?getInteger({data:e.min,defaultValue:1,validate:e=>!0}):"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[qn](){const e=this[ds](),t=this.min;""===this.min&&(this.min=e instanceof PageArea||e instanceof PageSet?0:1);""===this.max&&(this.max=""===t?e instanceof PageArea||e instanceof PageSet?-1:1:this.min);-1!==this.max&&this.max!0});this.name=e.name||"";this.numbered=getInteger({data:e.numbered,defaultValue:1,validate:e=>!0});this.oddOrEven=getStringOption(e.oddOrEven,["any","even","odd"]);this.pagePosition=getStringOption(e.pagePosition,["any","first","last","only","rest"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.desc=null;this.extras=null;this.medium=null;this.occur=null;this.area=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.draw=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.subform=new XFAObjectArray}[Is](){if(!this[Jn]){this[Jn]={numberOfUse:0};return!0}return!this.occur||-1===this.occur.max||this[Jn].numberOfUsee.oddOrEven===t&&e.pagePosition===a);if(r)return r;r=this.pageArea.children.find(e=>"any"===e.oddOrEven&&e.pagePosition===a);if(r)return r;r=this.pageArea.children.find(e=>"any"===e.oddOrEven&&"any"===e.pagePosition);return r||this.pageArea.children[0]}}class Para extends XFAObject{constructor(e){super(No,"para",!0);this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.lineHeight=e.lineHeight?getMeasurement(e.lineHeight,"0pt"):"";this.marginLeft=e.marginLeft?getMeasurement(e.marginLeft,"0pt"):"";this.marginRight=e.marginRight?getMeasurement(e.marginRight,"0pt"):"";this.orphans=getInteger({data:e.orphans,defaultValue:0,validate:e=>e>=0});this.preserve=e.preserve||"";this.radixOffset=e.radixOffset?getMeasurement(e.radixOffset,"0pt"):"";this.spaceAbove=e.spaceAbove?getMeasurement(e.spaceAbove,"0pt"):"";this.spaceBelow=e.spaceBelow?getMeasurement(e.spaceBelow,"0pt"):"";this.tabDefault=e.tabDefault?getMeasurement(this.tabDefault):"";this.tabStops=(e.tabStops||"").trim().split(/\s+/).map((e,t)=>t%2==1?getMeasurement(e):e);this.textIndent=e.textIndent?getMeasurement(e.textIndent,"0pt"):"";this.use=e.use||"";this.usehref=e.usehref||"";this.vAlign=getStringOption(e.vAlign,["top","bottom","middle"]);this.widows=getInteger({data:e.widows,defaultValue:0,validate:e=>e>=0});this.hyphenation=null}[Ys](){const e=toStyle(this,"hAlign");""!==this.marginLeft&&(e.paddingLeft=measureToString(this.marginLeft));""!==this.marginRight&&(e.paddingRight=measureToString(this.marginRight));""!==this.spaceAbove&&(e.paddingTop=measureToString(this.spaceAbove));""!==this.spaceBelow&&(e.paddingBottom=measureToString(this.spaceBelow));if(""!==this.textIndent){e.textIndent=measureToString(this.textIndent);fixTextIndent(e)}this.lineHeight>0&&(e.lineHeight=measureToString(this.lineHeight));""!==this.tabDefault&&(e.tabSize=measureToString(this.tabDefault));this.tabStops.length;this.hyphenatation&&Object.assign(e,this.hyphenatation[Ys]());return e}}class PasswordEdit extends XFAObject{constructor(e){super(No,"passwordEdit",!0);this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.passwordChar=e.passwordChar||"*";this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.margin=null}}class template_Pattern extends XFAObject{constructor(e){super(No,"pattern",!0);this.id=e.id||"";this.type=getStringOption(e.type,["crossHatch","crossDiagonal","diagonalLeft","diagonalRight","horizontal","vertical"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){e=e?e[Ys]():"#FFFFFF";const t=this.color?this.color[Ys]():"#000000",a="repeating-linear-gradient",r=`${e},${e} 5px,${t} 5px,${t} 10px`;switch(this.type){case"crossHatch":return`${a}(to top,${r}) ${a}(to right,${r})`;case"crossDiagonal":return`${a}(45deg,${r}) ${a}(-45deg,${r})`;case"diagonalLeft":return`${a}(45deg,${r})`;case"diagonalRight":return`${a}(-45deg,${r})`;case"horizontal":return`${a}(to top,${r})`;case"vertical":return`${a}(to right,${r})`}return""}}class Picture extends StringObject{constructor(e){super(No,"picture");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Proto extends XFAObject{constructor(e){super(No,"proto",!0);this.appearanceFilter=new XFAObjectArray;this.arc=new XFAObjectArray;this.area=new XFAObjectArray;this.assist=new XFAObjectArray;this.barcode=new XFAObjectArray;this.bindItems=new XFAObjectArray;this.bookend=new XFAObjectArray;this.boolean=new XFAObjectArray;this.border=new XFAObjectArray;this.break=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.button=new XFAObjectArray;this.calculate=new XFAObjectArray;this.caption=new XFAObjectArray;this.certificate=new XFAObjectArray;this.certificates=new XFAObjectArray;this.checkButton=new XFAObjectArray;this.choiceList=new XFAObjectArray;this.color=new XFAObjectArray;this.comb=new XFAObjectArray;this.connect=new XFAObjectArray;this.contentArea=new XFAObjectArray;this.corner=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.dateTimeEdit=new XFAObjectArray;this.decimal=new XFAObjectArray;this.defaultUi=new XFAObjectArray;this.desc=new XFAObjectArray;this.digestMethod=new XFAObjectArray;this.digestMethods=new XFAObjectArray;this.draw=new XFAObjectArray;this.edge=new XFAObjectArray;this.encoding=new XFAObjectArray;this.encodings=new XFAObjectArray;this.encrypt=new XFAObjectArray;this.encryptData=new XFAObjectArray;this.encryption=new XFAObjectArray;this.encryptionMethod=new XFAObjectArray;this.encryptionMethods=new XFAObjectArray;this.event=new XFAObjectArray;this.exData=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.execute=new XFAObjectArray;this.extras=new XFAObjectArray;this.field=new XFAObjectArray;this.fill=new XFAObjectArray;this.filter=new XFAObjectArray;this.float=new XFAObjectArray;this.font=new XFAObjectArray;this.format=new XFAObjectArray;this.handler=new XFAObjectArray;this.hyphenation=new XFAObjectArray;this.image=new XFAObjectArray;this.imageEdit=new XFAObjectArray;this.integer=new XFAObjectArray;this.issuers=new XFAObjectArray;this.items=new XFAObjectArray;this.keep=new XFAObjectArray;this.keyUsage=new XFAObjectArray;this.line=new XFAObjectArray;this.linear=new XFAObjectArray;this.lockDocument=new XFAObjectArray;this.manifest=new XFAObjectArray;this.margin=new XFAObjectArray;this.mdp=new XFAObjectArray;this.medium=new XFAObjectArray;this.message=new XFAObjectArray;this.numericEdit=new XFAObjectArray;this.occur=new XFAObjectArray;this.oid=new XFAObjectArray;this.oids=new XFAObjectArray;this.overflow=new XFAObjectArray;this.pageArea=new XFAObjectArray;this.pageSet=new XFAObjectArray;this.para=new XFAObjectArray;this.passwordEdit=new XFAObjectArray;this.pattern=new XFAObjectArray;this.picture=new XFAObjectArray;this.radial=new XFAObjectArray;this.reason=new XFAObjectArray;this.reasons=new XFAObjectArray;this.rectangle=new XFAObjectArray;this.ref=new XFAObjectArray;this.script=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.signData=new XFAObjectArray;this.signature=new XFAObjectArray;this.signing=new XFAObjectArray;this.solid=new XFAObjectArray;this.speak=new XFAObjectArray;this.stipple=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray;this.subjectDN=new XFAObjectArray;this.subjectDNs=new XFAObjectArray;this.submit=new XFAObjectArray;this.text=new XFAObjectArray;this.textEdit=new XFAObjectArray;this.time=new XFAObjectArray;this.timeStamp=new XFAObjectArray;this.toolTip=new XFAObjectArray;this.traversal=new XFAObjectArray;this.traverse=new XFAObjectArray;this.ui=new XFAObjectArray;this.validate=new XFAObjectArray;this.value=new XFAObjectArray;this.variables=new XFAObjectArray}}class Radial extends XFAObject{constructor(e){super(No,"radial",!0);this.id=e.id||"";this.type=getStringOption(e.type,["toEdge","toCenter"]);this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){e=e?e[Ys]():"#FFFFFF";const t=this.color?this.color[Ys]():"#000000";return`radial-gradient(circle at center, ${"toEdge"===this.type?`${e},${t}`:`${t},${e}`})`}}class Reason extends StringObject{constructor(e){super(No,"reason");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Reasons extends XFAObject{constructor(e){super(No,"reasons",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.reason=new XFAObjectArray}}class Rectangle extends XFAObject{constructor(e){super(No,"rectangle",!0);this.hand=getStringOption(e.hand,["even","left","right"]);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.corner=new XFAObjectArray(4);this.edge=new XFAObjectArray(4);this.fill=null}[Ks](){const e=this.edge.children.length?this.edge.children[0]:new Edge({}),t=e[Ys](),a=Object.create(null);"visible"===this.fill?.presence?Object.assign(a,this.fill[Ys]()):a.fill="transparent";a.strokeWidth=measureToString("visible"===e.presence?e.thickness:0);a.stroke=t.color;const r=(this.corner.children.length?this.corner.children[0]:new Corner({}))[Ys](),i={name:"svg",children:[{name:"rect",attributes:{xmlns:Eo,width:"100%",height:"100%",x:0,y:0,rx:r.radius,ry:r.radius,style:a}}],attributes:{xmlns:Eo,style:{overflow:"visible"},width:"100%",height:"100%"}};if(hasMargin(this[ds]()[ds]()))return HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[i]});i.attributes.style.position="absolute";return HTMLResult.success(i)}}class RefElement extends StringObject{constructor(e){super(No,"ref");this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Script extends StringObject{constructor(e){super(No,"script");this.binding=e.binding||"";this.contentType=e.contentType||"";this.id=e.id||"";this.name=e.name||"";this.runAt=getStringOption(e.runAt,["client","both","server"]);this.use=e.use||"";this.usehref=e.usehref||""}}class SetProperty extends XFAObject{constructor(e){super(No,"setProperty");this.connection=e.connection||"";this.ref=e.ref||"";this.target=e.target||""}}class SignData extends XFAObject{constructor(e){super(No,"signData",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["sign","clear","verify"]);this.ref=e.ref||"";this.target=e.target||"";this.use=e.use||"";this.usehref=e.usehref||"";this.filter=null;this.manifest=null}}class Signature extends XFAObject{constructor(e){super(No,"signature",!0);this.id=e.id||"";this.type=getStringOption(e.type,["PDF1.3","PDF1.6"]);this.use=e.use||"";this.usehref=e.usehref||"";this.border=null;this.extras=null;this.filter=null;this.manifest=null;this.margin=null}}class Signing extends XFAObject{constructor(e){super(No,"signing",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.certificate=new XFAObjectArray}}class Solid extends XFAObject{constructor(e){super(No,"solid",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null}[Ys](e){return e?e[Ys]():"#FFFFFF"}}class Speak extends StringObject{constructor(e){super(No,"speak");this.disable=getInteger({data:e.disable,defaultValue:0,validate:e=>1===e});this.id=e.id||"";this.priority=getStringOption(e.priority,["custom","caption","name","toolTip"]);this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Stipple extends XFAObject{constructor(e){super(No,"stipple",!0);this.id=e.id||"";this.rate=getInteger({data:e.rate,defaultValue:50,validate:e=>e>=0&&e<=100});this.use=e.use||"";this.usehref=e.usehref||"";this.color=null;this.extras=null}[Ys](e){const t=this.rate/100;return Util.makeHexColor(Math.round(e.value.r*(1-t)+this.value.r*t),Math.round(e.value.g*(1-t)+this.value.g*t),Math.round(e.value.b*(1-t)+this.value.b*t))}}class Subform extends XFAObject{constructor(e){super(No,"subform",!0);this.access=getStringOption(e.access,["open","nonInteractive","protected","readOnly"]);this.allowMacro=getInteger({data:e.allowMacro,defaultValue:0,validate:e=>1===e});this.anchorType=getStringOption(e.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]);this.colSpan=getInteger({data:e.colSpan,defaultValue:1,validate:e=>e>=1||-1===e});this.columnWidths=(e.columnWidths||"").trim().split(/\s+/).map(e=>"-1"===e?-1:getMeasurement(e));this.h=e.h?getMeasurement(e.h):"";this.hAlign=getStringOption(e.hAlign,["left","center","justify","justifyAll","radix","right"]);this.id=e.id||"";this.layout=getStringOption(e.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]);this.locale=e.locale||"";this.maxH=getMeasurement(e.maxH,"0pt");this.maxW=getMeasurement(e.maxW,"0pt");this.mergeMode=getStringOption(e.mergeMode,["consumeData","matchTemplate"]);this.minH=getMeasurement(e.minH,"0pt");this.minW=getMeasurement(e.minW,"0pt");this.name=e.name||"";this.presence=getStringOption(e.presence,["visible","hidden","inactive","invisible"]);this.relevant=getRelevant(e.relevant);this.restoreState=getStringOption(e.restoreState,["manual","auto"]);this.scope=getStringOption(e.scope,["name","none"]);this.use=e.use||"";this.usehref=e.usehref||"";this.w=e.w?getMeasurement(e.w):"";this.x=getMeasurement(e.x,"0pt");this.y=getMeasurement(e.y,"0pt");this.assist=null;this.bind=null;this.bookend=null;this.border=null;this.break=null;this.calculate=null;this.desc=null;this.extras=null;this.keep=null;this.margin=null;this.occur=null;this.overflow=null;this.pageSet=null;this.para=null;this.traversal=null;this.validate=null;this.variables=null;this.area=new XFAObjectArray;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.connect=new XFAObjectArray;this.draw=new XFAObjectArray;this.event=new XFAObjectArray;this.exObject=new XFAObjectArray;this.exclGroup=new XFAObjectArray;this.field=new XFAObjectArray;this.proto=new XFAObjectArray;this.setProperty=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}[us](){const e=this[ds]();return e instanceof SubformSet?e[us]():e}[xs](){return!0}[vs](){return this.layout.endsWith("-tb")&&0===this[Jn].attempt&&this[Jn].numberInLine>0||this[ds]()[vs]()}*[ls](){yield*getContainedChildren(this)}[Zn](){return flushHTML(this)}[Un](e,t){addHTML(this,e,t)}[ts](){return getAvailableSpace(this)}[Cs](){const e=this[us]();if(!e[Cs]())return!1;if(void 0!==this[Jn]._isSplittable)return this[Jn]._isSplittable;if("position"===this.layout||this.layout.includes("row")){this[Jn]._isSplittable=!1;return!1}if(this.keep&&"none"!==this.keep.intact){this[Jn]._isSplittable=!1;return!1}if(e.layout?.endsWith("-tb")&&0!==e[Jn].numberInLine)return!1;this[Jn]._isSplittable=!0;return!0}[Ks](e){setTabIndex(this);if(this.break){if("auto"!==this.break.after||""!==this.break.afterTarget){const e=new BreakAfter({targetType:this.break.after,target:this.break.afterTarget,startNew:this.break.startNew.toString()});e[gs]=this[gs];this[jn](e);this.breakAfter.push(e)}if("auto"!==this.break.before||""!==this.break.beforeTarget){const e=new BreakBefore({targetType:this.break.before,target:this.break.beforeTarget,startNew:this.break.startNew.toString()});e[gs]=this[gs];this[jn](e);this.breakBefore.push(e)}if(""!==this.break.overflowTarget){const e=new Overflow({target:this.break.overflowTarget,leader:this.break.overflowLeader,trailer:this.break.overflowTrailer});e[gs]=this[gs];this[jn](e);this.overflow.push(e)}this[Us](this.break);this.break=null}if("hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;(this.breakBefore.children.length>1||this.breakAfter.children.length>1)&&warn("XFA - Several breakBefore or breakAfter in subforms: please file a bug.");if(this.breakBefore.children.length>=1){const e=this.breakBefore.children[0];if(handleBreak(e))return HTMLResult.breakNode(e)}if(this[Jn]?.afterBreakAfter)return HTMLResult.EMPTY;fixDimensions(this);const t=[],a={id:this[Zs],class:[]};setAccess(this,a.class);this[Jn]||=Object.create(null);Object.assign(this[Jn],{children:t,line:null,attributes:a,attempt:0,numberInLine:0,availableSpace:{width:Math.min(this.w||1/0,e.width),height:Math.min(this.h||1/0,e.height)},width:0,height:0,prevHeight:0,currentWidth:0});const r=this[fs](),i=r[Jn].noLayoutFailure,n=this[Cs]();n||setFirstUnsplittable(this);if(!checkDimensions(this,e))return HTMLResult.FAILURE;const s=new Set(["area","draw","exclGroup","field","subform","subformSet"]);if(this.layout.includes("row")){const e=this[us]().columnWidths;if(Array.isArray(e)&&e.length>0){this[Jn].columnWidths=e;this[Jn].currentColumn=0}}const o=toStyle(this,"anchorType","dimensions","position","presence","border","margin","hAlign"),c=["xfaSubform"],l=layoutClass(this);l&&c.push(l);a.style=o;a.class=c;this.name&&(a.xfaName=this.name);if(this.overflow){const t=this.overflow[ss]();if(t.addLeader){t.addLeader=!1;handleOverflow(this,t.leader,e)}}this[_s]();const h="lr-tb"===this.layout||"rl-tb"===this.layout,u=h?2:1;for(;this[Jn].attempt=1){const e=this.breakAfter.children[0];if(handleBreak(e)){this[Jn].afterBreakAfter=y;return HTMLResult.breakNode(e)}}delete this[Jn];return y}}class SubformSet extends XFAObject{constructor(e){super(No,"subformSet",!0);this.id=e.id||"";this.name=e.name||"";this.relation=getStringOption(e.relation,["ordered","choice","unordered"]);this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.bookend=null;this.break=null;this.desc=null;this.extras=null;this.occur=null;this.overflow=null;this.breakAfter=new XFAObjectArray;this.breakBefore=new XFAObjectArray;this.subform=new XFAObjectArray;this.subformSet=new XFAObjectArray}*[ls](){yield*getContainedChildren(this)}[us](){let e=this[ds]();for(;!(e instanceof Subform);)e=e[ds]();return e}[xs](){return!0}}class SubjectDN extends ContentObject{constructor(e){super(No,"subjectDN");this.delimiter=e.delimiter||",";this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){this[$n]=new Map(this[$n].split(this.delimiter).map(e=>{(e=e.split("=",2))[0]=e[0].trim();return e}))}}class SubjectDNs extends XFAObject{constructor(e){super(No,"subjectDNs",!0);this.id=e.id||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||"";this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(e){super(No,"submit",!0);this.embedPDF=getInteger({data:e.embedPDF,defaultValue:0,validate:e=>1===e});this.format=getStringOption(e.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]);this.id=e.id||"";this.target=e.target||"";this.textEncoding=getKeyword({data:e.textEncoding?e.textEncoding.toLowerCase():"",defaultValue:"",validate:e=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(e)||e.match(/iso-8859-\d{2}/)});this.use=e.use||"";this.usehref=e.usehref||"";this.xdpContent=e.xdpContent||"";this.encrypt=null;this.encryptData=new XFAObjectArray;this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(e){super(No,"template",!0);this.baseProfile=getStringOption(e.baseProfile,["full","interactiveForms"]);this.extras=null;this.subform=new XFAObjectArray}[Yn](){0===this.subform.children.length&&warn("XFA - No subforms in template node.");this.subform.children.length>=2&&warn("XFA - Several subforms in template node: please file a bug.");this[zs]=5e3}[Cs](){return!0}[qs](e,t){return e.startsWith("#")?[this[ms].get(e.slice(1))]:searchNode(this,t,e,!0,!0)}*[Vs](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[Jn]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const e=this.subform.children[0];e.pageSet[Hn]();const t=e.pageSet.pageArea.children,a={name:"div",children:[]};let r=null,i=null,n=null;if(e.breakBefore.children.length>=1){i=e.breakBefore.children[0];n=i.target}else if(e.subform.children.length>=1&&e.subform.children[0].breakBefore.children.length>=1){i=e.subform.children[0].breakBefore.children[0];n=i.target}else if(e.break?.beforeTarget){i=e.break;n=i.beforeTarget}else if(e.subform.children.length>=1&&e.subform.children[0].break?.beforeTarget){i=e.subform.children[0].break;n=i.beforeTarget}if(i){const e=this[qs](n,i[ds]());if(e instanceof PageArea){r=e;i[Jn]={}}}r||=t[0];r[Jn]={numberOfUse:1};const s=r[ds]();s[Jn]={numberOfUse:1,pageIndex:s.pageArea.children.indexOf(r),pageSetIndex:0};let o,c=null,l=null,h=!0,u=0,d=0;for(;;){if(h)u=0;else{a.children.pop();if(3===++u){warn("XFA - Something goes wrong: please file a bug.");return a}}o=null;this[Jn].currentPageArea=r;const t=r[Ks]().html;a.children.push(t);if(c){this[Jn].noLayoutFailure=!0;t.children.push(c[Ks](r[Jn].space).html);c=null}if(l){this[Jn].noLayoutFailure=!0;t.children.push(l[Ks](r[Jn].space).html);l=null}const i=r.contentArea.children,n=t.children.filter(e=>e.attributes.class.includes("xfaContentarea"));h=!1;this[Jn].firstUnsplittable=null;this[Jn].noLayoutFailure=!1;const flush=t=>{const a=e[Zn]();if(a){h||=a.children?.length>0;n[t].children.push(a)}};for(let t=d,r=i.length;t0;n[t].children.push(u.html)}else!h&&a.children.length>1&&a.children.pop();return a}if(u.isBreak()){const e=u.breakNode;flush(t);if("auto"===e.targetType)continue;if(e.leader){c=this[qs](e.leader,e[ds]());c=c?c[0]:null}if(e.trailer){l=this[qs](e.trailer,e[ds]());l=l?l[0]:null}if("pageArea"===e.targetType){o=e[Jn].target;t=1/0}else if(e[Jn].target){o=e[Jn].target;d=e[Jn].index+1;t=1/0}else t=e[Jn].index;continue}if(this[Jn].overflowNode){const e=this[Jn].overflowNode;this[Jn].overflowNode=null;const a=e[ss](),r=a.target;a.addLeader=null!==a.leader;a.addTrailer=null!==a.trailer;flush(t);const n=t;t=1/0;if(r instanceof PageArea)o=r;else if(r instanceof ContentArea){const e=i.indexOf(r);if(-1!==e)e>n?t=e-1:d=e;else{o=r[ds]();d=o.contentArea.children.indexOf(r)}}continue}flush(t)}this[Jn].pageNumber+=1;o&&(o[Is]()?o[Jn].numberOfUse+=1:o=null);r=o||r[hs]();yield null}}}class Text extends ContentObject{constructor(e){super(No,"text");this.id=e.id||"";this.maxChars=getInteger({data:e.maxChars,defaultValue:0,validate:e=>e>=0});this.name=e.name||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}[_n](){return!0}[Bs](e){if(e[Os]===eo.xhtml.id){this[$n]=e;return!0}warn(`XFA - Invalid content in Text: ${e[Ms]}.`);return!1}[Ns](e){this[$n]instanceof XFAObject||super[Ns](e)}[Yn](){"string"==typeof this[$n]&&(this[$n]=this[$n].replaceAll("\r\n","\n"))}[ss](){return"string"==typeof this[$n]?this[$n].split(/[\u2029\u2028\n]/).filter(e=>!!e).join("\n"):this[$n][$s]()}[Ks](e){if("string"==typeof this[$n]){const e=valueToHtml(this[$n]).html;if(this[$n].includes("\u2029")){e.name="div";e.children=[];this[$n].split("\u2029").map(e=>e.split(/[\u2028\n]/).flatMap(e=>[{name:"span",value:e},{name:"br"}])).forEach(t=>{e.children.push({name:"p",children:t})})}else if(/[\u2028\n]/.test(this[$n])){e.name="div";e.children=[];this[$n].split(/[\u2028\n]/).forEach(t=>{e.children.push({name:"span",value:t},{name:"br"})})}return HTMLResult.success(e)}return this[$n][Ks](e)}}class TextEdit extends XFAObject{constructor(e){super(No,"textEdit",!0);this.allowRichText=getInteger({data:e.allowRichText,defaultValue:0,validate:e=>1===e});this.hScrollPolicy=getStringOption(e.hScrollPolicy,["auto","off","on"]);this.id=e.id||"";this.multiLine=getInteger({data:e.multiLine,defaultValue:"",validate:e=>0===e||1===e});this.use=e.use||"";this.usehref=e.usehref||"";this.vScrollPolicy=getStringOption(e.vScrollPolicy,["auto","off","on"]);this.border=null;this.comb=null;this.extras=null;this.margin=null}[Ks](e){const t=toStyle(this,"border","font","margin");let a;const r=this[ds]()[ds]();""===this.multiLine&&(this.multiLine=r instanceof Draw?1:0);a=1===this.multiLine?{name:"textarea",attributes:{dataId:r[Vn]?.[Zs]||r[Zs],fieldId:r[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:r[Vn]?.[Zs]||r[Zs],fieldId:r[Zs],class:["xfaTextfield"],style:t,"aria-label":ariaLabel(r),"aria-required":!1}};if(isRequired(r)){a.attributes["aria-required"]=!0;a.attributes.required=!0}return HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[a]})}}class Time extends StringObject{constructor(e){super(No,"time");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}[Yn](){const e=this[$n].trim();this[$n]=e?new Date(e):null}[Ks](e){return valueToHtml(this[$n]?this[$n].toString():"")}}class TimeStamp extends XFAObject{constructor(e){super(No,"timeStamp");this.id=e.id||"";this.server=e.server||"";this.type=getStringOption(e.type,["optional","required"]);this.use=e.use||"";this.usehref=e.usehref||""}}class ToolTip extends StringObject{constructor(e){super(No,"toolTip");this.id=e.id||"";this.rid=e.rid||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Traversal extends XFAObject{constructor(e){super(No,"traversal",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(e){super(No,"traverse",!0);this.id=e.id||"";this.operation=getStringOption(e.operation,["next","back","down","first","left","right","up"]);this.ref=e.ref||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.script=null}get name(){return this.operation}[Fs](){return!1}}class Ui extends XFAObject{constructor(e){super(No,"ui",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.picture=null;this.barcode=null;this.button=null;this.checkButton=null;this.choiceList=null;this.dateTimeEdit=null;this.defaultUi=null;this.imageEdit=null;this.numericEdit=null;this.passwordEdit=null;this.signature=null;this.textEdit=null}[ss](){if(void 0===this[Jn]){for(const e of Object.getOwnPropertyNames(this)){if("extras"===e||"picture"===e)continue;const t=this[e];if(t instanceof XFAObject){this[Jn]=t;return t}}this[Jn]=null}return this[Jn]}[Ks](e){const t=this[ss]();return t?t[Ks](e):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(e){super(No,"validate",!0);this.formatTest=getStringOption(e.formatTest,["warning","disabled","error"]);this.id=e.id||"";this.nullTest=getStringOption(e.nullTest,["disabled","error","warning"]);this.scriptTest=getStringOption(e.scriptTest,["error","disabled","warning"]);this.use=e.use||"";this.usehref=e.usehref||"";this.extras=null;this.message=null;this.picture=null;this.script=null}}class Value extends XFAObject{constructor(e){super(No,"value",!0);this.id=e.id||"";this.override=getInteger({data:e.override,defaultValue:0,validate:e=>1===e});this.relevant=getRelevant(e.relevant);this.use=e.use||"";this.usehref=e.usehref||"";this.arc=null;this.boolean=null;this.date=null;this.dateTime=null;this.decimal=null;this.exData=null;this.float=null;this.image=null;this.integer=null;this.line=null;this.rectangle=null;this.text=null;this.time=null}[Gs](e){const t=this[ds]();if(t instanceof Field&&t.ui?.imageEdit){if(!this.image){this.image=new Image({});this[jn](this.image)}this.image[$n]=e[$n];return}const a=e[Ms];if(null===this[a]){for(const e of Object.getOwnPropertyNames(this)){const t=this[e];if(t instanceof XFAObject){this[e]=null;this[Us](t)}}this[e[Ms]]=e;this[jn](e)}else this[a][$n]=e[$n]}[$s](){if(this.exData)return"string"==typeof this.exData[$n]?this.exData[$n].trim():this.exData[$n][$s]().trim();for(const e of Object.getOwnPropertyNames(this)){if("image"===e)continue;const t=this[e];if(t instanceof XFAObject)return(t[$n]||"").toString().trim()}return null}[Ks](e){for(const t of Object.getOwnPropertyNames(this)){const a=this[t];if(a instanceof XFAObject)return a[Ks](e)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(e){super(No,"variables",!0);this.id=e.id||"";this.use=e.use||"";this.usehref=e.usehref||"";this.boolean=new XFAObjectArray;this.date=new XFAObjectArray;this.dateTime=new XFAObjectArray;this.decimal=new XFAObjectArray;this.exData=new XFAObjectArray;this.float=new XFAObjectArray;this.image=new XFAObjectArray;this.integer=new XFAObjectArray;this.manifest=new XFAObjectArray;this.script=new XFAObjectArray;this.text=new XFAObjectArray;this.time=new XFAObjectArray}[Fs](){return!0}}class TemplateNamespace{static[Qs](e,t){if(TemplateNamespace.hasOwnProperty(e)){const a=TemplateNamespace[e](t);a[Ws](t);return a}}static appearanceFilter(e){return new AppearanceFilter(e)}static arc(e){return new Arc(e)}static area(e){return new Area(e)}static assist(e){return new Assist(e)}static barcode(e){return new Barcode(e)}static bind(e){return new Bind(e)}static bindItems(e){return new BindItems(e)}static bookend(e){return new Bookend(e)}static boolean(e){return new BooleanElement(e)}static border(e){return new Border(e)}static break(e){return new Break(e)}static breakAfter(e){return new BreakAfter(e)}static breakBefore(e){return new BreakBefore(e)}static button(e){return new Button(e)}static calculate(e){return new Calculate(e)}static caption(e){return new Caption(e)}static certificate(e){return new Certificate(e)}static certificates(e){return new Certificates(e)}static checkButton(e){return new CheckButton(e)}static choiceList(e){return new ChoiceList(e)}static color(e){return new Color(e)}static comb(e){return new Comb(e)}static connect(e){return new Connect(e)}static contentArea(e){return new ContentArea(e)}static corner(e){return new Corner(e)}static date(e){return new DateElement(e)}static dateTime(e){return new DateTime(e)}static dateTimeEdit(e){return new DateTimeEdit(e)}static decimal(e){return new Decimal(e)}static defaultUi(e){return new DefaultUi(e)}static desc(e){return new Desc(e)}static digestMethod(e){return new DigestMethod(e)}static digestMethods(e){return new DigestMethods(e)}static draw(e){return new Draw(e)}static edge(e){return new Edge(e)}static encoding(e){return new Encoding(e)}static encodings(e){return new Encodings(e)}static encrypt(e){return new Encrypt(e)}static encryptData(e){return new EncryptData(e)}static encryption(e){return new Encryption(e)}static encryptionMethod(e){return new EncryptionMethod(e)}static encryptionMethods(e){return new EncryptionMethods(e)}static event(e){return new Event(e)}static exData(e){return new ExData(e)}static exObject(e){return new ExObject(e)}static exclGroup(e){return new ExclGroup(e)}static execute(e){return new Execute(e)}static extras(e){return new Extras(e)}static field(e){return new Field(e)}static fill(e){return new Fill(e)}static filter(e){return new Filter(e)}static float(e){return new Float(e)}static font(e){return new template_Font(e)}static format(e){return new Format(e)}static handler(e){return new Handler(e)}static hyphenation(e){return new Hyphenation(e)}static image(e){return new Image(e)}static imageEdit(e){return new ImageEdit(e)}static integer(e){return new Integer(e)}static issuers(e){return new Issuers(e)}static items(e){return new Items(e)}static keep(e){return new Keep(e)}static keyUsage(e){return new KeyUsage(e)}static line(e){return new Line(e)}static linear(e){return new Linear(e)}static lockDocument(e){return new LockDocument(e)}static manifest(e){return new Manifest(e)}static margin(e){return new Margin(e)}static mdp(e){return new Mdp(e)}static medium(e){return new Medium(e)}static message(e){return new Message(e)}static numericEdit(e){return new NumericEdit(e)}static occur(e){return new Occur(e)}static oid(e){return new Oid(e)}static oids(e){return new Oids(e)}static overflow(e){return new Overflow(e)}static pageArea(e){return new PageArea(e)}static pageSet(e){return new PageSet(e)}static para(e){return new Para(e)}static passwordEdit(e){return new PasswordEdit(e)}static pattern(e){return new template_Pattern(e)}static picture(e){return new Picture(e)}static proto(e){return new Proto(e)}static radial(e){return new Radial(e)}static reason(e){return new Reason(e)}static reasons(e){return new Reasons(e)}static rectangle(e){return new Rectangle(e)}static ref(e){return new RefElement(e)}static script(e){return new Script(e)}static setProperty(e){return new SetProperty(e)}static signData(e){return new SignData(e)}static signature(e){return new Signature(e)}static signing(e){return new Signing(e)}static solid(e){return new Solid(e)}static speak(e){return new Speak(e)}static stipple(e){return new Stipple(e)}static subform(e){return new Subform(e)}static subformSet(e){return new SubformSet(e)}static subjectDN(e){return new SubjectDN(e)}static subjectDNs(e){return new SubjectDNs(e)}static submit(e){return new Submit(e)}static template(e){return new Template(e)}static text(e){return new Text(e)}static textEdit(e){return new TextEdit(e)}static time(e){return new Time(e)}static timeStamp(e){return new TimeStamp(e)}static toolTip(e){return new ToolTip(e)}static traversal(e){return new Traversal(e)}static traverse(e){return new Traverse(e)}static ui(e){return new Ui(e)}static validate(e){return new Validate(e)}static value(e){return new Value(e)}static variables(e){return new Variables(e)}}const Uo=eo.datasets.id;function createText(e){const t=new Text({});t[$n]=e;return t}class Binder{constructor(e){this.root=e;this.datasets=e.datasets;this.data=e.datasets?.data||new XmlObject(eo.datasets.id,"data");this.emptyMerge=0===this.data[cs]().length;this.root.form=this.form=e.template[Gn]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){this._bindElement(this.form,this.data);return this.form}getData(){return this.data}_bindValue(e,t,a){e[Vn]=t;if(e[ps]())if(t[Ss]()){const a=t[ns]();e[Gs](createText(a))}else if(e instanceof Field&&"multiSelect"===e.ui?.choiceList?.open){const a=t[cs]().map(e=>e[$n].trim()).join("\n");e[Gs](createText(a))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!t[Ss]()||this._isMatchTemplate()?this._bindElement(e,t):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(e,t,a,r){if(!e)return null;let i,n;for(let r=0;r<3;r++){i=a[os](e,!1,!0);for(;;){n=i.next().value;if(!n)break;if(t===n[Ss]())return n}if(a[Os]===eo.datasets.id&&"data"===a[Ms])break;a=a[ds]()}if(!r)return null;i=this.data[os](e,!0,!1);n=i.next().value;if(n)return n;i=this.data[Qn](e,!0);n=i.next().value;return n?.[Ss]()?n:null}_setProperties(e,t){if(e.hasOwnProperty("setProperty"))for(const{ref:a,target:r,connection:i}of e.setProperty.children){if(i)continue;if(!a)continue;const n=searchNode(this.root,t,a,!1,!1);if(!n){warn(`XFA - Invalid reference: ${a}.`);continue}const[s]=n;if(!s[As](this.data)){warn("XFA - Invalid node: must be a data node.");continue}const o=searchNode(this.root,e,r,!1,!1);if(!o){warn(`XFA - Invalid target: ${r}.`);continue}const[c]=o;if(!c[As](e)){warn("XFA - Invalid target: must be a property or subproperty.");continue}const l=c[ds]();if(c instanceof SetProperty||l instanceof SetProperty){warn("XFA - Invalid target: cannot be a setProperty or one of its properties.");continue}if(c instanceof BindItems||l instanceof BindItems){warn("XFA - Invalid target: cannot be a bindItems or one of its properties.");continue}const h=s[$s](),u=c[Ms];if(c instanceof XFAAttribute){const e=Object.create(null);e[u]=h;const t=Reflect.construct(Object.getPrototypeOf(l).constructor,[e]);l[u]=t[u];continue}if(c.hasOwnProperty($n)){c[Vn]=s;c[$n]=h;c[Yn]()}else warn("XFA - Invalid node to use in setProperty")}}_bindItems(e,t){if(!e.hasOwnProperty("items")||!e.hasOwnProperty("bindItems")||e.bindItems.isEmpty())return;for(const t of e.items.children)e[Us](t);e.items.clear();const a=new Items({}),r=new Items({});e[jn](a);e.items.push(a);e[jn](r);e.items.push(r);for(const{ref:i,labelRef:n,valueRef:s,connection:o}of e.bindItems.children){if(o)continue;if(!i)continue;const e=searchNode(this.root,t,i,!1,!1);if(e)for(const t of e){if(!t[As](this.datasets)){warn(`XFA - Invalid ref (${i}): must be a datasets child.`);continue}const e=searchNode(this.root,t,n,!0,!1);if(!e){warn(`XFA - Invalid label: ${n}.`);continue}const[o]=e;if(!o[As](this.datasets)){warn("XFA - Invalid label: must be a datasets child.");continue}const c=searchNode(this.root,t,s,!0,!1);if(!c){warn(`XFA - Invalid value: ${s}.`);continue}const[l]=c;if(!l[As](this.datasets)){warn("XFA - Invalid value: must be a datasets child.");continue}const h=createText(o[$s]()),u=createText(l[$s]());a[jn](h);a.text.push(h);r[jn](u);r.text.push(u)}else warn(`XFA - Invalid reference: ${i}.`)}}_bindOccurrences(e,t,a){let r;if(t.length>1){r=e[Gn]();r[Us](r.occur);r.occur=null}this._bindValue(e,t[0],a);this._setProperties(e,t[0]);this._bindItems(e,t[0]);if(1===t.length)return;const i=e[ds](),n=e[Ms],s=i[bs](e);for(let e=1,o=t.length;et.name===e.name).length:a[r].children.length;const n=a[bs](e)+1,s=t.initial-i;if(s){const t=e[Gn]();t[Us](t.occur);t.occur=null;a[r].push(t);a[ys](n,t);for(let e=1;e0)this._bindOccurrences(r,[e[0]],null);else if(this.emptyMerge){const e=t[Os]===Uo?-1:t[Os],a=r[Vn]=new XmlObject(e,r.name||"root");t[jn](a);this._bindElement(r,a)}continue}if(!r[xs]())continue;let e=!1,i=null,n=null,s=null;if(r.bind){switch(r.bind.match){case"none":this._setAndBind(r,t);continue;case"global":e=!0;break;case"dataRef":if(!r.bind.ref){warn(`XFA - ref is empty in node ${r[Ms]}.`);this._setAndBind(r,t);continue}n=r.bind.ref}r.bind.picture&&(i=r.bind.picture[$n])}const[o,c]=this._getOccurInfo(r);if(n){s=searchNode(this.root,t,n,!0,!1);if(null===s){s=createDataNode(this.data,t,n);if(!s)continue;this._isConsumeData()&&(s[zn]=!0);this._setAndBind(r,s);continue}this._isConsumeData()&&(s=s.filter(e=>!e[zn]));s.length>c?s=s.slice(0,c):0===s.length&&(s=null);s&&this._isConsumeData()&&s.forEach(e=>{e[zn]=!0})}else{if(!r.name){this._setAndBind(r,t);continue}if(this._isConsumeData()){const a=[];for(;a.length0?a:null}else{s=t[os](r.name,!1,this.emptyMerge).next().value;if(!s){if(0===o){a.push(r);continue}const e=t[Os]===Uo?-1:t[Os];s=r[Vn]=new XmlObject(e,r.name);this.emptyMerge&&(s[zn]=!0);t[jn](s);this._setAndBind(r,s);continue}this.emptyMerge&&(s[zn]=!0);s=[s]}}s?this._bindOccurrences(r,s,i):o>0?this._setAndBind(r,t):a.push(r)}a.forEach(e=>e[ds]()[Us](e))}}class DataHandler{constructor(e,t){this.data=t;this.dataset=e.datasets||null}serialize(e){const t=[[-1,this.data[cs]()]];for(;t.length>0;){const a=t.at(-1),[r,i]=a;if(r+1===i.length){t.pop();continue}const n=i[++a[0]],s=e.get(n[Zs]);if(s)n[Gs](s);else{const t=n[es]();for(const a of t.values()){const t=e.get(a[Zs]);if(t){a[Gs](t);break}}}const o=n[cs]();o.length>0&&t.push([-1,o])}const a=[''];if(this.dataset)for(const e of this.dataset[cs]())"data"!==e[Ms]&&e[Js](a);this.data[Js](a);a.push("");return a.join("")}}const jo=eo.config.id;class Acrobat extends XFAObject{constructor(e){super(jo,"acrobat",!0);this.acrobat7=null;this.autoSave=null;this.common=null;this.validate=null;this.validateApprovalSignatures=null;this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(e){super(jo,"acrobat7",!0);this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(e){super(jo,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(e){super(jo,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(e){super(jo,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(e){super(jo,"addViewerPreferences")}}class AdjustData extends Option10{constructor(e){super(jo,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(e){super(jo,"adobeExtensionLevel",0,e=>e>=1&&e<=8)}}class Agent extends XFAObject{constructor(e){super(jo,"agent",!0);this.name=e.name?e.name.trim():"";this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(e){super(jo,"alwaysEmbed")}}class Amd extends StringObject{constructor(e){super(jo,"amd")}}class config_Area extends XFAObject{constructor(e){super(jo,"area");this.level=getInteger({data:e.level,defaultValue:0,validate:e=>e>=1&&e<=3});this.name=getStringOption(e.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(e){super(jo,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(e){super(jo,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(e){super(jo,"base")}}class BatchOutput extends XFAObject{constructor(e){super(jo,"batchOutput");this.format=getStringOption(e.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(e){super(jo,"behaviorOverride")}[Yn](){this[$n]=new Map(this[$n].trim().split(/\s+/).filter(e=>e.includes(":")).map(e=>e.split(":",2)))}}class Cache extends XFAObject{constructor(e){super(jo,"cache",!0);this.templateCache=null}}class Change extends Option01{constructor(e){super(jo,"change")}}class Common extends XFAObject{constructor(e){super(jo,"common",!0);this.data=null;this.locale=null;this.localeSet=null;this.messaging=null;this.suppressBanner=null;this.template=null;this.validationMessaging=null;this.versionControl=null;this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(e){super(jo,"compress");this.scope=getStringOption(e.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(e){super(jo,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(e){super(jo,"compressObjectStream")}}class Compression extends XFAObject{constructor(e){super(jo,"compression",!0);this.compressLogicalStructure=null;this.compressObjectStream=null;this.level=null;this.type=null}}class Config extends XFAObject{constructor(e){super(jo,"config",!0);this.acrobat=null;this.present=null;this.trace=null;this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(e){super(jo,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(e){super(jo,"contentCopy")}}class Copies extends IntegerObject{constructor(e){super(jo,"copies",1,e=>e>=1)}}class Creator extends StringObject{constructor(e){super(jo,"creator")}}class CurrentPage extends IntegerObject{constructor(e){super(jo,"currentPage",0,e=>e>=0)}}class Data extends XFAObject{constructor(e){super(jo,"data",!0);this.adjustData=null;this.attributes=null;this.incrementalLoad=null;this.outputXSL=null;this.range=null;this.record=null;this.startNode=null;this.uri=null;this.window=null;this.xsl=null;this.excludeNS=new XFAObjectArray;this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(e){super(jo,"debug",!0);this.uri=null}}class DefaultTypeface extends ContentObject{constructor(e){super(jo,"defaultTypeface");this.writingScript=getStringOption(e.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(e){super(jo,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(e){super(jo,"documentAssembly")}}class Driver extends XFAObject{constructor(e){super(jo,"driver",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class DuplexOption extends OptionObject{constructor(e){super(jo,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(e){super(jo,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(e){super(jo,"embed")}}class config_Encrypt extends Option01{constructor(e){super(jo,"encrypt")}}class config_Encryption extends XFAObject{constructor(e){super(jo,"encryption",!0);this.encrypt=null;this.encryptionLevel=null;this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(e){super(jo,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(e){super(jo,"enforce")}}class Equate extends XFAObject{constructor(e){super(jo,"equate");this.force=getInteger({data:e.force,defaultValue:1,validate:e=>0===e});this.from=e.from||"";this.to=e.to||""}}class EquateRange extends XFAObject{constructor(e){super(jo,"equateRange");this.from=e.from||"";this.to=e.to||"";this._unicodeRange=e.unicodeRange||""}get unicodeRange(){const e=[],t=/U\+([0-9a-fA-F]+)/,a=this._unicodeRange;for(let r of a.split(",").map(e=>e.trim()).filter(e=>!!e)){r=r.split("-",2).map(e=>{const a=e.match(t);return a?parseInt(a[1],16):0});1===r.length&&r.push(r[0]);e.push(r)}return shadow(this,"unicodeRange",e)}}class Exclude extends ContentObject{constructor(e){super(jo,"exclude")}[Yn](){this[$n]=this[$n].trim().split(/\s+/).filter(e=>e&&["calculate","close","enter","exit","initialize","ready","validate"].includes(e))}}class ExcludeNS extends StringObject{constructor(e){super(jo,"excludeNS")}}class FlipLabel extends OptionObject{constructor(e){super(jo,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(e){super(jo,"fontInfo",!0);this.embed=null;this.map=null;this.subsetBelow=null;this.alwaysEmbed=new XFAObjectArray;this.defaultTypeface=new XFAObjectArray;this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(e){super(jo,"formFieldFilling")}}class GroupParent extends StringObject{constructor(e){super(jo,"groupParent")}}class IfEmpty extends OptionObject{constructor(e){super(jo,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(e){super(jo,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(e){super(jo,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(e){super(jo,"incrementalMerge")}}class Interactive extends Option01{constructor(e){super(jo,"interactive")}}class Jog extends OptionObject{constructor(e){super(jo,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(e){super(jo,"labelPrinter",!0);this.name=getStringOption(e.name,["zpl","dpl","ipl","tcpl"]);this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class Layout extends OptionObject{constructor(e){super(jo,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(e){super(jo,"level",0,e=>e>0)}}class Linearized extends Option01{constructor(e){super(jo,"linearized")}}class Locale extends StringObject{constructor(e){super(jo,"locale")}}class LocaleSet extends StringObject{constructor(e){super(jo,"localeSet")}}class Log extends XFAObject{constructor(e){super(jo,"log",!0);this.mode=null;this.threshold=null;this.to=null;this.uri=null}}class MapElement extends XFAObject{constructor(e){super(jo,"map",!0);this.equate=new XFAObjectArray;this.equateRange=new XFAObjectArray}}class MediumInfo extends XFAObject{constructor(e){super(jo,"mediumInfo",!0);this.map=null}}class config_Message extends XFAObject{constructor(e){super(jo,"message",!0);this.msgId=null;this.severity=null}}class Messaging extends XFAObject{constructor(e){super(jo,"messaging",!0);this.message=new XFAObjectArray}}class Mode extends OptionObject{constructor(e){super(jo,"mode",["append","overwrite"])}}class ModifyAnnots extends Option01{constructor(e){super(jo,"modifyAnnots")}}class MsgId extends IntegerObject{constructor(e){super(jo,"msgId",1,e=>e>=1)}}class NameAttr extends StringObject{constructor(e){super(jo,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(e){super(jo,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(e){super(jo,"numberOfCopies",null,e=>e>=2&&e<=5)}}class OpenAction extends XFAObject{constructor(e){super(jo,"openAction",!0);this.destination=null}}class Output extends XFAObject{constructor(e){super(jo,"output",!0);this.to=null;this.type=null;this.uri=null}}class OutputBin extends StringObject{constructor(e){super(jo,"outputBin")}}class OutputXSL extends XFAObject{constructor(e){super(jo,"outputXSL",!0);this.uri=null}}class Overprint extends OptionObject{constructor(e){super(jo,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(e){super(jo,"packets")}[Yn](){"*"!==this[$n]&&(this[$n]=this[$n].trim().split(/\s+/).filter(e=>["config","datasets","template","xfdf","xslt"].includes(e)))}}class PageOffset extends XFAObject{constructor(e){super(jo,"pageOffset");this.x=getInteger({data:e.x,defaultValue:"useXDCSetting",validate:e=>!0});this.y=getInteger({data:e.y,defaultValue:"useXDCSetting",validate:e=>!0})}}class PageRange extends StringObject{constructor(e){super(jo,"pageRange")}[Yn](){const e=this[$n].trim().split(/\s+/).map(e=>parseInt(e,10)),t=[];for(let a=0,r=e.length;a!1)}}class Pcl extends XFAObject{constructor(e){super(jo,"pcl",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.pageOffset=null;this.staple=null;this.xdc=null}}class Pdf extends XFAObject{constructor(e){super(jo,"pdf",!0);this.name=e.name||"";this.adobeExtensionLevel=null;this.batchOutput=null;this.compression=null;this.creator=null;this.encryption=null;this.fontInfo=null;this.interactive=null;this.linearized=null;this.openAction=null;this.pdfa=null;this.producer=null;this.renderPolicy=null;this.scriptModel=null;this.silentPrint=null;this.submitFormat=null;this.tagged=null;this.version=null;this.viewerPreferences=null;this.xdc=null}}class Pdfa extends XFAObject{constructor(e){super(jo,"pdfa",!0);this.amd=null;this.conformance=null;this.includeXDPContent=null;this.part=null}}class Permissions extends XFAObject{constructor(e){super(jo,"permissions",!0);this.accessibleContent=null;this.change=null;this.contentCopy=null;this.documentAssembly=null;this.formFieldFilling=null;this.modifyAnnots=null;this.plaintextMetadata=null;this.print=null;this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(e){super(jo,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(e){super(jo,"picture")}}class PlaintextMetadata extends Option01{constructor(e){super(jo,"plaintextMetadata")}}class Presence extends OptionObject{constructor(e){super(jo,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(e){super(jo,"present",!0);this.behaviorOverride=null;this.cache=null;this.common=null;this.copies=null;this.destination=null;this.incrementalMerge=null;this.layout=null;this.output=null;this.overprint=null;this.pagination=null;this.paginationOverride=null;this.script=null;this.validate=null;this.xdp=null;this.driver=new XFAObjectArray;this.labelPrinter=new XFAObjectArray;this.pcl=new XFAObjectArray;this.pdf=new XFAObjectArray;this.ps=new XFAObjectArray;this.submitUrl=new XFAObjectArray;this.webClient=new XFAObjectArray;this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(e){super(jo,"print")}}class PrintHighQuality extends Option01{constructor(e){super(jo,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(e){super(jo,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(e){super(jo,"printerName")}}class Producer extends StringObject{constructor(e){super(jo,"producer")}}class Ps extends XFAObject{constructor(e){super(jo,"ps",!0);this.name=e.name||"";this.batchOutput=null;this.fontInfo=null;this.jog=null;this.mediumInfo=null;this.outputBin=null;this.staple=null;this.xdc=null}}class Range extends ContentObject{constructor(e){super(jo,"range")}[Yn](){this[$n]=this[$n].split(",",2).map(e=>e.split("-").map(e=>parseInt(e.trim(),10))).filter(e=>e.every(e=>!isNaN(e))).map(e=>{1===e.length&&e.push(e[0]);return e})}}class Record extends ContentObject{constructor(e){super(jo,"record")}[Yn](){this[$n]=this[$n].trim();const e=parseInt(this[$n],10);!isNaN(e)&&e>=0&&(this[$n]=e)}}class Relevant extends ContentObject{constructor(e){super(jo,"relevant")}[Yn](){this[$n]=this[$n].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(e){super(jo,"rename")}[Yn](){this[$n]=this[$n].trim();(this[$n].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[$n]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(e){super(jo,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(e){super(jo,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(e){super(jo,"script",!0);this.currentPage=null;this.exclude=null;this.runScripts=null}}class ScriptModel extends OptionObject{constructor(e){super(jo,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(e){super(jo,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(e){super(jo,"silentPrint",!0);this.addSilentPrint=null;this.printerName=null}}class Staple extends XFAObject{constructor(e){super(jo,"staple");this.mode=getStringOption(e.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(e){super(jo,"startNode")}}class StartPage extends IntegerObject{constructor(e){super(jo,"startPage",0,e=>!0)}}class SubmitFormat extends OptionObject{constructor(e){super(jo,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(e){super(jo,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(e){super(jo,"subsetBelow",100,e=>e>=0&&e<=100)}}class SuppressBanner extends Option01{constructor(e){super(jo,"suppressBanner")}}class Tagged extends Option01{constructor(e){super(jo,"tagged")}}class config_Template extends XFAObject{constructor(e){super(jo,"template",!0);this.base=null;this.relevant=null;this.startPage=null;this.uri=null;this.xsl=null}}class Threshold extends OptionObject{constructor(e){super(jo,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(e){super(jo,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(e){super(jo,"templateCache");this.maxEntries=getInteger({data:e.maxEntries,defaultValue:5,validate:e=>e>=0})}}class Trace extends XFAObject{constructor(e){super(jo,"trace",!0);this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(e){super(jo,"transform",!0);this.groupParent=null;this.ifEmpty=null;this.nameAttr=null;this.picture=null;this.presence=null;this.rename=null;this.whitespace=null}}class Type extends OptionObject{constructor(e){super(jo,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(e){super(jo,"uri")}}class config_Validate extends OptionObject{constructor(e){super(jo,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(e){super(jo,"validateApprovalSignatures")}[Yn](){this[$n]=this[$n].trim().split(/\s+/).filter(e=>["docReady","postSign"].includes(e))}}class ValidationMessaging extends OptionObject{constructor(e){super(jo,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(e){super(jo,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(e){super(jo,"VersionControl");this.outputBelow=getStringOption(e.outputBelow,["warn","error","update"]);this.sourceAbove=getStringOption(e.sourceAbove,["warn","error"]);this.sourceBelow=getStringOption(e.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(e){super(jo,"viewerPreferences",!0);this.ADBE_JSConsole=null;this.ADBE_JSDebugger=null;this.addViewerPreferences=null;this.duplexOption=null;this.enforce=null;this.numberOfCopies=null;this.pageRange=null;this.pickTrayByPDFSize=null;this.printScaling=null}}class WebClient extends XFAObject{constructor(e){super(jo,"webClient",!0);this.name=e.name?e.name.trim():"";this.fontInfo=null;this.xdc=null}}class Whitespace extends OptionObject{constructor(e){super(jo,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(e){super(jo,"window")}[Yn](){const e=this[$n].split(",",2).map(e=>parseInt(e.trim(),10));if(e.some(e=>isNaN(e)))this[$n]=[0,0];else{1===e.length&&e.push(e[0]);this[$n]=e}}}class Xdc extends XFAObject{constructor(e){super(jo,"xdc",!0);this.uri=new XFAObjectArray;this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(e){super(jo,"xdp",!0);this.packets=null}}class Xsl extends XFAObject{constructor(e){super(jo,"xsl",!0);this.debug=null;this.uri=null}}class Zpl extends XFAObject{constructor(e){super(jo,"zpl",!0);this.name=e.name?e.name.trim():"";this.batchOutput=null;this.flipLabel=null;this.fontInfo=null;this.xdc=null}}class ConfigNamespace{static[Qs](e,t){if(ConfigNamespace.hasOwnProperty(e))return ConfigNamespace[e](t)}static acrobat(e){return new Acrobat(e)}static acrobat7(e){return new Acrobat7(e)}static ADBE_JSConsole(e){return new ADBE_JSConsole(e)}static ADBE_JSDebugger(e){return new ADBE_JSDebugger(e)}static addSilentPrint(e){return new AddSilentPrint(e)}static addViewerPreferences(e){return new AddViewerPreferences(e)}static adjustData(e){return new AdjustData(e)}static adobeExtensionLevel(e){return new AdobeExtensionLevel(e)}static agent(e){return new Agent(e)}static alwaysEmbed(e){return new AlwaysEmbed(e)}static amd(e){return new Amd(e)}static area(e){return new config_Area(e)}static attributes(e){return new Attributes(e)}static autoSave(e){return new AutoSave(e)}static base(e){return new Base(e)}static batchOutput(e){return new BatchOutput(e)}static behaviorOverride(e){return new BehaviorOverride(e)}static cache(e){return new Cache(e)}static change(e){return new Change(e)}static common(e){return new Common(e)}static compress(e){return new Compress(e)}static compressLogicalStructure(e){return new CompressLogicalStructure(e)}static compressObjectStream(e){return new CompressObjectStream(e)}static compression(e){return new Compression(e)}static config(e){return new Config(e)}static conformance(e){return new Conformance(e)}static contentCopy(e){return new ContentCopy(e)}static copies(e){return new Copies(e)}static creator(e){return new Creator(e)}static currentPage(e){return new CurrentPage(e)}static data(e){return new Data(e)}static debug(e){return new Debug(e)}static defaultTypeface(e){return new DefaultTypeface(e)}static destination(e){return new Destination(e)}static documentAssembly(e){return new DocumentAssembly(e)}static driver(e){return new Driver(e)}static duplexOption(e){return new DuplexOption(e)}static dynamicRender(e){return new DynamicRender(e)}static embed(e){return new Embed(e)}static encrypt(e){return new config_Encrypt(e)}static encryption(e){return new config_Encryption(e)}static encryptionLevel(e){return new EncryptionLevel(e)}static enforce(e){return new Enforce(e)}static equate(e){return new Equate(e)}static equateRange(e){return new EquateRange(e)}static exclude(e){return new Exclude(e)}static excludeNS(e){return new ExcludeNS(e)}static flipLabel(e){return new FlipLabel(e)}static fontInfo(e){return new config_FontInfo(e)}static formFieldFilling(e){return new FormFieldFilling(e)}static groupParent(e){return new GroupParent(e)}static ifEmpty(e){return new IfEmpty(e)}static includeXDPContent(e){return new IncludeXDPContent(e)}static incrementalLoad(e){return new IncrementalLoad(e)}static incrementalMerge(e){return new IncrementalMerge(e)}static interactive(e){return new Interactive(e)}static jog(e){return new Jog(e)}static labelPrinter(e){return new LabelPrinter(e)}static layout(e){return new Layout(e)}static level(e){return new Level(e)}static linearized(e){return new Linearized(e)}static locale(e){return new Locale(e)}static localeSet(e){return new LocaleSet(e)}static log(e){return new Log(e)}static map(e){return new MapElement(e)}static mediumInfo(e){return new MediumInfo(e)}static message(e){return new config_Message(e)}static messaging(e){return new Messaging(e)}static mode(e){return new Mode(e)}static modifyAnnots(e){return new ModifyAnnots(e)}static msgId(e){return new MsgId(e)}static nameAttr(e){return new NameAttr(e)}static neverEmbed(e){return new NeverEmbed(e)}static numberOfCopies(e){return new NumberOfCopies(e)}static openAction(e){return new OpenAction(e)}static output(e){return new Output(e)}static outputBin(e){return new OutputBin(e)}static outputXSL(e){return new OutputXSL(e)}static overprint(e){return new Overprint(e)}static packets(e){return new Packets(e)}static pageOffset(e){return new PageOffset(e)}static pageRange(e){return new PageRange(e)}static pagination(e){return new Pagination(e)}static paginationOverride(e){return new PaginationOverride(e)}static part(e){return new Part(e)}static pcl(e){return new Pcl(e)}static pdf(e){return new Pdf(e)}static pdfa(e){return new Pdfa(e)}static permissions(e){return new Permissions(e)}static pickTrayByPDFSize(e){return new PickTrayByPDFSize(e)}static picture(e){return new config_Picture(e)}static plaintextMetadata(e){return new PlaintextMetadata(e)}static presence(e){return new Presence(e)}static present(e){return new Present(e)}static print(e){return new Print(e)}static printHighQuality(e){return new PrintHighQuality(e)}static printScaling(e){return new PrintScaling(e)}static printerName(e){return new PrinterName(e)}static producer(e){return new Producer(e)}static ps(e){return new Ps(e)}static range(e){return new Range(e)}static record(e){return new Record(e)}static relevant(e){return new Relevant(e)}static rename(e){return new Rename(e)}static renderPolicy(e){return new RenderPolicy(e)}static runScripts(e){return new RunScripts(e)}static script(e){return new config_Script(e)}static scriptModel(e){return new ScriptModel(e)}static severity(e){return new Severity(e)}static silentPrint(e){return new SilentPrint(e)}static staple(e){return new Staple(e)}static startNode(e){return new StartNode(e)}static startPage(e){return new StartPage(e)}static submitFormat(e){return new SubmitFormat(e)}static submitUrl(e){return new SubmitUrl(e)}static subsetBelow(e){return new SubsetBelow(e)}static suppressBanner(e){return new SuppressBanner(e)}static tagged(e){return new Tagged(e)}static template(e){return new config_Template(e)}static templateCache(e){return new TemplateCache(e)}static threshold(e){return new Threshold(e)}static to(e){return new To(e)}static trace(e){return new Trace(e)}static transform(e){return new Transform(e)}static type(e){return new Type(e)}static uri(e){return new Uri(e)}static validate(e){return new config_Validate(e)}static validateApprovalSignatures(e){return new ValidateApprovalSignatures(e)}static validationMessaging(e){return new ValidationMessaging(e)}static version(e){return new Version(e)}static versionControl(e){return new VersionControl(e)}static viewerPreferences(e){return new ViewerPreferences(e)}static webClient(e){return new WebClient(e)}static whitespace(e){return new Whitespace(e)}static window(e){return new Window(e)}static xdc(e){return new Xdc(e)}static xdp(e){return new Xdp(e)}static xsl(e){return new Xsl(e)}static zpl(e){return new Zpl(e)}}const Xo=eo.connectionSet.id;class ConnectionSet extends XFAObject{constructor(e){super(Xo,"connectionSet",!0);this.wsdlConnection=new XFAObjectArray;this.xmlConnection=new XFAObjectArray;this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(e){super(Xo,"effectiveInputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(e){super(Xo,"effectiveOutputPolicy");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class Operation extends StringObject{constructor(e){super(Xo,"operation");this.id=e.id||"";this.input=e.input||"";this.name=e.name||"";this.output=e.output||"";this.use=e.use||"";this.usehref=e.usehref||""}}class RootElement extends StringObject{constructor(e){super(Xo,"rootElement");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAction extends StringObject{constructor(e){super(Xo,"soapAction");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class SoapAddress extends StringObject{constructor(e){super(Xo,"soapAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class connection_set_Uri extends StringObject{constructor(e){super(Xo,"uri");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlAddress extends StringObject{constructor(e){super(Xo,"wsdlAddress");this.id=e.id||"";this.name=e.name||"";this.use=e.use||"";this.usehref=e.usehref||""}}class WsdlConnection extends XFAObject{constructor(e){super(Xo,"wsdlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.effectiveInputPolicy=null;this.effectiveOutputPolicy=null;this.operation=null;this.soapAction=null;this.soapAddress=null;this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(e){super(Xo,"xmlConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.uri=null}}class XsdConnection extends XFAObject{constructor(e){super(Xo,"xsdConnection",!0);this.dataDescription=e.dataDescription||"";this.name=e.name||"";this.rootElement=null;this.uri=null}}class ConnectionSetNamespace{static[Qs](e,t){if(ConnectionSetNamespace.hasOwnProperty(e))return ConnectionSetNamespace[e](t)}static connectionSet(e){return new ConnectionSet(e)}static effectiveInputPolicy(e){return new EffectiveInputPolicy(e)}static effectiveOutputPolicy(e){return new EffectiveOutputPolicy(e)}static operation(e){return new Operation(e)}static rootElement(e){return new RootElement(e)}static soapAction(e){return new SoapAction(e)}static soapAddress(e){return new SoapAddress(e)}static uri(e){return new connection_set_Uri(e)}static wsdlAddress(e){return new WsdlAddress(e)}static wsdlConnection(e){return new WsdlConnection(e)}static xmlConnection(e){return new XmlConnection(e)}static xsdConnection(e){return new XsdConnection(e)}}const qo=eo.datasets.id;class datasets_Data extends XmlObject{constructor(e){super(qo,"data",e)}[ks](){return!0}}class Datasets extends XFAObject{constructor(e){super(qo,"datasets",!0);this.data=null;this.Signature=null}[Bs](e){const t=e[Ms];("data"===t&&e[Os]===qo||"Signature"===t&&e[Os]===eo.signature.id)&&(this[t]=e);this[jn](e)}}class DatasetsNamespace{static[Qs](e,t){if(DatasetsNamespace.hasOwnProperty(e))return DatasetsNamespace[e](t)}static datasets(e){return new Datasets(e)}static data(e){return new datasets_Data(e)}}const Ho=eo.localeSet.id;class CalendarSymbols extends XFAObject{constructor(e){super(Ho,"calendarSymbols",!0);this.name="gregorian";this.dayNames=new XFAObjectArray(2);this.eraNames=null;this.meridiemNames=null;this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(e){super(Ho,"currencySymbol");this.name=getStringOption(e.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(e){super(Ho,"currencySymbols",!0);this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(e){super(Ho,"datePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(e){super(Ho,"datePatterns",!0);this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(e){super(Ho,"dateTimeSymbols")}}class Day extends StringObject{constructor(e){super(Ho,"day")}}class DayNames extends XFAObject{constructor(e){super(Ho,"dayNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(e){super(Ho,"era")}}class EraNames extends XFAObject{constructor(e){super(Ho,"eraNames",!0);this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(e){super(Ho,"locale",!0);this.desc=e.desc||"";this.name="isoname";this.calendarSymbols=null;this.currencySymbols=null;this.datePatterns=null;this.dateTimeSymbols=null;this.numberPatterns=null;this.numberSymbols=null;this.timePatterns=null;this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(e){super(Ho,"localeSet",!0);this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(e){super(Ho,"meridiem")}}class MeridiemNames extends XFAObject{constructor(e){super(Ho,"meridiemNames",!0);this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(e){super(Ho,"month")}}class MonthNames extends XFAObject{constructor(e){super(Ho,"monthNames",!0);this.abbr=getInteger({data:e.abbr,defaultValue:0,validate:e=>1===e});this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(e){super(Ho,"numberPattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(e){super(Ho,"numberPatterns",!0);this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(e){super(Ho,"numberSymbol");this.name=getStringOption(e.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(e){super(Ho,"numberSymbols",!0);this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(e){super(Ho,"timePattern");this.name=getStringOption(e.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(e){super(Ho,"timePatterns",!0);this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(e){super(Ho,"typeFace",!0);this.name=""|e.name}}class TypeFaces extends XFAObject{constructor(e){super(Ho,"typeFaces",!0);this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[Qs](e,t){if(LocaleSetNamespace.hasOwnProperty(e))return LocaleSetNamespace[e](t)}static calendarSymbols(e){return new CalendarSymbols(e)}static currencySymbol(e){return new CurrencySymbol(e)}static currencySymbols(e){return new CurrencySymbols(e)}static datePattern(e){return new DatePattern(e)}static datePatterns(e){return new DatePatterns(e)}static dateTimeSymbols(e){return new DateTimeSymbols(e)}static day(e){return new Day(e)}static dayNames(e){return new DayNames(e)}static era(e){return new Era(e)}static eraNames(e){return new EraNames(e)}static locale(e){return new locale_set_Locale(e)}static localeSet(e){return new locale_set_LocaleSet(e)}static meridiem(e){return new Meridiem(e)}static meridiemNames(e){return new MeridiemNames(e)}static month(e){return new Month(e)}static monthNames(e){return new MonthNames(e)}static numberPattern(e){return new NumberPattern(e)}static numberPatterns(e){return new NumberPatterns(e)}static numberSymbol(e){return new NumberSymbol(e)}static numberSymbols(e){return new NumberSymbols(e)}static timePattern(e){return new TimePattern(e)}static timePatterns(e){return new TimePatterns(e)}static typeFace(e){return new TypeFace(e)}static typeFaces(e){return new TypeFaces(e)}}const Wo=eo.signature.id;class signature_Signature extends XFAObject{constructor(e){super(Wo,"signature",!0)}}class SignatureNamespace{static[Qs](e,t){if(SignatureNamespace.hasOwnProperty(e))return SignatureNamespace[e](t)}static signature(e){return new signature_Signature(e)}}const Go=eo.stylesheet.id;class Stylesheet extends XFAObject{constructor(e){super(Go,"stylesheet",!0)}}class StylesheetNamespace{static[Qs](e,t){if(StylesheetNamespace.hasOwnProperty(e))return StylesheetNamespace[e](t)}static stylesheet(e){return new Stylesheet(e)}}const zo=eo.xdp.id;class xdp_Xdp extends XFAObject{constructor(e){super(zo,"xdp",!0);this.uuid=e.uuid||"";this.timeStamp=e.timeStamp||"";this.config=null;this.connectionSet=null;this.datasets=null;this.localeSet=null;this.stylesheet=new XFAObjectArray;this.template=null}[Rs](e){const t=eo[e[Ms]];return t&&e[Os]===t.id}}class XdpNamespace{static[Qs](e,t){if(XdpNamespace.hasOwnProperty(e))return XdpNamespace[e](t)}static xdp(e){return new xdp_Xdp(e)}}const $o=eo.xhtml.id,Vo=Symbol(),Ko=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),Jo=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",e=>"none"===e?"none":"normal"],["xfa-font-horizontal-scale",e=>`scaleX(${Math.max(0,parseInt(e)/100).toFixed(2)})`],["xfa-font-vertical-scale",e=>`scaleY(${Math.max(0,parseInt(e)/100).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(e,t)=>measureToString(.99*(e=t.fontSize=Math.abs(getMeasurement(e))))],["letter-spacing",e=>measureToString(getMeasurement(e))],["line-height",e=>measureToString(getMeasurement(e))],["margin",e=>measureToString(getMeasurement(e))],["margin-bottom",e=>measureToString(getMeasurement(e))],["margin-left",e=>measureToString(getMeasurement(e))],["margin-right",e=>measureToString(getMeasurement(e))],["margin-top",e=>measureToString(getMeasurement(e))],["text-indent",e=>measureToString(getMeasurement(e))],["font-family",e=>e],["vertical-align",e=>measureToString(getMeasurement(e))]]),Yo=/\s+/g,Zo=/[\r\n]+/g,Qo=/\r\n?/g;function mapStyle(e,t,a){const r=Object.create(null);if(!e)return r;const i=Object.create(null);for(const[t,a]of e.split(";").map(e=>e.split(":",2))){const e=Jo.get(t);if(""===e)continue;let n=a;e&&(n="string"==typeof e?e:e(a,i));t.endsWith("scale")?r.transform=r.transform?`${r[t]} ${n}`:n:r[t.replaceAll(/-([a-zA-Z])/g,(e,t)=>t.toUpperCase())]=n}r.fontFamily&&setFontFamily({typeface:r.fontFamily,weight:r.fontWeight||"normal",posture:r.fontStyle||"normal",size:i.fontSize||0},t,t[gs].fontFinder,r);if(a&&r.verticalAlign&&"0px"!==r.verticalAlign&&r.fontSize){const e=.583,t=.333,a=getMeasurement(r.fontSize);r.fontSize=measureToString(a*e);r.verticalAlign=measureToString(Math.sign(getMeasurement(r.verticalAlign))*a*t)}a&&r.fontSize&&(r.fontSize=`calc(${r.fontSize} * var(--total-scale-factor))`);fixTextIndent(r);return r}const ec=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(e,t){super($o,t);this[Vo]=!1;this.style=e.style||""}[qn](e){super[qn](e);this.style=function checkStyle(e){return e.style?e.style.split(";").filter(e=>!!e.trim()).map(e=>e.split(":",2).map(e=>e.trim())).filter(([t,a])=>{"font-family"===t&&e[gs].usedTypefaces.add(a);return Ko.has(t)}).map(e=>e.join(":")).join(";"):""}(this)}[_n](){return!ec.has(this[Ms])}[Ns](e,t=!1){if(t)this[Vo]=!0;else{e=e.replaceAll(Zo,"");this.style.includes("xfa-spacerun:yes")||(e=e.replaceAll(Yo," "))}e&&(this[$n]+=e)}[Es](e,t=!0){const a=Object.create(null),r={top:NaN,bottom:NaN,left:NaN,right:NaN};let i=null;for(const[e,t]of this.style.split(";").map(e=>e.split(":",2)))switch(e){case"font-family":a.typeface=stripQuotes(t);break;case"font-size":a.size=getMeasurement(t);break;case"font-weight":a.weight=t;break;case"font-style":a.posture=t;break;case"letter-spacing":a.letterSpacing=getMeasurement(t);break;case"margin":const e=t.split(/ \t/).map(e=>getMeasurement(e));switch(e.length){case 1:r.top=r.bottom=r.left=r.right=e[0];break;case 2:r.top=r.bottom=e[0];r.left=r.right=e[1];break;case 3:r.top=e[0];r.bottom=e[2];r.left=r.right=e[1];break;case 4:r.top=e[0];r.left=e[1];r.bottom=e[2];r.right=e[3]}break;case"margin-top":r.top=getMeasurement(t);break;case"margin-bottom":r.bottom=getMeasurement(t);break;case"margin-left":r.left=getMeasurement(t);break;case"margin-right":r.right=getMeasurement(t);break;case"line-height":i=getMeasurement(t)}e.pushData(a,r,i);if(this[$n])e.addString(this[$n]);else for(const t of this[cs]())"#text"!==t[Ms]?t[Es](e):e.addString(t[$n]);t&&e.popFont()}[Ks](e){const t=[];this[Jn]={children:t};this[Xn]({});if(0===t.length&&!this[$n])return HTMLResult.EMPTY;let a;a=this[Vo]?this[$n]?this[$n].replaceAll(Qo,"\n"):void 0:this[$n]||void 0;return HTMLResult.success({name:this[Ms],attributes:{href:this.href,style:mapStyle(this.style,this,this[Vo])},children:t,value:a})}}class A extends XhtmlObject{constructor(e){super(e,"a");this.href=fixURL(e.href)||""}}class B extends XhtmlObject{constructor(e){super(e,"b")}[Es](e){e.pushFont({weight:"bold"});super[Es](e);e.popFont()}}class Body extends XhtmlObject{constructor(e){super(e,"body")}[Ks](e){const t=super[Ks](e),{html:a}=t;if(!a)return HTMLResult.EMPTY;a.name="div";a.attributes.class=["xfaRich"];return t}}class Br extends XhtmlObject{constructor(e){super(e,"br")}[$s](){return"\n"}[Es](e){e.addString("\n")}[Ks](e){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(e){super(e,"html")}[Ks](e){const t=[];this[Jn]={children:t};this[Xn]({});if(0===t.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[$n]||""});if(1===t.length){const e=t[0];if(e.attributes?.class.includes("xfaRich"))return HTMLResult.success(e)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:t})}}class I extends XhtmlObject{constructor(e){super(e,"i")}[Es](e){e.pushFont({posture:"italic"});super[Es](e);e.popFont()}}class Li extends XhtmlObject{constructor(e){super(e,"li")}}class Ol extends XhtmlObject{constructor(e){super(e,"ol")}}class P extends XhtmlObject{constructor(e){super(e,"p")}[Es](e){super[Es](e,!1);e.addString("\n");e.addPara();e.popFont()}[$s](){return this[ds]()[cs]().at(-1)===this?super[$s]():super[$s]()+"\n"}}class Span extends XhtmlObject{constructor(e){super(e,"span")}}class Sub extends XhtmlObject{constructor(e){super(e,"sub")}}class Sup extends XhtmlObject{constructor(e){super(e,"sup")}}class Ul extends XhtmlObject{constructor(e){super(e,"ul")}}class XhtmlNamespace{static[Qs](e,t){if(XhtmlNamespace.hasOwnProperty(e))return XhtmlNamespace[e](t)}static a(e){return new A(e)}static b(e){return new B(e)}static body(e){return new Body(e)}static br(e){return new Br(e)}static html(e){return new Html(e)}static i(e){return new I(e)}static li(e){return new Li(e)}static ol(e){return new Ol(e)}static p(e){return new P(e)}static span(e){return new Span(e)}static sub(e){return new Sub(e)}static sup(e){return new Sup(e)}static ul(e){return new Ul(e)}}const tc={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(e){this.namespaceId=e}[Qs](e,t){return new XmlObject(this.namespaceId,e,t)}}class Root extends XFAObject{constructor(e){super(-1,"root",Object.create(null));this.element=null;this[ms]=e}[Bs](e){this.element=e;return!0}[Yn](){super[Yn]();if(this.element.template instanceof Template){this[ms].set(js,this.element);this.element.template[Xs](this[ms]);this.element.template[ms]=this[ms]}}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[Bs](e){return!1}}class Builder{constructor(e=null){this._namespaceStack=[];this._nsAgnosticLevel=0;this._namespacePrefixes=new Map;this._namespaces=new Map;this._nextNsId=Math.max(...Object.values(eo).map(({id:e})=>e));this._currentNamespace=e||new UnknownNamespace(++this._nextNsId)}buildRoot(e){return new Root(e)}build({nsPrefix:e,name:t,attributes:a,namespace:r,prefixes:i}){const n=null!==r;if(n){this._namespaceStack.push(this._currentNamespace);this._currentNamespace=this._searchNamespace(r)}i&&this._addNamespacePrefix(i);if(a.hasOwnProperty(Ds)){const e=tc.datasets,t=a[Ds];let r=null;for(const[a,i]of Object.entries(t)){if(this._getNamespaceToUse(a)===e){r={xfa:i};break}}r?a[Ds]=r:delete a[Ds]}const s=this._getNamespaceToUse(e),o=s?.[Qs](t,a)||new Empty;o[ks]()&&this._nsAgnosticLevel++;(n||i||o[ks]())&&(o[Wn]={hasNamespace:n,prefixes:i,nsAgnostic:o[ks]()});return o}isNsAgnostic(){return this._nsAgnosticLevel>0}_searchNamespace(e){let t=this._namespaces.get(e);if(t)return t;for(const[a,{check:r}]of Object.entries(eo))if(r(e)){t=tc[a];if(t){this._namespaces.set(e,t);return t}break}t=new UnknownNamespace(++this._nextNsId);this._namespaces.set(e,t);return t}_addNamespacePrefix(e){for(const{prefix:t,value:a}of e){const e=this._searchNamespace(a);let r=this._namespacePrefixes.get(t);if(!r){r=[];this._namespacePrefixes.set(t,r)}r.push(e)}}_getNamespaceToUse(e){if(!e)return this._currentNamespace;const t=this._namespacePrefixes.get(e);if(t?.length>0)return t.at(-1);warn(`Unknown namespace prefix: ${e}.`);return null}clean(e){const{hasNamespace:t,prefixes:a,nsAgnostic:r}=e;t&&(this._currentNamespace=this._namespaceStack.pop());a&&a.forEach(({prefix:e})=>{this._namespacePrefixes.get(e).pop()});r&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(e=null,t=!1){super();this._builder=new Builder(e);this._stack=[];this._globalData={usedTypefaces:new Set};this._ids=new Map;this._current=this._builder.buildRoot(this._ids);this._errorCode=vn;this._whiteRegex=/^\s+$/;this._nbsps=/\xa0+/g;this._richText=t}parse(e){this.parseXml(e);if(this._errorCode===vn){this._current[Yn]();return this._current.element}}onText(e){e=e.replace(this._nbsps,e=>e.slice(1)+" ");this._richText||this._current[_n]()?this._current[Ns](e,this._richText):this._whiteRegex.test(e)||this._current[Ns](e.trim())}onCdata(e){this._current[Ns](e)}_mkAttributes(e,t){let a=null,r=null;const i=Object.create({});for(const{name:n,value:s}of e)if("xmlns"===n)a?warn(`XFA - multiple namespace definition in <${t}>`):a=s;else if(n.startsWith("xmlns:")){const e=n.substring(6);r??=[];r.push({prefix:e,value:s})}else{const e=n.indexOf(":");if(-1===e)i[n]=s;else{const t=i[Ds]??=Object.create(null),[a,r]=[n.slice(0,e),n.slice(e+1)];(t[a]||=Object.create(null))[r]=s}}return[a,r,i]}_getNameAndPrefix(e,t){const a=e.indexOf(":");return-1===a?[e,null]:[e.substring(a+1),t?"":e.substring(0,a)]}onBeginElement(e,t,a){const[r,i,n]=this._mkAttributes(t,e),[s,o]=this._getNameAndPrefix(e,this._builder.isNsAgnostic()),c=this._builder.build({nsPrefix:o,name:s,attributes:n,namespace:r,prefixes:i});c[gs]=this._globalData;if(a){c[Yn]();this._current[Bs](c)&&c[Hs](this._ids);c[qn](this._builder)}else{this._stack.push(this._current);this._current=c}}onEndElement(e){const t=this._current;if(t[ws]()&&"string"==typeof t[$n]){const e=new XFAParser;e._globalData=this._globalData;const a=e.parse(t[$n]);t[$n]=null;t[Bs](a)}t[Yn]();this._current=this._stack.pop();this._current[Bs](t)&&t[Hs](this._ids);t[qn](this._builder)}onError(e){this._errorCode=e}}class XFAFactory{constructor(e){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(e));const t=new Binder(this.root);this.form=t.bind();this.dataHandler=new DataHandler(this.root,t.getData());this.form[gs].template=this.form}catch(e){warn(`XFA - an error occurred during parsing and binding: ${e}`)}}isValid(){return!(!this.root||!this.form)}_createPagesHelper(){const e=this.form[Vs]();return new Promise((t,a)=>{const nextIteration=()=>{try{const a=e.next();a.done?t(a.value):setTimeout(nextIteration,0)}catch(e){a(e)}};setTimeout(nextIteration,0)})}async _createPages(){try{this.pages=await this._createPagesHelper();this.dims=this.pages.children.map(e=>{const{width:t,height:a}=e.attributes.style;return[0,0,parseInt(t),parseInt(a)]})}catch(e){warn(`XFA - an error occurred during layout: ${e}`)}}getBoundingBox(e){return this.dims[e]}async getNumPages(){this.pages||await this._createPages();return this.dims.length}setImages(e){this.form[gs].images=e}setFonts(e){this.form[gs].fontFinder=new FontFinder(e);const t=[];for(let e of this.form[gs].usedTypefaces){e=stripQuotes(e);this.form[gs].fontFinder.find(e)||t.push(e)}return t.length>0?t:null}appendFonts(e,t){this.form[gs].fontFinder.add(e,t)}async getPages(){this.pages||await this._createPages();const e=this.pages;this.pages=null;return e}serializeData(e){return this.dataHandler.serialize(e)}static _createDocument(e){return e["/xdp:xdp"]?Object.values(e).join(""):e["xdp:xdp"]}static getRichTextAsHtml(e){if(!e||"string"!=typeof e)return null;try{let t=new XFAParser(XhtmlNamespace,!0).parse(e);if(!["body","xhtml"].includes(t[Ms])){const e=XhtmlNamespace.body({});e[jn](t);t=e}const a=t[Ks]();if(!a.success)return null;const{html:r}=a,{attributes:i}=r;if(i){i.class&&(i.class=i.class.filter(e=>!e.startsWith("xfa")));i.dir="auto"}return{html:r,str:t[$s]()}}catch(e){warn(`XFA - an error occurred during parsing of rich text: ${e}`)}return null}}class AnnotationFactory{static createGlobals(e){return Promise.all([e.ensureCatalog("acroForm"),e.ensureDoc("xfaDatasets"),e.ensureCatalog("structTreeRoot"),e.ensureCatalog("baseUrl"),e.ensureCatalog("attachments"),e.ensureCatalog("globalColorSpaceCache")]).then(([t,a,r,i,n,s])=>({pdfManager:e,acroForm:t instanceof Dict?t:Dict.empty,xfaDatasets:a,structTreeRoot:r,baseUrl:i,attachments:n,globalColorSpaceCache:s}),e=>{warn(`createGlobals: "${e}".`);return null})}static async create(e,t,a,r,i,n,s,o){const c=i?await this._getPageIndex(e,t,a.pdfManager):null;return a.pdfManager.ensure(this,"_create",[e,t,a,r,i,n,s,c,o])}static _create(e,t,a,r,i=!1,n=null,s=null,o=null,c=null){const l=e.fetchIfRef(t);if(!(l instanceof Dict))return;let h=l.get("Subtype");h=h instanceof Name?h.name:null;if(s&&!s.has(M[h.toUpperCase()]))return null;const{acroForm:u,pdfManager:d}=a,f=t instanceof Ref?t.toString():`annot_${r.createObjId()}`,g={xref:e,ref:t,dict:l,subtype:h,id:f,annotationGlobals:a,collectFields:i,orphanFields:n,needAppearances:!i&&!0===u.get("NeedAppearances"),pageIndex:o,evaluatorOptions:d.evaluatorOptions,pageRef:c};switch(h){case"Link":return new LinkAnnotation(g);case"Text":return new TextAnnotation(g);case"Widget":let e=getInheritableProperty({dict:l,key:"FT"});e=e instanceof Name?e.name:null;switch(e){case"Tx":return new TextWidgetAnnotation(g);case"Btn":return new ButtonWidgetAnnotation(g);case"Ch":return new ChoiceWidgetAnnotation(g);case"Sig":return new SignatureWidgetAnnotation(g)}warn(`Unimplemented widget field type "${e}", falling back to base field type.`);return new WidgetAnnotation(g);case"Popup":return new PopupAnnotation(g);case"FreeText":return new FreeTextAnnotation(g);case"Line":return new LineAnnotation(g);case"Square":return new SquareAnnotation(g);case"Circle":return new CircleAnnotation(g);case"PolyLine":return new PolylineAnnotation(g);case"Polygon":return new PolygonAnnotation(g);case"Caret":return new CaretAnnotation(g);case"Ink":return new InkAnnotation(g);case"Highlight":return new HighlightAnnotation(g);case"Underline":return new UnderlineAnnotation(g);case"Squiggly":return new SquigglyAnnotation(g);case"StrikeOut":return new StrikeOutAnnotation(g);case"Stamp":return new StampAnnotation(g);case"FileAttachment":return new FileAttachmentAnnotation(g);default:i||warn(h?`Unimplemented annotation type "${h}", falling back to base annotation.`:"Annotation is missing the required /Subtype.");return new Annotation(g)}}static async _getPageIndex(e,t,a){try{const r=await e.fetchIfRefAsync(t);if(!(r instanceof Dict))return-1;const i=r.getRaw("P");if(i instanceof Ref)try{return await a.ensureCatalog("getPageIndex",[i])}catch(e){info(`_getPageIndex -- not a valid page reference: "${e}".`)}if(r.has("Kids"))return-1;const n=await a.ensureDoc("numPages");for(let e=0;ee/255)||t}function getQuadPoints(e,t){const a=e.getArray("QuadPoints");if(!isNumberArray(a,null)||0===a.length||a.length%8>0)return null;const r=new Float32Array(a.length);for(let e=0,i=a.length;et[2]||gt[3]))return null;r.set([d,p,f,p,d,g,f,g],e)}return r}function getTransformMatrix(e,t,a){const r=new Float32Array([1/0,1/0,-1/0,-1/0]);Util.axialAlignedBoundingBox(t,a,r);const[i,n,s,o]=r;if(i===s||n===o)return[1,0,0,1,e[0],e[1]];const c=(e[2]-e[0])/(s-i),l=(e[3]-e[1])/(o-n);return[c,0,0,l,e[0]-i*c,e[1]-n*l]}class Annotation{constructor(e){const{dict:t,xref:a,annotationGlobals:r,ref:i,orphanFields:n}=e,s=n?.get(i);s&&t.set("Parent",s);this.setTitle(t.get("T"));this.setContents(t.get("Contents"));this.setModificationDate(t.get("M"));this.setFlags(t.get("F"));this.setRectangle(t.getArray("Rect"));this.setColor(t.getArray("C"));this.setBorderStyle(t);this.setAppearance(t);this.setOptionalContent(t);const o=t.get("MK");this.setBorderAndBackgroundColors(o);this.setRotation(o,t);this.ref=e.ref instanceof Ref?e.ref:null;this._streams=[];this.appearance&&this._streams.push(this.appearance);const c=!!(this.flags&j),l=!!(this.flags&X);this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:e.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:e.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&_),noHTML:c&&l,isEditable:!1,structParent:-1};if(r.structTreeRoot){let a=t.get("StructParent");this.data.structParent=a=Number.isInteger(a)&&a>=0?a:-1;r.structTreeRoot.addAnnotationIdToPage(e.pageRef,a)}if(e.collectFields){const r=t.get("Kids");if(Array.isArray(r)){const e=[];for(const t of r)t instanceof Ref&&e.push(t.toString());0!==e.length&&(this.data.kidIds=e)}this.data.actions=collectActions(a,t,ie);this.data.fieldName=this._constructFieldName(t);this.data.pageIndex=e.pageIndex}const h=t.get("IT");h instanceof Name&&(this.data.it=h.name);this._isOffscreenCanvasSupported=e.evaluatorOptions.isOffscreenCanvasSupported;this._fallbackFontDict=null;this._needAppearances=!1}_hasFlag(e,t){return!!(e&t)}_buildFlags(e,t){let{flags:a}=this;if(void 0===e){if(void 0===t)return;return t?a&~L:a&~E|L}if(e){a|=L;return t?a&~U|E:a&~E|U}a&=~(E|U);return t?a&~L:a|L}_isViewable(e){return!this._hasFlag(e,N)&&!this._hasFlag(e,U)}_isPrintable(e){return this._hasFlag(e,L)&&!this._hasFlag(e,E)&&!this._hasFlag(e,N)}mustBeViewed(e,t){const a=e?.get(this.data.id)?.noView;return void 0!==a?!a:this.viewable&&!this._hasFlag(this.flags,E)}mustBePrinted(e){const t=e?.get(this.data.id)?.noPrint;return void 0!==t?!t:this.printable}mustBeViewedWhenEditing(e,t=null){return e?!this.data.isEditable:!t?.has(this.data.id)}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&(0!==this.flags&&this._isPrintable(this.flags))}_parseStringHelper(e){const t="string"==typeof e?stringToPDFString(e):"";return{str:t,dir:t&&"rtl"===bidi(t).dir?"rtl":"ltr"}}setDefaultAppearance(e){const{dict:t,annotationGlobals:a}=e,r=getInheritableProperty({dict:t,key:"DA"})||a.acroForm.get("DA");this._defaultAppearance="string"==typeof r?r:"";this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(e){this._title=this._parseStringHelper(e)}setContents(e){this._contents=this._parseStringHelper(e)}setModificationDate(e){this.modificationDate="string"==typeof e?e:null}setFlags(e){this.flags=Number.isInteger(e)&&e>0?e:0;this.flags&N&&"Annotation"!==this.constructor.name&&(this.flags^=N)}hasFlag(e){return this._hasFlag(this.flags,e)}setRectangle(e){this.rectangle=lookupNormalRect(e,[0,0,0,0])}setColor(e){this.color=getRgbColor(e)}setLineEndings(e){this.lineEndings=["None","None"];if(Array.isArray(e)&&2===e.length)for(let t=0;t<2;t++){const a=e[t];if(a instanceof Name)switch(a.name){case"None":continue;case"Square":case"Circle":case"Diamond":case"OpenArrow":case"ClosedArrow":case"Butt":case"ROpenArrow":case"RClosedArrow":case"Slash":this.lineEndings[t]=a.name;continue}warn(`Ignoring invalid lineEnding: ${a}`)}}setRotation(e,t){this.rotation=0;let a=e instanceof Dict?e.get("R")||0:t.get("Rotate")||0;if(Number.isInteger(a)&&0!==a){a%=360;a<0&&(a+=360);a%90==0&&(this.rotation=a)}}setBorderAndBackgroundColors(e){if(e instanceof Dict){this.borderColor=getRgbColor(e.getArray("BC"),null);this.backgroundColor=getRgbColor(e.getArray("BG"),null)}else this.borderColor=this.backgroundColor=null}setBorderStyle(e){this.borderStyle=new AnnotationBorderStyle;if(e instanceof Dict)if(e.has("BS")){const t=e.get("BS");if(t instanceof Dict){const e=t.get("Type");if(!e||isName(e,"Border")){this.borderStyle.setWidth(t.get("W"),this.rectangle);this.borderStyle.setStyle(t.get("S"));this.borderStyle.setDashArray(t.getArray("D"))}}}else if(e.has("Border")){const t=e.getArray("Border");if(Array.isArray(t)&&t.length>=3){this.borderStyle.setHorizontalCornerRadius(t[0]);this.borderStyle.setVerticalCornerRadius(t[1]);this.borderStyle.setWidth(t[2],this.rectangle);4===t.length&&this.borderStyle.setDashArray(t[3],!0)}}else this.borderStyle.setWidth(0)}setAppearance(e){this.appearance=null;const t=e.get("AP");if(!(t instanceof Dict))return;const a=t.get("N");if(a instanceof BaseStream){this.appearance=a;return}if(!(a instanceof Dict))return;const r=e.get("AS");if(!(r instanceof Name&&a.has(r.name)))return;const i=a.get(r.name);i instanceof BaseStream&&(this.appearance=i)}setOptionalContent(e){this.oc=null;const t=e.get("OC");t instanceof Name?warn("setOptionalContent: Support for /Name-entry is not implemented."):t instanceof Dict&&(this.oc=t)}async loadResources(e,t){const a=await t.dict.getAsync("Resources");a&&await ObjectLoader.load(a,e,a.xref);return a}async getOperatorList(e,t,a,r){const{hasOwnCanvas:i,id:n,rect:o}=this.data;let c=this.appearance;const l=!!(i&&a&s);if(l&&(0===this.width||0===this.height)){this.data.hasOwnCanvas=!1;return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}if(!c){if(!l)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};c=new StringStream("");c.dict=new Dict}const h=c.dict,u=await this.loadResources(ga,c),d=lookupRect(h.getArray("BBox"),[0,0,1,1]),f=lookupMatrix(h.getArray("Matrix"),fa),g=getTransformMatrix(o,d,f),p=new OperatorList;let m;this.oc&&(m=await e.parseMarkedContentProps(this.oc,null));void 0!==m&&p.addOp(Ct,["OC",m]);p.addOp(Bt,[n,o,g,f,l]);await e.getOperatorList({stream:c,task:t,resources:u,operatorList:p,fallbackFontDict:this._fallbackFontDict});p.addOp(Rt,[]);void 0!==m&&p.addOp(vt,[]);this.reset();return{opList:p,separateForm:!1,separateCanvas:l}}async save(e,t,a,r){return null}get overlaysTextContent(){return!1}get hasTextContent(){return!1}async extractTextContent(e,t,a){if(!this.appearance)return;const r=await this.loadResources(pa,this.appearance),i=[],n=[];let s=null;const o={desiredSize:Math.Infinity,ready:!0,enqueue(e,t){for(const t of e.items)if(void 0!==t.str){s||=t.transform.slice(-2);n.push(t.str);if(t.hasEOL){i.push(n.join("").trimEnd());n.length=0}}}};await e.getTextContent({stream:this.appearance,task:t,resources:r,includeMarkedContent:!0,keepWhiteSpace:!0,sink:o,viewBox:a});this.reset();n.length&&i.push(n.join("").trimEnd());if(i.length>1||i[0]){const e=this.appearance.dict,t=lookupRect(e.getArray("BBox"),null),a=lookupMatrix(e.getArray("Matrix"),null);this.data.textPosition=this._transformPoint(s,t,a);this.data.textContent=i}}_transformPoint(e,t,a){const{rect:r}=this.data;t||=[0,0,1,1];a||=[1,0,0,1,0,0];const i=getTransformMatrix(r,t,a);i[4]-=r[0];i[5]-=r[1];const n=e.slice();Util.applyTransform(n,i);Util.applyTransform(n,a);return n}getFieldObject(){return this.data.kidIds?{id:this.data.id,actions:this.data.actions,name:this.data.fieldName,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,type:"",kidIds:this.data.kidIds,page:this.data.pageIndex,rotation:this.rotation}:null}reset(){for(const e of this._streams)e.reset()}_constructFieldName(e){if(!e.has("T")&&!e.has("Parent")){warn("Unknown field name, falling back to empty field name.");return""}if(!e.has("Parent"))return stringToPDFString(e.get("T"));const t=[];e.has("T")&&t.unshift(stringToPDFString(e.get("T")));let a=e;const r=new RefSet;e.objId&&r.put(e.objId);for(;a.has("Parent");){a=a.get("Parent");if(!(a instanceof Dict)||a.objId&&r.has(a.objId))break;a.objId&&r.put(a.objId);a.has("T")&&t.unshift(stringToPDFString(a.get("T")))}return t.join(".")}get width(){return this.data.rect[2]-this.data.rect[0]}get height(){return this.data.rect[3]-this.data.rect[1]}}class AnnotationBorderStyle{constructor(){this.width=1;this.rawWidth=1;this.style=Q;this.dashArray=[3];this.horizontalCornerRadius=0;this.verticalCornerRadius=0}setWidth(e,t=[0,0,0,0]){if(e instanceof Name)this.width=0;else if("number"==typeof e){if(e>0){this.rawWidth=e;const a=(t[2]-t[0])/2,r=(t[3]-t[1])/2;if(a>0&&r>0&&(e>a||e>r)){warn(`AnnotationBorderStyle.setWidth - ignoring width: ${e}`);e=1}}this.width=e}}setStyle(e){if(e instanceof Name)switch(e.name){case"S":this.style=Q;break;case"D":this.style=ee;break;case"B":this.style=te;break;case"I":this.style=ae;break;case"U":this.style=re}}setDashArray(e,t=!1){if(Array.isArray(e)){let a=!0,r=!0;for(const t of e){if(!(+t>=0)){a=!1;break}t>0&&(r=!1)}if(0===e.length||a&&!r){this.dashArray=e;t&&this.setStyle(Name.get("D"))}else this.width=0}else e&&(this.width=0)}setHorizontalCornerRadius(e){Number.isInteger(e)&&(this.horizontalCornerRadius=e)}setVerticalCornerRadius(e){Number.isInteger(e)&&(this.verticalCornerRadius=e)}}class MarkupAnnotation extends Annotation{constructor(e){super(e);const{dict:t}=e;if(t.has("IRT")){const e=t.getRaw("IRT");this.data.inReplyTo=e instanceof Ref?e.toString():null;const a=t.get("RT");this.data.replyType=a instanceof Name?a.name:R}let a=null;if(this.data.replyType===D){const e=t.get("IRT");this.setTitle(e.get("T"));this.data.titleObj=this._title;this.setContents(e.get("Contents"));this.data.contentsObj=this._contents;if(e.has("CreationDate")){this.setCreationDate(e.get("CreationDate"));this.data.creationDate=this.creationDate}else this.data.creationDate=null;if(e.has("M")){this.setModificationDate(e.get("M"));this.data.modificationDate=this.modificationDate}else this.data.modificationDate=null;a=e.getRaw("Popup");if(e.has("C")){this.setColor(e.getArray("C"));this.data.color=this.color}else this.data.color=null}else{this.data.titleObj=this._title;this.setCreationDate(t.get("CreationDate"));this.data.creationDate=this.creationDate;a=t.getRaw("Popup");t.has("C")||(this.data.color=null)}this.data.popupRef=a instanceof Ref?a.toString():null;t.has("RC")&&(this.data.richText=XFAFactory.getRichTextAsHtml(t.get("RC")))}setCreationDate(e){this.creationDate="string"==typeof e?e:null}_setDefaultAppearance({xref:e,extra:t,strokeColor:a,fillColor:r,blendMode:i,strokeAlpha:n,fillAlpha:s,pointsCallback:o}){const c=this.data.rect=[1/0,1/0,-1/0,-1/0],l=["q"];t&&l.push(t);a&&l.push(`${a[0]} ${a[1]} ${a[2]} RG`);r&&l.push(`${r[0]} ${r[1]} ${r[2]} rg`);const h=this.data.quadPoints||Float32Array.from([this.rectangle[0],this.rectangle[3],this.rectangle[2],this.rectangle[3],this.rectangle[0],this.rectangle[1],this.rectangle[2],this.rectangle[1]]);for(let e=0,t=h.length;e"string"==typeof e).map(e=>stringToPDFString(e)):e instanceof Name?stringToPDFString(e.name):"string"==typeof e?stringToPDFString(e):null}hasFieldFlag(e){return!!(this.data.fieldFlags&e)}_isViewable(e){return!0}mustBeViewed(e,t){return t?this.viewable:super.mustBeViewed(e,t)&&!this._hasFlag(this.flags,U)}getRotationMatrix(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);return 0===t?fa:getRotationMatrix(t,this.width,this.height)}getBorderAndBackgroundAppearances(e){let t=e?.get(this.data.id)?.rotation;void 0===t&&(t=this.rotation);if(!this.backgroundColor&&!this.borderColor)return"";const a=0===t||180===t?`0 0 ${this.width} ${this.height} re`:`0 0 ${this.height} ${this.width} re`;let r="";this.backgroundColor&&(r=`${getPdfColor(this.backgroundColor,!0)} ${a} f `);if(this.borderColor){r+=`${this.borderStyle.width||1} w ${getPdfColor(this.borderColor,!1)} ${a} S `}return r}async getOperatorList(e,t,a,r){if(a&l&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(e,t,a,r);const i=await this._getAppearance(e,t,a,r);if(this.appearance&&null===i)return super.getOperatorList(e,t,a,r);const n=new OperatorList;if(!this._defaultAppearance||null===i)return{opList:n,separateForm:!1,separateCanvas:!1};const o=!!(this.data.hasOwnCanvas&&a&s),c=[0,0,this.width,this.height],h=getTransformMatrix(this.data.rect,c,[1,0,0,1,0,0]);let u;this.oc&&(u=await e.parseMarkedContentProps(this.oc,null));void 0!==u&&n.addOp(Ct,["OC",u]);n.addOp(Bt,[this.data.id,this.data.rect,h,this.getRotationMatrix(r),o]);const d=new StringStream(i);await e.getOperatorList({stream:d,task:t,resources:this._fieldResources.mergedResources,operatorList:n});n.addOp(Rt,[]);void 0!==u&&n.addOp(vt,[]);return{opList:n,separateForm:!1,separateCanvas:o}}_getMKDict(e){const t=new Dict(null);e&&t.set("R",e);t.setIfArray("BC",getPdfColorArray(this.borderColor));t.setIfArray("BG",getPdfColorArray(this.backgroundColor));return t.size>0?t:null}amendSavedDict(e,t){}setValue(e,t,a,r){const{dict:i,ref:n}=function getParentToUpdate(e,t,a){const r=new RefSet,i=e,n={dict:null,ref:null};for(;e instanceof Dict&&!r.has(t);){r.put(t);if(e.has("T"))break;if(!((t=e.getRaw("Parent"))instanceof Ref))return n;e=a.fetch(t)}if(e instanceof Dict&&e!==i){n.dict=e;n.ref=t}return n}(e,this.ref,a);if(i){if(!r.has(n)){const e=i.clone();e.set("V",t);r.put(n,{data:e});return e}}else e.set("V",t);return null}async save(e,t,a,r){const i=a?.get(this.data.id),n=this._buildFlags(i?.noView,i?.noPrint);let s=i?.value,o=i?.rotation;if(s===this.data.fieldValue||void 0===s){if(!this._hasValueFromXFA&&void 0===o&&void 0===n)return;s||=this.data.fieldValue}if(void 0===o&&!this._hasValueFromXFA&&Array.isArray(s)&&Array.isArray(this.data.fieldValue)&&isArrayEqual(s,this.data.fieldValue)&&void 0===n)return;void 0===o&&(o=this.rotation);let l=null;if(!this._needAppearances){l=await this._getAppearance(e,t,c,a);if(null===l&&void 0===n)return}let h=!1;if(l?.needAppearances){h=!0;l=null}const{xref:u}=e,d=u.fetchIfRef(this.ref);if(!(d instanceof Dict))return;const f=new Dict(u);for(const e of d.getKeys())"AP"!==e&&f.set(e,d.getRaw(e));if(void 0!==n){f.set("F",n);if(null===l&&!h){const e=d.getRaw("AP");e&&f.set("AP",e)}}const g={path:this.data.fieldName,value:s},p=this.setValue(f,Array.isArray(s)?s.map(stringToAsciiOrUTF16BE):stringToAsciiOrUTF16BE(s),u,r);this.amendSavedDict(a,p||f);const m=this._getMKDict(o);m&&f.set("MK",m);r.put(this.ref,{data:f,xfa:g,needAppearances:h});if(null!==l){const e=u.getNewTemporaryRef(),t=new Dict(u);f.set("AP",t);t.set("N",e);const i=this._getSaveFieldResources(u),n=new StringStream(l),s=n.dict=new Dict(u);s.setIfName("Subtype","Form");s.set("Resources",i);const c=o%180==0?[0,0,this.width,this.height]:[0,0,this.height,this.width];s.set("BBox",c);const h=this.getRotationMatrix(a);h!==fa&&s.set("Matrix",h);r.put(e,{data:n,xfa:null,needAppearances:!1})}f.set("M",`D:${getModificationDate()}`)}async _getAppearance(e,t,a,r){if(this.data.password)return null;const n=r?.get(this.data.id);let s,o;if(n){s=n.formattedValue||n.value;o=n.rotation}if(void 0===o&&void 0===s&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;const l=this.getBorderAndBackgroundAppearances(r);if(void 0===s){s=this.data.fieldValue;if(!s)return`/Tx BMC q ${l}Q EMC`}Array.isArray(s)&&1===s.length&&(s=s[0]);assert("string"==typeof s,"Expected `value` to be a string.");s=s.trimEnd();if(this.data.combo){const e=this.data.options.find(({exportValue:e})=>s===e);s=e?.displayValue||s}if(""===s)return`/Tx BMC q ${l}Q EMC`;void 0===o&&(o=this.rotation);let h,u=-1;if(this.data.multiLine){h=s.split(/\r\n?|\n/).map(e=>e.normalize("NFC"));u=h.length}else h=[s.replace(/\r\n?|\n/,"").normalize("NFC")];let{width:d,height:f}=this;90!==o&&270!==o||([d,f]=[f,d]);this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g"));let g,p,m,b=await WidgetAnnotation._getFontData(e,t,this.data.defaultAppearanceData,this._fieldResources.mergedResources);const y=[];let w=!1;for(const e of h){const t=b.encodeString(e);t.length>1&&(w=!0);y.push(t.join(""))}if(w&&a&c)return{needAppearances:!0};if(w&&this._isOffscreenCanvasSupported){const a=this.data.comb?"monospace":"sans-serif",r=new FakeUnicodeFont(e.xref,a),i=r.createFontResources(h.join("")),n=i.getRaw("Font");if(this._fieldResources.mergedResources.has("Font")){const e=this._fieldResources.mergedResources.get("Font");for(const t of n.getKeys())e.set(t,n.getRaw(t))}else this._fieldResources.mergedResources.set("Font",n);const o=r.fontName.name;b=await WidgetAnnotation._getFontData(e,t,{fontName:o,fontSize:0},i);for(let e=0,t=y.length;e2)return`/Tx BMC q ${l}BT `+g+` 1 0 0 1 ${numberToString(2)} ${numberToString(C)} Tm (${escapeString(y[0])}) Tj ET Q EMC`;return`/Tx BMC q ${l}BT `+g+` 1 0 0 1 0 0 Tm ${this._renderText(y[0],b,p,d,k,{shift:0},2,C)} ET Q EMC`}static async _getFontData(e,t,a,r){const i=new OperatorList,n={font:null,clone(){return this}},{fontName:s,fontSize:o}=a;await e.handleSetFont(r,[s&&Name.get(s),o],null,i,t,n,null);return n.font}_getTextWidth(e,t){return Math.sumPrecise(t.charsToGlyphs(e).map(e=>e.width))/1e3}_computeFontSize(e,t,r,i,n){let{fontSize:s}=this.data.defaultAppearanceData,o=(s||12)*a,c=Math.round(e/o);if(!s){const roundWithTwoDigits=e=>Math.floor(100*e)/100;if(-1===n){const n=this._getTextWidth(r,i);s=roundWithTwoDigits(Math.min(e/a,t/n));c=1}else{const l=r.split(/\r\n?|\n/),h=[];for(const e of l){const t=i.encodeString(e).join(""),a=i.charsToGlyphs(t),r=i.getCharPositions(t);h.push({line:t,glyphs:a,positions:r})}const isTooBig=a=>{let r=0;for(const n of h){r+=this._splitLine(null,i,a,t,n).length*a;if(r>e)return!0}return!1};c=Math.max(c,n);for(;;){o=e/c;s=roundWithTwoDigits(o/a);if(!isTooBig(s))break;c++}}const{fontName:l,fontColor:h}=this.data.defaultAppearanceData;this._defaultAppearance=function createDefaultAppearance({fontSize:e,fontName:t,fontColor:a}){return`/${escapePDFName(t)} ${e} Tf ${getPdfColor(a,!0)}`}({fontSize:s,fontName:l,fontColor:h})}return[this._defaultAppearance,s,e/c]}_renderText(e,t,a,r,i,n,s,o){let c;if(1===i){c=(r-this._getTextWidth(e,t)*a)/2}else if(2===i){c=r-this._getTextWidth(e,t)*a-s}else c=s;const l=numberToString(c-n.shift);n.shift=c;return`${l} ${o=numberToString(o)} Td (${escapeString(e)}) Tj`}_getSaveFieldResources(e){const{localResources:t,appearanceResources:a,acroFormResources:r}=this._fieldResources,i=this.data.defaultAppearanceData?.fontName;if(!i)return t||Dict.empty;for(const e of[t,a])if(e instanceof Dict){const t=e.get("Font");if(t instanceof Dict&&t.has(i))return e}if(r instanceof Dict){const a=r.get("Font");if(a instanceof Dict&&a.has(i)){const r=new Dict(e);r.set(i,a.getRaw(i));const n=new Dict(e);n.set("Font",r);return Dict.merge({xref:e,dictArray:[n,t],mergeSubDicts:!0})}}return t||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t}=e;if(t.has("PMD")){this.flags|=E;this.data.hidden=!0;warn("Barcodes are not supported")}this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML;this._hasText=!0;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let a=getInheritableProperty({dict:t,key:"Q"});(!Number.isInteger(a)||a<0||a>2)&&(a=null);this.data.textAlignment=a;let r=getInheritableProperty({dict:t,key:"MaxLen"});(!Number.isInteger(r)||r<0)&&(r=0);this.data.maxLen=r;this.data.multiLine=this.hasFieldFlag(W);this.data.comb=this.hasFieldFlag(Z)&&!this.data.multiLine&&!this.data.password&&!this.hasFieldFlag(K)&&0!==this.data.maxLen;this.data.doNotScroll=this.hasFieldFlag(Y);const{data:{actions:i}}=this;if(!i)return;const n=/^AF(Date|Time)_(?:Keystroke|Format)(?:Ex)?\(['"]?([^'"]+)['"]?\);$/;let s=!1;(1===i.Format?.length&&1===i.Keystroke?.length&&n.test(i.Format[0])&&n.test(i.Keystroke[0])||0===i.Format?.length&&1===i.Keystroke?.length&&n.test(i.Keystroke[0])||0===i.Keystroke?.length&&1===i.Format?.length&&n.test(i.Format[0]))&&(s=!0);const o=[];i.Format&&o.push(...i.Format);i.Keystroke&&o.push(...i.Keystroke);if(s){delete i.Keystroke;i.Format=o}for(const e of o){const t=e.match(n);if(!t)continue;const a="Date"===t[1];let r=t[2];const i=parseInt(r,10);isNaN(i)||Math.floor(Math.log10(i))+1!==t[2].length||(r=(a?kn:Cn)[i]??r);this.data.datetimeFormat=r;if(!s)break;if(a){if(/HH|MM|ss|h/.test(r)){this.data.datetimeType="datetime-local";this.data.timeStep=/ss/.test(r)?1:60}else this.data.datetimeType="date";break}this.data.datetimeType="time";this.data.timeStep=/ss/.test(r)?1:60;break}}get hasTextContent(){return!!this.appearance&&!this._needAppearances}_getCombAppearance(e,t,a,r,i,n,s,o,c,l,h){const u=i/this.data.maxLen,d=this.getBorderAndBackgroundAppearances(h),f=[],g=t.getCharPositions(a);for(const[e,t]of g)f.push(`(${escapeString(a.substring(e,t))}) Tj`);const p=f.join(` ${numberToString(u)} 0 Td `);return`/Tx BMC q ${d}BT `+e+` 1 0 0 1 ${numberToString(s)} ${numberToString(o+c)} Tm ${p} ET Q EMC`}_getMultilineAppearance(e,t,a,r,i,n,s,o,c,l,h,u){const d=[],f=i-2*o,g={shift:0};for(let e=0,n=t.length;er){c.push(e.substring(d,a));d=a;f=p;l=-1;u=-1}else{f+=p;l=a;h=i;u=t}else if(f+p>r)if(-1!==l){c.push(e.substring(d,h));d=h;t=u+1;l=-1;f=0}else{c.push(e.substring(d,a));d=a;f=p}else f+=p}dt?`\\${t}`:"\\s+");new RegExp(`^\\s*${n}\\s*$`).test(this.data.fieldValue)&&(this.data.textContent=this.data.fieldValue.split("\n"))}getFieldObject(){return{id:this.data.id,value:this.data.fieldValue,defaultValue:this.data.defaultFieldValue||"",multiline:this.data.multiLine,password:this.data.password,charLimit:this.data.maxLen,comb:this.data.comb,editable:!this.data.readOnly,hidden:this.data.hidden,name:this.data.fieldName,rect:this.data.rect,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,datetimeFormat:this.data.datetimeFormat,hasDatetimeHTML:!!this.data.datetimeType,type:"text"}}}class ButtonWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);this.checkedAppearance=null;this.uncheckedAppearance=null;const t=this.hasFieldFlag(z),a=this.hasFieldFlag($);this.data.checkBox=!t&&!a;this.data.radioButton=t&&!a;this.data.pushButton=a;this.data.isTooltipOnly=!1;if(this.data.checkBox)this._processCheckBox(e);else if(this.data.radioButton)this._processRadioButton(e);else if(this.data.pushButton){this.data.hasOwnCanvas=!0;this.data.noHTML=!1;this._processPushButton(e)}else warn("Invalid field flags for button widget annotation")}async getOperatorList(e,t,a,r){if(this.data.pushButton)return super.getOperatorList(e,t,a,!1,r);let i=null,n=null;if(r){const e=r.get(this.data.id);i=e?e.value:null;n=e?e.rotation:null}if(null===i&&this.appearance)return super.getOperatorList(e,t,a,r);null==i&&(i=this.data.checkBox?this.data.fieldValue===this.data.exportValue:this.data.fieldValue===this.data.buttonValue);const s=i?this.checkedAppearance:this.uncheckedAppearance;if(s){const i=this.appearance,o=lookupMatrix(s.dict.getArray("Matrix"),fa);n&&s.dict.set("Matrix",this.getRotationMatrix(r));this.appearance=s;const c=super.getOperatorList(e,t,a,r);this.appearance=i;s.dict.set("Matrix",o);return c}return{opList:new OperatorList,separateForm:!1,separateCanvas:!1}}async save(e,t,a,r){this.data.checkBox?this._saveCheckbox(e,t,a,r):this.data.radioButton&&this._saveRadioButton(e,t,a,r)}async _saveCheckbox(e,t,a,r){if(!a)return;const i=a.get(this.data.id),n=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,o=i?.value;if(void 0===s&&void 0===n){if(void 0===o)return;if(this.data.fieldValue===this.data.exportValue===o)return}let c=e.xref.fetchIfRef(this.ref);if(!(c instanceof Dict))return;c=c.clone();void 0===s&&(s=this.rotation);void 0===o&&(o=this.data.fieldValue===this.data.exportValue);const l={path:this.data.fieldName,value:o?this.data.exportValue:""},h=Name.get(o?this.data.exportValue:"Off");this.setValue(c,h,e.xref,r);c.set("AS",h);c.set("M",`D:${getModificationDate()}`);void 0!==n&&c.set("F",n);const u=this._getMKDict(s);u&&c.set("MK",u);r.put(this.ref,{data:c,xfa:l,needAppearances:!1})}async _saveRadioButton(e,t,a,r){if(!a)return;const i=a.get(this.data.id),n=this._buildFlags(i?.noView,i?.noPrint);let s=i?.rotation,o=i?.value;if(void 0===s&&void 0===n){if(void 0===o)return;if(this.data.fieldValue===this.data.buttonValue===o)return}let c=e.xref.fetchIfRef(this.ref);if(!(c instanceof Dict))return;c=c.clone();void 0===o&&(o=this.data.fieldValue===this.data.buttonValue);void 0===s&&(s=this.rotation);const l={path:this.data.fieldName,value:o?this.data.buttonValue:""},h=Name.get(o?this.data.buttonValue:"Off");o&&this.setValue(c,h,e.xref,r);c.set("AS",h);c.set("M",`D:${getModificationDate()}`);void 0!==n&&c.set("F",n);const u=this._getMKDict(s);u&&c.set("MK",u);r.put(this.ref,{data:c,xfa:l,needAppearances:!1})}_getDefaultCheckedAppearance(e,t){const{width:a,height:r}=this,i=[0,0,a,r],n=.8*Math.min(a,r);let s,o;if("check"===t){s={width:.755*n,height:.705*n};o="3"}else if("disc"===t){s={width:.791*n,height:.705*n};o="l"}else unreachable(`_getDefaultCheckedAppearance - unsupported type: ${t}`);const c=`q BT /PdfJsZaDb ${n} Tf 0 g ${numberToString((a-s.width)/2)} ${numberToString((r-s.height)/2)} Td (${o}) Tj ET Q`,l=new Dict(e.xref);l.set("FormType",1);l.setIfName("Subtype","Form");l.setIfName("Type","XObject");l.set("BBox",i);l.set("Matrix",[1,0,0,1,0,0]);l.set("Length",c.length);const h=new Dict(e.xref),u=new Dict(e.xref);u.set("PdfJsZaDb",this.fallbackFontDict);h.set("Font",u);l.set("Resources",h);this.checkedAppearance=new StringStream(c);this.checkedAppearance.dict=l;this._streams.push(this.checkedAppearance)}_processCheckBox(e){const t=e.dict.get("AP");if(!(t instanceof Dict))return;const a=t.get("N");if(!(a instanceof Dict))return;const r=this._decodeFormValue(e.dict.get("AS"));"string"==typeof r&&(this.data.fieldValue=r);const i=null!==this.data.fieldValue&&"Off"!==this.data.fieldValue?this.data.fieldValue:"Yes",n=this._decodeFormValue(a.getKeys());if(0===n.length)n.push("Off",i);else if(1===n.length)"Off"===n[0]?n.push(i):n.unshift("Off");else if(n.includes(i)){n.length=0;n.push("Off",i)}else{const e=n.find(e=>"Off"!==e);n.length=0;n.push("Off",e)}n.includes(this.data.fieldValue)||(this.data.fieldValue="Off");this.data.exportValue=n[1];const s=a.get(this.data.exportValue);this.checkedAppearance=s instanceof BaseStream?s:null;const o=a.get("Off");this.uncheckedAppearance=o instanceof BaseStream?o:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"check");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processRadioButton(e){this.data.buttonValue=null;const t=e.dict.get("Parent");if(t instanceof Dict){this.parent=e.dict.getRaw("Parent");const a=t.get("V");a instanceof Name&&(this.data.fieldValue=this._decodeFormValue(a))}const a=e.dict.get("AP");if(!(a instanceof Dict))return;const r=a.get("N");if(!(r instanceof Dict))return;for(const e of r.getKeys())if("Off"!==e){this.data.buttonValue=this._decodeFormValue(e);break}const i=r.get(this.data.buttonValue);this.checkedAppearance=i instanceof BaseStream?i:null;const n=r.get("Off");this.uncheckedAppearance=n instanceof BaseStream?n:null;this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(e,"disc");this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance);this._fallbackFontDict=this.fallbackFontDict;null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}_processPushButton(e){const{dict:t,annotationGlobals:a}=e;if(t.has("A")||t.has("AA")||this.data.alternativeText){this.data.isTooltipOnly=!t.has("A")&&!t.has("AA");Catalog.parseDestDictionary({destDict:t,resultObj:this.data,docBaseUrl:a.baseUrl,docAttachments:a.attachments})}else warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let e,t="button";if(this.data.checkBox){t="checkbox";e=this.data.exportValue}else if(this.data.radioButton){t="radiobutton";e=this.data.buttonValue}return{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:e,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:t}}get fallbackFontDict(){const e=new Dict;e.setIfName("BaseFont","ZapfDingbats");e.setIfName("Type","FallbackType");e.setIfName("Subtype","FallbackType");e.setIfName("Encoding","ZapfDingbatsEncoding");return shadow(this,"fallbackFontDict",e)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.indices=t.getArray("I");this.hasIndices=Array.isArray(this.indices)&&this.indices.length>0;this.data.options=[];const r=getInheritableProperty({dict:t,key:"Opt"});if(Array.isArray(r))for(let e=0,t=r.length;e=0&&t0&&(this.data.options=this.data.fieldValue.map(e=>({exportValue:e,displayValue:e})));this.data.combo=this.hasFieldFlag(V);this.data.multiSelect=this.hasFieldFlag(J);this._hasText=!0}getFieldObject(){const e=this.data.combo?"combobox":"listbox",t=this.data.fieldValue.length>0?this.data.fieldValue[0]:null;return{id:this.data.id,value:t,defaultValue:this.data.defaultFieldValue,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,numItems:this.data.fieldValue.length,multipleSelection:this.data.multiSelect,hidden:this.data.hidden,actions:this.data.actions,items:this.data.options,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:e}}amendSavedDict(e,t){if(!this.hasIndices)return;let a=e?.get(this.data.id)?.value;Array.isArray(a)||(a=[a]);const r=[],{options:i}=this.data;for(let e=0,t=0,n=i.length;ea){a=r;t=e}}[f,g]=this._computeFontSize(e,c-4,t,d,-1)}const p=g*a,m=(p-g)/2,b=Math.floor(l/p);let y=0;if(u.length>0){const e=Math.min(...u),t=Math.max(...u);y=Math.max(0,t-b+1);y>e&&(y=e)}const w=Math.min(y+b+1,h),x=["/Tx BMC q",`1 1 ${c} ${l} re W n`];if(u.length){x.push("0.600006 0.756866 0.854904 rg");for(const e of u)y<=e&&ee.trimEnd());const{coords:e,bbox:t,matrix:r}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,a);this.data.textPosition=this._transformPoint(e,t,r)}if(this._isOffscreenCanvasSupported){const i=e.dict.get("CA"),n=new FakeUnicodeFont(r,"sans-serif");this.appearance=n.createAppearance(this._contents.str,this.rectangle,this.rotation,a,t,i);this._streams.push(this.appearance)}else warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,date:n,fontSize:s,oldAnnotation:o,rect:c,rotation:l,user:h,value:u}=e,d=o||new Dict(t);d.setIfNotExists("Type",Name.get("Annot"));d.setIfNotExists("Subtype",Name.get("FreeText"));d.set(o?"M":"CreationDate",`D:${getModificationDate(n)}`);o&&d.delete("RC");d.setIfArray("Rect",c);const f=`/Helv ${s} Tf ${getPdfColor(i,!0)}`;d.set("DA",f);d.setIfDefined("Contents",stringToAsciiOrUTF16BE(u));d.setIfNotExists("F",4);d.setIfNotExists("Border",[0,0,0]);d.setIfNumber("Rotate",l);d.setIfDefined("T",stringToAsciiOrUTF16BE(h));if(a||r){const e=new Dict(t);d.set("AP",e);e.set("N",a||r)}return d}static async createNewAppearanceStream(e,t,r){const{baseFontRef:i,evaluator:n,task:s}=r,{color:o,fontSize:c,rect:l,rotation:h,value:u}=e;if(!o)return null;const d=new Dict(t),f=new Dict(t);if(i)f.set("Helv",i);else{const e=new Dict(t);e.setIfName("BaseFont","Helvetica");e.setIfName("Type","Font");e.setIfName("Subtype","Type1");e.setIfName("Encoding","WinAnsiEncoding");f.set("Helv",e)}d.set("Font",f);const g=await WidgetAnnotation._getFontData(n,s,{fontName:"Helv",fontSize:c},d),[p,m,b,y]=l;let w=b-p,x=y-m;h%180!=0&&([w,x]=[x,w]);const S=u.split("\n"),k=c/1e3;let C=-1/0;const v=[];for(let e of S){const t=g.encodeString(e);if(t.length>1)return null;e=t.join("");v.push(e);let a=0;const r=g.charsToGlyphs(e);for(const e of r)a+=e.width*k;C=Math.max(C,a)}let F=1;C>w&&(F=w/C);let T=1;const O=a*c,M=1*c,D=O*S.length;D>x&&(T=x/D);const R=c*Math.min(F,T);let N,E,L;switch(h){case 0:L=[1,0,0,1];E=[l[0],l[1],w,x];N=[l[0],l[3]-M];break;case 90:L=[0,1,-1,0];E=[l[1],-l[2],w,x];N=[l[1],-l[0]-M];break;case 180:L=[-1,0,0,-1];E=[-l[2],-l[3],w,x];N=[-l[2],-l[1]-M];break;case 270:L=[0,-1,1,0];E=[-l[3],l[0],w,x];N=[-l[3],l[2]-M]}const _=["q",`${L.join(" ")} 0 0 cm`,`${E.join(" ")} re W n`,"BT",`${getPdfColor(o,!0)}`,`0 Tc /Helv ${numberToString(R)} Tf`];_.push(`${N.join(" ")} Td (${escapeString(v[0])}) Tj`);const U=numberToString(O);for(let e=1,t=v.length;e{e.push(`${r[0]} ${r[1]} m`,`${r[2]} ${r[3]} l`,"S");return[t[0]-o,t[7]-o,t[2]+o,t[3]+o]}})}}}class SquareAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=M.SQUARE;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA"),i=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),n=i?r:null;if(0===this.borderStyle.width&&!i)return;this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:i,strokeAlpha:r,fillAlpha:n,pointsCallback:(e,t)=>{const a=t[4]+this.borderStyle.width/2,r=t[5]+this.borderStyle.width/2,n=t[6]-t[4]-this.borderStyle.width,s=t[3]-t[7]-this.borderStyle.width;e.push(`${a} ${r} ${n} ${s} re`);i?e.push("B"):e.push("S");return[t[0],t[7],t[2],t[3]]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=M.CIRCLE;if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA"),i=getPdfColorArray(getRgbColor(t.getArray("IC"),null)),n=i?r:null;if(0===this.borderStyle.width&&!i)return;const s=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:a,extra:`${this.borderStyle.width} w`,strokeColor:e,fillColor:i,strokeAlpha:r,fillAlpha:n,pointsCallback:(e,t)=>{const a=t[0]+this.borderStyle.width/2,r=t[1]-this.borderStyle.width/2,n=t[6]-this.borderStyle.width/2,o=t[7]+this.borderStyle.width/2,c=a+(n-a)/2,l=r+(o-r)/2,h=(n-a)/2*s,u=(o-r)/2*s;e.push(`${c} ${o} m`,`${c+h} ${o} ${n} ${l+u} ${n} ${l} c`,`${n} ${l-u} ${c+h} ${r} ${c} ${r} c`,`${c-h} ${r} ${a} ${l-u} ${a} ${l} c`,`${a} ${l+u} ${c-h} ${o} ${c} ${o} c`,"h");i?e.push("B"):e.push("S");return[t[0],t[7],t[2],t[3]]}})}}}class PolylineAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=M.POLYLINE;this.data.hasOwnCanvas=this.data.noRotate;this.data.noHTML=!1;this.data.vertices=null;if(!(this instanceof PolygonAnnotation)){this.setLineEndings(t.getArray("LE"));this.data.lineEndings=this.lineEndings}const r=t.getArray("Vertices");if(!isNumberArray(r,null))return;const i=this.data.vertices=Float32Array.from(r);if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA");let n,s=getRgbColor(t.getArray("IC"),null);s&&(s=getPdfColorArray(s));n=s?this.color?s.every((t,a)=>t===e[a])?"f":"B":"f":"S";const o=this.borderStyle.width||1,c=2*o,l=[1/0,1/0,-1/0,-1/0];for(let e=0,t=i.length;e{for(let t=0,a=i.length;t{for(const t of this.data.inkLists){for(let a=0,r=t.length;a0){const e=new Dict(t);g.set("BS",e);e.set("W",d)}g.setIfArray("C",getPdfColorArray(n));g.setIfNumber("CA",o);if(r||a){const e=new Dict(t);g.set("AP",e);e.set("N",a||r)}return g}static async createNewAppearanceStream(e,t,a){if(e.outlines)return this.createNewAppearanceStreamForHighlight(e,t,a);const{color:r,rect:i,paths:n,thickness:s,opacity:o}=e;if(!r)return null;const c=[`${s} w 1 J 1 j`,`${getPdfColor(r,!1)}`];1!==o&&c.push("/R0 gs");for(const e of n.lines){c.push(`${numberToString(e[4])} ${numberToString(e[5])} m`);for(let t=6,a=e.length;t{e.push(`${t[0]} ${t[1]} m`,`${t[2]} ${t[3]} l`,`${t[6]} ${t[7]} l`,`${t[4]} ${t[5]} l`,"f");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}static createNewDict(e,t,{apRef:a,ap:r}){const{color:i,date:n,oldAnnotation:s,opacity:o,rect:c,rotation:l,user:h,quadPoints:u}=e,d=s||new Dict(t);d.setIfNotExists("Type",Name.get("Annot"));d.setIfNotExists("Subtype",Name.get("Highlight"));d.set(s?"M":"CreationDate",`D:${getModificationDate(n)}`);d.setIfArray("Rect",c);d.setIfNotExists("F",4);d.setIfNotExists("Border",[0,0,0]);d.setIfNumber("Rotate",l);d.setIfArray("QuadPoints",u);d.setIfArray("C",getPdfColorArray(i));d.setIfNumber("CA",o);d.setIfDefined("T",stringToAsciiOrUTF16BE(h));if(a||r){const e=new Dict(t);d.set("AP",e);e.set("N",a||r)}return d}static async createNewAppearanceStream(e,t,a){const{color:r,rect:i,outlines:n,opacity:s}=e;if(!r)return null;const o=[`${getPdfColor(r,!0)}`,"/R0 gs"],c=[];for(const e of n){c.length=0;c.push(`${numberToString(e[0])} ${numberToString(e[1])} m`);for(let t=2,a=e.length;t{e.push(`${t[4]} ${t[5]+1.3} m`,`${t[6]} ${t[7]+1.3} l`,"S");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class SquigglyAnnotation extends MarkupAnnotation{constructor(e){super(e);const{dict:t,xref:a}=e;this.data.annotationType=M.SQUIGGLY;if(this.data.quadPoints=getQuadPoints(t,null)){if(!this.appearance){const e=getPdfColorArray(this.color,[0,0,0]),r=t.get("CA");this._setDefaultAppearance({xref:a,extra:"[] 0 d 1 w",strokeColor:e,strokeAlpha:r,pointsCallback:(e,t)=>{const a=(t[1]-t[5])/6;let r=a,i=t[4];const n=t[5],s=t[6];e.push(`${i} ${n+r} m`);do{i+=2;r=0===r?a:0;e.push(`${i} ${n+r} l`)}while(i{e.push((t[0]+t[4])/2+" "+(t[1]+t[5])/2+" m",(t[2]+t[6])/2+" "+(t[3]+t[7])/2+" l","S");return[t[0],t[7],t[2],t[3]]}})}}else this.data.popupRef=null}get overlaysTextContent(){return!0}}class StampAnnotation extends MarkupAnnotation{#Re=null;constructor(e){super(e);this.data.annotationType=M.STAMP;this.data.hasOwnCanvas=this.data.noRotate;this.data.isEditable=!this.data.noHTML;this.data.noHTML=!1}mustBeViewedWhenEditing(e,t=null){if(e){if(!this.data.isEditable)return!0;this.#Re??=this.data.hasOwnCanvas;this.data.hasOwnCanvas=!0;return!0}if(null!==this.#Re){this.data.hasOwnCanvas=this.#Re;this.#Re=null}return!t?.has(this.data.id)}static async createImage(e,t){const{width:a,height:r}=e,i=new OffscreenCanvas(a,r),n=i.getContext("2d",{alpha:!0});n.drawImage(e,0,0);const s=n.getImageData(0,0,a,r).data,o=new Uint32Array(s.buffer),c=o.some(FeatureTest.isLittleEndian?e=>e>>>24!=255:e=>!!(255&~e));if(c){n.fillStyle="white";n.fillRect(0,0,a,r);n.drawImage(e,0,0)}const l=i.convertToBlob({type:"image/jpeg",quality:1}).then(e=>e.arrayBuffer()),h=Name.get("XObject"),u=Name.get("Image"),d=new Dict(t);d.set("Type",h);d.set("Subtype",u);d.set("BitsPerComponent",8);d.setIfName("ColorSpace","DeviceRGB");d.setIfName("Filter","DCTDecode");d.set("BBox",[0,0,a,r]);d.set("Width",a);d.set("Height",r);let f=null;if(c){const e=new Uint8Array(o.length);if(FeatureTest.isLittleEndian)for(let t=0,a=o.length;t>>24;else for(let t=0,a=o.length;t=0&&n<=1?n:null}}const ac={get r(){return shadow(this,"r",new Uint8Array([7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21]))},get k(){return shadow(this,"k",new Int32Array([-680876936,-389564586,606105819,-1044525330,-176418897,1200080426,-1473231341,-45705983,1770035416,-1958414417,-42063,-1990404162,1804603682,-40341101,-1502002290,1236535329,-165796510,-1069501632,643717713,-373897302,-701558691,38016083,-660478335,-405537848,568446438,-1019803690,-187363961,1163531501,-1444681467,-51403784,1735328473,-1926607734,-378558,-2022574463,1839030562,-35309556,-1530992060,1272893353,-155497632,-1094730640,681279174,-358537222,-722521979,76029189,-640364487,-421815835,530742520,-995338651,-198630844,1126891415,-1416354905,-57434055,1700485571,-1894986606,-1051523,-2054922799,1873313359,-30611744,-1560198380,1309151649,-145523070,-1120210379,718787259,-343485551]))}};function calculateMD5(e,t,a){let r=1732584193,i=-271733879,n=-1732584194,s=271733878;const o=a+72&-64,c=new Uint8Array(o);let l,h;for(l=0;l>5&255;c[l++]=a>>13&255;c[l++]=a>>21&255;c[l++]=a>>>29&255;l+=3;const d=new Int32Array(16),{k:f,r:g}=ac;for(l=0;l>>32-n)|0;a=r}r=r+a|0;i=i+o|0;n=n+u|0;s=s+p|0}return new Uint8Array([255&r,r>>8&255,r>>16&255,r>>>24&255,255&i,i>>8&255,i>>16&255,i>>>24&255,255&n,n>>8&255,n>>16&255,n>>>24&255,255&s,s>>8&255,s>>16&255,s>>>24&255])}function decodeString(e){try{return stringToUTF8String(e)}catch(t){warn(`UTF-8 decoding failed: "${t}".`);return e}}class DatasetXMLParser extends SimpleXMLParser{constructor(e){super(e);this.node=null}onEndElement(e){const t=super.onEndElement(e);if(t&&"xfa:datasets"===e){this.node=t;throw new Error("Aborting DatasetXMLParser.")}}}class DatasetReader{constructor(e){if(e.datasets)this.node=new SimpleXMLParser({hasAttributes:!0}).parseFromString(e.datasets).documentElement;else{const t=new DatasetXMLParser({hasAttributes:!0});try{t.parseFromString(e["xdp:xdp"])}catch{}this.node=t.node}}getValue(e){if(!this.node||!e)return"";const t=this.node.searchNode(parseXFAPath(e),0);if(!t)return"";const a=t.firstChild;return"value"===a?.nodeName?t.children.map(e=>decodeString(e.textContent)):decodeString(t.textContent)}}class SingleIntersector{#Ee;minX=1/0;minY=1/0;maxX=-1/0;maxY=-1/0;#Pe=null;#Le=[];#_e=[];#Ue=-1;#je=!1;constructor(e){this.#Ee=e;const t=e.data.quadPoints;if(t){for(let e=0,a=t.length;e8&&(this.#Pe=t)}else[this.minX,this.minY,this.maxX,this.maxY]=e.data.rect}#Xe(e,t){if(this.minX>=e||this.maxX<=e||this.minY>=t||this.maxY<=t)return!1;const a=this.#Pe;if(!a)return!0;if(this.#Ue>=0){const r=this.#Ue;if(!(a[r]>=e||a[r+2]<=e||a[r+5]>=t||a[r+1]<=t))return!0;this.#Ue=-1}for(let r=0,i=a.length;r=e||a[r+2]<=e||a[r+5]>=t||a[r+1]<=t)){this.#Ue=r;return!0}return!1}addGlyph(e,t,a){if(!this.#Xe(e,t)){this.disableExtraChars();return!1}if(this.#_e.length>0){this.#Le.push(this.#_e.join(""));this.#_e.length=0}this.#Le.push(a);this.#je=!0;return!0}addExtraChar(e){this.#je&&this.#_e.push(e)}disableExtraChars(){if(this.#je){this.#je=!1;this.#_e.length=0}}setText(){this.#Ee.data.overlaidText=this.#Le.join("")}}const rc=64;class Intersector{#qe=[];#He=[];#We;#Ge;#ze;#$e;#Ve;#Ke;constructor(e){let t=1/0,a=1/0,r=-1/0,i=-1/0;const n=this.#qe;for(const s of e){if(!s.data.quadPoints&&!s.data.rect)continue;const e=new SingleIntersector(s);n.push(e);t=Math.min(t,e.minX);a=Math.min(a,e.minY);r=Math.max(r,e.maxX);i=Math.max(i,e.maxY)}this.#We=t;this.#ze=a;this.#Ge=r;this.#$e=i;this.#Ve=63/(r-t);this.#Ke=63/(i-a);for(const e of n){const t=this.#Je(e.minX,e.minY),a=this.#Je(e.maxX,e.maxY),r=(a-t)%rc,i=Math.floor((a-t)/rc);for(let a=t;a<=t+i*rc;a+=rc)for(let t=0;t<=r;t++){let r=this.#He[a+t];r||(this.#He[a+t]=r=[]);r.push(e)}}}#Je(e,t){return Math.floor((e-this.#We)*this.#Ve)+Math.floor((t-this.#ze)*this.#Ke)*rc}addGlyph(e,t,a,r){const i=e[4]+t/2,n=e[5]+a/2;if(ithis.#Ge||n>this.#$e)return;const s=this.#He[this.#Je(i,n)];if(s)for(const e of s)e.addGlyph(i,n,r)}addExtraChar(e){for(const t of this.#qe)t.addExtraChar(e)}setText(){for(const e of this.#qe)e.setText()}}class Word64{constructor(e,t){this.high=0|e;this.low=0|t}and(e){this.high&=e.high;this.low&=e.low}xor(e){this.high^=e.high;this.low^=e.low}shiftRight(e){if(e>=32){this.low=this.high>>>e-32|0;this.high=0}else{this.low=this.low>>>e|this.high<<32-e;this.high=this.high>>>e|0}}rotateRight(e){let t,a;if(32&e){a=this.low;t=this.high}else{t=this.low;a=this.high}e&=31;this.low=t>>>e|a<<32-e;this.high=a>>>e|t<<32-e}not(){this.high=~this.high;this.low=~this.low}add(e){const t=(this.low>>>0)+(e.low>>>0);let a=(this.high>>>0)+(e.high>>>0);t>4294967295&&(a+=1);this.low=0|t;this.high=0|a}copyTo(e,t){e[t]=this.high>>>24&255;e[t+1]=this.high>>16&255;e[t+2]=this.high>>8&255;e[t+3]=255&this.high;e[t+4]=this.low>>>24&255;e[t+5]=this.low>>16&255;e[t+6]=this.low>>8&255;e[t+7]=255&this.low}assign(e){this.high=e.high;this.low=e.low}}const ic={get k(){return shadow(this,"k",[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)])}};function ch(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.not();i.and(r);e.xor(i)}function maj(e,t,a,r,i){e.assign(t);e.and(a);i.assign(t);i.and(r);e.xor(i);i.assign(a);i.and(r);e.xor(i)}function sigma(e,t,a){e.assign(t);e.rotateRight(28);a.assign(t);a.rotateRight(34);e.xor(a);a.assign(t);a.rotateRight(39);e.xor(a)}function sigmaPrime(e,t,a){e.assign(t);e.rotateRight(14);a.assign(t);a.rotateRight(18);e.xor(a);a.assign(t);a.rotateRight(41);e.xor(a)}function littleSigma(e,t,a){e.assign(t);e.rotateRight(1);a.assign(t);a.rotateRight(8);e.xor(a);a.assign(t);a.shiftRight(7);e.xor(a)}function littleSigmaPrime(e,t,a){e.assign(t);e.rotateRight(19);a.assign(t);a.rotateRight(61);e.xor(a);a.assign(t);a.shiftRight(6);e.xor(a)}function calculateSHA512(e,t,a,r=!1){let i,n,s,o,c,l,h,u;if(r){i=new Word64(3418070365,3238371032);n=new Word64(1654270250,914150663);s=new Word64(2438529370,812702999);o=new Word64(355462360,4144912697);c=new Word64(1731405415,4290775857);l=new Word64(2394180231,1750603025);h=new Word64(3675008525,1694076839);u=new Word64(1203062813,3204075428)}else{i=new Word64(1779033703,4089235720);n=new Word64(3144134277,2227873595);s=new Word64(1013904242,4271175723);o=new Word64(2773480762,1595750129);c=new Word64(1359893119,2917565137);l=new Word64(2600822924,725511199);h=new Word64(528734635,4215389547);u=new Word64(1541459225,327033209)}const d=128*Math.ceil((a+17)/128),f=new Uint8Array(d);let g,p;for(g=0;g>>29&255;f[g++]=a>>21&255;f[g++]=a>>13&255;f[g++]=a>>5&255;f[g++]=a<<3&255;const b=new Array(80);for(g=0;g<80;g++)b[g]=new Word64(0,0);const{k:y}=ic;let w=new Word64(0,0),x=new Word64(0,0),S=new Word64(0,0),k=new Word64(0,0),C=new Word64(0,0),v=new Word64(0,0),F=new Word64(0,0),T=new Word64(0,0);const O=new Word64(0,0),M=new Word64(0,0),D=new Word64(0,0),R=new Word64(0,0);let N,E;for(g=0;g>>t|e<<32-t}function calculate_sha256_ch(e,t,a){return e&t^~e&a}function calculate_sha256_maj(e,t,a){return e&t^e&a^t&a}function calculate_sha256_sigma(e){return rotr(e,2)^rotr(e,13)^rotr(e,22)}function calculate_sha256_sigmaPrime(e){return rotr(e,6)^rotr(e,11)^rotr(e,25)}function calculate_sha256_littleSigma(e){return rotr(e,7)^rotr(e,18)^e>>>3}function calculate_sha256_littleSigmaPrime(e){return rotr(e,17)^rotr(e,19)^e>>>10}function calculateSHA256(e,t,a){let r=1779033703,i=3144134277,n=1013904242,s=2773480762,o=1359893119,c=2600822924,l=528734635,h=1541459225;const u=64*Math.ceil((a+9)/64),d=new Uint8Array(u);let f,g;for(f=0;f>>29&255;d[f++]=a>>21&255;d[f++]=a>>13&255;d[f++]=a>>5&255;d[f++]=a<<3&255;const m=new Uint32Array(64),{k:b}=nc;for(f=0;f>24&255,r>>16&255,r>>8&255,255&r,i>>24&255,i>>16&255,i>>8&255,255&i,n>>24&255,n>>16&255,n>>8&255,255&n,s>>24&255,s>>16&255,s>>8&255,255&s,o>>24&255,o>>16&255,o>>8&255,255&o,c>>24&255,c>>16&255,c>>8&255,255&c,l>>24&255,l>>16&255,l>>8&255,255&l,h>>24&255,h>>16&255,h>>8&255,255&h])}class DecryptStream extends DecodeStream{constructor(e,t,a){super(t);this.stream=e;this.dict=e.dict;this.decrypt=a;this.nextChunk=null;this.initialized=!1}readBlock(){let e;if(this.initialized)e=this.nextChunk;else{e=this.stream.getBytes(512);this.initialized=!0}if(!e?.length){this.eof=!0;return}this.nextChunk=this.stream.getBytes(512);const t=this.nextChunk?.length>0;e=(0,this.decrypt)(e,!t);const a=this.bufferLength,r=a+e.length;this.ensureBuffer(r).set(e,a);this.bufferLength=r}}class ARCFourCipher{constructor(e){this.a=0;this.b=0;const t=new Uint8Array(256),a=e.length;for(let e=0;e<256;++e)t[e]=e;for(let r=0,i=0;r<256;++r){const n=t[r];i=i+n+e[r%a]&255;t[r]=t[i];t[i]=n}this.s=t}encryptBlock(e){let t=this.a,a=this.b;const r=this.s,i=e.length,n=new Uint8Array(i);for(let s=0;st<128?t<<1:t<<1^27);constructor(){this.buffer=new Uint8Array(16);this.bufferPosition=0}_expandKey(e){unreachable("Cannot call `_expandKey` on the base class")}_decrypt(e,t){let a,r,i;const n=new Uint8Array(16);n.set(e);for(let e=0,a=this._keySize;e<16;++e,++a)n[e]^=t[a];for(let e=this._cyclesOfRepetition-1;e>=1;--e){a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e)n[e]=this._inv_s[n[e]];for(let a=0,r=16*e;a<16;++a,++r)n[a]^=t[r];for(let e=0;e<16;e+=4){const t=this._mix[n[e]],r=this._mix[n[e+1]],i=this._mix[n[e+2]],s=this._mix[n[e+3]];a=t^r>>>8^r<<24^i>>>16^i<<16^s>>>24^s<<8;n[e]=a>>>24&255;n[e+1]=a>>16&255;n[e+2]=a>>8&255;n[e+3]=255&a}}a=n[13];n[13]=n[9];n[9]=n[5];n[5]=n[1];n[1]=a;a=n[14];r=n[10];n[14]=n[6];n[10]=n[2];n[6]=a;n[2]=r;a=n[15];r=n[11];i=n[7];n[15]=n[3];n[11]=a;n[7]=r;n[3]=i;for(let e=0;e<16;++e){n[e]=this._inv_s[n[e]];n[e]^=t[e]}return n}_encrypt(e,t){const a=this._s;let r,i,n;const s=new Uint8Array(16);s.set(e);for(let e=0;e<16;++e)s[e]^=t[e];for(let e=1;e=r;--a)if(e[a]!==t){t=0;break}o-=t;n[n.length-1]=e.subarray(0,16-t)}}const c=new Uint8Array(o);for(let e=0,t=0,a=n.length;e=256&&(o=255&(27^o))}for(let t=0;t<4;++t){a[e]=r^=a[e-32];e++;a[e]=i^=a[e-32];e++;a[e]=n^=a[e-32];e++;a[e]=s^=a[e-32];e++}}return a}}class PDFBase{_hash(e,t,a){unreachable("Abstract method `_hash` called")}checkOwnerPassword(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);return isArrayEqual(this._hash(e,i,a),r)}checkUserPassword(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);return isArrayEqual(this._hash(e,r,[]),a)}getOwnerKey(e,t,a,r){const i=new Uint8Array(e.length+56);i.set(e,0);i.set(t,e.length);i.set(a,e.length+t.length);const n=this._hash(e,i,a);return new AES256Cipher(n).decryptBlock(r,!1,new Uint8Array(16))}getUserKey(e,t,a){const r=new Uint8Array(e.length+8);r.set(e,0);r.set(t,e.length);const i=this._hash(e,r,[]);return new AES256Cipher(i).decryptBlock(a,!1,new Uint8Array(16))}}class PDF17 extends PDFBase{_hash(e,t,a){return calculateSHA256(t,0,t.length)}}class PDF20 extends PDFBase{_hash(e,t,a){let r=calculateSHA256(t,0,t.length).subarray(0,32),i=[0],n=0;for(;n<64||i.at(-1)>n-32;){const t=e.length+r.length+a.length,s=new Uint8Array(t);let o=0;s.set(e,o);o+=e.length;s.set(r,o);o+=r.length;s.set(a,o);const c=new Uint8Array(64*t);for(let e=0,a=0;e<64;e++,a+=t)c.set(s,a);i=new AES128Cipher(r.subarray(0,16)).encrypt(c,r.subarray(16,32));const l=Math.sumPrecise(i.slice(0,16))%3;0===l?r=calculateSHA256(i,0,i.length):1===l?r=calculateSHA384(i,0,i.length):2===l&&(r=calculateSHA512(i,0,i.length));n++}return r.subarray(0,32)}}class CipherTransform{constructor(e,t){this.StringCipherConstructor=e;this.StreamCipherConstructor=t}createStream(e,t){const a=new this.StreamCipherConstructor;return new DecryptStream(e,t,function cipherTransformDecryptStream(e,t){return a.decryptBlock(e,t)})}decryptString(e){const t=new this.StringCipherConstructor;let a=stringToBytes(e);a=t.decryptBlock(a,!0);return bytesToString(a)}encryptString(e){const t=new this.StringCipherConstructor;if(t instanceof AESBaseCipher){const a=16-e.length%16;e+=String.fromCharCode(a).repeat(a);const r=new Uint8Array(16);crypto.getRandomValues(r);let i=stringToBytes(e);i=t.encrypt(i,r);const n=new Uint8Array(16+i.length);n.set(r);n.set(i,16);return bytesToString(n)}let a=stringToBytes(e);a=t.encrypt(a);return bytesToString(a)}}class CipherTransformFactory{static get _defaultPasswordBytes(){return shadow(this,"_defaultPasswordBytes",new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]))}#Ye(e,t,a,r,i,n,s,o,c,l,h,u){if(t){const e=Math.min(127,t.length);t=t.subarray(0,e)}else t=[];const d=6===e?new PDF20:new PDF17;return d.checkUserPassword(t,o,s)?d.getUserKey(t,c,h):t.length&&d.checkOwnerPassword(t,r,n,a)?d.getOwnerKey(t,i,n,l):null}#Ze(e,t,a,r,i,n,s,o){const c=40+a.length+e.length,l=new Uint8Array(c);let h,u,d=0;if(t){u=Math.min(32,t.length);for(;d>8&255;l[d++]=i>>16&255;l[d++]=i>>>24&255;l.set(e,d);d+=e.length;if(n>=4&&!o){l.fill(255,d,d+4);d+=4}let f=calculateMD5(l,0,d);const g=s>>3;if(n>=3)for(h=0;h<50;++h)f=calculateMD5(f,0,g);const p=f.subarray(0,g);let m,b;if(n>=3){d=0;l.set(CipherTransformFactory._defaultPasswordBytes,d);d+=32;l.set(e,d);d+=e.length;m=new ARCFourCipher(p);b=m.encryptBlock(calculateMD5(l,0,d));u=p.length;const t=new Uint8Array(u);for(h=1;h<=19;++h){for(let e=0;er[t]===e)?p:null}#Qe(e,t,a,r){const i=new Uint8Array(32);let n=0;const s=Math.min(32,e.length);for(;n>3;if(a>=3)for(o=0;o<50;++o)c=calculateMD5(c,0,c.length);let h,u;if(a>=3){u=t;const e=new Uint8Array(l);for(o=19;o>=0;o--){for(let t=0;t>8&255;n[s++]=e>>16&255;n[s++]=255&t;n[s++]=t>>8&255;if(r){n[s++]=115;n[s++]=65;n[s++]=108;n[s++]=84}return calculateMD5(n,0,s).subarray(0,Math.min(i+5,16))}#tt(e,t,a,r,i){if(!(t instanceof Name))throw new FormatError("Invalid crypt filter name.");const n=this,s=e.get(t.name),o=s?.get("CFM");if(!o||"None"===o.name)return function(){return new NullCipher};if("V2"===o.name)return function(){return new ARCFourCipher(n.#et(a,r,i,!1))};if("AESV2"===o.name)return function(){return new AES128Cipher(n.#et(a,r,i,!0))};if("AESV3"===o.name)return function(){return new AES256Cipher(i)};throw new FormatError("Unknown crypto method")}constructor(e,t,a){const r=e.get("Filter");if(!isName(r,"Standard"))throw new FormatError("unknown encryption method");this.filterName=r.name;this.dict=e;const i=e.get("V");if(!Number.isInteger(i)||1!==i&&2!==i&&4!==i&&5!==i)throw new FormatError("unsupported encryption algorithm");this.algorithm=i;let n=e.get("Length");if(!n)if(i<=3)n=40;else{const t=e.get("CF"),a=e.get("StmF");if(t instanceof Dict&&a instanceof Name){t.suppressEncryption=!0;const e=t.get(a.name);n=e?.get("Length")||128;n<40&&(n<<=3)}}if(!Number.isInteger(n)||n<40||n%8!=0)throw new FormatError("invalid key length");const s=stringToBytes(e.get("O")),o=stringToBytes(e.get("U")),c=s.subarray(0,32),l=o.subarray(0,32),h=e.get("P"),u=e.get("R"),d=(4===i||5===i)&&!1!==e.get("EncryptMetadata");this.encryptMetadata=d;const f=stringToBytes(t);let g,p;if(a){if(6===u)try{a=utf8StringToString(a)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}g=stringToBytes(a)}if(5!==i)p=this.#Ze(f,g,c,l,h,u,n,d);else{const t=s.subarray(32,40),a=s.subarray(40,48),r=o.subarray(0,48),i=o.subarray(32,40),n=o.subarray(40,48),h=stringToBytes(e.get("OE")),d=stringToBytes(e.get("UE")),f=stringToBytes(e.get("Perms"));p=this.#Ye(u,g,c,t,a,r,l,i,n,h,d,f)}if(!p){if(!a)throw new PasswordException("No password given",Yt);const e=this.#Qe(g,c,u,n);p=this.#Ze(f,e,c,l,h,u,n,d)}if(!p)throw new PasswordException("Incorrect Password",Zt);if(4===i&&p.length<16){this.encryptionKey=new Uint8Array(16);this.encryptionKey.set(p)}else this.encryptionKey=p;if(i>=4){const t=e.get("CF");t instanceof Dict&&(t.suppressEncryption=!0);this.cf=t;this.stmf=e.get("StmF")||Name.get("Identity");this.strf=e.get("StrF")||Name.get("Identity");this.eff=e.get("EFF")||this.stmf}}createCipherTransform(e,t){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#tt(this.cf,this.strf,e,t,this.encryptionKey),this.#tt(this.cf,this.stmf,e,t,this.encryptionKey));const a=this.#et(e,t,this.encryptionKey,!1),cipherConstructor=function(){return new ARCFourCipher(a)};return new CipherTransform(cipherConstructor,cipherConstructor)}}class XRef{constructor(e,t){this.stream=e;this.pdfManager=t;this.entries=[];this._xrefStms=new Set;this._cacheMap=new Map;this._pendingRefs=new RefSet;this._newPersistentRefNum=null;this._newTemporaryRefNum=null;this._persistentRefsCache=null}getNewPersistentRef(e){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);const t=this._newPersistentRefNum++;this._cacheMap.set(t,e);return Ref.get(t,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum){this._newTemporaryRefNum=this.entries.length||1;if(this._newPersistentRefNum){this._persistentRefsCache=new Map;for(let e=this._newTemporaryRefNum;e0;){const[s,o]=n;if(!Number.isInteger(s)||!Number.isInteger(o))throw new FormatError(`Invalid XRef range fields: ${s}, ${o}`);if(!Number.isInteger(a)||!Number.isInteger(r)||!Number.isInteger(i))throw new FormatError(`Invalid XRef entry fields length: ${s}, ${o}`);for(let n=t.entryNum;n=e.length);){a+=String.fromCharCode(r);r=e[t]}return a}function skipUntil(e,t,a){const r=a.length,i=e.length;let n=0;for(;t=r)break;t++;n++}return n}const e=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,t=/\b(startxref|\d+\s+\d+\s+obj)\b/g,a=/^(\d+)\s+(\d+)\s+obj\b/,r=new Uint8Array([116,114,97,105,108,101,114]),i=new Uint8Array([115,116,97,114,116,120,114,101,102]),n=new Uint8Array([47,88,82,101,102]);this.entries.length=0;this._cacheMap.clear();const s=this.stream;s.pos=0;const o=s.getBytes(),c=bytesToString(o),l=o.length;let h=s.start;const u=[],d=[];for(;h=l)break;f=o[h]}while(10!==f&&13!==f);continue}const g=readToken(o,h);let p;if(g.startsWith("xref")&&(4===g.length||/\s/.test(g[4]))){h+=skipUntil(o,h,r);u.push(h);h+=skipUntil(o,h,i)}else if(p=a.exec(g)){const t=0|p[1],a=0|p[2],r=h+g.length;let i,u=!1;if(this.entries[t]){if(this.entries[t].gen===a)try{new Parser({lexer:new Lexer(s.makeSubStream(r))}).getObj();u=!0}catch(e){e instanceof ParserEOFException?warn(`indexObjects -- checking object (${g}): "${e}".`):u=!0}}else u=!0;u&&(this.entries[t]={offset:h-s.start,gen:a,uncompressed:!0});e.lastIndex=r;const f=e.exec(c);if(f){i=e.lastIndex+1-h;if("endobj"!==f[1]){warn(`indexObjects: Found "${f[1]}" inside of another "obj", caused by missing "endobj" -- trying to recover.`);i-=f[1].length+1}}else i=l-h;const m=o.subarray(h,h+i),b=skipUntil(m,0,n);if(b0&&t[3]-t[1]>0)return t;warn(`Empty, or invalid, /${e} entry.`)}return null}get mediaBox(){return shadow(this,"mediaBox",this.#st("MediaBox")||sc)}get cropBox(){return shadow(this,"cropBox",this.#st("CropBox")||this.mediaBox)}get userUnit(){const e=this.pageDict.get("UserUnit");return shadow(this,"userUnit","number"==typeof e&&e>0?e:1)}get view(){const{cropBox:e,mediaBox:t}=this;if(e!==t&&!isArrayEqual(e,t)){const a=Util.intersect(e,t);if(a&&a[2]-a[0]>0&&a[3]-a[1]>0)return shadow(this,"view",a);warn("Empty /CropBox and /MediaBox intersection.")}return shadow(this,"view",t)}get rotate(){let e=this.#nt("Rotate")||0;e%90!=0?e=0:e>=360?e%=360:e<0&&(e=(e%360+360)%360);return shadow(this,"rotate",e)}#ot(e,t){if(!this.evaluatorOptions.ignoreErrors)throw e;warn(`getContentStream - ignoring sub-stream (${t}): "${e}".`)}async getContentStream(){const e=await this.pdfManager.ensure(this,"content");return e instanceof BaseStream?e:Array.isArray(e)?new StreamsSequenceStream(e,this.#ot.bind(this)):new NullStream}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}async#ct(e,t,a){const r=[];for(const i of e)if(i.id){const e=Ref.fromString(i.id);if(!e){warn(`A non-linked annotation cannot be modified: ${i.id}`);continue}if(i.deleted){t.put(e,e);if(i.popupRef){const e=Ref.fromString(i.popupRef);e&&t.put(e,e)}continue}if(i.popup?.deleted){const e=Ref.fromString(i.popupRef);e&&t.put(e,e)}a?.put(e);i.ref=e;r.push(this.xref.fetchAsync(e).then(e=>{e instanceof Dict&&(i.oldAnnotation=e.clone())},()=>{warn(`Cannot fetch \`oldAnnotation\` for: ${e}.`)}));delete i.id}await Promise.all(r)}async saveNewAnnotations(e,t,a,r,i){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");const n=this.#it(e),s=new RefSetCache,o=new RefSet;await this.#ct(a,s,o);const c=this.pageDict,l=this.annotations.filter(e=>!(e instanceof Ref&&s.has(e))),h=await AnnotationFactory.saveNewAnnotations(n,t,a,r,i);for(const{ref:e}of h.annotations)e instanceof Ref&&!o.has(e)&&l.push(e);const u=c.clone();u.set("Annots",l);i.put(this.ref,{data:u});for(const e of s)i.put(e,{data:null})}async save(e,t,a,r){const i=this.#it(e),n=await this._parsedAnnotations,s=[];for(const e of n)s.push(e.save(i,t,a,r).catch(function(e){warn(`save - ignoring annotation data during "${t.name}" task: "${e}".`);return null}));return Promise.all(s)}async loadResources(e){await(this.#rt??=this.pdfManager.ensure(this,"resources"));await ObjectLoader.load(this.resources,e,this.xref)}async#lt(e,t){const a=e?.get("Resources");if(!(a instanceof Dict&&a.size))return this.resources;await ObjectLoader.load(a,t,this.xref);return Dict.merge({xref:this.xref,dictArray:[a,this.resources],mergeSubDicts:!0})}async getOperatorList({handler:e,sink:t,task:a,intent:r,cacheKey:i,annotationStorage:c=null,modifiedIds:d=null}){const g=this.getContentStream(),p=this.loadResources(ga),m=this.#it(e),b=this.xfaFactory?null:getNewAnnotationsMap(c),y=b?.get(this.pageIndex);let w=Promise.resolve(null),x=null;if(y){const e=this.pdfManager.ensureDoc("annotationGlobals");let t;const r=new Set;for(const{bitmapId:e,bitmap:t}of y)!e||t||r.has(e)||r.add(e);const{isOffscreenCanvasSupported:i}=this.evaluatorOptions;if(r.size>0){const e=y.slice();for(const[t,a]of c)t.startsWith(f)&&a.bitmap&&r.has(a.bitmapId)&&e.push(a);t=AnnotationFactory.generateImages(e,this.xref,i)}else t=AnnotationFactory.generateImages(y,this.xref,i);x=new RefSet;w=Promise.all([e,this.#ct(y,x,null)]).then(([e])=>e?AnnotationFactory.printNewAnnotations(e,m,a,y,t):null)}const S=Promise.all([g,p]).then(async([n])=>{const s=await this.#lt(n.dict,ga),o=new OperatorList(r,t);e.send("StartRenderPage",{transparency:m.hasBlendModes(s,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:i});await m.getOperatorList({stream:n,task:a,resources:s,operatorList:o});return o});let[k,C,v]=await Promise.all([S,this._parsedAnnotations,w]);if(v){C=C.filter(e=>!(e.ref&&x.has(e.ref)));for(let e=0,t=v.length;ee.ref&&isRefsEqual(e.ref,a.refToReplace));if(r>=0){C.splice(r,1,a);v.splice(e--,1);t--}}}C=C.concat(v)}if(0===C.length||r&h){k.flush(!0);return{length:k.totalLength}}const F=!!(r&l),T=!!(r&u),O=!!(r&n),M=!!(r&s),D=!!(r&o),R=[];for(const e of C)(O||M&&e.mustBeViewed(c,F)&&e.mustBeViewedWhenEditing(T,d)||D&&e.mustBePrinted(c))&&R.push(e.getOperatorList(m,a,r,c).catch(function(e){warn(`getOperatorList - ignoring annotation data during "${a.name}" task: "${e}".`);return{opList:null,separateForm:!1,separateCanvas:!1}}));const N=await Promise.all(R);let E=!1,L=!1;for(const{opList:e,separateForm:t,separateCanvas:a}of N){k.addOpList(e);E||=t;L||=a}k.flush(!0,{form:E,canvas:L});return{length:k.totalLength}}async extractTextContent({handler:e,task:t,includeMarkedContent:a,disableNormalization:r,sink:i,intersector:n=null}){const s=this.getContentStream(),o=this.loadResources(pa),c=this.pdfManager.ensureCatalog("lang"),[l,,h]=await Promise.all([s,o,c]),u=await this.#lt(l.dict,pa);return this.#it(e).getTextContent({stream:l,task:t,resources:u,includeMarkedContent:a,disableNormalization:r,sink:i,viewBox:this.view,lang:h,intersector:n})}async getStructTree(){const e=await this.pdfManager.ensureCatalog("structTreeRoot");if(!e)return null;await this._parsedAnnotations;try{const t=await this.pdfManager.ensure(this,"_parseStructTree",[e]);return await this.pdfManager.ensure(t,"serializable")}catch(e){warn(`getStructTree: "${e}".`);return null}}_parseStructTree(e){const t=new StructTreePage(e,this.pageDict);t.parse(this.ref);return t}async getAnnotationsData(e,t,a){const r=await this._parsedAnnotations;if(0===r.length)return r;const i=[],c=[];let l;const h=!!(a&n),u=!!(a&s),d=!!(a&o),f=[];for(const a of r){const r=h||u&&a.viewable;(r||d&&a.printable)&&i.push(a.data);if(a.hasTextContent&&r){l??=this.#it(e);c.push(a.extractTextContent(l,t,[-1/0,-1/0,1/0,1/0]).catch(function(e){warn(`getAnnotationsData - ignoring textContent during "${t.name}" task: "${e}".`)}))}else a.overlaysTextContent&&r&&f.push(a)}if(f.length>0){const a=new Intersector(f);c.push(this.extractTextContent({handler:e,task:t,includeMarkedContent:!1,disableNormalization:!1,sink:null,viewBox:this.view,lang:null,intersector:a}).then(()=>{a.setText()}))}await Promise.all(c);return i}get annotations(){const e=this.#nt("Annots");return shadow(this,"annotations",Array.isArray(e)?e:[])}get _parsedAnnotations(){const e=this.pdfManager.ensure(this,"annotations").then(async e=>{if(0===e.length)return e;const[t,a]=await Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureDoc("fieldObjects")]);if(!t)return[];const r=a?.orphanFields,i=[];for(const a of e)i.push(AnnotationFactory.create(this.xref,a,t,this._localIdFactory,!1,r,null,this.ref).catch(function(e){warn(`_parsedAnnotations: "${e}".`);return null}));const n=[];let s,o;for(const e of await Promise.all(i))e&&(e instanceof WidgetAnnotation?(o||=[]).push(e):e instanceof PopupAnnotation?(s||=[]).push(e):n.push(e));o&&n.push(...o);s&&n.push(...s);return n});this.#at=!0;return shadow(this,"_parsedAnnotations",e)}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,se))}async collectAnnotationsByType(e,t,a,r,i){const{pageIndex:n}=this;if(this.#at){const e=await this._parsedAnnotations;for(const{data:t}of e)if(!a||a.has(t.annotationType)){t.pageIndex=n;r.push(Promise.resolve(t))}return}const s=await this.pdfManager.ensure(this,"annotations");for(const o of s)r.push(AnnotationFactory.create(this.xref,o,i,this._localIdFactory,!1,null,a,this.ref).then(async a=>{if(!a)return null;a.data.pageIndex=n;if(a.hasTextContent&&a.viewable){const r=this.#it(e);await a.extractTextContent(r,t,[-1/0,-1/0,1/0,1/0])}return a.data}).catch(function(e){warn(`collectAnnotationsByType: "${e}".`);return null}))}}const oc=new Uint8Array([37,80,68,70,45]),cc=new Uint8Array([115,116,97,114,116,120,114,101,102]),lc=new Uint8Array([101,110,100,111,98,106]);function find(e,t,a=1024,r=!1){const i=t.length,n=e.peekBytes(a),s=n.length-i;if(s<=0)return!1;if(r){const a=i-1;let r=n.length-1;for(;r>=a;){let s=0;for(;s=i){e.pos+=r-a;return!0}r--}}else{let a=0;for(;a<=s;){let r=0;for(;r=i){e.pos+=a;return!0}a++}}return!1}class PDFDocument{#ht=new Map;#ut=null;constructor(e,t){if(t.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=e;this.stream=t;this.xref=new XRef(t,e);const a={font:0};this._globalIdFactory=class{static getDocId(){return`g_${e.docId}`}static createFontId(){return"f"+ ++a.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(e){this.xref.parse(e);this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let e=null;try{e=Linearization.create(this.stream)}catch(e){if(e instanceof MissingDataException)throw e;info(e)}return shadow(this,"linearization",e)}get startXRef(){const e=this.stream;let t=0;if(this.linearization){e.reset();if(find(e,lc)){e.skip(6);let a=e.peekByte();for(;isWhiteSpace(a);){e.pos++;a=e.peekByte()}t=e.pos-e.start}}else{const a=1024,r=cc.length;let i=!1,n=e.end;for(;!i&&n>0;){n-=a-r;n<0&&(n=0);e.pos=n;i=find(e,cc,a,!0)}if(i){e.skip(9);let a;do{a=e.getByte()}while(isWhiteSpace(a));let r="";for(;a>=32&&a<=57;){r+=String.fromCharCode(a);a=e.getByte()}t=parseInt(r,10);isNaN(t)&&(t=0)}}return shadow(this,"startXRef",t)}checkHeader(){const e=this.stream;e.reset();if(!find(e,oc))return;e.moveStart();e.skip(oc.length);let t,a="";for(;(t=e.getByte())>32&&a.length<7;)a+=String.fromCharCode(t);ua.test(a)?this.#ut=a:warn(`Invalid PDF header version: ${a}`)}parseStartXRef(){this.xref.setStartXRef(this.startXRef)}get numPages(){let e=0;e=this.catalog.hasActualNumPages?this.catalog.numPages:this.xfaFactory?this.xfaFactory.getNumPages():this.linearization?this.linearization.numPages:this.catalog.numPages;return shadow(this,"numPages",e)}#dt(e,t=0){return!!Array.isArray(e)&&e.every(e=>{if(!((e=this.xref.fetchIfRef(e))instanceof Dict))return!1;if(e.has("Kids")){if(++t>10){warn("#hasOnlyDocumentSignatures: maximum recursion depth reached");return!1}return this.#dt(e.get("Kids"),t)}const a=isName(e.get("FT"),"Sig"),r=e.get("Rect"),i=Array.isArray(r)&&r.every(e=>0===e);return a&&i})}get _xfaStreams(){const{acroForm:e}=this.catalog;if(!e)return null;const t=e.get("XFA"),a=new Map(["xdp:xdp","template","datasets","config","connectionSet","localeSet","stylesheet","/xdp:xdp"].map(e=>[e,null]));if(t instanceof BaseStream&&!t.isEmpty){a.set("xdp:xdp",t);return a}if(!Array.isArray(t)||0===t.length)return null;for(let e=0,r=t.length;el.handleSetFont(r,[Name.get(e),1],null,h,t,d,a,i).catch(e=>{warn(`loadXfaFonts: "${e}".`);return null}),f=[];for(const[e,t]of i){const a=t.get("FontDescriptor");if(!(a instanceof Dict))continue;let r=a.get("FontFamily");r=r.replaceAll(/[ ]+(\d)/g,"$1");const i={fontFamily:r,fontWeight:a.get("FontWeight"),italicAngle:-a.get("ItalicAngle")};validateCSSFont(i)&&f.push(parseFont(e,null,i))}await Promise.all(f);const g=this.xfaFactory.setFonts(u);if(!g)return;n.ignoreErrors=!0;f.length=0;u.length=0;const p=new Set;for(const e of g)getXfaFontName(`${e}-Regular`)||p.add(e);p.size&&g.push("PdfJS-Fallback");for(const e of g)if(!p.has(e))for(const t of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){const a=`${e}-${t.name}`;f.push(parseFont(a,getXfaFontDict(a),{fontFamily:e,fontWeight:t.fontWeight,italicAngle:t.italicAngle}))}await Promise.all(f);this.xfaFactory.appendFonts(u,p)}loadXfaResources(e,t){return Promise.all([this.#gt(e,t).catch(()=>{}),this.#ft()])}serializeXfaData(e){return this.xfaFactory?this.xfaFactory.serializeData(e):null}get version(){return this.catalog.version||this.#ut}get formInfo(){const e={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},{acroForm:t}=this.catalog;if(!t)return shadow(this,"formInfo",e);try{const a=t.get("Fields"),r=Array.isArray(a)&&a.length>0;e.hasFields=r;const i=t.get("XFA");e.hasXfa=Array.isArray(i)&&i.length>0||i instanceof BaseStream&&!i.isEmpty;const n=!!(1&t.get("SigFlags")),s=n&&this.#dt(a);e.hasAcroForm=r&&!s;e.hasSignatures=n}catch(e){if(e instanceof MissingDataException)throw e;warn(`Cannot fetch form information: "${e}".`)}return shadow(this,"formInfo",e)}get documentInfo(){const{catalog:e,formInfo:t,xref:a}=this,r={PDFFormatVersion:this.version,Language:e.lang,EncryptFilterName:a.encrypt?.filterName??null,IsLinearized:!!this.linearization,IsAcroFormPresent:t.hasAcroForm,IsXFAPresent:t.hasXfa,IsCollectionPresent:!!e.collection,IsSignaturesPresent:t.hasSignatures};let i;try{i=a.trailer.get("Info")}catch(e){if(e instanceof MissingDataException)throw e;info("The document information dictionary is invalid.")}if(!(i instanceof Dict))return shadow(this,"documentInfo",r);for(const[e,t]of i){switch(e){case"Title":case"Author":case"Subject":case"Keywords":case"Creator":case"Producer":case"CreationDate":case"ModDate":if("string"==typeof t){r[e]=stringToPDFString(t);continue}break;case"Trapped":if(t instanceof Name){r[e]=t;continue}break;default:let a;switch(typeof t){case"string":a=stringToPDFString(t);break;case"number":case"boolean":a=t;break;default:t instanceof Name&&(a=t)}if(void 0===a){warn(`Bad value, for custom key "${e}", in Info: ${t}.`);continue}r.Custom??=Object.create(null);r.Custom[e]=a;continue}warn(`Bad value, for key "${e}", in Info: ${t}.`)}return shadow(this,"documentInfo",r)}get fingerprints(){const e="\0".repeat(16);function validate(t){return"string"==typeof t&&16===t.length&&t!==e}const t=this.xref.trailer.get("ID");let a,r;if(Array.isArray(t)&&validate(t[0])){a=stringToBytes(t[0]);t[1]!==t[0]&&validate(t[1])&&(r=stringToBytes(t[1]))}else a=calculateMD5(this.stream.getByteRange(0,1024),0,1024);return shadow(this,"fingerprints",[toHexUtil(a),r?toHexUtil(r):null])}async#pt(e){const{catalog:t,linearization:a,xref:r}=this,i=Ref.get(a.objectNumberFirst,0);try{const e=await r.fetchAsync(i);if(e instanceof Dict){let a=e.getRaw("Type");a instanceof Ref&&(a=await r.fetchAsync(a));if(isName(a,"Page")||!e.has("Type")&&!e.has("Kids")&&e.has("Contents")){t.pageKidsCountCache.has(i)||t.pageKidsCountCache.put(i,1);t.pageIndexCache.has(i)||t.pageIndexCache.put(i,0);return[e,i]}}throw new FormatError("The Linearization dictionary doesn't point to a valid Page dictionary.")}catch(a){warn(`_getLinearizationPage: "${a.message}".`);return t.getPageDict(e)}}getPage(e){const t=this.#ht.get(e);if(t)return t;const{catalog:a,linearization:r,xfaFactory:i}=this;let n;n=i?Promise.resolve([Dict.empty,null]):r?.pageFirst===e?this.#pt(e):a.getPageDict(e);n=n.then(([t,r])=>new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:e,pageDict:t,ref:r,globalIdFactory:this._globalIdFactory,fontCache:a.fontCache,builtInCMapCache:a.builtInCMapCache,standardFontDataCache:a.standardFontDataCache,globalColorSpaceCache:a.globalColorSpaceCache,globalImageCache:a.globalImageCache,systemFontCache:a.systemFontCache,nonBlendModesSet:a.nonBlendModesSet,xfaFactory:i}));this.#ht.set(e,n);return n}async checkFirstPage(e=!1){if(!e)try{await this.getPage(0)}catch(e){if(e instanceof XRefEntryException){this.#ht.delete(0);await this.cleanup();throw new XRefParseException}}}async checkLastPage(e=!1){const{catalog:t,pdfManager:a}=this;t.setActualNumPages();let r;try{await Promise.all([a.ensureDoc("xfaFactory"),a.ensureDoc("linearization"),a.ensureCatalog("numPages")]);if(this.xfaFactory)return;r=this.linearization?this.linearization.numPages:t.numPages;if(!Number.isInteger(r))throw new FormatError("Page count is not an integer.");if(r<=1)return;await this.getPage(r-1)}catch(i){this.#ht.delete(r-1);await this.cleanup();if(i instanceof XRefEntryException&&!e)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${r}.`);let n;try{n=await t.getAllPageDicts(e)}catch(a){if(a instanceof XRefEntryException&&!e)throw new XRefParseException;t.setActualNumPages(1);return}for(const[e,[r,i]]of n){let n;if(r instanceof Error){n=Promise.reject(r);n.catch(()=>{})}else n=Promise.resolve(new Page({pdfManager:a,xref:this.xref,pageIndex:e,pageDict:r,ref:i,globalIdFactory:this._globalIdFactory,fontCache:t.fontCache,builtInCMapCache:t.builtInCMapCache,standardFontDataCache:t.standardFontDataCache,globalColorSpaceCache:this.globalColorSpaceCache,globalImageCache:t.globalImageCache,systemFontCache:t.systemFontCache,nonBlendModesSet:t.nonBlendModesSet,xfaFactory:null}));this.#ht.set(e,n)}t.setActualNumPages(n.size)}}async fontFallback(e,t){const{catalog:a,pdfManager:r}=this;for(const i of await Promise.all(a.fontCache))if(i.loadedName===e){i.fallback(t,r.evaluatorOptions);return}}async cleanup(e=!1){return this.catalog?this.catalog.cleanup(e):clearGlobalCaches()}async#mt(e,t,a,r,i,n,s){const{xref:o}=this;if(!(a instanceof Ref)||n.has(a))return;n.put(a);const c=await o.fetchAsync(a);if(!(c instanceof Dict))return;let l=await c.getAsync("Subtype");l=l instanceof Name?l.name:null;if("Link"===l)return;if(c.has("T")){const t=stringToPDFString(await c.getAsync("T"));e=""===e?t:`${e}.${t}`}else{let a=c;for(;;){a=a.getRaw("Parent")||t;if(a instanceof Ref){if(n.has(a))break;a=await o.fetchAsync(a)}if(!(a instanceof Dict))break;if(a.has("T")){const t=stringToPDFString(await a.getAsync("T"));e=""===e?t:`${e}.${t}`;break}}}t&&!c.has("Parent")&&isName(c.get("Subtype"),"Widget")&&s.put(a,t);r.has(e)||r.set(e,[]);r.get(e).push(AnnotationFactory.create(o,a,i,null,!0,s,null,null).then(e=>e?.getFieldObject()).catch(function(e){warn(`#collectFieldObjects: "${e}".`);return null}));if(!c.has("Kids"))return;const h=await c.getAsync("Kids");if(Array.isArray(h))for(const t of h)await this.#mt(e,a,t,r,i,n,s)}get fieldObjects(){return shadow(this,"fieldObjects",this.pdfManager.ensureDoc("formInfo").then(async e=>{if(!e.hasFields)return null;const t=await this.annotationGlobals;if(!t)return null;const{acroForm:a}=t,r=new RefSet,i=Object.create(null),n=new Map,s=new RefSetCache;for(const e of a.get("Fields"))await this.#mt("",null,e,n,t,r,s);const o=[];for(const[e,t]of n)o.push(Promise.all(t).then(t=>{(t=t.filter(e=>!!e)).length>0&&(i[e]=t)}));await Promise.all(o);return{allFields:objectSize(i)>0?i:null,orphanFields:s}}))}get hasJSActions(){return shadow(this,"hasJSActions",this.pdfManager.ensureDoc("_parseHasJSActions"))}async _parseHasJSActions(){const[e,t]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!e||!!t?.allFields&&Object.values(t.allFields).some(e=>e.some(e=>null!==e.actions))}get calculationOrderIds(){const e=this.catalog.acroForm?.get("CO");if(!Array.isArray(e)||0===e.length)return shadow(this,"calculationOrderIds",null);const t=[];for(const a of e)a instanceof Ref&&t.push(a.toString());return shadow(this,"calculationOrderIds",t.length?t:null)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}class BasePdfManager{constructor({docBaseUrl:e,docId:t,enableXfa:a,evaluatorOptions:r,handler:i,password:n}){this._docBaseUrl=function parseDocBaseUrl(e){if(e){const t=createValidAbsoluteUrl(e);if(t)return t.href;warn(`Invalid absolute docBaseUrl: "${e}".`)}return null}(e);this._docId=t;this._password=n;this.enableXfa=a;r.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported;r.isImageDecoderSupported&&=FeatureTest.isImageDecoderSupported;this.evaluatorOptions=Object.freeze(r);ImageResizer.setOptions(r);JpegStream.setOptions(r);OperatorList.setOptions(r);const s={...r,handler:i};JpxImage.setOptions(s);IccColorSpace.setOptions(s);CmykICCBasedCS.setOptions(s)}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}ensureDoc(e,t){return this.ensure(this.pdfDocument,e,t)}ensureXRef(e,t){return this.ensure(this.pdfDocument.xref,e,t)}ensureCatalog(e,t){return this.ensure(this.pdfDocument.catalog,e,t)}getPage(e){return this.pdfDocument.getPage(e)}fontFallback(e,t){return this.pdfDocument.fontFallback(e,t)}cleanup(e=!1){return this.pdfDocument.cleanup(e)}async ensure(e,t,a){unreachable("Abstract method `ensure` called")}requestRange(e,t){unreachable("Abstract method `requestRange` called")}requestLoadedStream(e=!1){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(e){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(e){this._password=e}terminate(e){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(e){super(e);const t=new Stream(e.source);this.pdfDocument=new PDFDocument(this,t);this._loadedStreamPromise=Promise.resolve(t)}async ensure(e,t,a){const r=e[t];return"function"==typeof r?r.apply(e,a):r}requestRange(e,t){return Promise.resolve()}requestLoadedStream(e=!1){return this._loadedStreamPromise}terminate(e){}}class NetworkPdfManager extends BasePdfManager{constructor(e){super(e);this.streamManager=new ChunkedStreamManager(e.source,{msgHandler:e.handler,length:e.length,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize});this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(e,t,a){try{const r=e[t];return"function"==typeof r?r.apply(e,a):r}catch(r){if(!(r instanceof MissingDataException))throw r;await this.requestRange(r.begin,r.end);return this.ensure(e,t,a)}}requestRange(e,t){return this.streamManager.requestRange(e,t)}requestLoadedStream(e=!1){return this.streamManager.requestAllChunks(e)}sendProgressiveData(e){this.streamManager.onReceiveData({chunk:e})}terminate(e){this.streamManager.abort(e)}}const hc=1,uc=2,dc=1,fc=2,gc=3,pc=4,mc=5,bc=6,yc=7,wc=8;function onFn(){}function wrapReason(e){if(e instanceof AbortException||e instanceof InvalidPDFException||e instanceof PasswordException||e instanceof ResponseException||e instanceof UnknownErrorException)return e;e instanceof Error||"object"==typeof e&&null!==e||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(e.name){case"AbortException":return new AbortException(e.message);case"InvalidPDFException":return new InvalidPDFException(e.message);case"PasswordException":return new PasswordException(e.message,e.code);case"ResponseException":return new ResponseException(e.message,e.status,e.missing);case"UnknownErrorException":return new UnknownErrorException(e.message,e.details)}return new UnknownErrorException(e.message,e.toString())}class MessageHandler{#bt=new AbortController;constructor(e,t,a){this.sourceName=e;this.targetName=t;this.comObj=a;this.callbackId=1;this.streamId=1;this.streamSinks=Object.create(null);this.streamControllers=Object.create(null);this.callbackCapabilities=Object.create(null);this.actionHandler=Object.create(null);a.addEventListener("message",this.#yt.bind(this),{signal:this.#bt.signal})}#yt({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#wt(e);return}if(e.callback){const t=e.callbackId,a=this.callbackCapabilities[t];if(!a)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===hc)a.resolve(e.data);else{if(e.callback!==uc)throw new Error("Unexpected callback case");a.reject(wrapReason(e.reason))}return}const t=this.actionHandler[e.action];if(!t)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const a=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:a,targetName:r,callback:hc,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:a,targetName:r,callback:uc,callbackId:e.callbackId,reason:wrapReason(t)})});return}e.streamId?this.#xt(e):t(e.data)}on(e,t){const a=this.actionHandler;if(a[e])throw new Error(`There is already an actionName called "${e}"`);a[e]=t}send(e,t,a){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},a)}sendWithPromise(e,t,a){const r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},a)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,a,r){const i=this.streamId++,n=this.sourceName,s=this.targetName,o=this.comObj;return new ReadableStream({start:a=>{const c=Promise.withResolvers();this.streamControllers[i]={controller:a,startCall:c,pullCall:null,cancelCall:null,isClosed:!1};o.postMessage({sourceName:n,targetName:s,action:e,streamId:i,data:t,desiredSize:a.desiredSize},r);return c.promise},pull:e=>{const t=Promise.withResolvers();this.streamControllers[i].pullCall=t;o.postMessage({sourceName:n,targetName:s,stream:bc,streamId:i,desiredSize:e.desiredSize});return t.promise},cancel:e=>{assert(e instanceof Error,"cancel must have a valid reason");const t=Promise.withResolvers();this.streamControllers[i].cancelCall=t;this.streamControllers[i].isClosed=!0;o.postMessage({sourceName:n,targetName:s,stream:dc,streamId:i,reason:wrapReason(e)});return t.promise}},a)}#xt(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this,s=this.actionHandler[e.action],o={enqueue(e,n=1,s){if(this.isCancelled)return;const o=this.desiredSize;this.desiredSize-=n;if(o>0&&this.desiredSize<=0){this.sinkCapability=Promise.withResolvers();this.ready=this.sinkCapability.promise}i.postMessage({sourceName:a,targetName:r,stream:pc,streamId:t,chunk:e},s)},close(){if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:gc,streamId:t});delete n.streamSinks[t]}},error(e){assert(e instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;i.postMessage({sourceName:a,targetName:r,stream:mc,streamId:t,reason:wrapReason(e)})}},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};o.sinkCapability.resolve();o.ready=o.sinkCapability.promise;this.streamSinks[t]=o;Promise.try(s,e.data,o).then(function(){i.postMessage({sourceName:a,targetName:r,stream:wc,streamId:t,success:!0})},function(e){i.postMessage({sourceName:a,targetName:r,stream:wc,streamId:t,reason:wrapReason(e)})})}#wt(e){const t=e.streamId,a=this.sourceName,r=e.sourceName,i=this.comObj,n=this.streamControllers[t],s=this.streamSinks[t];switch(e.stream){case wc:e.success?n.startCall.resolve():n.startCall.reject(wrapReason(e.reason));break;case yc:e.success?n.pullCall.resolve():n.pullCall.reject(wrapReason(e.reason));break;case bc:if(!s){i.postMessage({sourceName:a,targetName:r,stream:yc,streamId:t,success:!0});break}s.desiredSize<=0&&e.desiredSize>0&&s.sinkCapability.resolve();s.desiredSize=e.desiredSize;Promise.try(s.onPull||onFn).then(function(){i.postMessage({sourceName:a,targetName:r,stream:yc,streamId:t,success:!0})},function(e){i.postMessage({sourceName:a,targetName:r,stream:yc,streamId:t,reason:wrapReason(e)})});break;case pc:assert(n,"enqueue should have stream controller");if(n.isClosed)break;n.controller.enqueue(e.chunk);break;case gc:assert(n,"close should have stream controller");if(n.isClosed)break;n.isClosed=!0;n.controller.close();this.#St(n,t);break;case mc:assert(n,"error should have stream controller");n.controller.error(wrapReason(e.reason));this.#St(n,t);break;case fc:e.success?n.cancelCall.resolve():n.cancelCall.reject(wrapReason(e.reason));this.#St(n,t);break;case dc:if(!s)break;const o=wrapReason(e.reason);Promise.try(s.onCancel||onFn,o).then(function(){i.postMessage({sourceName:a,targetName:r,stream:fc,streamId:t,success:!0})},function(e){i.postMessage({sourceName:a,targetName:r,stream:fc,streamId:t,reason:wrapReason(e)})});s.sinkCapability.reject(o);s.isCancelled=!0;delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}}async#St(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]);delete this.streamControllers[t]}destroy(){this.#bt?.abort();this.#bt=null}}async function writeObject(e,t,a,{encrypt:r=null}){const i=r?.createCipherTransform(e.num,e.gen);a.push(`${e.num} ${e.gen} obj\n`);t instanceof Dict?await writeDict(t,a,i):t instanceof BaseStream?await writeStream(t,a,i):(Array.isArray(t)||ArrayBuffer.isView(t))&&await writeArray(t,a,i);a.push("\nendobj\n")}async function writeDict(e,t,a){t.push("<<");for(const r of e.getKeys()){t.push(` /${escapePDFName(r)} `);await writeValue(e.getRaw(r),t,a)}t.push(">>")}async function writeStream(e,t,a){let r=e.getBytes();const{dict:i}=e,[n,s]=await Promise.all([i.getAsync("Filter"),i.getAsync("DecodeParms")]),o=isName(Array.isArray(n)?await i.xref.fetchIfRefAsync(n[0]):n,"FlateDecode");if(r.length>=256||o)try{const e=new CompressionStream("deflate"),t=e.writable.getWriter();await t.ready;t.write(r).then(async()=>{await t.ready;await t.close()}).catch(()=>{});const a=await new Response(e.readable).arrayBuffer();r=new Uint8Array(a);let c,l;if(n){if(!o){c=Array.isArray(n)?[Name.get("FlateDecode"),...n]:[Name.get("FlateDecode"),n];s&&(l=Array.isArray(s)?[null,...s]:[null,s])}}else c=Name.get("FlateDecode");c&&i.set("Filter",c);l&&i.set("DecodeParms",l)}catch(e){info(`writeStream - cannot compress data: "${e}".`)}let c=bytesToString(r);a&&(c=a.encryptString(c));i.set("Length",c.length);await writeDict(i,t,a);t.push(" stream\n",c,"\nendstream")}async function writeArray(e,t,a){t.push("[");let r=!0;for(const i of e){r?r=!1:t.push(" ");await writeValue(i,t,a)}t.push("]")}async function writeValue(e,t,a){if(e instanceof Name)t.push(`/${escapePDFName(e.name)}`);else if(e instanceof Ref)t.push(`${e.num} ${e.gen} R`);else if(Array.isArray(e)||ArrayBuffer.isView(e))await writeArray(e,t,a);else if("string"==typeof e){a&&(e=a.encryptString(e));t.push(`(${escapeString(e)})`)}else"number"==typeof e?t.push(numberToString(e)):"boolean"==typeof e?t.push(e.toString()):e instanceof Dict?await writeDict(e,t,a):e instanceof BaseStream?await writeStream(e,t,a):null===e?t.push("null"):warn(`Unhandled value in writer: ${typeof e}, please file a bug.`)}function writeInt(e,t,a,r){for(let i=t+a-1;i>a-1;i--){r[i]=255&e;e>>=8}return a+t}function writeString(e,t,a){const r=e.length;for(let i=0;i1&&(n=a.documentElement.searchNode([i.at(-1)],0));n?n.childNodes=Array.isArray(r)?r.map(e=>new SimpleDOMNode("value",e)):[new SimpleDOMNode("#text",r)]:warn(`Node not found for path: ${t}`)}const r=[];a.documentElement.dump(r);return r.join("")}(r.fetchIfRef(t).getString(),a)}const i=new StringStream(e);i.dict=new Dict(r);i.dict.setIfName("Type","EmbeddedFile");a.put(t,{data:i})}function getIndexes(e){const t=[];for(const{ref:a}of e)a.num===t.at(-2)+t.at(-1)?t[t.length-1]+=1:t.push(a.num,1);return t}function computeIDs(e,t,a){if(Array.isArray(t.fileIds)&&t.fileIds.length>0){const r=function computeMD5(e,t){const a=Math.floor(Date.now()/1e3),r=t.filename||"",i=[a.toString(),r,e.toString(),...t.infoMap.values()],n=Math.sumPrecise(i.map(e=>e.length)),s=new Uint8Array(n);let o=0;for(const e of i)o=writeString(e,o,s);return bytesToString(calculateMD5(s,0,s.length))}(e,t);a.set("ID",[t.fileIds[0],r])}}async function incrementalUpdate({originalData:e,xrefInfo:t,changes:a,xref:r=null,hasXfa:i=!1,xfaDatasetsRef:n=null,hasXfaDatasetsEntry:s=!1,needAppearances:o,acroFormRef:c=null,acroForm:l=null,xfaData:h=null,useXrefStream:u=!1}){await async function updateAcroform({xref:e,acroForm:t,acroFormRef:a,hasXfa:r,hasXfaDatasetsEntry:i,xfaDatasetsRef:n,needAppearances:s,changes:o}){!r||i||n||warn("XFA - Cannot save it");if(!s&&(!r||!n||i))return;const c=t.clone();if(r&&!i){const e=t.get("XFA").slice();e.splice(2,0,"datasets");e.splice(3,0,n);c.set("XFA",e)}s&&c.set("NeedAppearances",!0);o.put(a,{data:c})}({xref:r,acroForm:l,acroFormRef:c,hasXfa:i,hasXfaDatasetsEntry:s,xfaDatasetsRef:n,needAppearances:o,changes:a});i&&updateXFA({xfaData:h,xfaDatasetsRef:n,changes:a,xref:r});const d=function getTrailerDict(e,t,a){const r=new Dict(null);r.set("Prev",e.startXRef);const i=e.newRef;if(a){t.put(i,{data:""});r.set("Size",i.num+1);r.setIfName("Type","XRef")}else r.set("Size",i.num);null!==e.rootRef&&r.set("Root",e.rootRef);null!==e.infoRef&&r.set("Info",e.infoRef);null!==e.encryptRef&&r.set("Encrypt",e.encryptRef);return r}(t,a,u),f=[],g=await async function writeChanges(e,t,a=[]){const r=[];for(const[i,{data:n}]of e.items())if(null!==n&&"string"!=typeof n){await writeObject(i,n,a,t);r.push({ref:i,data:a.join("")});a.length=0}else r.push({ref:i,data:n});return r.sort((e,t)=>e.ref.num-t.ref.num)}(a,r,f);let p=e.length;const m=e.at(-1);if(10!==m&&13!==m){f.push("\n");p+=1}for(const{data:e}of g)null!==e&&f.push(e);await(u?async function getXRefStreamTable(e,t,a,r,i){const n=[];let s=0,o=0;for(const{ref:e,data:r}of a){let a;s=Math.max(s,t);if(null!==r){a=Math.min(e.gen,65535);n.push([1,t,a]);t+=r.length}else{a=Math.min(e.gen+1,65535);n.push([0,0,a])}o=Math.max(o,a)}r.set("Index",getIndexes(a));const c=[1,getSizeInBytes(s),getSizeInBytes(o)];r.set("W",c);computeIDs(t,e,r);const l=Math.sumPrecise(c),h=new Uint8Array(l*n.length),u=new Stream(h);u.dict=r;let d=0;for(const[e,t,a]of n){d=writeInt(e,c[0],d,h);d=writeInt(t,c[1],d,h);d=writeInt(a,c[2],d,h)}await writeObject(e.newRef,u,i,{});i.push("startxref\n",t.toString(),"\n%%EOF\n")}(t,p,g,d,f):async function getXRefTable(e,t,a,r,i){i.push("xref\n");const n=getIndexes(a);let s=0;for(const{ref:e,data:r}of a){if(e.num===n[s]){i.push(`${n[s]} ${n[s+1]}\n`);s+=2}if(null!==r){i.push(`${t.toString().padStart(10,"0")} ${Math.min(e.gen,65535).toString().padStart(5,"0")} n\r\n`);t+=r.length}else i.push(`0000000000 ${Math.min(e.gen+1,65535).toString().padStart(5,"0")} f\r\n`)}computeIDs(t,e,r);i.push("trailer\n");await writeDict(r,i);i.push("\nstartxref\n",t.toString(),"\n%%EOF\n")}(t,p,g,d,f));const b=e.length+Math.sumPrecise(f.map(e=>e.length)),y=new Uint8Array(b);y.set(e);let w=e.length;for(const e of f)w=writeString(e,w,y);return y}class PDFWorkerStream{constructor(e){this._msgHandler=e;this._contentLength=null;this._fullRequestReader=null;this._rangeRequestReaders=[]}getFullReader(){assert(!this._fullRequestReader,"PDFWorkerStream.getFullReader can only be called once.");this._fullRequestReader=new PDFWorkerStreamReader(this._msgHandler);return this._fullRequestReader}getRangeReader(e,t){const a=new PDFWorkerStreamRangeReader(e,t,this._msgHandler);this._rangeRequestReaders.push(a);return a}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(const t of this._rangeRequestReaders.slice(0))t.cancel(e)}}class PDFWorkerStreamReader{constructor(e){this._msgHandler=e;this.onProgress=null;this._contentLength=null;this._isRangeSupported=!1;this._isStreamingSupported=!1;const t=this._msgHandler.sendWithStream("GetReader");this._reader=t.getReader();this._headersReady=this._msgHandler.sendWithPromise("ReaderHeadersReady").then(e=>{this._isStreamingSupported=e.isStreamingSupported;this._isRangeSupported=e.isRangeSupported;this._contentLength=e.contentLength})}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class PDFWorkerStreamRangeReader{constructor(e,t,a){this._msgHandler=a;this.onProgress=null;const r=this._msgHandler.sendWithStream("GetRangeReader",{begin:e,end:t});this._reader=r.getReader()}get isStreamingSupported(){return!1}async read(){const{value:e,done:t}=await this._reader.read();return t?{value:void 0,done:!0}:{value:e.buffer,done:!1}}cancel(e){this._reader.cancel(e)}}class WorkerTask{constructor(e){this.name=e;this.terminated=!1;this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static{"undefined"==typeof window&&!e&&"undefined"!=typeof self&&"function"==typeof self.postMessage&&"onmessage"in self&&this.initializeFromPort(self)}static setup(e,t){let a=!1;e.on("test",t=>{if(!a){a=!0;e.send("test",t instanceof Uint8Array)}});e.on("configure",e=>{!function setVerbosityLevel(e){Number.isInteger(e)&&(Qt=e)}(e.verbosity)});e.on("GetDocRequest",e=>this.createDocumentHandler(e,t))}static createDocumentHandler(e,t){let a,r=!1,i=null;const n=new Set,s=getVerbosityLevel(),{docId:o,apiVersion:c}=e,l="5.4.394";if(c!==l)throw new Error(`The API version "${c}" does not match the Worker version "${l}".`);const buildMsg=(e,t)=>`The \`${e}.prototype\` contains unexpected enumerable property "${t}", thus breaking e.g. \`for...in\` iteration of ${e}s.`;for(const e in{})throw new Error(buildMsg("Object",e));for(const e in[])throw new Error(buildMsg("Array",e));const h=o+"_worker";let u=new MessageHandler(h,o,t);function ensureNotTerminated(){if(r)throw new Error("Worker was terminated")}function startWorkerTask(e){n.add(e)}function finishWorkerTask(e){e.finish();n.delete(e)}async function loadDocument(e){await a.ensureDoc("checkHeader");await a.ensureDoc("parseStartXRef");await a.ensureDoc("parse",[e]);await a.ensureDoc("checkFirstPage",[e]);await a.ensureDoc("checkLastPage",[e]);const t=await a.ensureDoc("isPureXfa");if(t){const e=new WorkerTask("loadXfaResources");startWorkerTask(e);await a.ensureDoc("loadXfaResources",[u,e]);finishWorkerTask(e)}const[r,i]=await Promise.all([a.ensureDoc("numPages"),a.ensureDoc("fingerprints")]);return{numPages:r,fingerprints:i,htmlForXfa:t?await a.ensureDoc("htmlForXfa"):null}}function setupDoc(e){function onSuccess(e){ensureNotTerminated();u.send("GetDoc",{pdfInfo:e})}function onFailure(e){ensureNotTerminated();if(e instanceof PasswordException){const t=new WorkerTask(`PasswordException: response ${e.code}`);startWorkerTask(t);u.sendWithPromise("PasswordRequest",e).then(function({password:e}){finishWorkerTask(t);a.updatePassword(e);pdfManagerReady()}).catch(function(){finishWorkerTask(t);u.send("DocException",e)})}else u.send("DocException",wrapReason(e))}function pdfManagerReady(){ensureNotTerminated();loadDocument(!1).then(onSuccess,function(e){ensureNotTerminated();e instanceof XRefParseException?a.requestLoadedStream().then(function(){ensureNotTerminated();loadDocument(!0).then(onSuccess,onFailure)}):onFailure(e)})}ensureNotTerminated();(async function getPdfManager({data:e,password:t,disableAutoFetch:a,rangeChunkSize:r,length:n,docBaseUrl:s,enableXfa:c,evaluatorOptions:l}){const h={source:null,disableAutoFetch:a,docBaseUrl:s,docId:o,enableXfa:c,evaluatorOptions:l,handler:u,length:n,password:t,rangeChunkSize:r};if(e){h.source=e;return new LocalPdfManager(h)}const d=new PDFWorkerStream(u),f=d.getFullReader(),g=Promise.withResolvers();let p,m=[],b=0;f.headersReady.then(function(){if(f.isRangeSupported){h.source=d;h.length=f.contentLength;h.disableAutoFetch||=f.isStreamingSupported;p=new NetworkPdfManager(h);for(const e of m)p.sendProgressiveData(e);m=[];g.resolve(p);i=null}}).catch(function(e){g.reject(e);i=null});new Promise(function(e,t){const readChunk=function({value:e,done:a}){try{ensureNotTerminated();if(a){if(!p){const e=arrayBuffersToBytes(m);m=[];n&&e.length!==n&&warn("reported HTTP length is different from actual");h.source=e;p=new LocalPdfManager(h);g.resolve(p)}i=null;return}b+=e.byteLength;f.isStreamingSupported||u.send("DocProgress",{loaded:b,total:Math.max(b,f.contentLength||0)});p?p.sendProgressiveData(e):m.push(e);f.read().then(readChunk,t)}catch(e){t(e)}};f.read().then(readChunk,t)}).catch(function(e){g.reject(e);i=null});i=e=>{d.cancelAllRequests(e)};return g.promise})(e).then(function(e){if(r){e.terminate(new AbortException("Worker was terminated."));throw new Error("Worker was terminated")}a=e;a.requestLoadedStream(!0).then(e=>{u.send("DataLoaded",{length:e.bytes.byteLength})})}).then(pdfManagerReady,onFailure)}u.on("GetPage",function(e){return a.getPage(e.pageIndex).then(function(e){return Promise.all([a.ensure(e,"rotate"),a.ensure(e,"ref"),a.ensure(e,"userUnit"),a.ensure(e,"view")]).then(function([e,t,a,r]){return{rotate:e,ref:t,refStr:t?.toString()??null,userUnit:a,view:r}})})});u.on("GetPageIndex",function(e){const t=Ref.get(e.num,e.gen);return a.ensureCatalog("getPageIndex",[t])});u.on("GetDestinations",function(e){return a.ensureCatalog("destinations")});u.on("GetDestination",function(e){return a.ensureCatalog("getDestination",[e.id])});u.on("GetPageLabels",function(e){return a.ensureCatalog("pageLabels")});u.on("GetPageLayout",function(e){return a.ensureCatalog("pageLayout")});u.on("GetPageMode",function(e){return a.ensureCatalog("pageMode")});u.on("GetViewerPreferences",function(e){return a.ensureCatalog("viewerPreferences")});u.on("GetOpenAction",function(e){return a.ensureCatalog("openAction")});u.on("GetAttachments",function(e){return a.ensureCatalog("attachments")});u.on("GetDocJSActions",function(e){return a.ensureCatalog("jsActions")});u.on("GetPageJSActions",function({pageIndex:e}){return a.getPage(e).then(e=>a.ensure(e,"jsActions"))});u.on("GetAnnotationsByType",async function({types:e,pageIndexesToSkip:t}){const[r,i]=await Promise.all([a.ensureDoc("numPages"),a.ensureDoc("annotationGlobals")]);if(!i)return null;const n=[],s=[];let o=null;try{for(let c=0,l=r;ct&&t.collectAnnotationsByType(u,o,e,s,i)||[]))}await Promise.all(n);return(await Promise.all(s)).filter(e=>!!e)}finally{o&&finishWorkerTask(o)}});u.on("GetOutline",function(e){return a.ensureCatalog("documentOutline")});u.on("GetOptionalContentConfig",function(e){return a.ensureCatalog("optionalContentConfig")});u.on("GetPermissions",function(e){return a.ensureCatalog("permissions")});u.on("GetMetadata",function(e){return Promise.all([a.ensureDoc("documentInfo"),a.ensureCatalog("metadata")])});u.on("GetMarkInfo",function(e){return a.ensureCatalog("markInfo")});u.on("GetData",function(e){return a.requestLoadedStream().then(e=>e.bytes)});u.on("GetAnnotations",function({pageIndex:e,intent:t}){return a.getPage(e).then(function(a){const r=new WorkerTask(`GetAnnotations: page ${e}`);startWorkerTask(r);return a.getAnnotationsData(u,r,t).then(e=>{finishWorkerTask(r);return e},e=>{finishWorkerTask(r);throw e})})});u.on("GetFieldObjects",function(e){return a.ensureDoc("fieldObjects").then(e=>e?.allFields||null)});u.on("HasJSActions",function(e){return a.ensureDoc("hasJSActions")});u.on("GetCalculationOrderIds",function(e){return a.ensureDoc("calculationOrderIds")});u.on("SaveDocument",async function({isPureXfa:e,numPages:t,annotationStorage:r,filename:i}){const n=[a.requestLoadedStream(),a.ensureCatalog("acroForm"),a.ensureCatalog("acroFormRef"),a.ensureDoc("startXRef"),a.ensureDoc("xref"),a.ensureCatalog("structTreeRoot")],s=new RefSetCache,o=[],c=e?null:getNewAnnotationsMap(r),[l,h,d,f,g,p]=await Promise.all(n),m=g.trailer.getRaw("Root")||null;let b;if(c){p?await p.canUpdateStructTree({pdfManager:a,newAnnotationsByPage:c})&&(b=p):await StructTreeRoot.canCreateStructureTree({catalogRef:m,pdfManager:a,newAnnotationsByPage:c})&&(b=null);const e=AnnotationFactory.generateImages(r.values(),g,a.evaluatorOptions.isOffscreenCanvasSupported),t=void 0===b?o:[];for(const[r,i]of c)t.push(a.getPage(r).then(t=>{const a=new WorkerTask(`Save (editor): page ${r}`);startWorkerTask(a);return t.saveNewAnnotations(u,a,i,e,s).finally(function(){finishWorkerTask(a)})}));null===b?o.push(Promise.all(t).then(async()=>{await StructTreeRoot.createStructureTree({newAnnotationsByPage:c,xref:g,catalogRef:m,pdfManager:a,changes:s})})):b&&o.push(Promise.all(t).then(async()=>{await b.updateStructureTree({newAnnotationsByPage:c,pdfManager:a,changes:s})}))}if(e)o.push(a.ensureDoc("serializeXfaData",[r]));else for(let e=0;ee.needAppearances),S=h instanceof Dict&&h.get("XFA")||null;let k=null,C=!1;if(Array.isArray(S)){for(let e=0,t=S.length;e{g.resetNewTemporaryRef()})});u.on("GetOperatorList",function(e,t){const r=e.pageIndex;a.getPage(r).then(function(a){const i=new WorkerTask(`GetOperatorList: page ${r}`);startWorkerTask(i);const n=s>=ce?Date.now():0;a.getOperatorList({handler:u,sink:t,task:i,intent:e.intent,cacheKey:e.cacheKey,annotationStorage:e.annotationStorage,modifiedIds:e.modifiedIds}).then(function(e){finishWorkerTask(i);n&&info(`page=${r+1} - getOperatorList: time=${Date.now()-n}ms, len=${e.length}`);t.close()},function(e){finishWorkerTask(i);i.terminated||t.error(e)})})});u.on("GetTextContent",function(e,t){const{pageIndex:r,includeMarkedContent:i,disableNormalization:n}=e;a.getPage(r).then(function(e){const a=new WorkerTask("GetTextContent: page "+r);startWorkerTask(a);const o=s>=ce?Date.now():0;e.extractTextContent({handler:u,task:a,sink:t,includeMarkedContent:i,disableNormalization:n}).then(function(){finishWorkerTask(a);o&&info(`page=${r+1} - getTextContent: time=`+(Date.now()-o)+"ms");t.close()},function(e){finishWorkerTask(a);a.terminated||t.error(e)})})});u.on("GetStructTree",function(e){return a.getPage(e.pageIndex).then(e=>a.ensure(e,"getStructTree"))});u.on("FontFallback",function(e){return a.fontFallback(e.id,u)});u.on("Cleanup",function(e){return a.cleanup(!0)});u.on("Terminate",function(e){r=!0;const t=[];if(a){a.terminate(new AbortException("Worker was terminated."));const e=a.cleanup();t.push(e);a=null}else clearGlobalCaches();i?.(new AbortException("Worker was terminated."));for(const e of n){t.push(e.finished);e.terminate()}return Promise.all(t).then(function(){u.destroy();u=null})});u.on("Ready",function(t){setupDoc(e);e=null});return h}static initializeFromPort(e){const t=new MessageHandler("worker","main",e);this.setup(t,e);t.send("ready",null)}}globalThis.pdfjsWorker={WorkerMessageHandler};export{WorkerMessageHandler}; \ No newline at end of file diff --git a/sandbox.html b/sandbox.html new file mode 100644 index 0000000..850ca48 --- /dev/null +++ b/sandbox.html @@ -0,0 +1,15 @@ + + + + + + Sandboxed Content + + + + + + diff --git a/sandbox.js b/sandbox.js new file mode 100644 index 0000000..d4143c6 --- /dev/null +++ b/sandbox.js @@ -0,0 +1,57 @@ +// Minimal sandbox.js - just listens for sandbox-load and writes the content +window.addEventListener("message", (event) => { + if (event.data.type === "sandbox-load") { + // Validate HTML and JavaScript syntax before document.write() + try { + // Parse HTML to extract script tags + const parser = new DOMParser(); + const doc = parser.parseFromString(event.data.code, "text/html"); + + // Check for HTML parser errors + const parserError = doc.querySelector("parsererror"); + if (parserError) { + throw new Error(`HTML parse error: ${parserError.textContent}`); + } + + // Validate JavaScript in all script tags (except type="module") + const scriptTags = Array.from(doc.querySelectorAll("script")); + for (let i = 0; i < scriptTags.length; i++) { + const scriptContent = scriptTags[i].textContent || ""; + const scriptType = scriptTags[i].getAttribute("type"); + + // Skip validation for module scripts - new Function() can't validate module syntax + if (scriptType === "module") { + continue; + } + + if (scriptContent.trim()) { + try { + // Use Function constructor to validate syntax without executing + new Function(scriptContent); + } catch (jsError) { + throw new Error(`JavaScript syntax error in + + + + + + \ No newline at end of file diff --git a/sidepanel.js b/sidepanel.js new file mode 100644 index 0000000..149b079 --- /dev/null +++ b/sidepanel.js @@ -0,0 +1,335629 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, { + get: (a3, b4) => (typeof require !== "undefined" ? require : a3)[b4] +}) : x2)(function(x2) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x2 + '" is not supported'); +}); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require2() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to2, from2, except, desc) => { + if (from2 && typeof from2 === "object" || typeof from2 === "function") { + for (let key of __getOwnPropNames(from2)) + if (!__hasOwnProp.call(to2, key) && key !== except) + __defProp(to2, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable }); + } + return to2; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __decorateClass = (decorators, target, key, kind) => { + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + for (var i7 = decorators.length - 1, decorator; i7 >= 0; i7--) + if (decorator = decorators[i7]) + result = (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) __defProp(target, key, result); + return result; +}; + +// scripts/process-shim.js +var processShim, process_shim_default, process; +var init_process_shim = __esm({ + "scripts/process-shim.js"() { + "use strict"; + processShim = { + browser: true, + env: {}, + cwd: () => "/", + platform: "browser", + version: "", + versions: {}, + argv: [], + pid: 0, + title: "browser", + nextTick: (fn, ...args) => Promise.resolve().then(() => fn(...args)), + stderr: {}, + stdout: {}, + stdin: {} + }; + process_shim_default = processShim; + process = processShim; + } +}); + +// node_modules/@lit/reactive-element/css-tag.js +var t, e, s, o, n, r, S, c; +var init_css_tag = __esm({ + "node_modules/@lit/reactive-element/css-tag.js"() { + init_process_shim(); + t = globalThis; + e = t.ShadowRoot && (void 0 === t.ShadyCSS || t.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype; + s = Symbol(); + o = /* @__PURE__ */ new WeakMap(); + n = class { + constructor(t6, e9, o9) { + if (this._$cssResult$ = true, o9 !== s) throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead."); + this.cssText = t6, this.t = e9; + } + get styleSheet() { + let t6 = this.o; + const s6 = this.t; + if (e && void 0 === t6) { + const e9 = void 0 !== s6 && 1 === s6.length; + e9 && (t6 = o.get(s6)), void 0 === t6 && ((this.o = t6 = new CSSStyleSheet()).replaceSync(this.cssText), e9 && o.set(s6, t6)); + } + return t6; + } + toString() { + return this.cssText; + } + }; + r = (t6) => new n("string" == typeof t6 ? t6 : t6 + "", void 0, s); + S = (s6, o9) => { + if (e) s6.adoptedStyleSheets = o9.map((t6) => t6 instanceof CSSStyleSheet ? t6 : t6.styleSheet); + else for (const e9 of o9) { + const o10 = document.createElement("style"), n7 = t.litNonce; + void 0 !== n7 && o10.setAttribute("nonce", n7), o10.textContent = e9.cssText, s6.appendChild(o10); + } + }; + c = e ? (t6) => t6 : (t6) => t6 instanceof CSSStyleSheet ? ((t7) => { + let e9 = ""; + for (const s6 of t7.cssRules) e9 += s6.cssText; + return r(e9); + })(t6) : t6; + } +}); + +// node_modules/@lit/reactive-element/reactive-element.js +var i2, e2, h, r2, o2, n2, a, c2, l, p, d, u, f, b, y; +var init_reactive_element = __esm({ + "node_modules/@lit/reactive-element/reactive-element.js"() { + init_process_shim(); + init_css_tag(); + init_css_tag(); + ({ is: i2, defineProperty: e2, getOwnPropertyDescriptor: h, getOwnPropertyNames: r2, getOwnPropertySymbols: o2, getPrototypeOf: n2 } = Object); + a = globalThis; + c2 = a.trustedTypes; + l = c2 ? c2.emptyScript : ""; + p = a.reactiveElementPolyfillSupport; + d = (t6, s6) => t6; + u = { toAttribute(t6, s6) { + switch (s6) { + case Boolean: + t6 = t6 ? l : null; + break; + case Object: + case Array: + t6 = null == t6 ? t6 : JSON.stringify(t6); + } + return t6; + }, fromAttribute(t6, s6) { + let i7 = t6; + switch (s6) { + case Boolean: + i7 = null !== t6; + break; + case Number: + i7 = null === t6 ? null : Number(t6); + break; + case Object: + case Array: + try { + i7 = JSON.parse(t6); + } catch (t7) { + i7 = null; + } + } + return i7; + } }; + f = (t6, s6) => !i2(t6, s6); + b = { attribute: true, type: String, converter: u, reflect: false, useDefault: false, hasChanged: f }; + Symbol.metadata ??= Symbol("metadata"), a.litPropertyMetadata ??= /* @__PURE__ */ new WeakMap(); + y = class extends HTMLElement { + static addInitializer(t6) { + this._$Ei(), (this.l ??= []).push(t6); + } + static get observedAttributes() { + return this.finalize(), this._$Eh && [...this._$Eh.keys()]; + } + static createProperty(t6, s6 = b) { + if (s6.state && (s6.attribute = false), this._$Ei(), this.prototype.hasOwnProperty(t6) && ((s6 = Object.create(s6)).wrapped = true), this.elementProperties.set(t6, s6), !s6.noAccessor) { + const i7 = Symbol(), h7 = this.getPropertyDescriptor(t6, i7, s6); + void 0 !== h7 && e2(this.prototype, t6, h7); + } + } + static getPropertyDescriptor(t6, s6, i7) { + const { get: e9, set: r8 } = h(this.prototype, t6) ?? { get() { + return this[s6]; + }, set(t7) { + this[s6] = t7; + } }; + return { get: e9, set(s7) { + const h7 = e9?.call(this); + r8?.call(this, s7), this.requestUpdate(t6, h7, i7); + }, configurable: true, enumerable: true }; + } + static getPropertyOptions(t6) { + return this.elementProperties.get(t6) ?? b; + } + static _$Ei() { + if (this.hasOwnProperty(d("elementProperties"))) return; + const t6 = n2(this); + t6.finalize(), void 0 !== t6.l && (this.l = [...t6.l]), this.elementProperties = new Map(t6.elementProperties); + } + static finalize() { + if (this.hasOwnProperty(d("finalized"))) return; + if (this.finalized = true, this._$Ei(), this.hasOwnProperty(d("properties"))) { + const t7 = this.properties, s6 = [...r2(t7), ...o2(t7)]; + for (const i7 of s6) this.createProperty(i7, t7[i7]); + } + const t6 = this[Symbol.metadata]; + if (null !== t6) { + const s6 = litPropertyMetadata.get(t6); + if (void 0 !== s6) for (const [t7, i7] of s6) this.elementProperties.set(t7, i7); + } + this._$Eh = /* @__PURE__ */ new Map(); + for (const [t7, s6] of this.elementProperties) { + const i7 = this._$Eu(t7, s6); + void 0 !== i7 && this._$Eh.set(i7, t7); + } + this.elementStyles = this.finalizeStyles(this.styles); + } + static finalizeStyles(s6) { + const i7 = []; + if (Array.isArray(s6)) { + const e9 = new Set(s6.flat(1 / 0).reverse()); + for (const s7 of e9) i7.unshift(c(s7)); + } else void 0 !== s6 && i7.push(c(s6)); + return i7; + } + static _$Eu(t6, s6) { + const i7 = s6.attribute; + return false === i7 ? void 0 : "string" == typeof i7 ? i7 : "string" == typeof t6 ? t6.toLowerCase() : void 0; + } + constructor() { + super(), this._$Ep = void 0, this.isUpdatePending = false, this.hasUpdated = false, this._$Em = null, this._$Ev(); + } + _$Ev() { + this._$ES = new Promise((t6) => this.enableUpdating = t6), this._$AL = /* @__PURE__ */ new Map(), this._$E_(), this.requestUpdate(), this.constructor.l?.forEach((t6) => t6(this)); + } + addController(t6) { + (this._$EO ??= /* @__PURE__ */ new Set()).add(t6), void 0 !== this.renderRoot && this.isConnected && t6.hostConnected?.(); + } + removeController(t6) { + this._$EO?.delete(t6); + } + _$E_() { + const t6 = /* @__PURE__ */ new Map(), s6 = this.constructor.elementProperties; + for (const i7 of s6.keys()) this.hasOwnProperty(i7) && (t6.set(i7, this[i7]), delete this[i7]); + t6.size > 0 && (this._$Ep = t6); + } + createRenderRoot() { + const t6 = this.shadowRoot ?? this.attachShadow(this.constructor.shadowRootOptions); + return S(t6, this.constructor.elementStyles), t6; + } + connectedCallback() { + this.renderRoot ??= this.createRenderRoot(), this.enableUpdating(true), this._$EO?.forEach((t6) => t6.hostConnected?.()); + } + enableUpdating(t6) { + } + disconnectedCallback() { + this._$EO?.forEach((t6) => t6.hostDisconnected?.()); + } + attributeChangedCallback(t6, s6, i7) { + this._$AK(t6, i7); + } + _$ET(t6, s6) { + const i7 = this.constructor.elementProperties.get(t6), e9 = this.constructor._$Eu(t6, i7); + if (void 0 !== e9 && true === i7.reflect) { + const h7 = (void 0 !== i7.converter?.toAttribute ? i7.converter : u).toAttribute(s6, i7.type); + this._$Em = t6, null == h7 ? this.removeAttribute(e9) : this.setAttribute(e9, h7), this._$Em = null; + } + } + _$AK(t6, s6) { + const i7 = this.constructor, e9 = i7._$Eh.get(t6); + if (void 0 !== e9 && this._$Em !== e9) { + const t7 = i7.getPropertyOptions(e9), h7 = "function" == typeof t7.converter ? { fromAttribute: t7.converter } : void 0 !== t7.converter?.fromAttribute ? t7.converter : u; + this._$Em = e9; + const r8 = h7.fromAttribute(s6, t7.type); + this[e9] = r8 ?? this._$Ej?.get(e9) ?? r8, this._$Em = null; + } + } + requestUpdate(t6, s6, i7, e9 = false, h7) { + if (void 0 !== t6) { + const r8 = this.constructor; + if (false === e9 && (h7 = this[t6]), i7 ??= r8.getPropertyOptions(t6), !((i7.hasChanged ?? f)(h7, s6) || i7.useDefault && i7.reflect && h7 === this._$Ej?.get(t6) && !this.hasAttribute(r8._$Eu(t6, i7)))) return; + this.C(t6, s6, i7); + } + false === this.isUpdatePending && (this._$ES = this._$EP()); + } + C(t6, s6, { useDefault: i7, reflect: e9, wrapped: h7 }, r8) { + i7 && !(this._$Ej ??= /* @__PURE__ */ new Map()).has(t6) && (this._$Ej.set(t6, r8 ?? s6 ?? this[t6]), true !== h7 || void 0 !== r8) || (this._$AL.has(t6) || (this.hasUpdated || i7 || (s6 = void 0), this._$AL.set(t6, s6)), true === e9 && this._$Em !== t6 && (this._$Eq ??= /* @__PURE__ */ new Set()).add(t6)); + } + async _$EP() { + this.isUpdatePending = true; + try { + await this._$ES; + } catch (t7) { + Promise.reject(t7); + } + const t6 = this.scheduleUpdate(); + return null != t6 && await t6, !this.isUpdatePending; + } + scheduleUpdate() { + return this.performUpdate(); + } + performUpdate() { + if (!this.isUpdatePending) return; + if (!this.hasUpdated) { + if (this.renderRoot ??= this.createRenderRoot(), this._$Ep) { + for (const [t8, s7] of this._$Ep) this[t8] = s7; + this._$Ep = void 0; + } + const t7 = this.constructor.elementProperties; + if (t7.size > 0) for (const [s7, i7] of t7) { + const { wrapped: t8 } = i7, e9 = this[s7]; + true !== t8 || this._$AL.has(s7) || void 0 === e9 || this.C(s7, void 0, i7, e9); + } + } + let t6 = false; + const s6 = this._$AL; + try { + t6 = this.shouldUpdate(s6), t6 ? (this.willUpdate(s6), this._$EO?.forEach((t7) => t7.hostUpdate?.()), this.update(s6)) : this._$EM(); + } catch (s7) { + throw t6 = false, this._$EM(), s7; + } + t6 && this._$AE(s6); + } + willUpdate(t6) { + } + _$AE(t6) { + this._$EO?.forEach((t7) => t7.hostUpdated?.()), this.hasUpdated || (this.hasUpdated = true, this.firstUpdated(t6)), this.updated(t6); + } + _$EM() { + this._$AL = /* @__PURE__ */ new Map(), this.isUpdatePending = false; + } + get updateComplete() { + return this.getUpdateComplete(); + } + getUpdateComplete() { + return this._$ES; + } + shouldUpdate(t6) { + return true; + } + update(t6) { + this._$Eq &&= this._$Eq.forEach((t7) => this._$ET(t7, this[t7])), this._$EM(); + } + updated(t6) { + } + firstUpdated(t6) { + } + }; + y.elementStyles = [], y.shadowRootOptions = { mode: "open" }, y[d("elementProperties")] = /* @__PURE__ */ new Map(), y[d("finalized")] = /* @__PURE__ */ new Map(), p?.({ ReactiveElement: y }), (a.reactiveElementVersions ??= []).push("2.1.2"); + } +}); + +// node_modules/lit-html/lit-html.js +function V(t6, i7) { + if (!u2(t6) || !t6.hasOwnProperty("raw")) throw Error("invalid template strings array"); + return void 0 !== e3 ? e3.createHTML(i7) : i7; +} +function M(t6, i7, s6 = t6, e9) { + if (i7 === E) return i7; + let h7 = void 0 !== e9 ? s6._$Co?.[e9] : s6._$Cl; + const o9 = a2(i7) ? void 0 : i7._$litDirective$; + return h7?.constructor !== o9 && (h7?._$AO?.(false), void 0 === o9 ? h7 = void 0 : (h7 = new o9(t6), h7._$AT(t6, s6, e9)), void 0 !== e9 ? (s6._$Co ??= [])[e9] = h7 : s6._$Cl = h7), void 0 !== h7 && (i7 = M(t6, h7._$AS(t6, i7.values), h7, e9)), i7; +} +var t2, i3, s2, e3, h2, o3, n3, r3, l2, c3, a2, u2, d2, f2, v, _, m, p2, g, $2, y2, x, b2, w, T, E, A, C, P, N, S2, R, k, H, I, L, z, Z, j, B, D; +var init_lit_html = __esm({ + "node_modules/lit-html/lit-html.js"() { + init_process_shim(); + t2 = globalThis; + i3 = (t6) => t6; + s2 = t2.trustedTypes; + e3 = s2 ? s2.createPolicy("lit-html", { createHTML: (t6) => t6 }) : void 0; + h2 = "$lit$"; + o3 = `lit$${Math.random().toFixed(9).slice(2)}$`; + n3 = "?" + o3; + r3 = `<${n3}>`; + l2 = document; + c3 = () => l2.createComment(""); + a2 = (t6) => null === t6 || "object" != typeof t6 && "function" != typeof t6; + u2 = Array.isArray; + d2 = (t6) => u2(t6) || "function" == typeof t6?.[Symbol.iterator]; + f2 = "[ \n\f\r]"; + v = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g; + _ = /-->/g; + m = />/g; + p2 = RegExp(`>|${f2}(?:([^\\s"'>=/]+)(${f2}*=${f2}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`, "g"); + g = /'/g; + $2 = /"/g; + y2 = /^(?:script|style|textarea|title)$/i; + x = (t6) => (i7, ...s6) => ({ _$litType$: t6, strings: i7, values: s6 }); + b2 = x(1); + w = x(2); + T = x(3); + E = Symbol.for("lit-noChange"); + A = Symbol.for("lit-nothing"); + C = /* @__PURE__ */ new WeakMap(); + P = l2.createTreeWalker(l2, 129); + N = (t6, i7) => { + const s6 = t6.length - 1, e9 = []; + let n7, l5 = 2 === i7 ? "" : 3 === i7 ? "" : "", c6 = v; + for (let i8 = 0; i8 < s6; i8++) { + const s7 = t6[i8]; + let a3, u5, d4 = -1, f4 = 0; + for (; f4 < s7.length && (c6.lastIndex = f4, u5 = c6.exec(s7), null !== u5); ) f4 = c6.lastIndex, c6 === v ? "!--" === u5[1] ? c6 = _ : void 0 !== u5[1] ? c6 = m : void 0 !== u5[2] ? (y2.test(u5[2]) && (n7 = RegExp("" === u5[0] ? (c6 = n7 ?? v, d4 = -1) : void 0 === u5[1] ? d4 = -2 : (d4 = c6.lastIndex - u5[2].length, a3 = u5[1], c6 = void 0 === u5[3] ? p2 : '"' === u5[3] ? $2 : g) : c6 === $2 || c6 === g ? c6 = p2 : c6 === _ || c6 === m ? c6 = v : (c6 = p2, n7 = void 0); + const x2 = c6 === p2 && t6[i8 + 1].startsWith("/>") ? " " : ""; + l5 += c6 === v ? s7 + r3 : d4 >= 0 ? (e9.push(a3), s7.slice(0, d4) + h2 + s7.slice(d4) + o3 + x2) : s7 + o3 + (-2 === d4 ? i8 : x2); + } + return [V(t6, l5 + (t6[s6] || "") + (2 === i7 ? "" : 3 === i7 ? "" : "")), e9]; + }; + S2 = class _S { + constructor({ strings: t6, _$litType$: i7 }, e9) { + let r8; + this.parts = []; + let l5 = 0, a3 = 0; + const u5 = t6.length - 1, d4 = this.parts, [f4, v4] = N(t6, i7); + if (this.el = _S.createElement(f4, e9), P.currentNode = this.el.content, 2 === i7 || 3 === i7) { + const t7 = this.el.content.firstChild; + t7.replaceWith(...t7.childNodes); + } + for (; null !== (r8 = P.nextNode()) && d4.length < u5; ) { + if (1 === r8.nodeType) { + if (r8.hasAttributes()) for (const t7 of r8.getAttributeNames()) if (t7.endsWith(h2)) { + const i8 = v4[a3++], s6 = r8.getAttribute(t7).split(o3), e10 = /([.?@])?(.*)/.exec(i8); + d4.push({ type: 1, index: l5, name: e10[2], strings: s6, ctor: "." === e10[1] ? I : "?" === e10[1] ? L : "@" === e10[1] ? z : H }), r8.removeAttribute(t7); + } else t7.startsWith(o3) && (d4.push({ type: 6, index: l5 }), r8.removeAttribute(t7)); + if (y2.test(r8.tagName)) { + const t7 = r8.textContent.split(o3), i8 = t7.length - 1; + if (i8 > 0) { + r8.textContent = s2 ? s2.emptyScript : ""; + for (let s6 = 0; s6 < i8; s6++) r8.append(t7[s6], c3()), P.nextNode(), d4.push({ type: 2, index: ++l5 }); + r8.append(t7[i8], c3()); + } + } + } else if (8 === r8.nodeType) if (r8.data === n3) d4.push({ type: 2, index: l5 }); + else { + let t7 = -1; + for (; -1 !== (t7 = r8.data.indexOf(o3, t7 + 1)); ) d4.push({ type: 7, index: l5 }), t7 += o3.length - 1; + } + l5++; + } + } + static createElement(t6, i7) { + const s6 = l2.createElement("template"); + return s6.innerHTML = t6, s6; + } + }; + R = class { + constructor(t6, i7) { + this._$AV = [], this._$AN = void 0, this._$AD = t6, this._$AM = i7; + } + get parentNode() { + return this._$AM.parentNode; + } + get _$AU() { + return this._$AM._$AU; + } + u(t6) { + const { el: { content: i7 }, parts: s6 } = this._$AD, e9 = (t6?.creationScope ?? l2).importNode(i7, true); + P.currentNode = e9; + let h7 = P.nextNode(), o9 = 0, n7 = 0, r8 = s6[0]; + for (; void 0 !== r8; ) { + if (o9 === r8.index) { + let i8; + 2 === r8.type ? i8 = new k(h7, h7.nextSibling, this, t6) : 1 === r8.type ? i8 = new r8.ctor(h7, r8.name, r8.strings, this, t6) : 6 === r8.type && (i8 = new Z(h7, this, t6)), this._$AV.push(i8), r8 = s6[++n7]; + } + o9 !== r8?.index && (h7 = P.nextNode(), o9++); + } + return P.currentNode = l2, e9; + } + p(t6) { + let i7 = 0; + for (const s6 of this._$AV) void 0 !== s6 && (void 0 !== s6.strings ? (s6._$AI(t6, s6, i7), i7 += s6.strings.length - 2) : s6._$AI(t6[i7])), i7++; + } + }; + k = class _k { + get _$AU() { + return this._$AM?._$AU ?? this._$Cv; + } + constructor(t6, i7, s6, e9) { + this.type = 2, this._$AH = A, this._$AN = void 0, this._$AA = t6, this._$AB = i7, this._$AM = s6, this.options = e9, this._$Cv = e9?.isConnected ?? true; + } + get parentNode() { + let t6 = this._$AA.parentNode; + const i7 = this._$AM; + return void 0 !== i7 && 11 === t6?.nodeType && (t6 = i7.parentNode), t6; + } + get startNode() { + return this._$AA; + } + get endNode() { + return this._$AB; + } + _$AI(t6, i7 = this) { + t6 = M(this, t6, i7), a2(t6) ? t6 === A || null == t6 || "" === t6 ? (this._$AH !== A && this._$AR(), this._$AH = A) : t6 !== this._$AH && t6 !== E && this._(t6) : void 0 !== t6._$litType$ ? this.$(t6) : void 0 !== t6.nodeType ? this.T(t6) : d2(t6) ? this.k(t6) : this._(t6); + } + O(t6) { + return this._$AA.parentNode.insertBefore(t6, this._$AB); + } + T(t6) { + this._$AH !== t6 && (this._$AR(), this._$AH = this.O(t6)); + } + _(t6) { + this._$AH !== A && a2(this._$AH) ? this._$AA.nextSibling.data = t6 : this.T(l2.createTextNode(t6)), this._$AH = t6; + } + $(t6) { + const { values: i7, _$litType$: s6 } = t6, e9 = "number" == typeof s6 ? this._$AC(t6) : (void 0 === s6.el && (s6.el = S2.createElement(V(s6.h, s6.h[0]), this.options)), s6); + if (this._$AH?._$AD === e9) this._$AH.p(i7); + else { + const t7 = new R(e9, this), s7 = t7.u(this.options); + t7.p(i7), this.T(s7), this._$AH = t7; + } + } + _$AC(t6) { + let i7 = C.get(t6.strings); + return void 0 === i7 && C.set(t6.strings, i7 = new S2(t6)), i7; + } + k(t6) { + u2(this._$AH) || (this._$AH = [], this._$AR()); + const i7 = this._$AH; + let s6, e9 = 0; + for (const h7 of t6) e9 === i7.length ? i7.push(s6 = new _k(this.O(c3()), this.O(c3()), this, this.options)) : s6 = i7[e9], s6._$AI(h7), e9++; + e9 < i7.length && (this._$AR(s6 && s6._$AB.nextSibling, e9), i7.length = e9); + } + _$AR(t6 = this._$AA.nextSibling, s6) { + for (this._$AP?.(false, true, s6); t6 !== this._$AB; ) { + const s7 = i3(t6).nextSibling; + i3(t6).remove(), t6 = s7; + } + } + setConnected(t6) { + void 0 === this._$AM && (this._$Cv = t6, this._$AP?.(t6)); + } + }; + H = class { + get tagName() { + return this.element.tagName; + } + get _$AU() { + return this._$AM._$AU; + } + constructor(t6, i7, s6, e9, h7) { + this.type = 1, this._$AH = A, this._$AN = void 0, this.element = t6, this.name = i7, this._$AM = e9, this.options = h7, s6.length > 2 || "" !== s6[0] || "" !== s6[1] ? (this._$AH = Array(s6.length - 1).fill(new String()), this.strings = s6) : this._$AH = A; + } + _$AI(t6, i7 = this, s6, e9) { + const h7 = this.strings; + let o9 = false; + if (void 0 === h7) t6 = M(this, t6, i7, 0), o9 = !a2(t6) || t6 !== this._$AH && t6 !== E, o9 && (this._$AH = t6); + else { + const e10 = t6; + let n7, r8; + for (t6 = h7[0], n7 = 0; n7 < h7.length - 1; n7++) r8 = M(this, e10[s6 + n7], i7, n7), r8 === E && (r8 = this._$AH[n7]), o9 ||= !a2(r8) || r8 !== this._$AH[n7], r8 === A ? t6 = A : t6 !== A && (t6 += (r8 ?? "") + h7[n7 + 1]), this._$AH[n7] = r8; + } + o9 && !e9 && this.j(t6); + } + j(t6) { + t6 === A ? this.element.removeAttribute(this.name) : this.element.setAttribute(this.name, t6 ?? ""); + } + }; + I = class extends H { + constructor() { + super(...arguments), this.type = 3; + } + j(t6) { + this.element[this.name] = t6 === A ? void 0 : t6; + } + }; + L = class extends H { + constructor() { + super(...arguments), this.type = 4; + } + j(t6) { + this.element.toggleAttribute(this.name, !!t6 && t6 !== A); + } + }; + z = class extends H { + constructor(t6, i7, s6, e9, h7) { + super(t6, i7, s6, e9, h7), this.type = 5; + } + _$AI(t6, i7 = this) { + if ((t6 = M(this, t6, i7, 0) ?? A) === E) return; + const s6 = this._$AH, e9 = t6 === A && s6 !== A || t6.capture !== s6.capture || t6.once !== s6.once || t6.passive !== s6.passive, h7 = t6 !== A && (s6 === A || e9); + e9 && this.element.removeEventListener(this.name, this, s6), h7 && this.element.addEventListener(this.name, this, t6), this._$AH = t6; + } + handleEvent(t6) { + "function" == typeof this._$AH ? this._$AH.call(this.options?.host ?? this.element, t6) : this._$AH.handleEvent(t6); + } + }; + Z = class { + constructor(t6, i7, s6) { + this.element = t6, this.type = 6, this._$AN = void 0, this._$AM = i7, this.options = s6; + } + get _$AU() { + return this._$AM._$AU; + } + _$AI(t6) { + M(this, t6); + } + }; + j = { M: h2, P: o3, A: n3, C: 1, L: N, R, D: d2, V: M, I: k, H, N: L, U: z, B: I, F: Z }; + B = t2.litHtmlPolyfillSupport; + B?.(S2, k), (t2.litHtmlVersions ??= []).push("3.3.2"); + D = (t6, i7, s6) => { + const e9 = s6?.renderBefore ?? i7; + let h7 = e9._$litPart$; + if (void 0 === h7) { + const t7 = s6?.renderBefore ?? null; + e9._$litPart$ = h7 = new k(i7.insertBefore(c3(), t7), t7, void 0, s6 ?? {}); + } + return h7._$AI(t6), h7; + }; + } +}); + +// node_modules/lit-element/lit-element.js +var s3, i4, o4; +var init_lit_element = __esm({ + "node_modules/lit-element/lit-element.js"() { + init_process_shim(); + init_reactive_element(); + init_reactive_element(); + init_lit_html(); + init_lit_html(); + s3 = globalThis; + i4 = class extends y { + constructor() { + super(...arguments), this.renderOptions = { host: this }, this._$Do = void 0; + } + createRenderRoot() { + const t6 = super.createRenderRoot(); + return this.renderOptions.renderBefore ??= t6.firstChild, t6; + } + update(t6) { + const r8 = this.render(); + this.hasUpdated || (this.renderOptions.isConnected = this.isConnected), super.update(t6), this._$Do = D(r8, this.renderRoot, this.renderOptions); + } + connectedCallback() { + super.connectedCallback(), this._$Do?.setConnected(true); + } + disconnectedCallback() { + super.disconnectedCallback(), this._$Do?.setConnected(false); + } + render() { + return E; + } + }; + i4._$litElement$ = true, i4["finalized"] = true, s3.litElementHydrateSupport?.({ LitElement: i4 }); + o4 = s3.litElementPolyfillSupport; + o4?.({ LitElement: i4 }); + (s3.litElementVersions ??= []).push("4.2.2"); + } +}); + +// node_modules/lit-html/is-server.js +var init_is_server = __esm({ + "node_modules/lit-html/is-server.js"() { + init_process_shim(); + } +}); + +// node_modules/lit/index.js +var init_lit = __esm({ + "node_modules/lit/index.js"() { + init_process_shim(); + init_reactive_element(); + init_lit_html(); + init_lit_element(); + init_is_server(); + } +}); + +// node_modules/lit-html/directive-helpers.js +var t3, i5, r4, s4, v2, u3, m2, p3, M2, h3; +var init_directive_helpers = __esm({ + "node_modules/lit-html/directive-helpers.js"() { + init_process_shim(); + init_lit_html(); + ({ I: t3 } = j); + i5 = (o9) => o9; + r4 = (o9) => void 0 === o9.strings; + s4 = () => document.createComment(""); + v2 = (o9, n7, e9) => { + const l5 = o9._$AA.parentNode, d4 = void 0 === n7 ? o9._$AB : n7._$AA; + if (void 0 === e9) { + const i7 = l5.insertBefore(s4(), d4), n8 = l5.insertBefore(s4(), d4); + e9 = new t3(i7, n8, o9, o9.options); + } else { + const t6 = e9._$AB.nextSibling, n8 = e9._$AM, c6 = n8 !== o9; + if (c6) { + let t7; + e9._$AQ?.(o9), e9._$AM = o9, void 0 !== e9._$AP && (t7 = o9._$AU) !== n8._$AU && e9._$AP(t7); + } + if (t6 !== d4 || c6) { + let o10 = e9._$AA; + for (; o10 !== t6; ) { + const t7 = i5(o10).nextSibling; + i5(l5).insertBefore(o10, d4), o10 = t7; + } + } + } + return e9; + }; + u3 = (o9, t6, i7 = o9) => (o9._$AI(t6, i7), o9); + m2 = {}; + p3 = (o9, t6 = m2) => o9._$AH = t6; + M2 = (o9) => o9._$AH; + h3 = (o9) => { + o9._$AR(), o9._$AA.remove(); + }; + } +}); + +// node_modules/lit-html/directive.js +var t4, e4, i6; +var init_directive = __esm({ + "node_modules/lit-html/directive.js"() { + init_process_shim(); + t4 = { ATTRIBUTE: 1, CHILD: 2, PROPERTY: 3, BOOLEAN_ATTRIBUTE: 4, EVENT: 5, ELEMENT: 6 }; + e4 = (t6) => (...e9) => ({ _$litDirective$: t6, values: e9 }); + i6 = class { + constructor(t6) { + } + get _$AU() { + return this._$AM._$AU; + } + _$AT(t6, e9, i7) { + this._$Ct = t6, this._$AM = e9, this._$Ci = i7; + } + _$AS(t6, e9) { + return this.update(t6, e9); + } + update(t6, e9) { + return this.render(...e9); + } + }; + } +}); + +// node_modules/lit-html/async-directive.js +function h4(i7) { + void 0 !== this._$AN ? (o5(this), this._$AM = i7, r5(this)) : this._$AM = i7; +} +function n4(i7, t6 = false, e9 = 0) { + const r8 = this._$AH, h7 = this._$AN; + if (void 0 !== h7 && 0 !== h7.size) if (t6) if (Array.isArray(r8)) for (let i8 = e9; i8 < r8.length; i8++) s5(r8[i8], false), o5(r8[i8]); + else null != r8 && (s5(r8, false), o5(r8)); + else s5(this, i7); +} +var s5, o5, r5, c4, f3; +var init_async_directive = __esm({ + "node_modules/lit-html/async-directive.js"() { + init_process_shim(); + init_directive_helpers(); + init_directive(); + init_directive(); + s5 = (i7, t6) => { + const e9 = i7._$AN; + if (void 0 === e9) return false; + for (const i8 of e9) i8._$AO?.(t6, false), s5(i8, t6); + return true; + }; + o5 = (i7) => { + let t6, e9; + do { + if (void 0 === (t6 = i7._$AM)) break; + e9 = t6._$AN, e9.delete(i7), i7 = t6; + } while (0 === e9?.size); + }; + r5 = (i7) => { + for (let t6; t6 = i7._$AM; i7 = t6) { + let e9 = t6._$AN; + if (void 0 === e9) t6._$AN = e9 = /* @__PURE__ */ new Set(); + else if (e9.has(i7)) break; + e9.add(i7), c4(t6); + } + }; + c4 = (i7) => { + i7.type == t4.CHILD && (i7._$AP ??= n4, i7._$AQ ??= h4); + }; + f3 = class extends i6 { + constructor() { + super(...arguments), this._$AN = void 0; + } + _$AT(i7, t6, e9) { + super._$AT(i7, t6, e9), r5(this), this.isConnected = i7._$AU; + } + _$AO(i7, t6 = true) { + i7 !== this.isConnected && (this.isConnected = i7, i7 ? this.reconnected?.() : this.disconnected?.()), t6 && (s5(this, i7), o5(this)); + } + setValue(t6) { + if (r4(this._$Ct)) this._$Ct._$AI(t6, this); + else { + const i7 = [...this._$Ct._$AH]; + i7[this._$Ci] = t6, this._$Ct._$AI(i7, this, 0); + } + } + disconnected() { + } + reconnected() { + } + }; + } +}); + +// node_modules/lit-html/directives/ref.js +var e5, h5, o6, n5; +var init_ref = __esm({ + "node_modules/lit-html/directives/ref.js"() { + init_process_shim(); + init_lit_html(); + init_async_directive(); + init_directive(); + e5 = () => new h5(); + h5 = class { + }; + o6 = /* @__PURE__ */ new WeakMap(); + n5 = e4(class extends f3 { + render(i7) { + return A; + } + update(i7, [s6]) { + const e9 = s6 !== this.G; + return e9 && void 0 !== this.G && this.rt(void 0), (e9 || this.lt !== this.ct) && (this.G = s6, this.ht = i7.options?.host, this.rt(this.ct = i7.element)), A; + } + rt(t6) { + if (this.isConnected || (t6 = void 0), "function" == typeof this.G) { + const i7 = this.ht ?? globalThis; + let s6 = o6.get(i7); + void 0 === s6 && (s6 = /* @__PURE__ */ new WeakMap(), o6.set(i7, s6)), void 0 !== s6.get(this.G) && this.G.call(this.ht, void 0), s6.set(this.G, t6), void 0 !== t6 && this.G.call(this.ht, t6); + } else this.G.value = t6; + } + get lt() { + return "function" == typeof this.G ? o6.get(this.ht ?? globalThis)?.get(this.G) : this.G?.value; + } + disconnected() { + this.lt === this.ct && this.rt(void 0); + } + reconnected() { + this.rt(this.ct); + } + }); + } +}); + +// node_modules/lit/directives/ref.js +var init_ref2 = __esm({ + "node_modules/lit/directives/ref.js"() { + init_process_shim(); + init_ref(); + } +}); + +// ../mini-lit/dist/mini.js +function fc(renderFn) { + return (props) => renderFn(props || {}); +} +var init_mini = __esm({ + "../mini-lit/dist/mini.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_ref2(); + } +}); + +// ../mini-lit/dist/component.js +var init_component = __esm({ + "../mini-lit/dist/component.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_mini(); + init_mini(); + } +}); + +// ../mini-lit/dist/i18n.js +function setTranslations(customTranslations) { + userTranslations = customTranslations; + translations = customTranslations; +} +function getCurrentLanguage() { + const stored = localStorage.getItem("language"); + if (stored && translations[stored]) { + return stored; + } + const userLocale = navigator.language || navigator.userLanguage; + const languageCode = userLocale ? userLocale.split("-")[0] : "en"; + return translations[languageCode] ? languageCode : "en"; +} +function i18n(categoryOrKey, key) { + const languageCode = getCurrentLanguage(); + const implementation = translations[languageCode] || translations.en; + if (key === void 0) { + const value = implementation[categoryOrKey]; + if (!value) { + if (typeof value === "function") { + return value; + } + console.error(`Unknown i18n key: ${categoryOrKey}`); + return categoryOrKey; + } + return value; + } else { + const category = implementation[categoryOrKey]; + if (!category || typeof category !== "object") { + console.error(`Unknown i18n category: ${categoryOrKey}`); + return key; + } + const value = category[key]; + if (!value) { + console.error(`Unknown i18n key: ${categoryOrKey}.${key}`); + return key; + } + return value; + } +} +var defaultEnglish, defaultGerman, userTranslations, translations, i18n_default; +var init_i18n = __esm({ + "../mini-lit/dist/i18n.js"() { + "use strict"; + init_process_shim(); + defaultEnglish = { + "*": "*", + Copy: "Copy", + "Copy code": "Copy code", + "Copied!": "Copied!", + Download: "Download", + Close: "Close", + Preview: "Preview", + Code: "Code", + "Loading...": "Loading...", + "Select an option": "Select an option", + "Mode 1": "Mode 1", + "Mode 2": "Mode 2", + Required: "Required", + Optional: "Optional", + "Input Required": "Input Required", + Cancel: "Cancel", + Confirm: "Confirm" + }; + defaultGerman = { + "*": "*", + Copy: "Kopieren", + "Copy code": "Code kopieren", + "Copied!": "Kopiert!", + Download: "Herunterladen", + Close: "Schlie\xDFen", + Preview: "Vorschau", + Code: "Code", + "Loading...": "Laden...", + "Select an option": "Option ausw\xE4hlen", + "Mode 1": "Modus 1", + "Mode 2": "Modus 2", + Required: "Erforderlich", + Optional: "Optional", + "Input Required": "Eingabe erforderlich", + Cancel: "Abbrechen", + Confirm: "Best\xE4tigen" + }; + userTranslations = null; + translations = { + en: defaultEnglish, + de: defaultGerman + }; + i18n_default = i18n; + } +}); + +// node_modules/lit-html/directives/unsafe-html.js +var e6, o7; +var init_unsafe_html = __esm({ + "node_modules/lit-html/directives/unsafe-html.js"() { + init_process_shim(); + init_lit_html(); + init_directive(); + e6 = class extends i6 { + constructor(i7) { + if (super(i7), this.it = A, i7.type !== t4.CHILD) throw Error(this.constructor.directiveName + "() can only be used in child bindings"); + } + render(r8) { + if (r8 === A || null == r8) return this._t = void 0, this.it = r8; + if (r8 === E) return r8; + if ("string" != typeof r8) throw Error(this.constructor.directiveName + "() called with a non-string value"); + if (r8 === this.it) return this._t; + this.it = r8; + const s6 = [r8]; + return s6.raw = s6, this._t = { _$litType$: this.constructor.resultType, strings: s6, values: [] }; + } + }; + e6.directiveName = "unsafeHTML", e6.resultType = 1; + o7 = e4(e6); + } +}); + +// node_modules/lit/directives/unsafe-html.js +var init_unsafe_html2 = __esm({ + "node_modules/lit/directives/unsafe-html.js"() { + init_process_shim(); + init_unsafe_html(); + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/defaultAttributes.js +var defaultAttributes; +var init_defaultAttributes = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/defaultAttributes.js"() { + init_process_shim(); + defaultAttributes = { + xmlns: "http://www.w3.org/2000/svg", + width: 24, + height: 24, + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + "stroke-width": 2, + "stroke-linecap": "round", + "stroke-linejoin": "round" + }; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/createElement.js +var createSVGElement, createElement; +var init_createElement = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/createElement.js"() { + init_process_shim(); + init_defaultAttributes(); + createSVGElement = ([tag, attrs, children]) => { + const element = document.createElementNS("http://www.w3.org/2000/svg", tag); + Object.keys(attrs).forEach((name) => { + element.setAttribute(name, String(attrs[name])); + }); + if (children?.length) { + children.forEach((child) => { + const childElement = createSVGElement(child); + element.appendChild(childElement); + }); + } + return element; + }; + createElement = (iconNode, customAttrs = {}) => { + const tag = "svg"; + const attrs = { + ...defaultAttributes, + ...customAttrs + }; + return createSVGElement([tag, attrs, iconNode]); + }; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/check.js +var Check; +var init_check = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/check.js"() { + init_process_shim(); + Check = [["path", { d: "M20 6 9 17l-5-5" }]]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/code.js +var Code; +var init_code = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/code.js"() { + init_process_shim(); + Code = [ + ["path", { d: "m16 18 6-6-6-6" }], + ["path", { d: "m8 6-6 6 6 6" }] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/copy.js +var Copy; +var init_copy = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/copy.js"() { + init_process_shim(); + Copy = [ + ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }], + ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/download.js +var Download; +var init_download = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/download.js"() { + init_process_shim(); + Download = [ + ["path", { d: "M12 15V3" }], + ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }], + ["path", { d: "m7 10 5 5 5-5" }] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/eye.js +var Eye; +var init_eye = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/eye.js"() { + init_process_shim(); + Eye = [ + [ + "path", + { + d: "M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" + } + ], + ["circle", { cx: "12", cy: "12", r: "3" }] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/monitor.js +var Monitor; +var init_monitor = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/monitor.js"() { + init_process_shim(); + Monitor = [ + ["rect", { width: "20", height: "14", x: "2", y: "3", rx: "2" }], + ["line", { x1: "8", x2: "16", y1: "21", y2: "21" }], + ["line", { x1: "12", x2: "12", y1: "17", y2: "21" }] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/moon.js +var Moon; +var init_moon = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/moon.js"() { + init_process_shim(); + Moon = [ + [ + "path", + { + d: "M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401" + } + ] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/icons/sun.js +var Sun; +var init_sun = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/icons/sun.js"() { + init_process_shim(); + Sun = [ + ["circle", { cx: "12", cy: "12", r: "4" }], + ["path", { d: "M12 2v2" }], + ["path", { d: "M12 20v2" }], + ["path", { d: "m4.93 4.93 1.41 1.41" }], + ["path", { d: "m17.66 17.66 1.41 1.41" }], + ["path", { d: "M2 12h2" }], + ["path", { d: "M20 12h2" }], + ["path", { d: "m6.34 17.66-1.41 1.41" }], + ["path", { d: "m19.07 4.93-1.41 1.41" }] + ]; + } +}); + +// ../mini-lit/node_modules/lucide/dist/esm/lucide.js +var init_lucide = __esm({ + "../mini-lit/node_modules/lucide/dist/esm/lucide.js"() { + init_process_shim(); + init_createElement(); + init_check(); + init_code(); + init_copy(); + init_download(); + init_eye(); + init_monitor(); + init_moon(); + init_sun(); + } +}); + +// ../mini-lit/dist/icons.js +function icon(lucideIcon, size = "md", className) { + return b2`${o7(iconDOM(lucideIcon, size, className).outerHTML)}`; +} +function iconDOM(lucideIcon, size = "md", className) { + const element = createElement(lucideIcon, { + class: sizeClasses[size] + (className ? " " + className : "") + }); + return element; +} +var sizeClasses; +var init_icons = __esm({ + "../mini-lit/dist/icons.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_unsafe_html2(); + init_lucide(); + sizeClasses = { + xs: "w-3 h-3", + sm: "w-4 h-4", + md: "w-5 h-5", + lg: "w-6 h-6", + xl: "w-8 h-8" + }; + } +}); + +// ../mini-lit/dist/index.js +var init_dist = __esm({ + "../mini-lit/dist/index.js"() { + "use strict"; + init_process_shim(); + init_component(); + init_i18n(); + init_icons(); + } +}); + +// ../mini-lit/dist/Button.js +var Button; +var init_Button = __esm({ + "../mini-lit/dist/Button.js"() { + "use strict"; + init_process_shim(); + init_mini(); + Button = fc(({ variant = "default", size = "md", disabled = false, type = "button", loading = false, onClick, title, className = "", children }) => { + const sizeClasses2 = { + sm: "h-8 rounded-md px-3 text-xs", + md: "h-9 rounded-md px-4 text-sm", + lg: "h-10 rounded-md px-8 text-sm", + icon: "size-8 rounded-md" + }; + const variantClasses = { + default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", + destructive: "bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90", + outline: "border border-input bg-background text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground", + secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", + ghost: "text-foreground hover:bg-accent hover:text-accent-foreground", + link: "text-primary underline-offset-4 hover:underline" + }; + const baseClasses = "inline-flex items-center justify-center whitespace-nowrap text-sm font-medium transition-all cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive"; + const gapClass = size === "icon" ? "" : "gap-2"; + const paddingAdjustClass = size === "icon" ? "" : "has-[>svg]:px-2.5"; + const variantClass = variantClasses[variant] || variantClasses.default; + const handleClick = (e9) => { + if (disabled || loading) { + e9.preventDefault(); + e9.stopPropagation(); + return; + } + onClick?.(e9); + }; + return b2` + + `; + }); + } +}); + +// ../mini-lit/dist/Input.js +var Input; +var init_Input = __esm({ + "../mini-lit/dist/Input.js"() { + "use strict"; + init_process_shim(); + init_ref2(); + init_i18n(); + init_mini(); + Input = fc(({ id = "", type = "text", size = "md", value = "", placeholder = "", label = "", error = "", disabled = false, readonly = false, required = false, name = "", autocomplete = "", min, max, step, inputRef, onInput, onChange, onKeyDown, onKeyUp, className = "" }) => { + const sizeClasses2 = { + sm: "h-8 px-3 py-1 text-sm", + md: "h-9 px-3 py-1 text-sm md:text-sm", + lg: "h-10 px-4 py-1 text-base" + }; + const baseClasses = "flex w-full min-w-0 rounded-md border bg-transparent text-foreground shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium"; + const interactionClasses = "placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground"; + const focusClasses = "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"; + const darkClasses = "dark:bg-input/30"; + const stateClasses = error ? "border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40" : "border-input"; + const disabledClasses = "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"; + const handleInput = (e9) => { + onInput?.(e9); + }; + const handleChange = (e9) => { + onChange?.(e9); + }; + return b2` +
+ ${label ? b2` + + ` : ""} + + ${error ? b2`${error}` : ""} +
+ `; + }); + } +}); + +// node_modules/@lit/reactive-element/decorators/custom-element.js +var t5; +var init_custom_element = __esm({ + "node_modules/@lit/reactive-element/decorators/custom-element.js"() { + init_process_shim(); + t5 = (t6) => (e9, o9) => { + void 0 !== o9 ? o9.addInitializer(() => { + customElements.define(t6, e9); + }) : customElements.define(t6, e9); + }; + } +}); + +// node_modules/@lit/reactive-element/decorators/property.js +function n6(t6) { + return (e9, o9) => "object" == typeof o9 ? r6(t6, e9, o9) : ((t7, e10, o10) => { + const r8 = e10.hasOwnProperty(o10); + return e10.constructor.createProperty(o10, t7), r8 ? Object.getOwnPropertyDescriptor(e10, o10) : void 0; + })(t6, e9, o9); +} +var o8, r6; +var init_property = __esm({ + "node_modules/@lit/reactive-element/decorators/property.js"() { + init_process_shim(); + init_reactive_element(); + o8 = { attribute: true, type: String, converter: u, reflect: false, hasChanged: f }; + r6 = (t6 = o8, e9, r8) => { + const { kind: n7, metadata: i7 } = r8; + let s6 = globalThis.litPropertyMetadata.get(i7); + if (void 0 === s6 && globalThis.litPropertyMetadata.set(i7, s6 = /* @__PURE__ */ new Map()), "setter" === n7 && ((t6 = Object.create(t6)).wrapped = true), s6.set(r8.name, t6), "accessor" === n7) { + const { name: o9 } = r8; + return { set(r9) { + const n8 = e9.get.call(this); + e9.set.call(this, r9), this.requestUpdate(o9, n8, t6, true, r9); + }, init(e10) { + return void 0 !== e10 && this.C(o9, void 0, t6, e10), e10; + } }; + } + if ("setter" === n7) { + const { name: o9 } = r8; + return function(r9) { + const n8 = this[o9]; + e9.call(this, r9), this.requestUpdate(o9, n8, t6, true, r9); + }; + } + throw Error("Unsupported decorator location: " + n7); + }; + } +}); + +// node_modules/@lit/reactive-element/decorators/state.js +function r7(r8) { + return n6({ ...r8, state: true, attribute: false }); +} +var init_state = __esm({ + "node_modules/@lit/reactive-element/decorators/state.js"() { + init_process_shim(); + init_property(); + } +}); + +// node_modules/@lit/reactive-element/decorators/event-options.js +var init_event_options = __esm({ + "node_modules/@lit/reactive-element/decorators/event-options.js"() { + init_process_shim(); + } +}); + +// node_modules/@lit/reactive-element/decorators/base.js +var e7; +var init_base = __esm({ + "node_modules/@lit/reactive-element/decorators/base.js"() { + init_process_shim(); + e7 = (e9, t6, c6) => (c6.configurable = true, c6.enumerable = true, Reflect.decorate && "object" != typeof t6 && Object.defineProperty(e9, t6, c6), c6); + } +}); + +// node_modules/@lit/reactive-element/decorators/query.js +function e8(e9, r8) { + return (n7, s6, i7) => { + const o9 = (t6) => t6.renderRoot?.querySelector(e9) ?? null; + if (r8) { + const { get: e10, set: r9 } = "object" == typeof s6 ? n7 : i7 ?? (() => { + const t6 = Symbol(); + return { get() { + return this[t6]; + }, set(e11) { + this[t6] = e11; + } }; + })(); + return e7(n7, s6, { get() { + let t6 = e10.call(this); + return void 0 === t6 && (t6 = o9(this), (null !== t6 || this.hasUpdated) && r9.call(this, t6)), t6; + } }); + } + return e7(n7, s6, { get() { + return o9(this); + } }); + }; +} +var init_query = __esm({ + "node_modules/@lit/reactive-element/decorators/query.js"() { + init_process_shim(); + init_base(); + } +}); + +// node_modules/@lit/reactive-element/decorators/query-all.js +var init_query_all = __esm({ + "node_modules/@lit/reactive-element/decorators/query-all.js"() { + init_process_shim(); + init_base(); + } +}); + +// node_modules/@lit/reactive-element/decorators/query-async.js +var init_query_async = __esm({ + "node_modules/@lit/reactive-element/decorators/query-async.js"() { + init_process_shim(); + init_base(); + } +}); + +// node_modules/@lit/reactive-element/decorators/query-assigned-elements.js +var init_query_assigned_elements = __esm({ + "node_modules/@lit/reactive-element/decorators/query-assigned-elements.js"() { + init_process_shim(); + init_base(); + } +}); + +// node_modules/@lit/reactive-element/decorators/query-assigned-nodes.js +var init_query_assigned_nodes = __esm({ + "node_modules/@lit/reactive-element/decorators/query-assigned-nodes.js"() { + init_process_shim(); + init_base(); + } +}); + +// node_modules/lit/decorators.js +var init_decorators = __esm({ + "node_modules/lit/decorators.js"() { + init_process_shim(); + init_custom_element(); + init_property(); + init_state(); + init_event_options(); + init_query(); + init_query_all(); + init_query_async(); + init_query_assigned_elements(); + init_query_assigned_nodes(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs +var value_exports = {}; +__export(value_exports, { + HasPropertyKey: () => HasPropertyKey, + IsArray: () => IsArray, + IsAsyncIterator: () => IsAsyncIterator, + IsBigInt: () => IsBigInt, + IsBoolean: () => IsBoolean, + IsDate: () => IsDate, + IsFunction: () => IsFunction, + IsIterator: () => IsIterator, + IsNull: () => IsNull, + IsNumber: () => IsNumber, + IsObject: () => IsObject, + IsRegExp: () => IsRegExp, + IsString: () => IsString, + IsSymbol: () => IsSymbol, + IsUint8Array: () => IsUint8Array, + IsUndefined: () => IsUndefined +}); +function HasPropertyKey(value, key) { + return key in value; +} +function IsAsyncIterator(value) { + return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.asyncIterator in value; +} +function IsArray(value) { + return Array.isArray(value); +} +function IsBigInt(value) { + return typeof value === "bigint"; +} +function IsBoolean(value) { + return typeof value === "boolean"; +} +function IsDate(value) { + return value instanceof globalThis.Date; +} +function IsFunction(value) { + return typeof value === "function"; +} +function IsIterator(value) { + return IsObject(value) && !IsArray(value) && !IsUint8Array(value) && Symbol.iterator in value; +} +function IsNull(value) { + return value === null; +} +function IsNumber(value) { + return typeof value === "number"; +} +function IsObject(value) { + return typeof value === "object" && value !== null; +} +function IsRegExp(value) { + return value instanceof globalThis.RegExp; +} +function IsString(value) { + return typeof value === "string"; +} +function IsSymbol(value) { + return typeof value === "symbol"; +} +function IsUint8Array(value) { + return value instanceof globalThis.Uint8Array; +} +function IsUndefined(value) { + return value === void 0; +} +var init_value = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/value.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs +function ArrayType(value) { + return value.map((value2) => Visit(value2)); +} +function DateType(value) { + return new Date(value.getTime()); +} +function Uint8ArrayType(value) { + return new Uint8Array(value); +} +function RegExpType(value) { + return new RegExp(value.source, value.flags); +} +function ObjectType(value) { + const result = {}; + for (const key of Object.getOwnPropertyNames(value)) { + result[key] = Visit(value[key]); + } + for (const key of Object.getOwnPropertySymbols(value)) { + result[key] = Visit(value[key]); + } + return result; +} +function Visit(value) { + return IsArray(value) ? ArrayType(value) : IsDate(value) ? DateType(value) : IsUint8Array(value) ? Uint8ArrayType(value) : IsRegExp(value) ? RegExpType(value) : IsObject(value) ? ObjectType(value) : value; +} +function Clone(value) { + return Visit(value); +} +var init_value2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/value.mjs"() { + init_process_shim(); + init_value(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs +function CloneType(schema, options) { + return options === void 0 ? Clone(schema) : Clone({ ...options, ...schema }); +} +var init_type = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/type.mjs"() { + init_process_shim(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/index.mjs +var init_clone = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/clone/index.mjs"() { + init_process_shim(); + init_type(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs +function IsObject2(value) { + return value !== null && typeof value === "object"; +} +function IsArray2(value) { + return globalThis.Array.isArray(value) && !globalThis.ArrayBuffer.isView(value); +} +function IsUndefined2(value) { + return value === void 0; +} +function IsNumber2(value) { + return typeof value === "number"; +} +var init_guard = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/value/guard/guard.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/value/guard/index.mjs +var init_guard2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/value/guard/index.mjs"() { + init_process_shim(); + init_guard(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/system/policy.mjs +var TypeSystemPolicy; +var init_policy = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/system/policy.mjs"() { + init_process_shim(); + init_guard2(); + (function(TypeSystemPolicy3) { + TypeSystemPolicy3.InstanceMode = "default"; + TypeSystemPolicy3.ExactOptionalPropertyTypes = false; + TypeSystemPolicy3.AllowArrayObject = false; + TypeSystemPolicy3.AllowNaN = false; + TypeSystemPolicy3.AllowNullVoid = false; + function IsExactOptionalProperty(value, key) { + return TypeSystemPolicy3.ExactOptionalPropertyTypes ? key in value : value[key] !== void 0; + } + TypeSystemPolicy3.IsExactOptionalProperty = IsExactOptionalProperty; + function IsObjectLike(value) { + const isObject4 = IsObject2(value); + return TypeSystemPolicy3.AllowArrayObject ? isObject4 : isObject4 && !IsArray2(value); + } + TypeSystemPolicy3.IsObjectLike = IsObjectLike; + function IsRecordLike(value) { + return IsObjectLike(value) && !(value instanceof Date) && !(value instanceof Uint8Array); + } + TypeSystemPolicy3.IsRecordLike = IsRecordLike; + function IsNumberLike(value) { + return TypeSystemPolicy3.AllowNaN ? IsNumber2(value) : Number.isFinite(value); + } + TypeSystemPolicy3.IsNumberLike = IsNumberLike; + function IsVoidLike(value) { + const isUndefined2 = IsUndefined2(value); + return TypeSystemPolicy3.AllowNullVoid ? isUndefined2 || value === null : isUndefined2; + } + TypeSystemPolicy3.IsVoidLike = IsVoidLike; + })(TypeSystemPolicy || (TypeSystemPolicy = {})); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs +function ImmutableArray(value) { + return globalThis.Object.freeze(value).map((value2) => Immutable(value2)); +} +function ImmutableDate(value) { + return value; +} +function ImmutableUint8Array(value) { + return value; +} +function ImmutableRegExp(value) { + return value; +} +function ImmutableObject(value) { + const result = {}; + for (const key of Object.getOwnPropertyNames(value)) { + result[key] = Immutable(value[key]); + } + for (const key of Object.getOwnPropertySymbols(value)) { + result[key] = Immutable(value[key]); + } + return globalThis.Object.freeze(result); +} +function Immutable(value) { + return IsArray(value) ? ImmutableArray(value) : IsDate(value) ? ImmutableDate(value) : IsUint8Array(value) ? ImmutableUint8Array(value) : IsRegExp(value) ? ImmutableRegExp(value) : IsObject(value) ? ImmutableObject(value) : value; +} +var init_immutable = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/immutable.mjs"() { + init_process_shim(); + init_value(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/type.mjs +function CreateType(schema, options) { + const result = options !== void 0 ? { ...options, ...schema } : schema; + switch (TypeSystemPolicy.InstanceMode) { + case "freeze": + return Immutable(result); + case "clone": + return Clone(result); + default: + return result; + } +} +var init_type2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/type.mjs"() { + init_process_shim(); + init_policy(); + init_immutable(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/index.mjs +var init_create = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/create/index.mjs"() { + init_process_shim(); + init_type2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/error/error.mjs +var TypeBoxError; +var init_error = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/error/error.mjs"() { + init_process_shim(); + TypeBoxError = class extends Error { + constructor(message) { + super(message); + } + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/error/index.mjs +var init_error2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/error/index.mjs"() { + init_process_shim(); + init_error(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs +var TransformKind, ReadonlyKind, OptionalKind, Hint, Kind; +var init_symbols = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbols/symbols.mjs"() { + init_process_shim(); + TransformKind = Symbol.for("TypeBox.Transform"); + ReadonlyKind = Symbol.for("TypeBox.Readonly"); + OptionalKind = Symbol.for("TypeBox.Optional"); + Hint = Symbol.for("TypeBox.Hint"); + Kind = Symbol.for("TypeBox.Kind"); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbols/index.mjs +var init_symbols2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbols/index.mjs"() { + init_process_shim(); + init_symbols(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs +function IsReadonly(value) { + return IsObject(value) && value[ReadonlyKind] === "Readonly"; +} +function IsOptional(value) { + return IsObject(value) && value[OptionalKind] === "Optional"; +} +function IsAny(value) { + return IsKindOf(value, "Any"); +} +function IsArgument(value) { + return IsKindOf(value, "Argument"); +} +function IsArray3(value) { + return IsKindOf(value, "Array"); +} +function IsAsyncIterator2(value) { + return IsKindOf(value, "AsyncIterator"); +} +function IsBigInt2(value) { + return IsKindOf(value, "BigInt"); +} +function IsBoolean2(value) { + return IsKindOf(value, "Boolean"); +} +function IsComputed(value) { + return IsKindOf(value, "Computed"); +} +function IsConstructor(value) { + return IsKindOf(value, "Constructor"); +} +function IsDate2(value) { + return IsKindOf(value, "Date"); +} +function IsFunction2(value) { + return IsKindOf(value, "Function"); +} +function IsInteger(value) { + return IsKindOf(value, "Integer"); +} +function IsIntersect(value) { + return IsKindOf(value, "Intersect"); +} +function IsIterator2(value) { + return IsKindOf(value, "Iterator"); +} +function IsKindOf(value, kind) { + return IsObject(value) && Kind in value && value[Kind] === kind; +} +function IsLiteralValue(value) { + return IsBoolean(value) || IsNumber(value) || IsString(value); +} +function IsLiteral(value) { + return IsKindOf(value, "Literal"); +} +function IsMappedKey(value) { + return IsKindOf(value, "MappedKey"); +} +function IsMappedResult(value) { + return IsKindOf(value, "MappedResult"); +} +function IsNever(value) { + return IsKindOf(value, "Never"); +} +function IsNot(value) { + return IsKindOf(value, "Not"); +} +function IsNull2(value) { + return IsKindOf(value, "Null"); +} +function IsNumber3(value) { + return IsKindOf(value, "Number"); +} +function IsObject3(value) { + return IsKindOf(value, "Object"); +} +function IsPromise(value) { + return IsKindOf(value, "Promise"); +} +function IsRecord(value) { + return IsKindOf(value, "Record"); +} +function IsRef(value) { + return IsKindOf(value, "Ref"); +} +function IsRegExp2(value) { + return IsKindOf(value, "RegExp"); +} +function IsString2(value) { + return IsKindOf(value, "String"); +} +function IsSymbol2(value) { + return IsKindOf(value, "Symbol"); +} +function IsTemplateLiteral(value) { + return IsKindOf(value, "TemplateLiteral"); +} +function IsThis(value) { + return IsKindOf(value, "This"); +} +function IsTransform(value) { + return IsObject(value) && TransformKind in value; +} +function IsTuple(value) { + return IsKindOf(value, "Tuple"); +} +function IsUndefined3(value) { + return IsKindOf(value, "Undefined"); +} +function IsUnion(value) { + return IsKindOf(value, "Union"); +} +function IsUint8Array2(value) { + return IsKindOf(value, "Uint8Array"); +} +function IsUnknown(value) { + return IsKindOf(value, "Unknown"); +} +function IsUnsafe(value) { + return IsKindOf(value, "Unsafe"); +} +function IsVoid(value) { + return IsKindOf(value, "Void"); +} +function IsKind(value) { + return IsObject(value) && Kind in value && IsString(value[Kind]); +} +function IsSchema(value) { + return IsAny(value) || IsArgument(value) || IsArray3(value) || IsBoolean2(value) || IsBigInt2(value) || IsAsyncIterator2(value) || IsComputed(value) || IsConstructor(value) || IsDate2(value) || IsFunction2(value) || IsInteger(value) || IsIntersect(value) || IsIterator2(value) || IsLiteral(value) || IsMappedKey(value) || IsMappedResult(value) || IsNever(value) || IsNot(value) || IsNull2(value) || IsNumber3(value) || IsObject3(value) || IsPromise(value) || IsRecord(value) || IsRef(value) || IsRegExp2(value) || IsString2(value) || IsSymbol2(value) || IsTemplateLiteral(value) || IsThis(value) || IsTuple(value) || IsUndefined3(value) || IsUnion(value) || IsUint8Array2(value) || IsUnknown(value) || IsUnsafe(value) || IsVoid(value) || IsKind(value); +} +var init_kind = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/kind.mjs"() { + init_process_shim(); + init_value(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs +var type_exports = {}; +__export(type_exports, { + IsAny: () => IsAny2, + IsArgument: () => IsArgument2, + IsArray: () => IsArray4, + IsAsyncIterator: () => IsAsyncIterator3, + IsBigInt: () => IsBigInt3, + IsBoolean: () => IsBoolean3, + IsComputed: () => IsComputed2, + IsConstructor: () => IsConstructor2, + IsDate: () => IsDate3, + IsFunction: () => IsFunction3, + IsImport: () => IsImport, + IsInteger: () => IsInteger2, + IsIntersect: () => IsIntersect2, + IsIterator: () => IsIterator3, + IsKind: () => IsKind2, + IsKindOf: () => IsKindOf2, + IsLiteral: () => IsLiteral2, + IsLiteralBoolean: () => IsLiteralBoolean, + IsLiteralNumber: () => IsLiteralNumber, + IsLiteralString: () => IsLiteralString, + IsLiteralValue: () => IsLiteralValue2, + IsMappedKey: () => IsMappedKey2, + IsMappedResult: () => IsMappedResult2, + IsNever: () => IsNever2, + IsNot: () => IsNot2, + IsNull: () => IsNull3, + IsNumber: () => IsNumber4, + IsObject: () => IsObject4, + IsOptional: () => IsOptional2, + IsPromise: () => IsPromise2, + IsProperties: () => IsProperties, + IsReadonly: () => IsReadonly2, + IsRecord: () => IsRecord2, + IsRecursive: () => IsRecursive, + IsRef: () => IsRef2, + IsRegExp: () => IsRegExp3, + IsSchema: () => IsSchema2, + IsString: () => IsString3, + IsSymbol: () => IsSymbol3, + IsTemplateLiteral: () => IsTemplateLiteral2, + IsThis: () => IsThis2, + IsTransform: () => IsTransform2, + IsTuple: () => IsTuple2, + IsUint8Array: () => IsUint8Array3, + IsUndefined: () => IsUndefined4, + IsUnion: () => IsUnion2, + IsUnionLiteral: () => IsUnionLiteral, + IsUnknown: () => IsUnknown2, + IsUnsafe: () => IsUnsafe2, + IsVoid: () => IsVoid2, + TypeGuardUnknownTypeError: () => TypeGuardUnknownTypeError +}); +function IsPattern(value) { + try { + new RegExp(value); + return true; + } catch { + return false; + } +} +function IsControlCharacterFree(value) { + if (!IsString(value)) + return false; + for (let i7 = 0; i7 < value.length; i7++) { + const code = value.charCodeAt(i7); + if (code >= 7 && code <= 13 || code === 27 || code === 127) { + return false; + } + } + return true; +} +function IsAdditionalProperties(value) { + return IsOptionalBoolean(value) || IsSchema2(value); +} +function IsOptionalBigInt(value) { + return IsUndefined(value) || IsBigInt(value); +} +function IsOptionalNumber(value) { + return IsUndefined(value) || IsNumber(value); +} +function IsOptionalBoolean(value) { + return IsUndefined(value) || IsBoolean(value); +} +function IsOptionalString(value) { + return IsUndefined(value) || IsString(value); +} +function IsOptionalPattern(value) { + return IsUndefined(value) || IsString(value) && IsControlCharacterFree(value) && IsPattern(value); +} +function IsOptionalFormat(value) { + return IsUndefined(value) || IsString(value) && IsControlCharacterFree(value); +} +function IsOptionalSchema(value) { + return IsUndefined(value) || IsSchema2(value); +} +function IsReadonly2(value) { + return IsObject(value) && value[ReadonlyKind] === "Readonly"; +} +function IsOptional2(value) { + return IsObject(value) && value[OptionalKind] === "Optional"; +} +function IsAny2(value) { + return IsKindOf2(value, "Any") && IsOptionalString(value.$id); +} +function IsArgument2(value) { + return IsKindOf2(value, "Argument") && IsNumber(value.index); +} +function IsArray4(value) { + return IsKindOf2(value, "Array") && value.type === "array" && IsOptionalString(value.$id) && IsSchema2(value.items) && IsOptionalNumber(value.minItems) && IsOptionalNumber(value.maxItems) && IsOptionalBoolean(value.uniqueItems) && IsOptionalSchema(value.contains) && IsOptionalNumber(value.minContains) && IsOptionalNumber(value.maxContains); +} +function IsAsyncIterator3(value) { + return IsKindOf2(value, "AsyncIterator") && value.type === "AsyncIterator" && IsOptionalString(value.$id) && IsSchema2(value.items); +} +function IsBigInt3(value) { + return IsKindOf2(value, "BigInt") && value.type === "bigint" && IsOptionalString(value.$id) && IsOptionalBigInt(value.exclusiveMaximum) && IsOptionalBigInt(value.exclusiveMinimum) && IsOptionalBigInt(value.maximum) && IsOptionalBigInt(value.minimum) && IsOptionalBigInt(value.multipleOf); +} +function IsBoolean3(value) { + return IsKindOf2(value, "Boolean") && value.type === "boolean" && IsOptionalString(value.$id); +} +function IsComputed2(value) { + return IsKindOf2(value, "Computed") && IsString(value.target) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)); +} +function IsConstructor2(value) { + return IsKindOf2(value, "Constructor") && value.type === "Constructor" && IsOptionalString(value.$id) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)) && IsSchema2(value.returns); +} +function IsDate3(value) { + return IsKindOf2(value, "Date") && value.type === "Date" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximumTimestamp) && IsOptionalNumber(value.exclusiveMinimumTimestamp) && IsOptionalNumber(value.maximumTimestamp) && IsOptionalNumber(value.minimumTimestamp) && IsOptionalNumber(value.multipleOfTimestamp); +} +function IsFunction3(value) { + return IsKindOf2(value, "Function") && value.type === "Function" && IsOptionalString(value.$id) && IsArray(value.parameters) && value.parameters.every((schema) => IsSchema2(schema)) && IsSchema2(value.returns); +} +function IsImport(value) { + return IsKindOf2(value, "Import") && HasPropertyKey(value, "$defs") && IsObject(value.$defs) && IsProperties(value.$defs) && HasPropertyKey(value, "$ref") && IsString(value.$ref) && value.$ref in value.$defs; +} +function IsInteger2(value) { + return IsKindOf2(value, "Integer") && value.type === "integer" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf); +} +function IsProperties(value) { + return IsObject(value) && Object.entries(value).every(([key, schema]) => IsControlCharacterFree(key) && IsSchema2(schema)); +} +function IsIntersect2(value) { + return IsKindOf2(value, "Intersect") && (IsString(value.type) && value.type !== "object" ? false : true) && IsArray(value.allOf) && value.allOf.every((schema) => IsSchema2(schema) && !IsTransform2(schema)) && IsOptionalString(value.type) && (IsOptionalBoolean(value.unevaluatedProperties) || IsOptionalSchema(value.unevaluatedProperties)) && IsOptionalString(value.$id); +} +function IsIterator3(value) { + return IsKindOf2(value, "Iterator") && value.type === "Iterator" && IsOptionalString(value.$id) && IsSchema2(value.items); +} +function IsKindOf2(value, kind) { + return IsObject(value) && Kind in value && value[Kind] === kind; +} +function IsLiteralString(value) { + return IsLiteral2(value) && IsString(value.const); +} +function IsLiteralNumber(value) { + return IsLiteral2(value) && IsNumber(value.const); +} +function IsLiteralBoolean(value) { + return IsLiteral2(value) && IsBoolean(value.const); +} +function IsLiteral2(value) { + return IsKindOf2(value, "Literal") && IsOptionalString(value.$id) && IsLiteralValue2(value.const); +} +function IsLiteralValue2(value) { + return IsBoolean(value) || IsNumber(value) || IsString(value); +} +function IsMappedKey2(value) { + return IsKindOf2(value, "MappedKey") && IsArray(value.keys) && value.keys.every((key) => IsNumber(key) || IsString(key)); +} +function IsMappedResult2(value) { + return IsKindOf2(value, "MappedResult") && IsProperties(value.properties); +} +function IsNever2(value) { + return IsKindOf2(value, "Never") && IsObject(value.not) && Object.getOwnPropertyNames(value.not).length === 0; +} +function IsNot2(value) { + return IsKindOf2(value, "Not") && IsSchema2(value.not); +} +function IsNull3(value) { + return IsKindOf2(value, "Null") && value.type === "null" && IsOptionalString(value.$id); +} +function IsNumber4(value) { + return IsKindOf2(value, "Number") && value.type === "number" && IsOptionalString(value.$id) && IsOptionalNumber(value.exclusiveMaximum) && IsOptionalNumber(value.exclusiveMinimum) && IsOptionalNumber(value.maximum) && IsOptionalNumber(value.minimum) && IsOptionalNumber(value.multipleOf); +} +function IsObject4(value) { + return IsKindOf2(value, "Object") && value.type === "object" && IsOptionalString(value.$id) && IsProperties(value.properties) && IsAdditionalProperties(value.additionalProperties) && IsOptionalNumber(value.minProperties) && IsOptionalNumber(value.maxProperties); +} +function IsPromise2(value) { + return IsKindOf2(value, "Promise") && value.type === "Promise" && IsOptionalString(value.$id) && IsSchema2(value.item); +} +function IsRecord2(value) { + return IsKindOf2(value, "Record") && value.type === "object" && IsOptionalString(value.$id) && IsAdditionalProperties(value.additionalProperties) && IsObject(value.patternProperties) && ((schema) => { + const keys2 = Object.getOwnPropertyNames(schema.patternProperties); + return keys2.length === 1 && IsPattern(keys2[0]) && IsObject(schema.patternProperties) && IsSchema2(schema.patternProperties[keys2[0]]); + })(value); +} +function IsRecursive(value) { + return IsObject(value) && Hint in value && value[Hint] === "Recursive"; +} +function IsRef2(value) { + return IsKindOf2(value, "Ref") && IsOptionalString(value.$id) && IsString(value.$ref); +} +function IsRegExp3(value) { + return IsKindOf2(value, "RegExp") && IsOptionalString(value.$id) && IsString(value.source) && IsString(value.flags) && IsOptionalNumber(value.maxLength) && IsOptionalNumber(value.minLength); +} +function IsString3(value) { + return IsKindOf2(value, "String") && value.type === "string" && IsOptionalString(value.$id) && IsOptionalNumber(value.minLength) && IsOptionalNumber(value.maxLength) && IsOptionalPattern(value.pattern) && IsOptionalFormat(value.format); +} +function IsSymbol3(value) { + return IsKindOf2(value, "Symbol") && value.type === "symbol" && IsOptionalString(value.$id); +} +function IsTemplateLiteral2(value) { + return IsKindOf2(value, "TemplateLiteral") && value.type === "string" && IsString(value.pattern) && value.pattern[0] === "^" && value.pattern[value.pattern.length - 1] === "$"; +} +function IsThis2(value) { + return IsKindOf2(value, "This") && IsOptionalString(value.$id) && IsString(value.$ref); +} +function IsTransform2(value) { + return IsObject(value) && TransformKind in value; +} +function IsTuple2(value) { + return IsKindOf2(value, "Tuple") && value.type === "array" && IsOptionalString(value.$id) && IsNumber(value.minItems) && IsNumber(value.maxItems) && value.minItems === value.maxItems && // empty + (IsUndefined(value.items) && IsUndefined(value.additionalItems) && value.minItems === 0 || IsArray(value.items) && value.items.every((schema) => IsSchema2(schema))); +} +function IsUndefined4(value) { + return IsKindOf2(value, "Undefined") && value.type === "undefined" && IsOptionalString(value.$id); +} +function IsUnionLiteral(value) { + return IsUnion2(value) && value.anyOf.every((schema) => IsLiteralString(schema) || IsLiteralNumber(schema)); +} +function IsUnion2(value) { + return IsKindOf2(value, "Union") && IsOptionalString(value.$id) && IsObject(value) && IsArray(value.anyOf) && value.anyOf.every((schema) => IsSchema2(schema)); +} +function IsUint8Array3(value) { + return IsKindOf2(value, "Uint8Array") && value.type === "Uint8Array" && IsOptionalString(value.$id) && IsOptionalNumber(value.minByteLength) && IsOptionalNumber(value.maxByteLength); +} +function IsUnknown2(value) { + return IsKindOf2(value, "Unknown") && IsOptionalString(value.$id); +} +function IsUnsafe2(value) { + return IsKindOf2(value, "Unsafe"); +} +function IsVoid2(value) { + return IsKindOf2(value, "Void") && value.type === "void" && IsOptionalString(value.$id); +} +function IsKind2(value) { + return IsObject(value) && Kind in value && IsString(value[Kind]) && !KnownTypes.includes(value[Kind]); +} +function IsSchema2(value) { + return IsObject(value) && (IsAny2(value) || IsArgument2(value) || IsArray4(value) || IsBoolean3(value) || IsBigInt3(value) || IsAsyncIterator3(value) || IsComputed2(value) || IsConstructor2(value) || IsDate3(value) || IsFunction3(value) || IsInteger2(value) || IsIntersect2(value) || IsIterator3(value) || IsLiteral2(value) || IsMappedKey2(value) || IsMappedResult2(value) || IsNever2(value) || IsNot2(value) || IsNull3(value) || IsNumber4(value) || IsObject4(value) || IsPromise2(value) || IsRecord2(value) || IsRef2(value) || IsRegExp3(value) || IsString3(value) || IsSymbol3(value) || IsTemplateLiteral2(value) || IsThis2(value) || IsTuple2(value) || IsUndefined4(value) || IsUnion2(value) || IsUint8Array3(value) || IsUnknown2(value) || IsUnsafe2(value) || IsVoid2(value) || IsKind2(value)); +} +var TypeGuardUnknownTypeError, KnownTypes; +var init_type3 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/type.mjs"() { + init_process_shim(); + init_value(); + init_symbols2(); + init_error2(); + TypeGuardUnknownTypeError = class extends TypeBoxError { + }; + KnownTypes = [ + "Argument", + "Any", + "Array", + "AsyncIterator", + "BigInt", + "Boolean", + "Computed", + "Constructor", + "Date", + "Enum", + "Function", + "Integer", + "Intersect", + "Iterator", + "Literal", + "MappedKey", + "MappedResult", + "Not", + "Null", + "Number", + "Object", + "Promise", + "Record", + "Ref", + "RegExp", + "String", + "Symbol", + "TemplateLiteral", + "This", + "Tuple", + "Undefined", + "Union", + "Uint8Array", + "Unknown", + "Void" + ]; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/index.mjs +var init_guard3 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/guard/index.mjs"() { + init_process_shim(); + init_kind(); + init_type3(); + init_value(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/helpers/helpers.mjs +var init_helpers = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/helpers/helpers.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/helpers/index.mjs +var init_helpers2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/helpers/index.mjs"() { + init_process_shim(); + init_helpers(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs +var PatternBoolean, PatternNumber, PatternString, PatternNever, PatternBooleanExact, PatternNumberExact, PatternStringExact, PatternNeverExact; +var init_patterns = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/patterns/patterns.mjs"() { + init_process_shim(); + PatternBoolean = "(true|false)"; + PatternNumber = "(0|[1-9][0-9]*)"; + PatternString = "(.*)"; + PatternNever = "(?!.*)"; + PatternBooleanExact = `^${PatternBoolean}$`; + PatternNumberExact = `^${PatternNumber}$`; + PatternStringExact = `^${PatternString}$`; + PatternNeverExact = `^${PatternNever}$`; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/patterns/index.mjs +var init_patterns2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/patterns/index.mjs"() { + init_process_shim(); + init_patterns(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/registry/format.mjs +var init_format = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/registry/format.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/registry/type.mjs +var init_type4 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/registry/type.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/registry/index.mjs +var init_registry = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/registry/index.mjs"() { + init_process_shim(); + init_format(); + init_type4(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs +function SetIncludes(T3, S5) { + return T3.includes(S5); +} +function SetDistinct(T3) { + return [...new Set(T3)]; +} +function SetIntersect(T3, S5) { + return T3.filter((L3) => S5.includes(L3)); +} +function SetIntersectManyResolve(T3, Init) { + return T3.reduce((Acc, L3) => { + return SetIntersect(Acc, L3); + }, Init); +} +function SetIntersectMany(T3) { + return T3.length === 1 ? T3[0] : T3.length > 1 ? SetIntersectManyResolve(T3.slice(1), T3[0]) : []; +} +function SetUnionMany(T3) { + const Acc = []; + for (const L3 of T3) + Acc.push(...L3); + return Acc; +} +var init_set = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/sets/set.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/sets/index.mjs +var init_sets = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/sets/index.mjs"() { + init_process_shim(); + init_set(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/any/any.mjs +function Any(options) { + return CreateType({ [Kind]: "Any" }, options); +} +var init_any = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/any/any.mjs"() { + init_process_shim(); + init_create(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/any/index.mjs +var init_any2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/any/index.mjs"() { + init_process_shim(); + init_any(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/array/array.mjs +function Array2(items, options) { + return CreateType({ [Kind]: "Array", type: "array", items }, options); +} +var init_array = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/array/array.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/array/index.mjs +var init_array2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/array/index.mjs"() { + init_process_shim(); + init_array(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs +function Argument(index2) { + return CreateType({ [Kind]: "Argument", index: index2 }); +} +var init_argument = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/argument/argument.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/argument/index.mjs +var init_argument2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/argument/index.mjs"() { + init_process_shim(); + init_argument(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs +function AsyncIterator2(items, options) { + return CreateType({ [Kind]: "AsyncIterator", type: "AsyncIterator", items }, options); +} +var init_async_iterator = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/async-iterator/async-iterator.mjs"() { + init_process_shim(); + init_symbols2(); + init_type2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/async-iterator/index.mjs +var init_async_iterator2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/async-iterator/index.mjs"() { + init_process_shim(); + init_async_iterator(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs +function Computed(target, parameters, options) { + return CreateType({ [Kind]: "Computed", target, parameters }, options); +} +var init_computed = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/computed/computed.mjs"() { + init_process_shim(); + init_create(); + init_symbols(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/computed/index.mjs +var init_computed2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/computed/index.mjs"() { + init_process_shim(); + init_computed(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs +function DiscardKey(value, key) { + const { [key]: _3, ...rest } = value; + return rest; +} +function Discard(value, keys2) { + return keys2.reduce((acc, key) => DiscardKey(acc, key), value); +} +var init_discard = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/discard/discard.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/discard/index.mjs +var init_discard2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/discard/index.mjs"() { + init_process_shim(); + init_discard(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/never/never.mjs +function Never(options) { + return CreateType({ [Kind]: "Never", not: {} }, options); +} +var init_never = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/never/never.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/never/index.mjs +var init_never2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/never/index.mjs"() { + init_process_shim(); + init_never(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-key.mjs +var init_mapped_key = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-key.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs +function MappedResult(properties) { + return CreateType({ + [Kind]: "MappedResult", + properties + }); +} +var init_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped-result.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs +function Constructor(parameters, returns, options) { + return CreateType({ [Kind]: "Constructor", type: "Constructor", parameters, returns }, options); +} +var init_constructor = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor/constructor.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor/index.mjs +var init_constructor2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor/index.mjs"() { + init_process_shim(); + init_constructor(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/function/function.mjs +function Function2(parameters, returns, options) { + return CreateType({ [Kind]: "Function", type: "Function", parameters, returns }, options); +} +var init_function = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/function/function.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/function/index.mjs +var init_function2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/function/index.mjs"() { + init_process_shim(); + init_function(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs +function UnionCreate(T3, options) { + return CreateType({ [Kind]: "Union", anyOf: T3 }, options); +} +var init_union_create = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-create.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs +function IsUnionOptional(types2) { + return types2.some((type) => IsOptional(type)); +} +function RemoveOptionalFromRest(types2) { + return types2.map((left) => IsOptional(left) ? RemoveOptionalFromType(left) : left); +} +function RemoveOptionalFromType(T3) { + return Discard(T3, [OptionalKind]); +} +function ResolveUnion(types2, options) { + const isOptional = IsUnionOptional(types2); + return isOptional ? Optional(UnionCreate(RemoveOptionalFromRest(types2), options)) : UnionCreate(RemoveOptionalFromRest(types2), options); +} +function UnionEvaluated(T3, options) { + return T3.length === 1 ? CreateType(T3[0], options) : T3.length === 0 ? Never(options) : ResolveUnion(T3, options); +} +var init_union_evaluated = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-evaluated.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + init_discard2(); + init_never2(); + init_optional2(); + init_union_create(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-type.mjs +var init_union_type = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union-type.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union.mjs +function Union(types2, options) { + return types2.length === 0 ? Never(options) : types2.length === 1 ? CreateType(types2[0], options) : UnionCreate(types2, options); +} +var init_union = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/union.mjs"() { + init_process_shim(); + init_never2(); + init_type2(); + init_union_create(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/index.mjs +var init_union2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/union/index.mjs"() { + init_process_shim(); + init_union_evaluated(); + init_union_type(); + init_union(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs +function Unescape(pattern) { + return pattern.replace(/\\\$/g, "$").replace(/\\\*/g, "*").replace(/\\\^/g, "^").replace(/\\\|/g, "|").replace(/\\\(/g, "(").replace(/\\\)/g, ")"); +} +function IsNonEscaped(pattern, index2, char) { + return pattern[index2] === char && pattern.charCodeAt(index2 - 1) !== 92; +} +function IsOpenParen(pattern, index2) { + return IsNonEscaped(pattern, index2, "("); +} +function IsCloseParen(pattern, index2) { + return IsNonEscaped(pattern, index2, ")"); +} +function IsSeparator(pattern, index2) { + return IsNonEscaped(pattern, index2, "|"); +} +function IsGroup(pattern) { + if (!(IsOpenParen(pattern, 0) && IsCloseParen(pattern, pattern.length - 1))) + return false; + let count = 0; + for (let index2 = 0; index2 < pattern.length; index2++) { + if (IsOpenParen(pattern, index2)) + count += 1; + if (IsCloseParen(pattern, index2)) + count -= 1; + if (count === 0 && index2 !== pattern.length - 1) + return false; + } + return true; +} +function InGroup(pattern) { + return pattern.slice(1, pattern.length - 1); +} +function IsPrecedenceOr(pattern) { + let count = 0; + for (let index2 = 0; index2 < pattern.length; index2++) { + if (IsOpenParen(pattern, index2)) + count += 1; + if (IsCloseParen(pattern, index2)) + count -= 1; + if (IsSeparator(pattern, index2) && count === 0) + return true; + } + return false; +} +function IsPrecedenceAnd(pattern) { + for (let index2 = 0; index2 < pattern.length; index2++) { + if (IsOpenParen(pattern, index2)) + return true; + } + return false; +} +function Or(pattern) { + let [count, start] = [0, 0]; + const expressions = []; + for (let index2 = 0; index2 < pattern.length; index2++) { + if (IsOpenParen(pattern, index2)) + count += 1; + if (IsCloseParen(pattern, index2)) + count -= 1; + if (IsSeparator(pattern, index2) && count === 0) { + const range3 = pattern.slice(start, index2); + if (range3.length > 0) + expressions.push(TemplateLiteralParse(range3)); + start = index2 + 1; + } + } + const range2 = pattern.slice(start); + if (range2.length > 0) + expressions.push(TemplateLiteralParse(range2)); + if (expressions.length === 0) + return { type: "const", const: "" }; + if (expressions.length === 1) + return expressions[0]; + return { type: "or", expr: expressions }; +} +function And(pattern) { + function Group2(value, index2) { + if (!IsOpenParen(value, index2)) + throw new TemplateLiteralParserError(`TemplateLiteralParser: Index must point to open parens`); + let count = 0; + for (let scan2 = index2; scan2 < value.length; scan2++) { + if (IsOpenParen(value, scan2)) + count += 1; + if (IsCloseParen(value, scan2)) + count -= 1; + if (count === 0) + return [index2, scan2]; + } + throw new TemplateLiteralParserError(`TemplateLiteralParser: Unclosed group parens in expression`); + } + function Range2(pattern2, index2) { + for (let scan2 = index2; scan2 < pattern2.length; scan2++) { + if (IsOpenParen(pattern2, scan2)) + return [index2, scan2]; + } + return [index2, pattern2.length]; + } + const expressions = []; + for (let index2 = 0; index2 < pattern.length; index2++) { + if (IsOpenParen(pattern, index2)) { + const [start, end] = Group2(pattern, index2); + const range2 = pattern.slice(start, end + 1); + expressions.push(TemplateLiteralParse(range2)); + index2 = end; + } else { + const [start, end] = Range2(pattern, index2); + const range2 = pattern.slice(start, end); + if (range2.length > 0) + expressions.push(TemplateLiteralParse(range2)); + index2 = end - 1; + } + } + return expressions.length === 0 ? { type: "const", const: "" } : expressions.length === 1 ? expressions[0] : { type: "and", expr: expressions }; +} +function TemplateLiteralParse(pattern) { + return IsGroup(pattern) ? TemplateLiteralParse(InGroup(pattern)) : IsPrecedenceOr(pattern) ? Or(pattern) : IsPrecedenceAnd(pattern) ? And(pattern) : { type: "const", const: Unescape(pattern) }; +} +function TemplateLiteralParseExact(pattern) { + return TemplateLiteralParse(pattern.slice(1, pattern.length - 1)); +} +var TemplateLiteralParserError; +var init_parse = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/parse.mjs"() { + init_process_shim(); + init_error2(); + TemplateLiteralParserError = class extends TypeBoxError { + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs +function IsNumberExpression(expression) { + return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "0" && expression.expr[1].type === "const" && expression.expr[1].const === "[1-9][0-9]*"; +} +function IsBooleanExpression(expression) { + return expression.type === "or" && expression.expr.length === 2 && expression.expr[0].type === "const" && expression.expr[0].const === "true" && expression.expr[1].type === "const" && expression.expr[1].const === "false"; +} +function IsStringExpression(expression) { + return expression.type === "const" && expression.const === ".*"; +} +function IsTemplateLiteralExpressionFinite(expression) { + return IsNumberExpression(expression) || IsStringExpression(expression) ? false : IsBooleanExpression(expression) ? true : expression.type === "and" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "or" ? expression.expr.every((expr) => IsTemplateLiteralExpressionFinite(expr)) : expression.type === "const" ? true : (() => { + throw new TemplateLiteralFiniteError(`Unknown expression type`); + })(); +} +function IsTemplateLiteralFinite(schema) { + const expression = TemplateLiteralParseExact(schema.pattern); + return IsTemplateLiteralExpressionFinite(expression); +} +var TemplateLiteralFiniteError; +var init_finite = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/finite.mjs"() { + init_process_shim(); + init_parse(); + init_error2(); + TemplateLiteralFiniteError = class extends TypeBoxError { + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs +function* GenerateReduce(buffer) { + if (buffer.length === 1) + return yield* buffer[0]; + for (const left of buffer[0]) { + for (const right of GenerateReduce(buffer.slice(1))) { + yield `${left}${right}`; + } + } +} +function* GenerateAnd(expression) { + return yield* GenerateReduce(expression.expr.map((expr) => [...TemplateLiteralExpressionGenerate(expr)])); +} +function* GenerateOr(expression) { + for (const expr of expression.expr) + yield* TemplateLiteralExpressionGenerate(expr); +} +function* GenerateConst(expression) { + return yield expression.const; +} +function* TemplateLiteralExpressionGenerate(expression) { + return expression.type === "and" ? yield* GenerateAnd(expression) : expression.type === "or" ? yield* GenerateOr(expression) : expression.type === "const" ? yield* GenerateConst(expression) : (() => { + throw new TemplateLiteralGenerateError("Unknown expression"); + })(); +} +function TemplateLiteralGenerate(schema) { + const expression = TemplateLiteralParseExact(schema.pattern); + return IsTemplateLiteralExpressionFinite(expression) ? [...TemplateLiteralExpressionGenerate(expression)] : []; +} +var TemplateLiteralGenerateError; +var init_generate = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/generate.mjs"() { + init_process_shim(); + init_finite(); + init_parse(); + init_error2(); + TemplateLiteralGenerateError = class extends TypeBoxError { + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs +function Literal(value, options) { + return CreateType({ + [Kind]: "Literal", + const: value, + type: typeof value + }, options); +} +var init_literal = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/literal/literal.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/literal/index.mjs +var init_literal2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/literal/index.mjs"() { + init_process_shim(); + init_literal(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs +function Boolean2(options) { + return CreateType({ [Kind]: "Boolean", type: "boolean" }, options); +} +var init_boolean = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/boolean/boolean.mjs"() { + init_process_shim(); + init_symbols2(); + init_create(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/boolean/index.mjs +var init_boolean2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/boolean/index.mjs"() { + init_process_shim(); + init_boolean(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs +function BigInt2(options) { + return CreateType({ [Kind]: "BigInt", type: "bigint" }, options); +} +var init_bigint = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/bigint/bigint.mjs"() { + init_process_shim(); + init_symbols2(); + init_create(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/bigint/index.mjs +var init_bigint2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/bigint/index.mjs"() { + init_process_shim(); + init_bigint(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/number/number.mjs +function Number2(options) { + return CreateType({ [Kind]: "Number", type: "number" }, options); +} +var init_number = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/number/number.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/number/index.mjs +var init_number2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/number/index.mjs"() { + init_process_shim(); + init_number(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/string/string.mjs +function String2(options) { + return CreateType({ [Kind]: "String", type: "string" }, options); +} +var init_string = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/string/string.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/string/index.mjs +var init_string2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/string/index.mjs"() { + init_process_shim(); + init_string(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs +function* FromUnion(syntax) { + const trim = syntax.trim().replace(/"|'/g, ""); + return trim === "boolean" ? yield Boolean2() : trim === "number" ? yield Number2() : trim === "bigint" ? yield BigInt2() : trim === "string" ? yield String2() : yield (() => { + const literals = trim.split("|").map((literal) => Literal(literal.trim())); + return literals.length === 0 ? Never() : literals.length === 1 ? literals[0] : UnionEvaluated(literals); + })(); +} +function* FromTerminal(syntax) { + if (syntax[1] !== "{") { + const L3 = Literal("$"); + const R3 = FromSyntax(syntax.slice(1)); + return yield* [L3, ...R3]; + } + for (let i7 = 2; i7 < syntax.length; i7++) { + if (syntax[i7] === "}") { + const L3 = FromUnion(syntax.slice(2, i7)); + const R3 = FromSyntax(syntax.slice(i7 + 1)); + return yield* [...L3, ...R3]; + } + } + yield Literal(syntax); +} +function* FromSyntax(syntax) { + for (let i7 = 0; i7 < syntax.length; i7++) { + if (syntax[i7] === "$") { + const L3 = Literal(syntax.slice(0, i7)); + const R3 = FromTerminal(syntax.slice(i7)); + return yield* [L3, ...R3]; + } + } + yield Literal(syntax); +} +function TemplateLiteralSyntax(syntax) { + return [...FromSyntax(syntax)]; +} +var init_syntax = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/syntax.mjs"() { + init_process_shim(); + init_literal2(); + init_boolean2(); + init_bigint2(); + init_number2(); + init_string2(); + init_union2(); + init_never2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs +function Escape(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function Visit2(schema, acc) { + return IsTemplateLiteral(schema) ? schema.pattern.slice(1, schema.pattern.length - 1) : IsUnion(schema) ? `(${schema.anyOf.map((schema2) => Visit2(schema2, acc)).join("|")})` : IsNumber3(schema) ? `${acc}${PatternNumber}` : IsInteger(schema) ? `${acc}${PatternNumber}` : IsBigInt2(schema) ? `${acc}${PatternNumber}` : IsString2(schema) ? `${acc}${PatternString}` : IsLiteral(schema) ? `${acc}${Escape(schema.const.toString())}` : IsBoolean2(schema) ? `${acc}${PatternBoolean}` : (() => { + throw new TemplateLiteralPatternError(`Unexpected Kind '${schema[Kind]}'`); + })(); +} +function TemplateLiteralPattern(kinds) { + return `^${kinds.map((schema) => Visit2(schema, "")).join("")}$`; +} +var TemplateLiteralPatternError; +var init_pattern = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/pattern.mjs"() { + init_process_shim(); + init_patterns2(); + init_symbols2(); + init_error2(); + init_kind(); + TemplateLiteralPatternError = class extends TypeBoxError { + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs +function TemplateLiteralToUnion(schema) { + const R3 = TemplateLiteralGenerate(schema); + const L3 = R3.map((S5) => Literal(S5)); + return UnionEvaluated(L3); +} +var init_union3 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/union.mjs"() { + init_process_shim(); + init_union2(); + init_literal2(); + init_generate(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs +function TemplateLiteral(unresolved, options) { + const pattern = IsString(unresolved) ? TemplateLiteralPattern(TemplateLiteralSyntax(unresolved)) : TemplateLiteralPattern(unresolved); + return CreateType({ [Kind]: "TemplateLiteral", type: "string", pattern }, options); +} +var init_template_literal = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/template-literal.mjs"() { + init_process_shim(); + init_type2(); + init_syntax(); + init_pattern(); + init_value(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/index.mjs +var init_template_literal2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/template-literal/index.mjs"() { + init_process_shim(); + init_finite(); + init_generate(); + init_syntax(); + init_parse(); + init_pattern(); + init_union3(); + init_template_literal(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs +function FromTemplateLiteral(templateLiteral) { + const keys2 = TemplateLiteralGenerate(templateLiteral); + return keys2.map((key) => key.toString()); +} +function FromUnion2(types2) { + const result = []; + for (const type of types2) + result.push(...IndexPropertyKeys(type)); + return result; +} +function FromLiteral(literalValue) { + return [literalValue.toString()]; +} +function IndexPropertyKeys(type) { + return [...new Set(IsTemplateLiteral(type) ? FromTemplateLiteral(type) : IsUnion(type) ? FromUnion2(type.anyOf) : IsLiteral(type) ? FromLiteral(type.const) : IsNumber3(type) ? ["[number]"] : IsInteger(type) ? ["[number]"] : [])]; +} +var init_indexed_property_keys = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-property-keys.mjs"() { + init_process_shim(); + init_template_literal2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs +function FromProperties(type, properties, options) { + const result = {}; + for (const K2 of Object.getOwnPropertyNames(properties)) { + result[K2] = Index(type, IndexPropertyKeys(properties[K2]), options); + } + return result; +} +function FromMappedResult(type, mappedResult, options) { + return FromProperties(type, mappedResult.properties, options); +} +function IndexFromMappedResult(type, mappedResult, options) { + const properties = FromMappedResult(type, mappedResult, options); + return MappedResult(properties); +} +var init_indexed_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_indexed_property_keys(); + init_indexed2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs +function FromRest(types2, key) { + return types2.map((type) => IndexFromPropertyKey(type, key)); +} +function FromIntersectRest(types2) { + return types2.filter((type) => !IsNever(type)); +} +function FromIntersect(types2, key) { + return IntersectEvaluated(FromIntersectRest(FromRest(types2, key))); +} +function FromUnionRest(types2) { + return types2.some((L3) => IsNever(L3)) ? [] : types2; +} +function FromUnion3(types2, key) { + return UnionEvaluated(FromUnionRest(FromRest(types2, key))); +} +function FromTuple(types2, key) { + return key in types2 ? types2[key] : key === "[number]" ? UnionEvaluated(types2) : Never(); +} +function FromArray(type, key) { + return key === "[number]" ? type : Never(); +} +function FromProperty(properties, propertyKey) { + return propertyKey in properties ? properties[propertyKey] : Never(); +} +function IndexFromPropertyKey(type, propertyKey) { + return IsIntersect(type) ? FromIntersect(type.allOf, propertyKey) : IsUnion(type) ? FromUnion3(type.anyOf, propertyKey) : IsTuple(type) ? FromTuple(type.items ?? [], propertyKey) : IsArray3(type) ? FromArray(type.items, propertyKey) : IsObject3(type) ? FromProperty(type.properties, propertyKey) : Never(); +} +function IndexFromPropertyKeys(type, propertyKeys) { + return propertyKeys.map((propertyKey) => IndexFromPropertyKey(type, propertyKey)); +} +function FromSchema(type, propertyKeys) { + return UnionEvaluated(IndexFromPropertyKeys(type, propertyKeys)); +} +function Index(type, key, options) { + if (IsRef(type) || IsRef(key)) { + const error = `Index types using Ref parameters require both Type and Key to be of TSchema`; + if (!IsSchema(type) || !IsSchema(key)) + throw new TypeBoxError(error); + return Computed("Index", [type, key]); + } + if (IsMappedResult(key)) + return IndexFromMappedResult(type, key, options); + if (IsMappedKey(key)) + return IndexFromMappedKey(type, key, options); + return CreateType(IsSchema(key) ? FromSchema(type, IndexPropertyKeys(key)) : FromSchema(type, key), options); +} +var init_indexed = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed.mjs"() { + init_process_shim(); + init_type2(); + init_error2(); + init_computed2(); + init_never2(); + init_intersect2(); + init_union2(); + init_indexed_property_keys(); + init_indexed_from_mapped_key(); + init_indexed_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs +function MappedIndexPropertyKey(type, key, options) { + return { [key]: Index(type, [key], Clone(options)) }; +} +function MappedIndexPropertyKeys(type, propertyKeys, options) { + return propertyKeys.reduce((result, left) => { + return { ...result, ...MappedIndexPropertyKey(type, left, options) }; + }, {}); +} +function MappedIndexProperties(type, mappedKey, options) { + return MappedIndexPropertyKeys(type, mappedKey.keys, options); +} +function IndexFromMappedKey(type, mappedKey, options) { + const properties = MappedIndexProperties(type, mappedKey, options); + return MappedResult(properties); +} +var init_indexed_from_mapped_key = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/indexed-from-mapped-key.mjs"() { + init_process_shim(); + init_indexed(); + init_mapped2(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/index.mjs +var init_indexed2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/indexed/index.mjs"() { + init_process_shim(); + init_indexed_from_mapped_key(); + init_indexed_from_mapped_result(); + init_indexed_property_keys(); + init_indexed(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs +function Iterator(items, options) { + return CreateType({ [Kind]: "Iterator", type: "Iterator", items }, options); +} +var init_iterator = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/iterator/iterator.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/iterator/index.mjs +var init_iterator2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/iterator/index.mjs"() { + init_process_shim(); + init_iterator(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/object/object.mjs +function RequiredArray(properties) { + return globalThis.Object.keys(properties).filter((key) => !IsOptional(properties[key])); +} +function _Object(properties, options) { + const required = RequiredArray(properties); + const schema = required.length > 0 ? { [Kind]: "Object", type: "object", required, properties } : { [Kind]: "Object", type: "object", properties }; + return CreateType(schema, options); +} +var Object2; +var init_object = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/object/object.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + init_kind(); + Object2 = _Object; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/object/index.mjs +var init_object2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/object/index.mjs"() { + init_process_shim(); + init_object(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs +function Promise2(item, options) { + return CreateType({ [Kind]: "Promise", type: "Promise", item }, options); +} +var init_promise = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/promise/promise.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/promise/index.mjs +var init_promise2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/promise/index.mjs"() { + init_process_shim(); + init_promise(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs +function RemoveReadonly(schema) { + return CreateType(Discard(schema, [ReadonlyKind])); +} +function AddReadonly(schema) { + return CreateType({ ...schema, [ReadonlyKind]: "Readonly" }); +} +function ReadonlyWithFlag(schema, F2) { + return F2 === false ? RemoveReadonly(schema) : AddReadonly(schema); +} +function Readonly(schema, enable) { + const F2 = enable ?? true; + return IsMappedResult(schema) ? ReadonlyFromMappedResult(schema, F2) : ReadonlyWithFlag(schema, F2); +} +var init_readonly = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + init_discard2(); + init_readonly_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs +function FromProperties2(K2, F2) { + const Acc = {}; + for (const K22 of globalThis.Object.getOwnPropertyNames(K2)) + Acc[K22] = Readonly(K2[K22], F2); + return Acc; +} +function FromMappedResult2(R3, F2) { + return FromProperties2(R3.properties, F2); +} +function ReadonlyFromMappedResult(R3, F2) { + const P3 = FromMappedResult2(R3, F2); + return MappedResult(P3); +} +var init_readonly_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/readonly-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_readonly(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/index.mjs +var init_readonly2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly/index.mjs"() { + init_process_shim(); + init_readonly_from_mapped_result(); + init_readonly(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs +function Tuple(types2, options) { + return CreateType(types2.length > 0 ? { [Kind]: "Tuple", type: "array", items: types2, additionalItems: false, minItems: types2.length, maxItems: types2.length } : { [Kind]: "Tuple", type: "array", minItems: types2.length, maxItems: types2.length }, options); +} +var init_tuple = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/tuple/tuple.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/tuple/index.mjs +var init_tuple2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/tuple/index.mjs"() { + init_process_shim(); + init_tuple(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs +function FromMappedResult3(K2, P3) { + return K2 in P3 ? FromSchemaType(K2, P3[K2]) : MappedResult(P3); +} +function MappedKeyToKnownMappedResultProperties(K2) { + return { [K2]: Literal(K2) }; +} +function MappedKeyToUnknownMappedResultProperties(P3) { + const Acc = {}; + for (const L3 of P3) + Acc[L3] = Literal(L3); + return Acc; +} +function MappedKeyToMappedResultProperties(K2, P3) { + return SetIncludes(P3, K2) ? MappedKeyToKnownMappedResultProperties(K2) : MappedKeyToUnknownMappedResultProperties(P3); +} +function FromMappedKey(K2, P3) { + const R3 = MappedKeyToMappedResultProperties(K2, P3); + return FromMappedResult3(K2, R3); +} +function FromRest2(K2, T3) { + return T3.map((L3) => FromSchemaType(K2, L3)); +} +function FromProperties3(K2, T3) { + const Acc = {}; + for (const K22 of globalThis.Object.getOwnPropertyNames(T3)) + Acc[K22] = FromSchemaType(K2, T3[K22]); + return Acc; +} +function FromSchemaType(K2, T3) { + const options = { ...T3 }; + return ( + // unevaluated modifier types + IsOptional(T3) ? Optional(FromSchemaType(K2, Discard(T3, [OptionalKind]))) : IsReadonly(T3) ? Readonly(FromSchemaType(K2, Discard(T3, [ReadonlyKind]))) : ( + // unevaluated mapped types + IsMappedResult(T3) ? FromMappedResult3(K2, T3.properties) : IsMappedKey(T3) ? FromMappedKey(K2, T3.keys) : ( + // unevaluated types + IsConstructor(T3) ? Constructor(FromRest2(K2, T3.parameters), FromSchemaType(K2, T3.returns), options) : IsFunction2(T3) ? Function2(FromRest2(K2, T3.parameters), FromSchemaType(K2, T3.returns), options) : IsAsyncIterator2(T3) ? AsyncIterator2(FromSchemaType(K2, T3.items), options) : IsIterator2(T3) ? Iterator(FromSchemaType(K2, T3.items), options) : IsIntersect(T3) ? Intersect(FromRest2(K2, T3.allOf), options) : IsUnion(T3) ? Union(FromRest2(K2, T3.anyOf), options) : IsTuple(T3) ? Tuple(FromRest2(K2, T3.items ?? []), options) : IsObject3(T3) ? Object2(FromProperties3(K2, T3.properties), options) : IsArray3(T3) ? Array2(FromSchemaType(K2, T3.items), options) : IsPromise(T3) ? Promise2(FromSchemaType(K2, T3.item), options) : T3 + ) + ) + ); +} +function MappedFunctionReturnType(K2, T3) { + const Acc = {}; + for (const L3 of K2) + Acc[L3] = FromSchemaType(L3, T3); + return Acc; +} +function Mapped(key, map3, options) { + const K2 = IsSchema(key) ? IndexPropertyKeys(key) : key; + const RT = map3({ [Kind]: "MappedKey", keys: K2 }); + const R3 = MappedFunctionReturnType(K2, RT); + return Object2(R3, options); +} +var init_mapped = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/mapped.mjs"() { + init_process_shim(); + init_symbols2(); + init_discard2(); + init_array2(); + init_async_iterator2(); + init_constructor2(); + init_function2(); + init_indexed2(); + init_intersect2(); + init_iterator2(); + init_literal2(); + init_object2(); + init_optional2(); + init_promise2(); + init_readonly2(); + init_tuple2(); + init_union2(); + init_sets(); + init_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/index.mjs +var init_mapped2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/mapped/index.mjs"() { + init_process_shim(); + init_mapped_key(); + init_mapped_result(); + init_mapped(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs +function RemoveOptional(schema) { + return CreateType(Discard(schema, [OptionalKind])); +} +function AddOptional(schema) { + return CreateType({ ...schema, [OptionalKind]: "Optional" }); +} +function OptionalWithFlag(schema, F2) { + return F2 === false ? RemoveOptional(schema) : AddOptional(schema); +} +function Optional(schema, enable) { + const F2 = enable ?? true; + return IsMappedResult(schema) ? OptionalFromMappedResult(schema, F2) : OptionalWithFlag(schema, F2); +} +var init_optional = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + init_discard2(); + init_optional_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs +function FromProperties4(P3, F2) { + const Acc = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(P3)) + Acc[K2] = Optional(P3[K2], F2); + return Acc; +} +function FromMappedResult4(R3, F2) { + return FromProperties4(R3.properties, F2); +} +function OptionalFromMappedResult(R3, F2) { + const P3 = FromMappedResult4(R3, F2); + return MappedResult(P3); +} +var init_optional_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/optional-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_optional(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/index.mjs +var init_optional2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/optional/index.mjs"() { + init_process_shim(); + init_optional_from_mapped_result(); + init_optional(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs +function IntersectCreate(T3, options = {}) { + const allObjects = T3.every((schema) => IsObject3(schema)); + const clonedUnevaluatedProperties = IsSchema(options.unevaluatedProperties) ? { unevaluatedProperties: options.unevaluatedProperties } : {}; + return CreateType(options.unevaluatedProperties === false || IsSchema(options.unevaluatedProperties) || allObjects ? { ...clonedUnevaluatedProperties, [Kind]: "Intersect", type: "object", allOf: T3 } : { ...clonedUnevaluatedProperties, [Kind]: "Intersect", allOf: T3 }, options); +} +var init_intersect_create = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-create.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs +function IsIntersectOptional(types2) { + return types2.every((left) => IsOptional(left)); +} +function RemoveOptionalFromType2(type) { + return Discard(type, [OptionalKind]); +} +function RemoveOptionalFromRest2(types2) { + return types2.map((left) => IsOptional(left) ? RemoveOptionalFromType2(left) : left); +} +function ResolveIntersect(types2, options) { + return IsIntersectOptional(types2) ? Optional(IntersectCreate(RemoveOptionalFromRest2(types2), options)) : IntersectCreate(RemoveOptionalFromRest2(types2), options); +} +function IntersectEvaluated(types2, options = {}) { + if (types2.length === 1) + return CreateType(types2[0], options); + if (types2.length === 0) + return Never(options); + if (types2.some((schema) => IsTransform(schema))) + throw new Error("Cannot intersect transform types"); + return ResolveIntersect(types2, options); +} +var init_intersect_evaluated = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-evaluated.mjs"() { + init_process_shim(); + init_symbols2(); + init_type2(); + init_discard2(); + init_never2(); + init_optional2(); + init_intersect_create(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-type.mjs +var init_intersect_type = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect-type.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs +function Intersect(types2, options) { + if (types2.length === 1) + return CreateType(types2[0], options); + if (types2.length === 0) + return Never(options); + if (types2.some((schema) => IsTransform(schema))) + throw new Error("Cannot intersect transform types"); + return IntersectCreate(types2, options); +} +var init_intersect = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/intersect.mjs"() { + init_process_shim(); + init_type2(); + init_never2(); + init_intersect_create(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/index.mjs +var init_intersect2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intersect/index.mjs"() { + init_process_shim(); + init_intersect_evaluated(); + init_intersect_type(); + init_intersect(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs +function Ref(...args) { + const [$ref, options] = typeof args[0] === "string" ? [args[0], args[1]] : [args[0].$id, args[1]]; + if (typeof $ref !== "string") + throw new TypeBoxError("Ref: $ref must be a string"); + return CreateType({ [Kind]: "Ref", $ref }, options); +} +var init_ref3 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/ref/ref.mjs"() { + init_process_shim(); + init_error2(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/ref/index.mjs +var init_ref4 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/ref/index.mjs"() { + init_process_shim(); + init_ref3(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs +function FromComputed(target, parameters) { + return Computed("Awaited", [Computed(target, parameters)]); +} +function FromRef($ref) { + return Computed("Awaited", [Ref($ref)]); +} +function FromIntersect2(types2) { + return Intersect(FromRest3(types2)); +} +function FromUnion4(types2) { + return Union(FromRest3(types2)); +} +function FromPromise(type) { + return Awaited(type); +} +function FromRest3(types2) { + return types2.map((type) => Awaited(type)); +} +function Awaited(type, options) { + return CreateType(IsComputed(type) ? FromComputed(type.target, type.parameters) : IsIntersect(type) ? FromIntersect2(type.allOf) : IsUnion(type) ? FromUnion4(type.anyOf) : IsPromise(type) ? FromPromise(type.item) : IsRef(type) ? FromRef(type.$ref) : type, options); +} +var init_awaited = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/awaited/awaited.mjs"() { + init_process_shim(); + init_type2(); + init_computed2(); + init_intersect2(); + init_union2(); + init_ref4(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/awaited/index.mjs +var init_awaited2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/awaited/index.mjs"() { + init_process_shim(); + init_awaited(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs +function FromRest4(types2) { + const result = []; + for (const L3 of types2) + result.push(KeyOfPropertyKeys(L3)); + return result; +} +function FromIntersect3(types2) { + const propertyKeysArray = FromRest4(types2); + const propertyKeys = SetUnionMany(propertyKeysArray); + return propertyKeys; +} +function FromUnion5(types2) { + const propertyKeysArray = FromRest4(types2); + const propertyKeys = SetIntersectMany(propertyKeysArray); + return propertyKeys; +} +function FromTuple2(types2) { + return types2.map((_3, indexer) => indexer.toString()); +} +function FromArray2(_3) { + return ["[number]"]; +} +function FromProperties5(T3) { + return globalThis.Object.getOwnPropertyNames(T3); +} +function FromPatternProperties(patternProperties) { + if (!includePatternProperties) + return []; + const patternPropertyKeys = globalThis.Object.getOwnPropertyNames(patternProperties); + return patternPropertyKeys.map((key) => { + return key[0] === "^" && key[key.length - 1] === "$" ? key.slice(1, key.length - 1) : key; + }); +} +function KeyOfPropertyKeys(type) { + return IsIntersect(type) ? FromIntersect3(type.allOf) : IsUnion(type) ? FromUnion5(type.anyOf) : IsTuple(type) ? FromTuple2(type.items ?? []) : IsArray3(type) ? FromArray2(type.items) : IsObject3(type) ? FromProperties5(type.properties) : IsRecord(type) ? FromPatternProperties(type.patternProperties) : []; +} +var includePatternProperties; +var init_keyof_property_keys = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-keys.mjs"() { + init_process_shim(); + init_sets(); + init_kind(); + includePatternProperties = false; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs +function FromComputed2(target, parameters) { + return Computed("KeyOf", [Computed(target, parameters)]); +} +function FromRef2($ref) { + return Computed("KeyOf", [Ref($ref)]); +} +function KeyOfFromType(type, options) { + const propertyKeys = KeyOfPropertyKeys(type); + const propertyKeyTypes = KeyOfPropertyKeysToRest(propertyKeys); + const result = UnionEvaluated(propertyKeyTypes); + return CreateType(result, options); +} +function KeyOfPropertyKeysToRest(propertyKeys) { + return propertyKeys.map((L3) => L3 === "[number]" ? Number2() : Literal(L3)); +} +function KeyOf(type, options) { + return IsComputed(type) ? FromComputed2(type.target, type.parameters) : IsRef(type) ? FromRef2(type.$ref) : IsMappedResult(type) ? KeyOfFromMappedResult(type, options) : KeyOfFromType(type, options); +} +var init_keyof = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof.mjs"() { + init_process_shim(); + init_type2(); + init_literal2(); + init_number2(); + init_computed2(); + init_ref4(); + init_keyof_property_keys(); + init_union2(); + init_keyof_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs +function FromProperties6(properties, options) { + const result = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) + result[K2] = KeyOf(properties[K2], Clone(options)); + return result; +} +function FromMappedResult5(mappedResult, options) { + return FromProperties6(mappedResult.properties, options); +} +function KeyOfFromMappedResult(mappedResult, options) { + const properties = FromMappedResult5(mappedResult, options); + return MappedResult(properties); +} +var init_keyof_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_keyof(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-entries.mjs +var init_keyof_property_entries = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/keyof-property-entries.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/index.mjs +var init_keyof2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/keyof/index.mjs"() { + init_process_shim(); + init_keyof_from_mapped_result(); + init_keyof_property_entries(); + init_keyof_property_keys(); + init_keyof(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs +function CompositeKeys(T3) { + const Acc = []; + for (const L3 of T3) + Acc.push(...KeyOfPropertyKeys(L3)); + return SetDistinct(Acc); +} +function FilterNever(T3) { + return T3.filter((L3) => !IsNever(L3)); +} +function CompositeProperty(T3, K2) { + const Acc = []; + for (const L3 of T3) + Acc.push(...IndexFromPropertyKeys(L3, [K2])); + return FilterNever(Acc); +} +function CompositeProperties(T3, K2) { + const Acc = {}; + for (const L3 of K2) { + Acc[L3] = IntersectEvaluated(CompositeProperty(T3, L3)); + } + return Acc; +} +function Composite(T3, options) { + const K2 = CompositeKeys(T3); + const P3 = CompositeProperties(T3, K2); + const R3 = Object2(P3, options); + return R3; +} +var init_composite = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/composite/composite.mjs"() { + init_process_shim(); + init_intersect2(); + init_indexed2(); + init_keyof2(); + init_object2(); + init_sets(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/composite/index.mjs +var init_composite2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/composite/index.mjs"() { + init_process_shim(); + init_composite(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/date/date.mjs +function Date2(options) { + return CreateType({ [Kind]: "Date", type: "Date" }, options); +} +var init_date = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/date/date.mjs"() { + init_process_shim(); + init_symbols2(); + init_type2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/date/index.mjs +var init_date2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/date/index.mjs"() { + init_process_shim(); + init_date(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/null/null.mjs +function Null(options) { + return CreateType({ [Kind]: "Null", type: "null" }, options); +} +var init_null = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/null/null.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/null/index.mjs +var init_null2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/null/index.mjs"() { + init_process_shim(); + init_null(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs +function Symbol2(options) { + return CreateType({ [Kind]: "Symbol", type: "symbol" }, options); +} +var init_symbol = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbol/symbol.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbol/index.mjs +var init_symbol2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/symbol/index.mjs"() { + init_process_shim(); + init_symbol(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs +function Undefined(options) { + return CreateType({ [Kind]: "Undefined", type: "undefined" }, options); +} +var init_undefined = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/undefined/undefined.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/undefined/index.mjs +var init_undefined2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/undefined/index.mjs"() { + init_process_shim(); + init_undefined(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs +function Uint8Array2(options) { + return CreateType({ [Kind]: "Uint8Array", type: "Uint8Array" }, options); +} +var init_uint8array = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/uint8array/uint8array.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/uint8array/index.mjs +var init_uint8array2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/uint8array/index.mjs"() { + init_process_shim(); + init_uint8array(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs +function Unknown(options) { + return CreateType({ [Kind]: "Unknown" }, options); +} +var init_unknown = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unknown/unknown.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unknown/index.mjs +var init_unknown2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unknown/index.mjs"() { + init_process_shim(); + init_unknown(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/const/const.mjs +function FromArray3(T3) { + return T3.map((L3) => FromValue(L3, false)); +} +function FromProperties7(value) { + const Acc = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(value)) + Acc[K2] = Readonly(FromValue(value[K2], false)); + return Acc; +} +function ConditionalReadonly(T3, root) { + return root === true ? T3 : Readonly(T3); +} +function FromValue(value, root) { + return IsAsyncIterator(value) ? ConditionalReadonly(Any(), root) : IsIterator(value) ? ConditionalReadonly(Any(), root) : IsArray(value) ? Readonly(Tuple(FromArray3(value))) : IsUint8Array(value) ? Uint8Array2() : IsDate(value) ? Date2() : IsObject(value) ? ConditionalReadonly(Object2(FromProperties7(value)), root) : IsFunction(value) ? ConditionalReadonly(Function2([], Unknown()), root) : IsUndefined(value) ? Undefined() : IsNull(value) ? Null() : IsSymbol(value) ? Symbol2() : IsBigInt(value) ? BigInt2() : IsNumber(value) ? Literal(value) : IsBoolean(value) ? Literal(value) : IsString(value) ? Literal(value) : Object2({}); +} +function Const(T3, options) { + return CreateType(FromValue(T3, true), options); +} +var init_const = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/const/const.mjs"() { + init_process_shim(); + init_any2(); + init_bigint2(); + init_date2(); + init_function2(); + init_literal2(); + init_null2(); + init_object2(); + init_symbol2(); + init_tuple2(); + init_readonly2(); + init_undefined2(); + init_uint8array2(); + init_unknown2(); + init_create(); + init_value(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/const/index.mjs +var init_const2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/const/index.mjs"() { + init_process_shim(); + init_const(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs +function ConstructorParameters(schema, options) { + return IsConstructor(schema) ? Tuple(schema.parameters, options) : Never(options); +} +var init_constructor_parameters = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/constructor-parameters.mjs"() { + init_process_shim(); + init_tuple2(); + init_never2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/index.mjs +var init_constructor_parameters2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/constructor-parameters/index.mjs"() { + init_process_shim(); + init_constructor_parameters(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs +function Enum(item, options) { + if (IsUndefined(item)) + throw new Error("Enum undefined or empty"); + const values1 = globalThis.Object.getOwnPropertyNames(item).filter((key) => isNaN(key)).map((key) => item[key]); + const values2 = [...new Set(values1)]; + const anyOf = values2.map((value) => Literal(value)); + return Union(anyOf, { ...options, [Hint]: "Enum" }); +} +var init_enum = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/enum/enum.mjs"() { + init_process_shim(); + init_literal2(); + init_symbols2(); + init_union2(); + init_value(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/enum/index.mjs +var init_enum2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/enum/index.mjs"() { + init_process_shim(); + init_enum(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs +function IntoBooleanResult(result) { + return result === ExtendsResult.False ? result : ExtendsResult.True; +} +function Throw(message) { + throw new ExtendsResolverError(message); +} +function IsStructuralRight(right) { + return type_exports.IsNever(right) || type_exports.IsIntersect(right) || type_exports.IsUnion(right) || type_exports.IsUnknown(right) || type_exports.IsAny(right); +} +function StructuralRight(left, right) { + return type_exports.IsNever(right) ? FromNeverRight(left, right) : type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsUnknown(right) ? FromUnknownRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : Throw("StructuralRight"); +} +function FromAnyRight(left, right) { + return ExtendsResult.True; +} +function FromAny(left, right) { + return type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) && right.anyOf.some((schema) => type_exports.IsAny(schema) || type_exports.IsUnknown(schema)) ? ExtendsResult.True : type_exports.IsUnion(right) ? ExtendsResult.Union : type_exports.IsUnknown(right) ? ExtendsResult.True : type_exports.IsAny(right) ? ExtendsResult.True : ExtendsResult.Union; +} +function FromArrayRight(left, right) { + return type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : type_exports.IsNever(left) ? ExtendsResult.True : ExtendsResult.False; +} +function FromArray4(left, right) { + return type_exports.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsArray(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items)); +} +function FromAsyncIterator(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsAsyncIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items)); +} +function FromBigInt(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsBigInt(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromBooleanRight(left, right) { + return type_exports.IsLiteralBoolean(left) ? ExtendsResult.True : type_exports.IsBoolean(left) ? ExtendsResult.True : ExtendsResult.False; +} +function FromBoolean(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsBoolean(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromConstructor(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsConstructor(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index2) => IntoBooleanResult(Visit3(right.parameters[index2], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.returns, right.returns)); +} +function FromDate(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsDate(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromFunction(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsFunction(right) ? ExtendsResult.False : left.parameters.length > right.parameters.length ? ExtendsResult.False : !left.parameters.every((schema, index2) => IntoBooleanResult(Visit3(right.parameters[index2], schema)) === ExtendsResult.True) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.returns, right.returns)); +} +function FromIntegerRight(left, right) { + return type_exports.IsLiteral(left) && value_exports.IsNumber(left.const) ? ExtendsResult.True : type_exports.IsNumber(left) || type_exports.IsInteger(left) ? ExtendsResult.True : ExtendsResult.False; +} +function FromInteger(left, right) { + return type_exports.IsInteger(right) || type_exports.IsNumber(right) ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : ExtendsResult.False; +} +function FromIntersectRight(left, right) { + return right.allOf.every((schema) => Visit3(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False; +} +function FromIntersect4(left, right) { + return left.allOf.some((schema) => Visit3(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False; +} +function FromIterator(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : !type_exports.IsIterator(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.items, right.items)); +} +function FromLiteral2(left, right) { + return type_exports.IsLiteral(right) && right.const === left.const ? ExtendsResult.True : IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsString(right) ? FromStringRight(left, right) : type_exports.IsNumber(right) ? FromNumberRight(left, right) : type_exports.IsInteger(right) ? FromIntegerRight(left, right) : type_exports.IsBoolean(right) ? FromBooleanRight(left, right) : ExtendsResult.False; +} +function FromNeverRight(left, right) { + return ExtendsResult.False; +} +function FromNever(left, right) { + return ExtendsResult.True; +} +function UnwrapTNot(schema) { + let [current2, depth] = [schema, 0]; + while (true) { + if (!type_exports.IsNot(current2)) + break; + current2 = current2.not; + depth += 1; + } + return depth % 2 === 0 ? current2 : Unknown(); +} +function FromNot(left, right) { + return type_exports.IsNot(left) ? Visit3(UnwrapTNot(left), right) : type_exports.IsNot(right) ? Visit3(left, UnwrapTNot(right)) : Throw("Invalid fallthrough for Not"); +} +function FromNull(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsNull(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromNumberRight(left, right) { + return type_exports.IsLiteralNumber(left) ? ExtendsResult.True : type_exports.IsNumber(left) || type_exports.IsInteger(left) ? ExtendsResult.True : ExtendsResult.False; +} +function FromNumber(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsInteger(right) || type_exports.IsNumber(right) ? ExtendsResult.True : ExtendsResult.False; +} +function IsObjectPropertyCount(schema, count) { + return Object.getOwnPropertyNames(schema.properties).length === count; +} +function IsObjectStringLike(schema) { + return IsObjectArrayLike(schema); +} +function IsObjectSymbolLike(schema) { + return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "description" in schema.properties && type_exports.IsUnion(schema.properties.description) && schema.properties.description.anyOf.length === 2 && (type_exports.IsString(schema.properties.description.anyOf[0]) && type_exports.IsUndefined(schema.properties.description.anyOf[1]) || type_exports.IsString(schema.properties.description.anyOf[1]) && type_exports.IsUndefined(schema.properties.description.anyOf[0])); +} +function IsObjectNumberLike(schema) { + return IsObjectPropertyCount(schema, 0); +} +function IsObjectBooleanLike(schema) { + return IsObjectPropertyCount(schema, 0); +} +function IsObjectBigIntLike(schema) { + return IsObjectPropertyCount(schema, 0); +} +function IsObjectDateLike(schema) { + return IsObjectPropertyCount(schema, 0); +} +function IsObjectUint8ArrayLike(schema) { + return IsObjectArrayLike(schema); +} +function IsObjectFunctionLike(schema) { + const length = Number2(); + return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit3(schema.properties["length"], length)) === ExtendsResult.True; +} +function IsObjectConstructorLike(schema) { + return IsObjectPropertyCount(schema, 0); +} +function IsObjectArrayLike(schema) { + const length = Number2(); + return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "length" in schema.properties && IntoBooleanResult(Visit3(schema.properties["length"], length)) === ExtendsResult.True; +} +function IsObjectPromiseLike(schema) { + const then = Function2([Any()], Any()); + return IsObjectPropertyCount(schema, 0) || IsObjectPropertyCount(schema, 1) && "then" in schema.properties && IntoBooleanResult(Visit3(schema.properties["then"], then)) === ExtendsResult.True; +} +function Property(left, right) { + return Visit3(left, right) === ExtendsResult.False ? ExtendsResult.False : type_exports.IsOptional(left) && !type_exports.IsOptional(right) ? ExtendsResult.False : ExtendsResult.True; +} +function FromObjectRight(left, right) { + return type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : type_exports.IsNever(left) || type_exports.IsLiteralString(left) && IsObjectStringLike(right) || type_exports.IsLiteralNumber(left) && IsObjectNumberLike(right) || type_exports.IsLiteralBoolean(left) && IsObjectBooleanLike(right) || type_exports.IsSymbol(left) && IsObjectSymbolLike(right) || type_exports.IsBigInt(left) && IsObjectBigIntLike(right) || type_exports.IsString(left) && IsObjectStringLike(right) || type_exports.IsSymbol(left) && IsObjectSymbolLike(right) || type_exports.IsNumber(left) && IsObjectNumberLike(right) || type_exports.IsInteger(left) && IsObjectNumberLike(right) || type_exports.IsBoolean(left) && IsObjectBooleanLike(right) || type_exports.IsUint8Array(left) && IsObjectUint8ArrayLike(right) || type_exports.IsDate(left) && IsObjectDateLike(right) || type_exports.IsConstructor(left) && IsObjectConstructorLike(right) || type_exports.IsFunction(left) && IsObjectFunctionLike(right) ? ExtendsResult.True : type_exports.IsRecord(left) && type_exports.IsString(RecordKey(left)) ? (() => { + return right[Hint] === "Record" ? ExtendsResult.True : ExtendsResult.False; + })() : type_exports.IsRecord(left) && type_exports.IsNumber(RecordKey(left)) ? (() => { + return IsObjectPropertyCount(right, 0) ? ExtendsResult.True : ExtendsResult.False; + })() : ExtendsResult.False; +} +function FromObject(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : !type_exports.IsObject(right) ? ExtendsResult.False : (() => { + for (const key of Object.getOwnPropertyNames(right.properties)) { + if (!(key in left.properties) && !type_exports.IsOptional(right.properties[key])) { + return ExtendsResult.False; + } + if (type_exports.IsOptional(right.properties[key])) { + return ExtendsResult.True; + } + if (Property(left.properties[key], right.properties[key]) === ExtendsResult.False) { + return ExtendsResult.False; + } + } + return ExtendsResult.True; + })(); +} +function FromPromise2(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) && IsObjectPromiseLike(right) ? ExtendsResult.True : !type_exports.IsPromise(right) ? ExtendsResult.False : IntoBooleanResult(Visit3(left.item, right.item)); +} +function RecordKey(schema) { + return PatternNumberExact in schema.patternProperties ? Number2() : PatternStringExact in schema.patternProperties ? String2() : Throw("Unknown record key pattern"); +} +function RecordValue(schema) { + return PatternNumberExact in schema.patternProperties ? schema.patternProperties[PatternNumberExact] : PatternStringExact in schema.patternProperties ? schema.patternProperties[PatternStringExact] : Throw("Unable to get record value schema"); +} +function FromRecordRight(left, right) { + const [Key, Value] = [RecordKey(right), RecordValue(right)]; + return type_exports.IsLiteralString(left) && type_exports.IsNumber(Key) && IntoBooleanResult(Visit3(left, Value)) === ExtendsResult.True ? ExtendsResult.True : type_exports.IsUint8Array(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsString(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsArray(left) && type_exports.IsNumber(Key) ? Visit3(left, Value) : type_exports.IsObject(left) ? (() => { + for (const key of Object.getOwnPropertyNames(left.properties)) { + if (Property(Value, left.properties[key]) === ExtendsResult.False) { + return ExtendsResult.False; + } + } + return ExtendsResult.True; + })() : ExtendsResult.False; +} +function FromRecord(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : !type_exports.IsRecord(right) ? ExtendsResult.False : Visit3(RecordValue(left), RecordValue(right)); +} +function FromRegExp(left, right) { + const L3 = type_exports.IsRegExp(left) ? String2() : left; + const R3 = type_exports.IsRegExp(right) ? String2() : right; + return Visit3(L3, R3); +} +function FromStringRight(left, right) { + return type_exports.IsLiteral(left) && value_exports.IsString(left.const) ? ExtendsResult.True : type_exports.IsString(left) ? ExtendsResult.True : ExtendsResult.False; +} +function FromString(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsString(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromSymbol(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsSymbol(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromTemplateLiteral2(left, right) { + return type_exports.IsTemplateLiteral(left) ? Visit3(TemplateLiteralToUnion(left), right) : type_exports.IsTemplateLiteral(right) ? Visit3(left, TemplateLiteralToUnion(right)) : Throw("Invalid fallthrough for TemplateLiteral"); +} +function IsArrayOfTuple(left, right) { + return type_exports.IsArray(right) && left.items !== void 0 && left.items.every((schema) => Visit3(schema, right.items) === ExtendsResult.True); +} +function FromTupleRight(left, right) { + return type_exports.IsNever(left) ? ExtendsResult.True : type_exports.IsUnknown(left) ? ExtendsResult.False : type_exports.IsAny(left) ? ExtendsResult.Union : ExtendsResult.False; +} +function FromTuple3(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) && IsObjectArrayLike(right) ? ExtendsResult.True : type_exports.IsArray(right) && IsArrayOfTuple(left, right) ? ExtendsResult.True : !type_exports.IsTuple(right) ? ExtendsResult.False : value_exports.IsUndefined(left.items) && !value_exports.IsUndefined(right.items) || !value_exports.IsUndefined(left.items) && value_exports.IsUndefined(right.items) ? ExtendsResult.False : value_exports.IsUndefined(left.items) && !value_exports.IsUndefined(right.items) ? ExtendsResult.True : left.items.every((schema, index2) => Visit3(schema, right.items[index2]) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False; +} +function FromUint8Array(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsUint8Array(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromUndefined(left, right) { + return IsStructuralRight(right) ? StructuralRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsRecord(right) ? FromRecordRight(left, right) : type_exports.IsVoid(right) ? FromVoidRight(left, right) : type_exports.IsUndefined(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromUnionRight(left, right) { + return right.anyOf.some((schema) => Visit3(left, schema) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False; +} +function FromUnion6(left, right) { + return left.anyOf.every((schema) => Visit3(schema, right) === ExtendsResult.True) ? ExtendsResult.True : ExtendsResult.False; +} +function FromUnknownRight(left, right) { + return ExtendsResult.True; +} +function FromUnknown(left, right) { + return type_exports.IsNever(right) ? FromNeverRight(left, right) : type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : type_exports.IsString(right) ? FromStringRight(left, right) : type_exports.IsNumber(right) ? FromNumberRight(left, right) : type_exports.IsInteger(right) ? FromIntegerRight(left, right) : type_exports.IsBoolean(right) ? FromBooleanRight(left, right) : type_exports.IsArray(right) ? FromArrayRight(left, right) : type_exports.IsTuple(right) ? FromTupleRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsUnknown(right) ? ExtendsResult.True : ExtendsResult.False; +} +function FromVoidRight(left, right) { + return type_exports.IsUndefined(left) ? ExtendsResult.True : type_exports.IsUndefined(left) ? ExtendsResult.True : ExtendsResult.False; +} +function FromVoid(left, right) { + return type_exports.IsIntersect(right) ? FromIntersectRight(left, right) : type_exports.IsUnion(right) ? FromUnionRight(left, right) : type_exports.IsUnknown(right) ? FromUnknownRight(left, right) : type_exports.IsAny(right) ? FromAnyRight(left, right) : type_exports.IsObject(right) ? FromObjectRight(left, right) : type_exports.IsVoid(right) ? ExtendsResult.True : ExtendsResult.False; +} +function Visit3(left, right) { + return ( + // resolvable + type_exports.IsTemplateLiteral(left) || type_exports.IsTemplateLiteral(right) ? FromTemplateLiteral2(left, right) : type_exports.IsRegExp(left) || type_exports.IsRegExp(right) ? FromRegExp(left, right) : type_exports.IsNot(left) || type_exports.IsNot(right) ? FromNot(left, right) : ( + // standard + type_exports.IsAny(left) ? FromAny(left, right) : type_exports.IsArray(left) ? FromArray4(left, right) : type_exports.IsBigInt(left) ? FromBigInt(left, right) : type_exports.IsBoolean(left) ? FromBoolean(left, right) : type_exports.IsAsyncIterator(left) ? FromAsyncIterator(left, right) : type_exports.IsConstructor(left) ? FromConstructor(left, right) : type_exports.IsDate(left) ? FromDate(left, right) : type_exports.IsFunction(left) ? FromFunction(left, right) : type_exports.IsInteger(left) ? FromInteger(left, right) : type_exports.IsIntersect(left) ? FromIntersect4(left, right) : type_exports.IsIterator(left) ? FromIterator(left, right) : type_exports.IsLiteral(left) ? FromLiteral2(left, right) : type_exports.IsNever(left) ? FromNever(left, right) : type_exports.IsNull(left) ? FromNull(left, right) : type_exports.IsNumber(left) ? FromNumber(left, right) : type_exports.IsObject(left) ? FromObject(left, right) : type_exports.IsRecord(left) ? FromRecord(left, right) : type_exports.IsString(left) ? FromString(left, right) : type_exports.IsSymbol(left) ? FromSymbol(left, right) : type_exports.IsTuple(left) ? FromTuple3(left, right) : type_exports.IsPromise(left) ? FromPromise2(left, right) : type_exports.IsUint8Array(left) ? FromUint8Array(left, right) : type_exports.IsUndefined(left) ? FromUndefined(left, right) : type_exports.IsUnion(left) ? FromUnion6(left, right) : type_exports.IsUnknown(left) ? FromUnknown(left, right) : type_exports.IsVoid(left) ? FromVoid(left, right) : Throw(`Unknown left type operand '${left[Kind]}'`) + ) + ); +} +function ExtendsCheck(left, right) { + return Visit3(left, right); +} +var ExtendsResolverError, ExtendsResult; +var init_extends_check = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-check.mjs"() { + init_process_shim(); + init_any2(); + init_function2(); + init_number2(); + init_string2(); + init_unknown2(); + init_template_literal2(); + init_patterns2(); + init_symbols2(); + init_error2(); + init_guard3(); + ExtendsResolverError = class extends TypeBoxError { + }; + (function(ExtendsResult3) { + ExtendsResult3[ExtendsResult3["Union"] = 0] = "Union"; + ExtendsResult3[ExtendsResult3["True"] = 1] = "True"; + ExtendsResult3[ExtendsResult3["False"] = 2] = "False"; + })(ExtendsResult || (ExtendsResult = {})); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs +function FromProperties8(P3, Right, True, False, options) { + const Acc = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(P3)) + Acc[K2] = Extends(P3[K2], Right, True, False, Clone(options)); + return Acc; +} +function FromMappedResult6(Left, Right, True, False, options) { + return FromProperties8(Left.properties, Right, True, False, options); +} +function ExtendsFromMappedResult(Left, Right, True, False, options) { + const P3 = FromMappedResult6(Left, Right, True, False, options); + return MappedResult(P3); +} +var init_extends_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_extends(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs +function ExtendsResolve(left, right, trueType, falseType) { + const R3 = ExtendsCheck(left, right); + return R3 === ExtendsResult.Union ? Union([trueType, falseType]) : R3 === ExtendsResult.True ? trueType : falseType; +} +function Extends(L3, R3, T3, F2, options) { + return IsMappedResult(L3) ? ExtendsFromMappedResult(L3, R3, T3, F2, options) : IsMappedKey(L3) ? CreateType(ExtendsFromMappedKey(L3, R3, T3, F2, options)) : CreateType(ExtendsResolve(L3, R3, T3, F2), options); +} +var init_extends = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends.mjs"() { + init_process_shim(); + init_type2(); + init_union2(); + init_extends_check(); + init_extends_from_mapped_key(); + init_extends_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs +function FromPropertyKey(K2, U2, L3, R3, options) { + return { + [K2]: Extends(Literal(K2), U2, L3, R3, Clone(options)) + }; +} +function FromPropertyKeys(K2, U2, L3, R3, options) { + return K2.reduce((Acc, LK) => { + return { ...Acc, ...FromPropertyKey(LK, U2, L3, R3, options) }; + }, {}); +} +function FromMappedKey2(K2, U2, L3, R3, options) { + return FromPropertyKeys(K2.keys, U2, L3, R3, options); +} +function ExtendsFromMappedKey(T3, U2, L3, R3, options) { + const P3 = FromMappedKey2(T3, U2, L3, R3, options); + return MappedResult(P3); +} +var init_extends_from_mapped_key = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-from-mapped-key.mjs"() { + init_process_shim(); + init_mapped2(); + init_literal2(); + init_extends(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-undefined.mjs +var init_extends_undefined = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/extends-undefined.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/index.mjs +var init_extends2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extends/index.mjs"() { + init_process_shim(); + init_extends_check(); + init_extends_from_mapped_key(); + init_extends_from_mapped_result(); + init_extends_undefined(); + init_extends(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs +function ExcludeFromTemplateLiteral(L3, R3) { + return Exclude(TemplateLiteralToUnion(L3), R3); +} +var init_exclude_from_template_literal = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-template-literal.mjs"() { + init_process_shim(); + init_exclude(); + init_template_literal2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs +function ExcludeRest(L3, R3) { + const excluded = L3.filter((inner2) => ExtendsCheck(inner2, R3) === ExtendsResult.False); + return excluded.length === 1 ? excluded[0] : Union(excluded); +} +function Exclude(L3, R3, options = {}) { + if (IsTemplateLiteral(L3)) + return CreateType(ExcludeFromTemplateLiteral(L3, R3), options); + if (IsMappedResult(L3)) + return CreateType(ExcludeFromMappedResult(L3, R3), options); + return CreateType(IsUnion(L3) ? ExcludeRest(L3.anyOf, R3) : ExtendsCheck(L3, R3) !== ExtendsResult.False ? Never() : L3, options); +} +var init_exclude = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude.mjs"() { + init_process_shim(); + init_type2(); + init_union2(); + init_never2(); + init_extends2(); + init_exclude_from_mapped_result(); + init_exclude_from_template_literal(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs +function FromProperties9(P3, U2) { + const Acc = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(P3)) + Acc[K2] = Exclude(P3[K2], U2); + return Acc; +} +function FromMappedResult7(R3, T3) { + return FromProperties9(R3.properties, T3); +} +function ExcludeFromMappedResult(R3, T3) { + const P3 = FromMappedResult7(R3, T3); + return MappedResult(P3); +} +var init_exclude_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/exclude-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_exclude(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/index.mjs +var init_exclude2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/exclude/index.mjs"() { + init_process_shim(); + init_exclude_from_mapped_result(); + init_exclude_from_template_literal(); + init_exclude(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs +function ExtractFromTemplateLiteral(L3, R3) { + return Extract(TemplateLiteralToUnion(L3), R3); +} +var init_extract_from_template_literal = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-template-literal.mjs"() { + init_process_shim(); + init_extract(); + init_template_literal2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs +function ExtractRest(L3, R3) { + const extracted = L3.filter((inner2) => ExtendsCheck(inner2, R3) !== ExtendsResult.False); + return extracted.length === 1 ? extracted[0] : Union(extracted); +} +function Extract(L3, R3, options) { + if (IsTemplateLiteral(L3)) + return CreateType(ExtractFromTemplateLiteral(L3, R3), options); + if (IsMappedResult(L3)) + return CreateType(ExtractFromMappedResult(L3, R3), options); + return CreateType(IsUnion(L3) ? ExtractRest(L3.anyOf, R3) : ExtendsCheck(L3, R3) !== ExtendsResult.False ? L3 : Never(), options); +} +var init_extract = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract.mjs"() { + init_process_shim(); + init_type2(); + init_union2(); + init_never2(); + init_extends2(); + init_extract_from_mapped_result(); + init_extract_from_template_literal(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs +function FromProperties10(P3, T3) { + const Acc = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(P3)) + Acc[K2] = Extract(P3[K2], T3); + return Acc; +} +function FromMappedResult8(R3, T3) { + return FromProperties10(R3.properties, T3); +} +function ExtractFromMappedResult(R3, T3) { + const P3 = FromMappedResult8(R3, T3); + return MappedResult(P3); +} +var init_extract_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/extract-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_extract(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/index.mjs +var init_extract2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/extract/index.mjs"() { + init_process_shim(); + init_extract_from_mapped_result(); + init_extract_from_template_literal(); + init_extract(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs +function InstanceType(schema, options) { + return IsConstructor(schema) ? CreateType(schema.returns, options) : Never(options); +} +var init_instance_type = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instance-type/instance-type.mjs"() { + init_process_shim(); + init_type2(); + init_never2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instance-type/index.mjs +var init_instance_type2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instance-type/index.mjs"() { + init_process_shim(); + init_instance_type(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs +function ReadonlyOptional(schema) { + return Readonly(Optional(schema)); +} +var init_readonly_optional = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/readonly-optional.mjs"() { + init_process_shim(); + init_readonly2(); + init_optional2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/index.mjs +var init_readonly_optional2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/readonly-optional/index.mjs"() { + init_process_shim(); + init_readonly_optional(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/record/record.mjs +function RecordCreateFromPattern(pattern, T3, options) { + return CreateType({ [Kind]: "Record", type: "object", patternProperties: { [pattern]: T3 } }, options); +} +function RecordCreateFromKeys(K2, T3, options) { + const result = {}; + for (const K22 of K2) + result[K22] = T3; + return Object2(result, { ...options, [Hint]: "Record" }); +} +function FromTemplateLiteralKey(K2, T3, options) { + return IsTemplateLiteralFinite(K2) ? RecordCreateFromKeys(IndexPropertyKeys(K2), T3, options) : RecordCreateFromPattern(K2.pattern, T3, options); +} +function FromUnionKey(key, type, options) { + return RecordCreateFromKeys(IndexPropertyKeys(Union(key)), type, options); +} +function FromLiteralKey(key, type, options) { + return RecordCreateFromKeys([key.toString()], type, options); +} +function FromRegExpKey(key, type, options) { + return RecordCreateFromPattern(key.source, type, options); +} +function FromStringKey(key, type, options) { + const pattern = IsUndefined(key.pattern) ? PatternStringExact : key.pattern; + return RecordCreateFromPattern(pattern, type, options); +} +function FromAnyKey(_3, type, options) { + return RecordCreateFromPattern(PatternStringExact, type, options); +} +function FromNeverKey(_key, type, options) { + return RecordCreateFromPattern(PatternNeverExact, type, options); +} +function FromBooleanKey(_key, type, options) { + return Object2({ true: type, false: type }, options); +} +function FromIntegerKey(_key, type, options) { + return RecordCreateFromPattern(PatternNumberExact, type, options); +} +function FromNumberKey(_3, type, options) { + return RecordCreateFromPattern(PatternNumberExact, type, options); +} +function Record(key, type, options = {}) { + return IsUnion(key) ? FromUnionKey(key.anyOf, type, options) : IsTemplateLiteral(key) ? FromTemplateLiteralKey(key, type, options) : IsLiteral(key) ? FromLiteralKey(key.const, type, options) : IsBoolean2(key) ? FromBooleanKey(key, type, options) : IsInteger(key) ? FromIntegerKey(key, type, options) : IsNumber3(key) ? FromNumberKey(key, type, options) : IsRegExp2(key) ? FromRegExpKey(key, type, options) : IsString2(key) ? FromStringKey(key, type, options) : IsAny(key) ? FromAnyKey(key, type, options) : IsNever(key) ? FromNeverKey(key, type, options) : Never(options); +} +function RecordPattern(record) { + return globalThis.Object.getOwnPropertyNames(record.patternProperties)[0]; +} +function RecordKey2(type) { + const pattern = RecordPattern(type); + return pattern === PatternStringExact ? String2() : pattern === PatternNumberExact ? Number2() : String2({ pattern }); +} +function RecordValue2(type) { + return type.patternProperties[RecordPattern(type)]; +} +var init_record = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/record/record.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + init_never2(); + init_number2(); + init_object2(); + init_string2(); + init_union2(); + init_template_literal2(); + init_patterns2(); + init_indexed2(); + init_value(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/record/index.mjs +var init_record2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/record/index.mjs"() { + init_process_shim(); + init_record(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs +function FromConstructor2(args, type) { + type.parameters = FromTypes(args, type.parameters); + type.returns = FromType(args, type.returns); + return type; +} +function FromFunction2(args, type) { + type.parameters = FromTypes(args, type.parameters); + type.returns = FromType(args, type.returns); + return type; +} +function FromIntersect5(args, type) { + type.allOf = FromTypes(args, type.allOf); + return type; +} +function FromUnion7(args, type) { + type.anyOf = FromTypes(args, type.anyOf); + return type; +} +function FromTuple4(args, type) { + if (IsUndefined(type.items)) + return type; + type.items = FromTypes(args, type.items); + return type; +} +function FromArray5(args, type) { + type.items = FromType(args, type.items); + return type; +} +function FromAsyncIterator2(args, type) { + type.items = FromType(args, type.items); + return type; +} +function FromIterator2(args, type) { + type.items = FromType(args, type.items); + return type; +} +function FromPromise3(args, type) { + type.item = FromType(args, type.item); + return type; +} +function FromObject2(args, type) { + const mappedProperties = FromProperties11(args, type.properties); + return { ...type, ...Object2(mappedProperties) }; +} +function FromRecord2(args, type) { + const mappedKey = FromType(args, RecordKey2(type)); + const mappedValue = FromType(args, RecordValue2(type)); + const result = Record(mappedKey, mappedValue); + return { ...type, ...result }; +} +function FromArgument(args, argument) { + return argument.index in args ? args[argument.index] : Unknown(); +} +function FromProperty2(args, type) { + const isReadonly = IsReadonly(type); + const isOptional = IsOptional(type); + const mapped = FromType(args, type); + return isReadonly && isOptional ? ReadonlyOptional(mapped) : isReadonly && !isOptional ? Readonly(mapped) : !isReadonly && isOptional ? Optional(mapped) : mapped; +} +function FromProperties11(args, properties) { + return globalThis.Object.getOwnPropertyNames(properties).reduce((result, key) => { + return { ...result, [key]: FromProperty2(args, properties[key]) }; + }, {}); +} +function FromTypes(args, types2) { + return types2.map((type) => FromType(args, type)); +} +function FromType(args, type) { + return IsConstructor(type) ? FromConstructor2(args, type) : IsFunction2(type) ? FromFunction2(args, type) : IsIntersect(type) ? FromIntersect5(args, type) : IsUnion(type) ? FromUnion7(args, type) : IsTuple(type) ? FromTuple4(args, type) : IsArray3(type) ? FromArray5(args, type) : IsAsyncIterator2(type) ? FromAsyncIterator2(args, type) : IsIterator2(type) ? FromIterator2(args, type) : IsPromise(type) ? FromPromise3(args, type) : IsObject3(type) ? FromObject2(args, type) : IsRecord(type) ? FromRecord2(args, type) : IsArgument(type) ? FromArgument(args, type) : type; +} +function Instantiate(type, args) { + return FromType(args, CloneType(type)); +} +var init_instantiate = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instantiate/instantiate.mjs"() { + init_process_shim(); + init_type(); + init_unknown2(); + init_readonly_optional2(); + init_readonly2(); + init_optional2(); + init_object2(); + init_record2(); + init_value(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instantiate/index.mjs +var init_instantiate2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/instantiate/index.mjs"() { + init_process_shim(); + init_instantiate(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs +function Integer(options) { + return CreateType({ [Kind]: "Integer", type: "integer" }, options); +} +var init_integer = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/integer/integer.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/integer/index.mjs +var init_integer2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/integer/index.mjs"() { + init_process_shim(); + init_integer(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs +function MappedIntrinsicPropertyKey(K2, M4, options) { + return { + [K2]: Intrinsic(Literal(K2), M4, Clone(options)) + }; +} +function MappedIntrinsicPropertyKeys(K2, M4, options) { + const result = K2.reduce((Acc, L3) => { + return { ...Acc, ...MappedIntrinsicPropertyKey(L3, M4, options) }; + }, {}); + return result; +} +function MappedIntrinsicProperties(T3, M4, options) { + return MappedIntrinsicPropertyKeys(T3["keys"], M4, options); +} +function IntrinsicFromMappedKey(T3, M4, options) { + const P3 = MappedIntrinsicProperties(T3, M4, options); + return MappedResult(P3); +} +var init_intrinsic_from_mapped_key = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic-from-mapped-key.mjs"() { + init_process_shim(); + init_mapped2(); + init_intrinsic(); + init_literal2(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs +function ApplyUncapitalize(value) { + const [first, rest] = [value.slice(0, 1), value.slice(1)]; + return [first.toLowerCase(), rest].join(""); +} +function ApplyCapitalize(value) { + const [first, rest] = [value.slice(0, 1), value.slice(1)]; + return [first.toUpperCase(), rest].join(""); +} +function ApplyUppercase(value) { + return value.toUpperCase(); +} +function ApplyLowercase(value) { + return value.toLowerCase(); +} +function FromTemplateLiteral3(schema, mode, options) { + const expression = TemplateLiteralParseExact(schema.pattern); + const finite = IsTemplateLiteralExpressionFinite(expression); + if (!finite) + return { ...schema, pattern: FromLiteralValue(schema.pattern, mode) }; + const strings = [...TemplateLiteralExpressionGenerate(expression)]; + const literals = strings.map((value) => Literal(value)); + const mapped = FromRest5(literals, mode); + const union = Union(mapped); + return TemplateLiteral([union], options); +} +function FromLiteralValue(value, mode) { + return typeof value === "string" ? mode === "Uncapitalize" ? ApplyUncapitalize(value) : mode === "Capitalize" ? ApplyCapitalize(value) : mode === "Uppercase" ? ApplyUppercase(value) : mode === "Lowercase" ? ApplyLowercase(value) : value : value.toString(); +} +function FromRest5(T3, M4) { + return T3.map((L3) => Intrinsic(L3, M4)); +} +function Intrinsic(schema, mode, options = {}) { + return ( + // Intrinsic-Mapped-Inference + IsMappedKey(schema) ? IntrinsicFromMappedKey(schema, mode, options) : ( + // Standard-Inference + IsTemplateLiteral(schema) ? FromTemplateLiteral3(schema, mode, options) : IsUnion(schema) ? Union(FromRest5(schema.anyOf, mode), options) : IsLiteral(schema) ? Literal(FromLiteralValue(schema.const, mode), options) : ( + // Default Type + CreateType(schema, options) + ) + ) + ); +} +var init_intrinsic = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/intrinsic.mjs"() { + init_process_shim(); + init_type2(); + init_template_literal2(); + init_intrinsic_from_mapped_key(); + init_literal2(); + init_union2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs +function Capitalize(T3, options = {}) { + return Intrinsic(T3, "Capitalize", options); +} +var init_capitalize = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/capitalize.mjs"() { + init_process_shim(); + init_intrinsic(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs +function Lowercase(T3, options = {}) { + return Intrinsic(T3, "Lowercase", options); +} +var init_lowercase = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/lowercase.mjs"() { + init_process_shim(); + init_intrinsic(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs +function Uncapitalize(T3, options = {}) { + return Intrinsic(T3, "Uncapitalize", options); +} +var init_uncapitalize = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uncapitalize.mjs"() { + init_process_shim(); + init_intrinsic(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs +function Uppercase(T3, options = {}) { + return Intrinsic(T3, "Uppercase", options); +} +var init_uppercase = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/uppercase.mjs"() { + init_process_shim(); + init_intrinsic(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/index.mjs +var init_intrinsic2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/intrinsic/index.mjs"() { + init_process_shim(); + init_capitalize(); + init_intrinsic_from_mapped_key(); + init_intrinsic(); + init_lowercase(); + init_uncapitalize(); + init_uppercase(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs +function FromProperties12(properties, propertyKeys, options) { + const result = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) + result[K2] = Omit(properties[K2], propertyKeys, Clone(options)); + return result; +} +function FromMappedResult9(mappedResult, propertyKeys, options) { + return FromProperties12(mappedResult.properties, propertyKeys, options); +} +function OmitFromMappedResult(mappedResult, propertyKeys, options) { + const properties = FromMappedResult9(mappedResult, propertyKeys, options); + return MappedResult(properties); +} +var init_omit_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_omit(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs +function FromIntersect6(types2, propertyKeys) { + return types2.map((type) => OmitResolve(type, propertyKeys)); +} +function FromUnion8(types2, propertyKeys) { + return types2.map((type) => OmitResolve(type, propertyKeys)); +} +function FromProperty3(properties, key) { + const { [key]: _3, ...R3 } = properties; + return R3; +} +function FromProperties13(properties, propertyKeys) { + return propertyKeys.reduce((T3, K2) => FromProperty3(T3, K2), properties); +} +function FromObject3(type, propertyKeys, properties) { + const options = Discard(type, [TransformKind, "$id", "required", "properties"]); + const mappedProperties = FromProperties13(properties, propertyKeys); + return Object2(mappedProperties, options); +} +function UnionFromPropertyKeys(propertyKeys) { + const result = propertyKeys.reduce((result2, key) => IsLiteralValue(key) ? [...result2, Literal(key)] : result2, []); + return Union(result); +} +function OmitResolve(type, propertyKeys) { + return IsIntersect(type) ? Intersect(FromIntersect6(type.allOf, propertyKeys)) : IsUnion(type) ? Union(FromUnion8(type.anyOf, propertyKeys)) : IsObject3(type) ? FromObject3(type, propertyKeys, type.properties) : Object2({}); +} +function Omit(type, key, options) { + const typeKey = IsArray(key) ? UnionFromPropertyKeys(key) : key; + const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key; + const isTypeRef = IsRef(type); + const isKeyRef = IsRef(key); + return IsMappedResult(type) ? OmitFromMappedResult(type, propertyKeys, options) : IsMappedKey(key) ? OmitFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Omit", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Omit", [type, typeKey], options) : CreateType({ ...OmitResolve(type, propertyKeys), ...options }); +} +var init_omit = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit.mjs"() { + init_process_shim(); + init_type2(); + init_discard(); + init_symbols(); + init_computed2(); + init_literal2(); + init_indexed2(); + init_intersect2(); + init_union2(); + init_object2(); + init_omit_from_mapped_key(); + init_omit_from_mapped_result(); + init_kind(); + init_value(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs +function FromPropertyKey2(type, key, options) { + return { [key]: Omit(type, [key], Clone(options)) }; +} +function FromPropertyKeys2(type, propertyKeys, options) { + return propertyKeys.reduce((Acc, LK) => { + return { ...Acc, ...FromPropertyKey2(type, LK, options) }; + }, {}); +} +function FromMappedKey3(type, mappedKey, options) { + return FromPropertyKeys2(type, mappedKey.keys, options); +} +function OmitFromMappedKey(type, mappedKey, options) { + const properties = FromMappedKey3(type, mappedKey, options); + return MappedResult(properties); +} +var init_omit_from_mapped_key = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/omit-from-mapped-key.mjs"() { + init_process_shim(); + init_mapped2(); + init_omit(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/index.mjs +var init_omit2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/omit/index.mjs"() { + init_process_shim(); + init_omit_from_mapped_key(); + init_omit_from_mapped_result(); + init_omit(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs +function FromProperties14(properties, propertyKeys, options) { + const result = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) + result[K2] = Pick(properties[K2], propertyKeys, Clone(options)); + return result; +} +function FromMappedResult10(mappedResult, propertyKeys, options) { + return FromProperties14(mappedResult.properties, propertyKeys, options); +} +function PickFromMappedResult(mappedResult, propertyKeys, options) { + const properties = FromMappedResult10(mappedResult, propertyKeys, options); + return MappedResult(properties); +} +var init_pick_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_pick(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs +function FromIntersect7(types2, propertyKeys) { + return types2.map((type) => PickResolve(type, propertyKeys)); +} +function FromUnion9(types2, propertyKeys) { + return types2.map((type) => PickResolve(type, propertyKeys)); +} +function FromProperties15(properties, propertyKeys) { + const result = {}; + for (const K2 of propertyKeys) + if (K2 in properties) + result[K2] = properties[K2]; + return result; +} +function FromObject4(Type4, keys2, properties) { + const options = Discard(Type4, [TransformKind, "$id", "required", "properties"]); + const mappedProperties = FromProperties15(properties, keys2); + return Object2(mappedProperties, options); +} +function UnionFromPropertyKeys2(propertyKeys) { + const result = propertyKeys.reduce((result2, key) => IsLiteralValue(key) ? [...result2, Literal(key)] : result2, []); + return Union(result); +} +function PickResolve(type, propertyKeys) { + return IsIntersect(type) ? Intersect(FromIntersect7(type.allOf, propertyKeys)) : IsUnion(type) ? Union(FromUnion9(type.anyOf, propertyKeys)) : IsObject3(type) ? FromObject4(type, propertyKeys, type.properties) : Object2({}); +} +function Pick(type, key, options) { + const typeKey = IsArray(key) ? UnionFromPropertyKeys2(key) : key; + const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key; + const isTypeRef = IsRef(type); + const isKeyRef = IsRef(key); + return IsMappedResult(type) ? PickFromMappedResult(type, propertyKeys, options) : IsMappedKey(key) ? PickFromMappedKey(type, key, options) : isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : !isTypeRef && isKeyRef ? Computed("Pick", [type, typeKey], options) : isTypeRef && !isKeyRef ? Computed("Pick", [type, typeKey], options) : CreateType({ ...PickResolve(type, propertyKeys), ...options }); +} +var init_pick = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick.mjs"() { + init_process_shim(); + init_type2(); + init_discard(); + init_computed2(); + init_intersect2(); + init_literal2(); + init_object2(); + init_union2(); + init_indexed2(); + init_symbols(); + init_kind(); + init_value(); + init_pick_from_mapped_key(); + init_pick_from_mapped_result(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs +function FromPropertyKey3(type, key, options) { + return { + [key]: Pick(type, [key], Clone(options)) + }; +} +function FromPropertyKeys3(type, propertyKeys, options) { + return propertyKeys.reduce((result, leftKey) => { + return { ...result, ...FromPropertyKey3(type, leftKey, options) }; + }, {}); +} +function FromMappedKey4(type, mappedKey, options) { + return FromPropertyKeys3(type, mappedKey.keys, options); +} +function PickFromMappedKey(type, mappedKey, options) { + const properties = FromMappedKey4(type, mappedKey, options); + return MappedResult(properties); +} +var init_pick_from_mapped_key = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/pick-from-mapped-key.mjs"() { + init_process_shim(); + init_mapped2(); + init_pick(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/index.mjs +var init_pick2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/pick/index.mjs"() { + init_process_shim(); + init_pick_from_mapped_key(); + init_pick_from_mapped_result(); + init_pick(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs +function FromComputed3(target, parameters) { + return Computed("Partial", [Computed(target, parameters)]); +} +function FromRef3($ref) { + return Computed("Partial", [Ref($ref)]); +} +function FromProperties16(properties) { + const partialProperties = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) + partialProperties[K2] = Optional(properties[K2]); + return partialProperties; +} +function FromObject5(type, properties) { + const options = Discard(type, [TransformKind, "$id", "required", "properties"]); + const mappedProperties = FromProperties16(properties); + return Object2(mappedProperties, options); +} +function FromRest6(types2) { + return types2.map((type) => PartialResolve(type)); +} +function PartialResolve(type) { + return ( + // Mappable + IsComputed(type) ? FromComputed3(type.target, type.parameters) : IsRef(type) ? FromRef3(type.$ref) : IsIntersect(type) ? Intersect(FromRest6(type.allOf)) : IsUnion(type) ? Union(FromRest6(type.anyOf)) : IsObject3(type) ? FromObject5(type, type.properties) : ( + // Intrinsic + IsBigInt2(type) ? type : IsBoolean2(type) ? type : IsInteger(type) ? type : IsLiteral(type) ? type : IsNull2(type) ? type : IsNumber3(type) ? type : IsString2(type) ? type : IsSymbol2(type) ? type : IsUndefined3(type) ? type : ( + // Passthrough + Object2({}) + ) + ) + ); +} +function Partial(type, options) { + if (IsMappedResult(type)) { + return PartialFromMappedResult(type, options); + } else { + return CreateType({ ...PartialResolve(type), ...options }); + } +} +var init_partial = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial.mjs"() { + init_process_shim(); + init_type2(); + init_computed2(); + init_optional2(); + init_object2(); + init_intersect2(); + init_union2(); + init_ref4(); + init_discard2(); + init_symbols2(); + init_partial_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs +function FromProperties17(K2, options) { + const Acc = {}; + for (const K22 of globalThis.Object.getOwnPropertyNames(K2)) + Acc[K22] = Partial(K2[K22], Clone(options)); + return Acc; +} +function FromMappedResult11(R3, options) { + return FromProperties17(R3.properties, options); +} +function PartialFromMappedResult(R3, options) { + const P3 = FromMappedResult11(R3, options); + return MappedResult(P3); +} +var init_partial_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/partial-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_partial(); + init_value2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/index.mjs +var init_partial2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/partial/index.mjs"() { + init_process_shim(); + init_partial_from_mapped_result(); + init_partial(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required.mjs +function FromComputed4(target, parameters) { + return Computed("Required", [Computed(target, parameters)]); +} +function FromRef4($ref) { + return Computed("Required", [Ref($ref)]); +} +function FromProperties18(properties) { + const requiredProperties = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(properties)) + requiredProperties[K2] = Discard(properties[K2], [OptionalKind]); + return requiredProperties; +} +function FromObject6(type, properties) { + const options = Discard(type, [TransformKind, "$id", "required", "properties"]); + const mappedProperties = FromProperties18(properties); + return Object2(mappedProperties, options); +} +function FromRest7(types2) { + return types2.map((type) => RequiredResolve(type)); +} +function RequiredResolve(type) { + return ( + // Mappable + IsComputed(type) ? FromComputed4(type.target, type.parameters) : IsRef(type) ? FromRef4(type.$ref) : IsIntersect(type) ? Intersect(FromRest7(type.allOf)) : IsUnion(type) ? Union(FromRest7(type.anyOf)) : IsObject3(type) ? FromObject6(type, type.properties) : ( + // Intrinsic + IsBigInt2(type) ? type : IsBoolean2(type) ? type : IsInteger(type) ? type : IsLiteral(type) ? type : IsNull2(type) ? type : IsNumber3(type) ? type : IsString2(type) ? type : IsSymbol2(type) ? type : IsUndefined3(type) ? type : ( + // Passthrough + Object2({}) + ) + ) + ); +} +function Required(type, options) { + if (IsMappedResult(type)) { + return RequiredFromMappedResult(type, options); + } else { + return CreateType({ ...RequiredResolve(type), ...options }); + } +} +var init_required = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required.mjs"() { + init_process_shim(); + init_type2(); + init_computed2(); + init_object2(); + init_intersect2(); + init_union2(); + init_ref4(); + init_symbols2(); + init_discard2(); + init_required_from_mapped_result(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs +function FromProperties19(P3, options) { + const Acc = {}; + for (const K2 of globalThis.Object.getOwnPropertyNames(P3)) + Acc[K2] = Required(P3[K2], options); + return Acc; +} +function FromMappedResult12(R3, options) { + return FromProperties19(R3.properties, options); +} +function RequiredFromMappedResult(R3, options) { + const P3 = FromMappedResult12(R3, options); + return MappedResult(P3); +} +var init_required_from_mapped_result = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/required-from-mapped-result.mjs"() { + init_process_shim(); + init_mapped2(); + init_required(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/index.mjs +var init_required2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/required/index.mjs"() { + init_process_shim(); + init_required_from_mapped_result(); + init_required(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs +function DereferenceParameters(moduleProperties, types2) { + return types2.map((type) => { + return IsRef(type) ? Dereference(moduleProperties, type.$ref) : FromType2(moduleProperties, type); + }); +} +function Dereference(moduleProperties, ref) { + return ref in moduleProperties ? IsRef(moduleProperties[ref]) ? Dereference(moduleProperties, moduleProperties[ref].$ref) : FromType2(moduleProperties, moduleProperties[ref]) : Never(); +} +function FromAwaited(parameters) { + return Awaited(parameters[0]); +} +function FromIndex(parameters) { + return Index(parameters[0], parameters[1]); +} +function FromKeyOf(parameters) { + return KeyOf(parameters[0]); +} +function FromPartial(parameters) { + return Partial(parameters[0]); +} +function FromOmit(parameters) { + return Omit(parameters[0], parameters[1]); +} +function FromPick(parameters) { + return Pick(parameters[0], parameters[1]); +} +function FromRequired(parameters) { + return Required(parameters[0]); +} +function FromComputed5(moduleProperties, target, parameters) { + const dereferenced = DereferenceParameters(moduleProperties, parameters); + return target === "Awaited" ? FromAwaited(dereferenced) : target === "Index" ? FromIndex(dereferenced) : target === "KeyOf" ? FromKeyOf(dereferenced) : target === "Partial" ? FromPartial(dereferenced) : target === "Omit" ? FromOmit(dereferenced) : target === "Pick" ? FromPick(dereferenced) : target === "Required" ? FromRequired(dereferenced) : Never(); +} +function FromArray6(moduleProperties, type) { + return Array2(FromType2(moduleProperties, type)); +} +function FromAsyncIterator3(moduleProperties, type) { + return AsyncIterator2(FromType2(moduleProperties, type)); +} +function FromConstructor3(moduleProperties, parameters, instanceType) { + return Constructor(FromTypes2(moduleProperties, parameters), FromType2(moduleProperties, instanceType)); +} +function FromFunction3(moduleProperties, parameters, returnType) { + return Function2(FromTypes2(moduleProperties, parameters), FromType2(moduleProperties, returnType)); +} +function FromIntersect8(moduleProperties, types2) { + return Intersect(FromTypes2(moduleProperties, types2)); +} +function FromIterator3(moduleProperties, type) { + return Iterator(FromType2(moduleProperties, type)); +} +function FromObject7(moduleProperties, properties) { + return Object2(globalThis.Object.keys(properties).reduce((result, key) => { + return { ...result, [key]: FromType2(moduleProperties, properties[key]) }; + }, {})); +} +function FromRecord3(moduleProperties, type) { + const [value, pattern] = [FromType2(moduleProperties, RecordValue2(type)), RecordPattern(type)]; + const result = CloneType(type); + result.patternProperties[pattern] = value; + return result; +} +function FromTransform(moduleProperties, transform) { + return IsRef(transform) ? { ...Dereference(moduleProperties, transform.$ref), [TransformKind]: transform[TransformKind] } : transform; +} +function FromTuple5(moduleProperties, types2) { + return Tuple(FromTypes2(moduleProperties, types2)); +} +function FromUnion10(moduleProperties, types2) { + return Union(FromTypes2(moduleProperties, types2)); +} +function FromTypes2(moduleProperties, types2) { + return types2.map((type) => FromType2(moduleProperties, type)); +} +function FromType2(moduleProperties, type) { + return ( + // Modifiers + IsOptional(type) ? CreateType(FromType2(moduleProperties, Discard(type, [OptionalKind])), type) : IsReadonly(type) ? CreateType(FromType2(moduleProperties, Discard(type, [ReadonlyKind])), type) : ( + // Transform + IsTransform(type) ? CreateType(FromTransform(moduleProperties, type), type) : ( + // Types + IsArray3(type) ? CreateType(FromArray6(moduleProperties, type.items), type) : IsAsyncIterator2(type) ? CreateType(FromAsyncIterator3(moduleProperties, type.items), type) : IsComputed(type) ? CreateType(FromComputed5(moduleProperties, type.target, type.parameters)) : IsConstructor(type) ? CreateType(FromConstructor3(moduleProperties, type.parameters, type.returns), type) : IsFunction2(type) ? CreateType(FromFunction3(moduleProperties, type.parameters, type.returns), type) : IsIntersect(type) ? CreateType(FromIntersect8(moduleProperties, type.allOf), type) : IsIterator2(type) ? CreateType(FromIterator3(moduleProperties, type.items), type) : IsObject3(type) ? CreateType(FromObject7(moduleProperties, type.properties), type) : IsRecord(type) ? CreateType(FromRecord3(moduleProperties, type)) : IsTuple(type) ? CreateType(FromTuple5(moduleProperties, type.items || []), type) : IsUnion(type) ? CreateType(FromUnion10(moduleProperties, type.anyOf), type) : type + ) + ) + ); +} +function ComputeType(moduleProperties, key) { + return key in moduleProperties ? FromType2(moduleProperties, moduleProperties[key]) : Never(); +} +function ComputeModuleProperties(moduleProperties) { + return globalThis.Object.getOwnPropertyNames(moduleProperties).reduce((result, key) => { + return { ...result, [key]: ComputeType(moduleProperties, key) }; + }, {}); +} +var init_compute = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/compute.mjs"() { + init_process_shim(); + init_create(); + init_clone(); + init_discard2(); + init_array2(); + init_awaited2(); + init_async_iterator2(); + init_constructor2(); + init_indexed2(); + init_function2(); + init_intersect2(); + init_iterator2(); + init_keyof2(); + init_object2(); + init_omit2(); + init_pick2(); + init_never2(); + init_partial2(); + init_record2(); + init_required2(); + init_tuple2(); + init_union2(); + init_symbols2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/module.mjs +function Module(properties) { + return new TModule(properties); +} +var TModule; +var init_module = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/module.mjs"() { + init_process_shim(); + init_create(); + init_symbols2(); + init_compute(); + TModule = class { + constructor($defs) { + const computed = ComputeModuleProperties($defs); + const identified = this.WithIdentifiers(computed); + this.$defs = identified; + } + /** `[Json]` Imports a Type by Key. */ + Import(key, options) { + const $defs = { ...this.$defs, [key]: CreateType(this.$defs[key], options) }; + return CreateType({ [Kind]: "Import", $defs, $ref: key }); + } + // prettier-ignore + WithIdentifiers($defs) { + return globalThis.Object.getOwnPropertyNames($defs).reduce((result, key) => { + return { ...result, [key]: { ...$defs[key], $id: key } }; + }, {}); + } + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/index.mjs +var init_module2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/module/index.mjs"() { + init_process_shim(); + init_module(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/not/not.mjs +function Not(type, options) { + return CreateType({ [Kind]: "Not", not: type }, options); +} +var init_not = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/not/not.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/not/index.mjs +var init_not2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/not/index.mjs"() { + init_process_shim(); + init_not(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs +function Parameters(schema, options) { + return IsFunction2(schema) ? Tuple(schema.parameters, options) : Never(); +} +var init_parameters = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/parameters/parameters.mjs"() { + init_process_shim(); + init_tuple2(); + init_never2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/parameters/index.mjs +var init_parameters2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/parameters/index.mjs"() { + init_process_shim(); + init_parameters(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs +function Recursive(callback2, options = {}) { + if (IsUndefined(options.$id)) + options.$id = `T${Ordinal++}`; + const thisType = CloneType(callback2({ [Kind]: "This", $ref: `${options.$id}` })); + thisType.$id = options.$id; + return CreateType({ [Hint]: "Recursive", ...thisType }, options); +} +var Ordinal; +var init_recursive = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/recursive/recursive.mjs"() { + init_process_shim(); + init_type(); + init_type2(); + init_value(); + init_symbols2(); + Ordinal = 0; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/recursive/index.mjs +var init_recursive2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/recursive/index.mjs"() { + init_process_shim(); + init_recursive(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs +function RegExp2(unresolved, options) { + const expr = IsString(unresolved) ? new globalThis.RegExp(unresolved) : unresolved; + return CreateType({ [Kind]: "RegExp", type: "RegExp", source: expr.source, flags: expr.flags }, options); +} +var init_regexp = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/regexp/regexp.mjs"() { + init_process_shim(); + init_type2(); + init_value(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/regexp/index.mjs +var init_regexp2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/regexp/index.mjs"() { + init_process_shim(); + init_regexp(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs +function RestResolve(T3) { + return IsIntersect(T3) ? T3.allOf : IsUnion(T3) ? T3.anyOf : IsTuple(T3) ? T3.items ?? [] : []; +} +function Rest(T3) { + return RestResolve(T3); +} +var init_rest = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/rest/rest.mjs"() { + init_process_shim(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/rest/index.mjs +var init_rest2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/rest/index.mjs"() { + init_process_shim(); + init_rest(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs +function ReturnType(schema, options) { + return IsFunction2(schema) ? CreateType(schema.returns, options) : Never(options); +} +var init_return_type = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/return-type/return-type.mjs"() { + init_process_shim(); + init_type2(); + init_never2(); + init_kind(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/return-type/index.mjs +var init_return_type2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/return-type/index.mjs"() { + init_process_shim(); + init_return_type(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/schema/anyschema.mjs +var init_anyschema = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/schema/anyschema.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/schema/schema.mjs +var init_schema = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/schema/schema.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/schema/index.mjs +var init_schema2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/schema/index.mjs"() { + init_process_shim(); + init_anyschema(); + init_schema(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/static/static.mjs +var init_static = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/static/static.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/static/index.mjs +var init_static2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/static/index.mjs"() { + init_process_shim(); + init_static(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs +function Transform(schema) { + return new TransformDecodeBuilder(schema); +} +var TransformDecodeBuilder, TransformEncodeBuilder; +var init_transform = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/transform/transform.mjs"() { + init_process_shim(); + init_symbols2(); + init_kind(); + TransformDecodeBuilder = class { + constructor(schema) { + this.schema = schema; + } + Decode(decode5) { + return new TransformEncodeBuilder(this.schema, decode5); + } + }; + TransformEncodeBuilder = class { + constructor(schema, decode5) { + this.schema = schema; + this.decode = decode5; + } + EncodeTransform(encode2, schema) { + const Encode = (value) => schema[TransformKind].Encode(encode2(value)); + const Decode = (value) => this.decode(schema[TransformKind].Decode(value)); + const Codec = { Encode, Decode }; + return { ...schema, [TransformKind]: Codec }; + } + EncodeSchema(encode2, schema) { + const Codec = { Decode: this.decode, Encode: encode2 }; + return { ...schema, [TransformKind]: Codec }; + } + Encode(encode2) { + return IsTransform(this.schema) ? this.EncodeTransform(encode2, this.schema) : this.EncodeSchema(encode2, this.schema); + } + }; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/transform/index.mjs +var init_transform2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/transform/index.mjs"() { + init_process_shim(); + init_transform(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs +function Unsafe(options = {}) { + return CreateType({ [Kind]: options[Kind] ?? "Unsafe" }, options); +} +var init_unsafe = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unsafe/unsafe.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unsafe/index.mjs +var init_unsafe2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/unsafe/index.mjs"() { + init_process_shim(); + init_unsafe(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/void/void.mjs +function Void(options) { + return CreateType({ [Kind]: "Void", type: "void" }, options); +} +var init_void = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/void/void.mjs"() { + init_process_shim(); + init_type2(); + init_symbols2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/void/index.mjs +var init_void2 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/void/index.mjs"() { + init_process_shim(); + init_void(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/type.mjs +var type_exports3 = {}; +__export(type_exports3, { + Any: () => Any, + Argument: () => Argument, + Array: () => Array2, + AsyncIterator: () => AsyncIterator2, + Awaited: () => Awaited, + BigInt: () => BigInt2, + Boolean: () => Boolean2, + Capitalize: () => Capitalize, + Composite: () => Composite, + Const: () => Const, + Constructor: () => Constructor, + ConstructorParameters: () => ConstructorParameters, + Date: () => Date2, + Enum: () => Enum, + Exclude: () => Exclude, + Extends: () => Extends, + Extract: () => Extract, + Function: () => Function2, + Index: () => Index, + InstanceType: () => InstanceType, + Instantiate: () => Instantiate, + Integer: () => Integer, + Intersect: () => Intersect, + Iterator: () => Iterator, + KeyOf: () => KeyOf, + Literal: () => Literal, + Lowercase: () => Lowercase, + Mapped: () => Mapped, + Module: () => Module, + Never: () => Never, + Not: () => Not, + Null: () => Null, + Number: () => Number2, + Object: () => Object2, + Omit: () => Omit, + Optional: () => Optional, + Parameters: () => Parameters, + Partial: () => Partial, + Pick: () => Pick, + Promise: () => Promise2, + Readonly: () => Readonly, + ReadonlyOptional: () => ReadonlyOptional, + Record: () => Record, + Recursive: () => Recursive, + Ref: () => Ref, + RegExp: () => RegExp2, + Required: () => Required, + Rest: () => Rest, + ReturnType: () => ReturnType, + String: () => String2, + Symbol: () => Symbol2, + TemplateLiteral: () => TemplateLiteral, + Transform: () => Transform, + Tuple: () => Tuple, + Uint8Array: () => Uint8Array2, + Uncapitalize: () => Uncapitalize, + Undefined: () => Undefined, + Union: () => Union, + Unknown: () => Unknown, + Unsafe: () => Unsafe, + Uppercase: () => Uppercase, + Void: () => Void +}); +var init_type5 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/type.mjs"() { + init_process_shim(); + init_any2(); + init_argument2(); + init_array2(); + init_async_iterator2(); + init_awaited2(); + init_bigint2(); + init_boolean2(); + init_composite2(); + init_const2(); + init_constructor2(); + init_constructor_parameters2(); + init_date2(); + init_enum2(); + init_exclude2(); + init_extends2(); + init_extract2(); + init_function2(); + init_indexed2(); + init_instance_type2(); + init_instantiate2(); + init_integer2(); + init_intersect2(); + init_intrinsic2(); + init_iterator2(); + init_keyof2(); + init_literal2(); + init_mapped2(); + init_module2(); + init_never2(); + init_not2(); + init_null2(); + init_number2(); + init_object2(); + init_omit2(); + init_optional2(); + init_parameters2(); + init_partial2(); + init_pick2(); + init_promise2(); + init_readonly2(); + init_readonly_optional2(); + init_record2(); + init_recursive2(); + init_ref4(); + init_regexp2(); + init_required2(); + init_rest2(); + init_return_type2(); + init_string2(); + init_symbol2(); + init_template_literal2(); + init_transform2(); + init_tuple2(); + init_uint8array2(); + init_undefined2(); + init_union2(); + init_unknown2(); + init_unsafe2(); + init_void2(); + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/index.mjs +var Type; +var init_type6 = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/type/type/index.mjs"() { + init_process_shim(); + init_type5(); + Type = type_exports3; + } +}); + +// ../pi-mono/node_modules/@sinclair/typebox/build/esm/index.mjs +var init_esm = __esm({ + "../pi-mono/node_modules/@sinclair/typebox/build/esm/index.mjs"() { + init_process_shim(); + init_clone(); + init_create(); + init_error2(); + init_guard3(); + init_helpers2(); + init_patterns2(); + init_registry(); + init_sets(); + init_symbols2(); + init_any2(); + init_array2(); + init_argument2(); + init_async_iterator2(); + init_awaited2(); + init_bigint2(); + init_boolean2(); + init_composite2(); + init_const2(); + init_constructor2(); + init_constructor_parameters2(); + init_date2(); + init_enum2(); + init_exclude2(); + init_extends2(); + init_extract2(); + init_function2(); + init_indexed2(); + init_instance_type2(); + init_instantiate2(); + init_integer2(); + init_intersect2(); + init_iterator2(); + init_intrinsic2(); + init_keyof2(); + init_literal2(); + init_module2(); + init_mapped2(); + init_never2(); + init_not2(); + init_null2(); + init_number2(); + init_object2(); + init_omit2(); + init_optional2(); + init_parameters2(); + init_partial2(); + init_pick2(); + init_promise2(); + init_readonly2(); + init_readonly_optional2(); + init_record2(); + init_recursive2(); + init_ref4(); + init_regexp2(); + init_required2(); + init_rest2(); + init_return_type2(); + init_schema2(); + init_static2(); + init_string2(); + init_symbol2(); + init_template_literal2(); + init_transform2(); + init_tuple2(); + init_uint8array2(); + init_undefined2(); + init_union2(); + init_unknown2(); + init_unsafe2(); + init_void2(); + init_type6(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f4) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f4) { + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); +} +var init_tslib = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/tslib.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs +var uuid4; +var init_uuid = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"() { + init_process_shim(); + uuid4 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid4 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c6) => (+c6 ^ randomByte() & 15 >> +c6 / 4).toString(16)); + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/errors.mjs +function isAbortError(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError; +var init_errors = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/errors.mjs"() { + init_process_shim(); + castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { + } + try { + return new Error(JSON.stringify(err)); + } catch { + } + } + return new Error(err); + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/core/error.mjs +var AnthropicError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError; +var init_error3 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/core/error.mjs"() { + init_process_shim(); + init_errors(); + AnthropicError = class extends Error { + }; + APIError = class _APIError extends AnthropicError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get("request-id"); + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new _APIError(status, error, message, headers); + } + }; + APIUserAbortError = class extends APIError { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } + }; + APIConnectionError = class extends APIError { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } + }; + APIConnectionTimeoutError = class extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } + }; + BadRequestError = class extends APIError { + }; + AuthenticationError = class extends APIError { + }; + PermissionDeniedError = class extends APIError { + }; + NotFoundError = class extends APIError { + }; + ConflictError = class extends APIError { + }; + UnprocessableEntityError = class extends APIError { + }; + RateLimitError = class extends APIError { + }; + InternalServerError = class extends APIError { + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs +function maybeObj(x2) { + if (typeof x2 !== "object") { + return {}; + } + return x2 ?? {}; +} +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +var startsWithSchemeRegexp, isAbsoluteURL, isArray, isReadonlyArray, validatePositiveInteger, safeJSON; +var init_values = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"() { + init_process_shim(); + init_error3(); + startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; + isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); + }; + isArray = (val2) => (isArray = Array.isArray, isArray(val2)); + isReadonlyArray = isArray; + validatePositiveInteger = (name, n7) => { + if (typeof n7 !== "number" || !Number.isInteger(n7)) { + throw new AnthropicError(`${name} must be an integer`); + } + if (n7 < 0) { + throw new AnthropicError(`${name} must be a positive integer`); + } + return n7; + }; + safeJSON = (text3) => { + try { + return JSON.parse(text3); + } catch (err) { + return void 0; + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs +var sleep; +var init_sleep = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"() { + init_process_shim(); + sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/version.mjs +var VERSION; +var init_version = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/version.mjs"() { + init_process_shim(); + VERSION = "0.73.0"; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs +function getDetectedPlatform() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +function getBrowserInfo() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match2 = pattern.exec(navigator.userAgent); + if (match2) { + const major = match2[1] || 0; + const minor = match2[2] || 0; + const patch = match2[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var isRunningInBrowser, getPlatformProperties, normalizeArch, normalizePlatform, _platformHeaders, getPlatformHeaders; +var init_detect_platform = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"() { + init_process_shim(); + init_version(); + isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== "undefined" && // @ts-ignore + typeof window.document !== "undefined" && // @ts-ignore + typeof navigator !== "undefined" + ); + }; + getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(Deno.build.os), + "X-Stainless-Arch": normalizeArch(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; + }; + normalizeArch = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; + }; + normalizePlatform = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; + }; + getPlatformHeaders = () => { + return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/shims.mjs +function getDefaultFetch() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream(...args) { + const ReadableStream2 = globalThis.ReadableStream; + if (typeof ReadableStream2 === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream2(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +function ReadableStreamToAsyncIterable(stream2) { + if (stream2[Symbol.asyncIterator]) + return stream2; + const reader = stream2.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); + return result; + } catch (e9) { + reader.releaseLock(); + throw e9; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: void 0 }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +async function CancelReadableStream(stream2) { + if (stream2 === null || typeof stream2 !== "object") + return; + if (stream2[Symbol.asyncIterator]) { + await stream2[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream2.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +var init_shims = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/shims.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/request-options.mjs +var FallbackEncoder; +var init_request_options = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/request-options.mjs"() { + init_process_shim(); + FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs +function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index2 = 0; + for (const buffer of buffers) { + output.set(buffer, index2); + index2 += buffer.length; + } + return output; +} +function encodeUTF8(str2) { + let encoder; + return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str2); +} +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); +} +var encodeUTF8_, decodeUTF8_; +var init_bytes = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs +function findNewlineIndex(buffer, startIndex) { + const newline = 10; + const carriage = 13; + for (let i7 = startIndex ?? 0; i7 < buffer.length; i7++) { + if (buffer[i7] === newline) { + return { preceding: i7, index: i7 + 1, carriage: false }; + } + if (buffer[i7] === carriage) { + return { preceding: i7, index: i7 + 1, carriage: true }; + } + } + return null; +} +function findDoubleNewlineIndex(buffer) { + const newline = 10; + const carriage = 13; + for (let i7 = 0; i7 < buffer.length - 1; i7++) { + if (buffer[i7] === newline && buffer[i7 + 1] === newline) { + return i7 + 2; + } + if (buffer[i7] === carriage && buffer[i7 + 1] === carriage) { + return i7 + 2; + } + if (buffer[i7] === carriage && buffer[i7 + 1] === newline && i7 + 3 < buffer.length && buffer[i7 + 2] === carriage && buffer[i7 + 3] === newline) { + return i7 + 4; + } + } + return -1; +} +var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex, LineDecoder; +var init_line = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"() { + init_process_shim(); + init_tslib(); + init_bytes(); + LineDecoder = class { + constructor() { + _LineDecoder_buffer.set(this, void 0); + _LineDecoder_carriageReturnIndex.set(this, void 0); + __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { + return []; + } + return this.decode("\n"); + } + }; + _LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap(); + LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]); + LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +function noop() { +} +function makeLogFn(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } else { + return logger2[fnLevel].bind(logger2); + } +} +function loggerFor(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn("error", logger2, logLevel), + warn: makeLogFn("warn", logger2, logLevel), + info: makeLogFn("info", logger2, logLevel), + debug: makeLogFn("debug", logger2, logLevel) + }; + cachedLoggers.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var levelNumbers, parseLogLevel, noopLogger, cachedLoggers, formatRequestDetails; +var init_log = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"() { + init_process_shim(); + init_values(); + levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 + }; + parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return void 0; + }; + noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop + }; + cachedLoggers = /* @__PURE__ */ new WeakMap(); + formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "x-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/core/streaming.mjs +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { + throw new AnthropicError(`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 AnthropicError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +async function* iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF8(chunk) : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +function partition(str2, delimiter2) { + const index2 = str2.indexOf(delimiter2); + if (index2 !== -1) { + return [str2.substring(0, index2), delimiter2, str2.substring(index2 + delimiter2.length)]; + } + return [str2, "", ""]; +} +var _Stream_client, Stream, SSEDecoder; +var init_streaming = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/core/streaming.mjs"() { + init_process_shim(); + init_tslib(); + init_error3(); + init_shims(); + init_line(); + init_shims(); + init_errors(); + init_values(); + init_bytes(); + init_log(); + init_error3(); + Stream = class _Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + _Stream_client.set(this, void 0); + this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); + } + static fromSSEResponse(response, controller, client) { + let consumed2 = false; + const logger2 = client ? loggerFor(client) : console; + async function* iterator() { + if (consumed2) { + throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed2 = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (sse.event === "completion") { + try { + yield JSON.parse(sse.data); + } catch (e9) { + logger2.error(`Could not parse message into JSON:`, sse.data); + logger2.error(`From chunk:`, sse.raw); + throw e9; + } + } + if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop") { + try { + yield JSON.parse(sse.data); + } catch (e9) { + logger2.error(`Could not parse message into JSON:`, sse.data); + logger2.error(`From chunk:`, sse.raw); + throw e9; + } + } + if (sse.event === "ping") { + continue; + } + if (sse.event === "error") { + throw new APIError(void 0, safeJSON(sse.data) ?? sse.data, void 0, response.headers); + } + } + done = true; + } catch (e9) { + if (isAbortError(e9)) + return; + throw e9; + } finally { + if (!done) + controller.abort(); + } + } + return new _Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed2 = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed2) { + throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed2 = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } catch (e9) { + if (isAbortError(e9)) + return; + throw e9; + } finally { + if (!done) + controller.abort(); + } + } + return new _Stream(iterator, controller, client); + } + [(_Stream_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + } + }; + }; + return [ + new _Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + new _Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")) + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self2 = this; + let iter; + return makeReadableStream({ + async start() { + iter = self2[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encodeUTF8(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + } + }); + } + }; + SSEDecoder = class { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith("\r")) { + line = line.substring(0, line.length - 1); + } + if (!line) { + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join("\n"), + raw: this.chunks + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(":")) { + return null; + } + let [fieldname, _3, value] = partition(line, ":"); + if (value.startsWith(" ")) { + value = value.substring(1); + } + if (fieldname === "event") { + this.event = value; + } else if (fieldname === "data") { + this.data.push(value); + } + return null; + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/parse.mjs +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug("response", response.status, response.url, response.headers, response.body); + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; + } + const json2 = await response.json(); + return addRequestID(json2, response); + } + const text3 = await response.text(); + return text3; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +function addRequestID(value, response) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return value; + } + return Object.defineProperty(value, "_request_id", { + value: response.headers.get("request-id"), + enumerable: false + }); +} +var init_parse2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/parse.mjs"() { + init_process_shim(); + init_streaming(); + init_log(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/core/api-promise.mjs +var _APIPromise_client, APIPromise; +var init_api_promise = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/core/api-promise.mjs"() { + init_process_shim(); + init_tslib(); + init_parse2(); + APIPromise = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse2 = defaultParseResponse) { + super((resolve2) => { + resolve2(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse2; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p4) => p4.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get("request-id") }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } + }; + _APIPromise_client = /* @__PURE__ */ new WeakMap(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/core/pagination.mjs +var _AbstractPage_client, AbstractPage, PagePromise, Page, PageCursor; +var init_pagination = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/core/pagination.mjs"() { + init_process_shim(); + init_tslib(); + init_error3(); + init_parse2(); + init_api_promise(); + init_values(); + AbstractPage = class { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } + }; + PagePromise = class extends APIPromise { + constructor(client, request, Page3) { + super(client, request, async (client2, props) => new Page3(client2, props.response, await defaultParseResponse(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } + }; + Page = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.first_id = body.first_id || null; + this.last_id = body.last_id || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + if (this.options.query?.["before_id"]) { + const first_id = this.first_id; + if (!first_id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + before_id: first_id + } + }; + } + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after_id: cursor + } + }; + } + }; + PageCursor = class extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page: cursor + } + }; + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/uploads.mjs +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName(value, stripPath) { + const val2 = typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || ""; + return stripPath ? val2.split(/[\\/]/).pop() || void 0 : val2; +} +function supportsFormData(fetchObject) { + const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch3); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor; + const data = new FormData(); + if (data.toString() === await new FetchResponse(data).text()) { + return false; + } + return true; + } catch { + return true; + } + })(); + supportsFormDataMap.set(fetch3, promise); + return promise; +} +var checkFileSupport, isAsyncIterable, multipartFormRequestOptions, supportsFormDataMap, createForm, isNamedBlob, addFormValue; +var init_uploads = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/uploads.mjs"() { + init_process_shim(); + init_shims(); + checkFileSupport = () => { + if (typeof File === "undefined") { + const { process: process2 } = globalThis; + const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } + }; + isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + multipartFormRequestOptions = async (opts, fetch3, stripFilenames = true) => { + return { ...opts, body: await createForm(opts.body, fetch3, stripFilenames) }; + }; + supportsFormDataMap = /* @__PURE__ */ new WeakMap(); + createForm = async (body, fetch3, stripFilenames = true) => { + if (!await supportsFormData(fetch3)) { + throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, stripFilenames))); + return form; + }; + isNamedBlob = (value) => value instanceof Blob && "name" in value; + addFormValue = async (form, key, value, stripFilenames) => { + if (value === void 0) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + form.append(key, String(value)); + } else if (value instanceof Response) { + let options = {}; + const contentType = value.headers.get("Content-Type"); + if (contentType) { + options = { type: contentType }; + } + form.append(key, makeFile([await value.blob()], getName(value, stripFilenames), options)); + } else if (isAsyncIterable(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, stripFilenames))); + } else if (isNamedBlob(value)) { + form.append(key, makeFile([value], getName(value, stripFilenames), { type: value.type })); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry, stripFilenames))); + } else if (typeof value === "object") { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, stripFilenames))); + } else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/to-file.mjs +async function toFile(value, name, options) { + checkFileSupport(); + value = await value; + name || (name = getName(value, true)); + if (isFileLike(value)) { + if (value instanceof File && name == null && options == null) { + return value; + } + return makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options + }); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await getBytes(blob), name, options); + } + const parts = await getBytes(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function getBytes(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable(value)) { + for await (const chunk of value) { + parts.push(...await getBytes(chunk)); + } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`; +} +var isBlobLike, isFileLike, isResponseLike; +var init_to_file = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/to-file.mjs"() { + init_process_shim(); + init_uploads(); + init_uploads(); + isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; + isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); + isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/core/uploads.mjs +var init_uploads2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/core/uploads.mjs"() { + init_process_shim(); + init_to_file(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/shared.mjs +var init_shared = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/shared.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/core/resource.mjs +var APIResource; +var init_resource = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/core/resource.mjs"() { + init_process_shim(); + APIResource = class { + constructor(client) { + this._client = client; + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/headers.mjs +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values: values2, nulls } = headers; + yield* values2.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values2 = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values2) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var brand_privateNullableHeaders, buildHeaders; +var init_headers = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/headers.mjs"() { + init_process_shim(); + init_values(); + brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders"); + buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs +function wasCreatedByStainlessHelper(value) { + return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value; +} +function collectStainlessHelpers(tools, messages) { + const helpers2 = /* @__PURE__ */ new Set(); + if (tools) { + for (const tool of tools) { + if (wasCreatedByStainlessHelper(tool)) { + helpers2.add(tool[SDK_HELPER_SYMBOL]); + } + } + } + if (messages) { + for (const message of messages) { + if (wasCreatedByStainlessHelper(message)) { + helpers2.add(message[SDK_HELPER_SYMBOL]); + } + if (Array.isArray(message.content)) { + for (const block of message.content) { + if (wasCreatedByStainlessHelper(block)) { + helpers2.add(block[SDK_HELPER_SYMBOL]); + } + } + } + } + } + return Array.from(helpers2); +} +function stainlessHelperHeader(tools, messages) { + const helpers2 = collectStainlessHelpers(tools, messages); + if (helpers2.length === 0) + return {}; + return { "x-stainless-helper": helpers2.join(", ") }; +} +function stainlessHelperHeaderFromFile(file) { + if (wasCreatedByStainlessHelper(file)) { + return { "x-stainless-helper": file[SDK_HELPER_SYMBOL] }; + } + return {}; +} +var SDK_HELPER_SYMBOL; +var init_stainless_helper_header = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs"() { + init_process_shim(); + SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper"); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs +function encodeURIPath(str2) { + return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY, createPathTagFunction, path; +var init_path = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs"() { + init_process_shim(); + init_error3(); + EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); + createPathTagFunction = (pathEncoder = encodeURIPath) => function path6(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path7 = statics.reduce((previousValue, currentValue, index2) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index2]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index2 !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index2 === params.length ? "" : encoded); + }, ""); + const pathOnly = path7.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match2; + while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match2.index, + length: match2[0].length, + error: `Value "${match2[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a3, b4) => a3.start - b4.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new AnthropicError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e9) => e9.error).join("\n")} +${path7} +${underline}`); + } + return path7; + }; + path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +var Files; +var init_files = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs"() { + init_process_shim(); + init_resource(); + init_pagination(); + init_headers(); + init_stainless_helper_header(); + init_uploads(); + init_path(); + Files = class extends APIResource { + /** + * List Files + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fileMetadata of client.beta.files.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/files", Page, { + query, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + options?.headers + ]) + }); + } + /** + * Delete File + * + * @example + * ```ts + * const deletedFile = await client.beta.files.delete( + * 'file_id', + * ); + * ``` + */ + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path`/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + options?.headers + ]) + }); + } + /** + * Download File + * + * @example + * ```ts + * const response = await client.beta.files.download( + * 'file_id', + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` + */ + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path`/v1/files/${fileID}/content`, { + ...options, + headers: buildHeaders([ + { + "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString(), + Accept: "application/binary" + }, + options?.headers + ]), + __binaryResponse: true + }); + } + /** + * Get File Metadata + * + * @example + * ```ts + * const fileMetadata = + * await client.beta.files.retrieveMetadata('file_id'); + * ``` + */ + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path`/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + options?.headers + ]) + }); + } + /** + * Upload File + * + * @example + * ```ts + * const fileMetadata = await client.beta.files.upload({ + * file: fs.createReadStream('path/to/file'), + * }); + * ``` + */ + upload(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/files", multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "files-api-2025-04-14"].toString() }, + stainlessHelperHeaderFromFile(body.file), + options?.headers + ]) + }, this._client)); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs +var Models; +var init_models = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs"() { + init_process_shim(); + init_resource(); + init_pagination(); + init_headers(); + init_path(); + Models = class extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + * + * @example + * ```ts + * const betaModelInfo = await client.beta.models.retrieve( + * 'model_id', + * ); + * ``` + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path`/v1/models/${modelID}?beta=true`, { + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, + options?.headers + ]) + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaModelInfo of client.beta.models.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/models?beta=true", Page, { + query, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, + options?.headers + ]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/error.mjs +var init_error4 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/error.mjs"() { + init_process_shim(); + init_error3(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/constants.mjs +var MODEL_NONSTREAMING_TOKENS; +var init_constants = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/constants.mjs"() { + init_process_shim(); + MODEL_NONSTREAMING_TOKENS = { + "claude-opus-4-20250514": 8192, + "claude-opus-4-0": 8192, + "claude-4-opus-20250514": 8192, + "anthropic.claude-opus-4-20250514-v1:0": 8192, + "claude-opus-4@20250514": 8192, + "claude-opus-4-1-20250805": 8192, + "anthropic.claude-opus-4-1-20250805-v1:0": 8192, + "claude-opus-4-1@20250805": 8192 + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs +function getOutputFormat(params) { + return params?.output_format ?? params?.output_config?.format; +} +function maybeParseBetaMessage(message, params, opts) { + const outputFormat = getOutputFormat(params); + if (!params || !("parse" in (outputFormat ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === "text") { + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: null, + enumerable: false + }); + return Object.defineProperty(parsedBlock, "parsed", { + get() { + opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); + return null; + }, + enumerable: false + }); + } + return block; + }), + parsed_output: null + }; + } + return parseBetaMessage(message, params, opts); +} +function parseBetaMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === "text") { + const parsedOutput = parseBetaOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: parsedOutput, + enumerable: false + }); + return Object.defineProperty(parsedBlock, "parsed", { + get() { + opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."); + return parsedOutput; + }, + enumerable: false + }); + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput + }; +} +function parseBetaOutputFormat(params, content) { + const outputFormat = getOutputFormat(params); + if (outputFormat?.type !== "json_schema") { + return null; + } + try { + if ("parse" in outputFormat) { + return outputFormat.parse(content); + } + return JSON.parse(content); + } catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } +} +var init_beta_parser = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs"() { + init_process_shim(); + init_error3(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs +var tokenize, strip, unstrip, generate, partialParse; +var init_parser = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs"() { + init_process_shim(); + tokenize = (input) => { + let current2 = 0; + let tokens = []; + while (current2 < input.length) { + let char = input[current2]; + if (char === "\\") { + current2++; + continue; + } + if (char === "{") { + tokens.push({ + type: "brace", + value: "{" + }); + current2++; + continue; + } + if (char === "}") { + tokens.push({ + type: "brace", + value: "}" + }); + current2++; + continue; + } + if (char === "[") { + tokens.push({ + type: "paren", + value: "[" + }); + current2++; + continue; + } + if (char === "]") { + tokens.push({ + type: "paren", + value: "]" + }); + current2++; + continue; + } + if (char === ":") { + tokens.push({ + type: "separator", + value: ":" + }); + current2++; + continue; + } + if (char === ",") { + tokens.push({ + type: "delimiter", + value: "," + }); + current2++; + continue; + } + if (char === '"') { + let value = ""; + let danglingQuote = false; + char = input[++current2]; + while (char !== '"') { + if (current2 === input.length) { + danglingQuote = true; + break; + } + if (char === "\\") { + current2++; + if (current2 === input.length) { + danglingQuote = true; + break; + } + value += char + input[current2]; + char = input[++current2]; + } else { + value += char; + char = input[++current2]; + } + } + char = input[++current2]; + if (!danglingQuote) { + tokens.push({ + type: "string", + value + }); + } + continue; + } + let WHITESPACE = /\s/; + if (char && WHITESPACE.test(char)) { + current2++; + continue; + } + let NUMBERS = /[0-9]/; + if (char && NUMBERS.test(char) || char === "-" || char === ".") { + let value = ""; + if (char === "-") { + value += char; + char = input[++current2]; + } + while (char && NUMBERS.test(char) || char === ".") { + value += char; + char = input[++current2]; + } + tokens.push({ + type: "number", + value + }); + continue; + } + let LETTERS = /[a-z]/i; + if (char && LETTERS.test(char)) { + let value = ""; + while (char && LETTERS.test(char)) { + if (current2 === input.length) { + break; + } + value += char; + char = input[++current2]; + } + if (value == "true" || value == "false" || value === "null") { + tokens.push({ + type: "name", + value + }); + } else { + current2++; + continue; + } + continue; + } + current2++; + } + return tokens; + }; + strip = (tokens) => { + if (tokens.length === 0) { + return tokens; + } + let lastToken = tokens[tokens.length - 1]; + switch (lastToken.type) { + case "separator": + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + break; + case "number": + let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; + if (lastCharacterOfLastToken === "." || lastCharacterOfLastToken === "-") { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + case "string": + let tokenBeforeTheLastToken = tokens[tokens.length - 2]; + if (tokenBeforeTheLastToken?.type === "delimiter") { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } else if (tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{") { + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + } + break; + case "delimiter": + tokens = tokens.slice(0, tokens.length - 1); + return strip(tokens); + break; + } + return tokens; + }; + unstrip = (tokens) => { + let tail = []; + tokens.map((token) => { + if (token.type === "brace") { + if (token.value === "{") { + tail.push("}"); + } else { + tail.splice(tail.lastIndexOf("}"), 1); + } + } + if (token.type === "paren") { + if (token.value === "[") { + tail.push("]"); + } else { + tail.splice(tail.lastIndexOf("]"), 1); + } + } + }); + if (tail.length > 0) { + tail.reverse().map((item) => { + if (item === "}") { + tokens.push({ + type: "brace", + value: "}" + }); + } else if (item === "]") { + tokens.push({ + type: "paren", + value: "]" + }); + } + }); + } + return tokens; + }; + generate = (tokens) => { + let output = ""; + tokens.map((token) => { + switch (token.type) { + case "string": + output += '"' + token.value + '"'; + break; + default: + output += token.value; + break; + } + }); + return output; + }; + partialParse = (input) => JSON.parse(generate(unstrip(strip(tokenize(input))))); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/streaming.mjs +var init_streaming2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/streaming.mjs"() { + init_process_shim(); + init_streaming(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs +function tracksToolInput(content) { + return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use"; +} +function checkNever(x2) { +} +var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, JSON_BUF_PROPERTY, BetaMessageStream; +var init_BetaMessageStream = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs"() { + init_process_shim(); + init_tslib(); + init_parser(); + init_error4(); + init_errors(); + init_streaming2(); + init_beta_parser(); + JSON_BUF_PROPERTY = "__json_buf"; + BetaMessageStream = class _BetaMessageStream { + constructor(params, opts) { + _BetaMessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _BetaMessageStream_currentMessageSnapshot.set(this, void 0); + _BetaMessageStream_params.set(this, null); + this.controller = new AbortController(); + _BetaMessageStream_connectedPromise.set(this, void 0); + _BetaMessageStream_resolveConnectedPromise.set(this, () => { + }); + _BetaMessageStream_rejectConnectedPromise.set(this, () => { + }); + _BetaMessageStream_endPromise.set(this, void 0); + _BetaMessageStream_resolveEndPromise.set(this, () => { + }); + _BetaMessageStream_rejectEndPromise.set(this, () => { + }); + _BetaMessageStream_listeners.set(this, {}); + _BetaMessageStream_ended.set(this, false); + _BetaMessageStream_errored.set(this, false); + _BetaMessageStream_aborted.set(this, false); + _BetaMessageStream_catchingPromiseCreated.set(this, false); + _BetaMessageStream_response.set(this, void 0); + _BetaMessageStream_request_id.set(this, void 0); + _BetaMessageStream_logger.set(this, void 0); + _BetaMessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); + if (isAbortError(error)) { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + return this._emit("abort", error); + } + if (error instanceof AnthropicError) { + return this._emit("error", error); + } + if (error instanceof Error) { + const anthropicError = new AnthropicError(error.message); + anthropicError.cause = error; + return this._emit("error", anthropicError); + } + return this._emit("error", new AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve2, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve2, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { + }); + __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { + }); + __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + if (!response) { + throw new Error("Could not resolve a `Response` object"); + } + return { + data: this, + response, + request_id: response.headers.get("request-id") + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream2) { + const runner = new _BetaMessageStream(null); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + static createMessage(messages, params, options, { logger: logger2 } = {}) { + const runner = new _BetaMessageStream(params, { logger: logger2 }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit("message", message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse(); + this._connected(response); + for await (const event of stream2) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index2 = listeners.findIndex((l5) => l5.listener === listener); + if (index2 >= 0) + listeners.splice(index2, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + if (event !== "error") + this.once("error", reject); + this.once(event, resolve2); + }); + } + async done() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) + return; + if (event === "end") { + __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l5) => !l5.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + return; + } + if (event === "error") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit("finalMessage", __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream2 = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream2) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + [(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_params = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_logger = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + return this.receivedMessages.at(-1); + }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); + if (textBlocks.length === 0) { + throw new AnthropicError("stream ended without producing a content block with type=text"); + } + return textBlocks.join(" "); + }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f"); + }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + this._emit("streamEvent", event, messageSnapshot); + switch (event.type) { + case "content_block_delta": { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case "text_delta": { + if (content.type === "text") { + this._emit("text", event.delta.text, content.text || ""); + } + break; + } + case "citations_delta": { + if (content.type === "text") { + this._emit("citation", event.delta.citation, content.citations ?? []); + } + break; + } + case "input_json_delta": { + if (tracksToolInput(content) && content.input) { + this._emit("inputJson", event.delta.partial_json, content.input); + } + break; + } + case "thinking_delta": { + if (content.type === "thinking") { + this._emit("thinking", event.delta.thinking, content.thinking); + } + break; + } + case "signature_delta": { + if (content.type === "thinking") { + this._emit("signature", content.signature); + } + break; + } + case "compaction_delta": { + if (content.type === "compaction" && content.content) { + this._emit("compaction", content.content); + } + break; + } + default: + checkNever(event.delta); + } + break; + } + case "message_stop": { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); + break; + } + case "content_block_stop": { + this._emit("contentBlock", messageSnapshot.content.at(-1)); + break; + } + case "message_start": { + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case "content_block_start": + case "message_delta": + break; + } + }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() { + if (this.ended) { + throw new AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f"); + return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); + }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) { + let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (event.type === "message_start") { + if (snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case "message_stop": + return snapshot; + case "message_delta": + snapshot.container = event.delta.container; + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + snapshot.context_management = event.context_management; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + if (event.usage.iterations != null) { + snapshot.usage.iterations = event.usage.iterations; + } + return snapshot; + case "content_block_start": + snapshot.content.push(event.content_block); + return snapshot; + case "content_block_delta": { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case "text_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || "") + event.delta.text + }; + } + break; + } + case "citations_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...snapshotContent.citations ?? [], event.delta.citation] + }; + } + break; + } + case "input_json_delta": { + if (snapshotContent && tracksToolInput(snapshotContent)) { + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ""; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true + }); + if (jsonBuf) { + try { + newContent.input = partialParse(jsonBuf); + } catch (err) { + const error = new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); + } + } + snapshot.content[event.index] = newContent; + } + break; + } + case "thinking_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking + }; + } + break; + } + case "signature_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature + }; + } + break; + } + case "compaction_delta": { + if (snapshotContent?.type === "compaction") { + snapshot.content[event.index] = { + ...snapshotContent, + content: (snapshotContent.content || "") + event.delta.content + }; + } + break; + } + default: + checkNever(event.delta); + } + return snapshot; + } + case "content_block_stop": + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("streamEvent", (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } + }); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(void 0); + } + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: void 0, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: void 0, done: true }; + } + }; + } + toReadableStream() { + const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream2.toReadableStream(); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs +var ToolError; +var init_ToolError = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs"() { + init_process_shim(); + ToolError = class extends Error { + constructor(content) { + const message = typeof content === "string" ? content : content.map((block) => { + if (block.type === "text") + return block.text; + return `[${block.type}]`; + }).join(" "); + super(message); + this.name = "ToolError"; + this.content = content; + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs +var DEFAULT_TOKEN_THRESHOLD, DEFAULT_SUMMARY_PROMPT; +var init_CompactionControl = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs"() { + init_process_shim(); + DEFAULT_TOKEN_THRESHOLD = 1e5; + DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: +1. Task Overview +The user's core request and success criteria +Any clarifications or constraints they specified +2. Current State +What has been completed so far +Files created, modified, or analyzed (with paths if relevant) +Key outputs or artifacts produced +3. Important Discoveries +Technical constraints or requirements uncovered +Decisions made and their rationale +Errors encountered and how they were resolved +What approaches were tried that didn't work (and why) +4. Next Steps +Specific actions needed to complete the task +Any blockers or open questions to resolve +Priority order if multiple steps remain +5. Context to Preserve +User preferences or style requirements +Domain-specific details that aren't obvious +Any promises made to the user +Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. +Wrap your summary in tags.`; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs +function promiseWithResolvers() { + let resolve2; + let reject; + const promise = new Promise((res, rej) => { + resolve2 = res; + reject = rej; + }); + return { promise, resolve: resolve2, reject }; +} +async function generateToolResponse(params, lastMessage = params.messages.at(-1)) { + if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") { + return null; + } + const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use"); + if (toolUseBlocks.length === 0) { + return null; + } + const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { + const tool = params.tools.find((t6) => ("name" in t6 ? t6.name : t6.mcp_server_name) === toolUse.name); + if (!tool || !("run" in tool)) { + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: `Error: Tool '${toolUse.name}' not found`, + is_error: true + }; + } + try { + let input = toolUse.input; + if ("parse" in tool && tool.parse) { + input = tool.parse(input); + } + const result = await tool.run(input); + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: result + }; + } catch (error) { + return { + type: "tool_result", + tool_use_id: toolUse.id, + content: error instanceof ToolError ? error.content : `Error: ${error instanceof Error ? error.message : String(error)}`, + is_error: true + }; + } + })); + return { + role: "user", + content: toolResults + }; +} +var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse, BetaToolRunner; +var init_BetaToolRunner = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs"() { + init_process_shim(); + init_tslib(); + init_ToolError(); + init_error3(); + init_headers(); + init_CompactionControl(); + init_stainless_helper_header(); + BetaToolRunner = class { + constructor(client, params, options) { + _BetaToolRunner_instances.add(this); + this.client = client; + _BetaToolRunner_consumed.set(this, false); + _BetaToolRunner_mutated.set(this, false); + _BetaToolRunner_state.set(this, void 0); + _BetaToolRunner_options.set(this, void 0); + _BetaToolRunner_message.set(this, void 0); + _BetaToolRunner_toolResponse.set(this, void 0); + _BetaToolRunner_completion.set(this, void 0); + _BetaToolRunner_iterationCount.set(this, 0); + __classPrivateFieldSet(this, _BetaToolRunner_state, { + params: { + // You can't clone the entire params since there are functions as handlers. + // You also don't really need to clone params.messages, but it probably will prevent a foot gun + // somewhere. + ...params, + messages: structuredClone(params.messages) + } + }, "f"); + const helpers2 = collectStainlessHelpers(params.tools, params.messages); + const helperValue = ["BetaToolRunner", ...helpers2].join(", "); + __classPrivateFieldSet(this, _BetaToolRunner_options, { + ...options, + headers: buildHeaders([{ "x-stainless-helper": helperValue }, options?.headers]) + }, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + } + async *[(_BetaToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_mutated = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_state = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_options = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_message = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_toolResponse = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_completion = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_iterationCount = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_instances = /* @__PURE__ */ new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact2() { + const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; + if (!compactionControl || !compactionControl.enabled) { + return false; + } + let tokensUsed = 0; + if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== void 0) { + try { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + const totalInputTokens = message.usage.input_tokens + (message.usage.cache_creation_input_tokens ?? 0) + (message.usage.cache_read_input_tokens ?? 0); + tokensUsed = totalInputTokens + message.usage.output_tokens; + } catch { + return false; + } + } + const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD; + if (tokensUsed < threshold) { + return false; + } + const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; + const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT; + const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; + if (messages[messages.length - 1].role === "assistant") { + const lastMessage = messages[messages.length - 1]; + if (Array.isArray(lastMessage.content)) { + const nonToolBlocks = lastMessage.content.filter((block) => block.type !== "tool_use"); + if (nonToolBlocks.length === 0) { + messages.pop(); + } else { + lastMessage.content = nonToolBlocks; + } + } + } + const response = await this.client.beta.messages.create({ + model, + messages: [ + ...messages, + { + role: "user", + content: [ + { + type: "text", + text: summaryPrompt + } + ] + } + ], + max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens + }, { + headers: { "x-stainless-helper": "compaction" } + }); + if (response.content[0]?.type !== "text") { + throw new AnthropicError("Expected text response for compaction"); + } + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [ + { + role: "user", + content: response.content + } + ]; + return true; + }, Symbol.asyncIterator)]() { + var _a7; + if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + throw new AnthropicError("Cannot iterate over a consumed stream"); + } + __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); + try { + while (true) { + let stream2; + try { + if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { + break; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a7 = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a7++, _a7), "f"); + __classPrivateFieldSet(this, _BetaToolRunner_message, void 0, "f"); + const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + if (params.stream) { + stream2 = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); + __classPrivateFieldSet(this, _BetaToolRunner_message, stream2.finalMessage(), "f"); + __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => { + }); + yield stream2; + } else { + __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + } + const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this); + if (!isCompacted) { + if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); + } + const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); + if (toolMessage) { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); + } else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + break; + } + } + } finally { + if (stream2) { + stream2.abort(); + } + } + } + if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { + throw new AnthropicError("ToolRunner concluded without a message from the server"); + } + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); + } catch (error) { + __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { + }); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + throw error; + } + } + setMessagesParams(paramsOrMutator) { + if (typeof paramsOrMutator === "function") { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); + } else { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, void 0, "f"); + } + /** + * Get the tool response for the last message from the assistant. + * Avoids redundant tool executions by caching results. + * + * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed + * + * @example + * const toolResponse = await runner.generateToolResponse(); + * if (toolResponse) { + * console.log('Tool results:', toolResponse.content); + * } + */ + async generateToolResponse() { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1); + if (!message) { + return null; + } + return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message); + } + /** + * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and + * will wait for an instance to start and go to completion. + * + * @returns A promise that resolves to the final BetaMessage when the iterator completes + * + * @example + * // Start consuming the iterator + * for await (const message of runner) { + * console.log('Message:', message.content); + * } + * + * // Meanwhile, wait for completion from another part of the code + * const finalMessage = await runner.done(); + * console.log('Final response:', finalMessage.content); + */ + done() { + return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; + } + /** + * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: + * * If the iterator has not been consumed, consume the entire iterator and return the final message from the + * assistant. + * * If the iterator has been consumed, waits for it to complete and returns the final message. + * + * @returns A promise that resolves to the final BetaMessage from the conversation + * @throws {AnthropicError} If no messages were processed during the conversation + * + * @example + * const finalMessage = await runner.runUntilDone(); + * console.log('Final response:', finalMessage.content); + */ + async runUntilDone() { + if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + for await (const _3 of this) { + } + } + return this.done(); + } + /** + * Get the current parameters being used by the ToolRunner. + * + * @returns A readonly view of the current ToolRunnerParams + * + * @example + * const currentParams = runner.params; + * console.log('Current model:', currentParams.model); + * console.log('Message count:', currentParams.messages.length); + */ + get params() { + return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + } + /** + * Add one or more messages to the conversation history. + * + * @param messages - One or more BetaMessageParam objects to add to the conversation + * + * @example + * runner.pushMessages( + * { role: 'user', content: 'Also, what about the weather in NYC?' } + * ); + * + * @example + * // Adding multiple messages + * runner.pushMessages( + * { role: 'user', content: 'What about NYC?' }, + * { role: 'user', content: 'And Boston?' } + * ); + */ + pushMessages(...messages) { + this.setMessagesParams((params) => ({ + ...params, + messages: [...params.messages, ...messages] + })); + } + /** + * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() + * This allows using `await runner` instead of `await runner.runUntilDone()` + */ + then(onfulfilled, onrejected) { + return this.runUntilDone().then(onfulfilled, onrejected); + } + }; + _BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse2(lastMessage) { + if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== void 0) { + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + } + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f"); + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs +var JSONLDecoder; +var init_jsonl = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs"() { + init_process_shim(); + init_error3(); + init_shims(); + init_line(); + JSONLDecoder = class _JSONLDecoder { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + async *decoder() { + const lineDecoder = new LineDecoder(); + for await (const chunk of this.iterator) { + for (const line of lineDecoder.decode(chunk)) { + yield JSON.parse(line); + } + } + for (const line of lineDecoder.flush()) { + yield JSON.parse(line); + } + } + [Symbol.asyncIterator]() { + return this.decoder(); + } + static fromResponse(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { + throw new AnthropicError(`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 AnthropicError(`Attempted to iterate over a response with no body`); + } + return new _JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs +var Batches; +var init_batches = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs"() { + init_process_shim(); + init_resource(); + init_pagination(); + init_headers(); + init_jsonl(); + init_error4(); + init_path(); + Batches = class extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-opus-4-6', + * }, + * }, + * ], + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/messages/batches?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaMessageBatch of client.beta.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/messages/batches?beta=true", Page, { + query, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaDeletedMessageBatch = + * await client.beta.messages.batches.delete( + * 'message_batch_id', + * ); + * ``` + */ + delete(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path`/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() }, + options?.headers + ]) + }); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatchIndividualResponse = + * await client.beta.messages.batches.results( + * 'message_batch_id', + * ); + * ``` + */ + async results(messageBatchID, params = {}, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + const { betas } = params ?? {}; + return this._client.get(batch.results_url, { + ...options, + headers: buildHeaders([ + { + "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(), + Accept: "application/binary" + }, + options?.headers + ]), + stream: true, + __binaryResponse: true + })._thenUnwrap((_3, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs +function transformOutputFormat(params) { + if (!params.output_format) { + return params; + } + if (params.output_config?.format) { + throw new AnthropicError("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated)."); + } + const { output_format, ...rest } = params; + return { + ...rest, + output_config: { + ...params.output_config, + format: output_format + } + }; +} +var DEPRECATED_MODELS, MODELS_TO_WARN_WITH_THINKING_ENABLED, Messages; +var init_messages = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs"() { + init_process_shim(); + init_error4(); + init_resource(); + init_constants(); + init_headers(); + init_stainless_helper_header(); + init_beta_parser(); + init_BetaMessageStream(); + init_BetaToolRunner(); + init_ToolError(); + init_batches(); + init_batches(); + init_BetaToolRunner(); + init_ToolError(); + DEPRECATED_MODELS = { + "claude-1.3": "November 6th, 2024", + "claude-1.3-100k": "November 6th, 2024", + "claude-instant-1.1": "November 6th, 2024", + "claude-instant-1.1-100k": "November 6th, 2024", + "claude-instant-1.2": "November 6th, 2024", + "claude-3-sonnet-20240229": "July 21st, 2025", + "claude-3-opus-20240229": "January 5th, 2026", + "claude-2.1": "July 21st, 2025", + "claude-2.0": "July 21st, 2025", + "claude-3-7-sonnet-latest": "February 19th, 2026", + "claude-3-7-sonnet-20250219": "February 19th, 2026" + }; + MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-opus-4-6"]; + Messages = class extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches(this._client); + } + create(params, options) { + const modifiedParams = transformOutputFormat(params); + const { betas, ...body } = modifiedParams; + if (body.model in DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]} +Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED && body.thinking && body.thinking.type === "enabled") { + console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post("/v1/messages?beta=true", { + body, + timeout: timeout ?? 6e5, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, + helperHeader, + options?.headers + ]), + stream: modifiedParams.stream ?? false + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.beta.messages.parse({ + * model: 'claude-3-5-sonnet-20241022', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'), + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + options = { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() }, + options?.headers + ]) + }; + return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream + */ + stream(body, options) { + return BetaMessageStream.createMessage(this, body, options); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const betaMessageTokensCount = + * await client.beta.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-opus-4-6', + * }); + * ``` + */ + countTokens(params, options) { + const modifiedParams = transformOutputFormat(params); + const { betas, ...body } = modifiedParams; + return this._client.post("/v1/messages/count_tokens?beta=true", { + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString() }, + options?.headers + ]) + }); + } + toolRunner(body, options) { + return new BetaToolRunner(this._client, body, options); + } + }; + Messages.Batches = Batches; + Messages.BetaToolRunner = BetaToolRunner; + Messages.ToolError = ToolError; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs +var Versions; +var init_versions = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs"() { + init_process_shim(); + init_resource(); + init_pagination(); + init_headers(); + init_uploads(); + init_path(); + Versions = class extends APIResource { + /** + * Create Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.create( + * 'skill_id', + * ); + * ``` + */ + create(skillID, params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post(path`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }, this._client)); + } + /** + * Get Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.retrieve( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + retrieve(version6, params, options) { + const { skill_id, betas } = params; + return this._client.get(path`/v1/skills/${skill_id}/versions/${version6}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + /** + * List Skill Versions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const versionListResponse of client.beta.skills.versions.list( + * 'skill_id', + * )) { + * // ... + * } + * ``` + */ + list(skillID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path`/v1/skills/${skillID}/versions?beta=true`, PageCursor, { + query, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + /** + * Delete Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.delete( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + delete(version6, params, options) { + const { skill_id, betas } = params; + return this._client.delete(path`/v1/skills/${skill_id}/versions/${version6}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs +var Skills; +var init_skills = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs"() { + init_process_shim(); + init_resource(); + init_versions(); + init_versions(); + init_pagination(); + init_headers(); + init_uploads(); + init_path(); + Skills = class extends APIResource { + constructor() { + super(...arguments); + this.versions = new Versions(this._client); + } + /** + * Create Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.create(); + * ``` + */ + create(params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }, this._client, false)); + } + /** + * Get Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.retrieve('skill_id'); + * ``` + */ + retrieve(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path`/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + /** + * List Skills + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const skillListResponse of client.beta.skills.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/skills?beta=true", PageCursor, { + query, + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + /** + * Delete Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.delete('skill_id'); + * ``` + */ + delete(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path`/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { "anthropic-beta": [...betas ?? [], "skills-2025-10-02"].toString() }, + options?.headers + ]) + }); + } + }; + Skills.Versions = Versions; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs +var Beta; +var init_beta = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs"() { + init_process_shim(); + init_resource(); + init_files(); + init_files(); + init_models(); + init_models(); + init_messages(); + init_messages(); + init_skills(); + init_skills(); + Beta = class extends APIResource { + constructor() { + super(...arguments); + this.models = new Models(this._client); + this.messages = new Messages(this._client); + this.files = new Files(this._client); + this.skills = new Skills(this._client); + } + }; + Beta.Models = Models; + Beta.Messages = Messages; + Beta.Files = Files; + Beta.Skills = Skills; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/completions.mjs +var Completions; +var init_completions = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/completions.mjs"() { + init_process_shim(); + init_resource(); + init_headers(); + Completions = class extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post("/v1/complete", { + body, + timeout: this._client._options.timeout ?? 6e5, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, + options?.headers + ]), + stream: params.stream ?? false + }); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/parser.mjs +function getOutputFormat2(params) { + return params?.output_config?.format; +} +function maybeParseMessage(message, params, opts) { + const outputFormat = getOutputFormat2(params); + if (!params || !("parse" in (outputFormat ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === "text") { + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: null, + enumerable: false + }); + return parsedBlock; + } + return block; + }), + parsed_output: null + }; + } + return parseMessage(message, params, opts); +} +function parseMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === "text") { + const parsedOutput = parseOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", { + value: parsedOutput, + enumerable: false + }); + return parsedBlock; + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput + }; +} +function parseOutputFormat(params, content) { + const outputFormat = getOutputFormat2(params); + if (outputFormat?.type !== "json_schema") { + return null; + } + try { + if ("parse" in outputFormat) { + return outputFormat.parse(content); + } + return JSON.parse(content); + } catch (error) { + throw new AnthropicError(`Failed to parse structured output: ${error}`); + } +} +var init_parser2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/parser.mjs"() { + init_process_shim(); + init_error3(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs +function tracksToolInput2(content) { + return content.type === "tool_use" || content.type === "server_tool_use"; +} +function checkNever2(x2) { +} +var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, JSON_BUF_PROPERTY2, MessageStream; +var init_MessageStream = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs"() { + init_process_shim(); + init_tslib(); + init_errors(); + init_error4(); + init_streaming2(); + init_parser(); + init_parser2(); + JSON_BUF_PROPERTY2 = "__json_buf"; + MessageStream = class _MessageStream { + constructor(params, opts) { + _MessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _MessageStream_currentMessageSnapshot.set(this, void 0); + _MessageStream_params.set(this, null); + this.controller = new AbortController(); + _MessageStream_connectedPromise.set(this, void 0); + _MessageStream_resolveConnectedPromise.set(this, () => { + }); + _MessageStream_rejectConnectedPromise.set(this, () => { + }); + _MessageStream_endPromise.set(this, void 0); + _MessageStream_resolveEndPromise.set(this, () => { + }); + _MessageStream_rejectEndPromise.set(this, () => { + }); + _MessageStream_listeners.set(this, {}); + _MessageStream_ended.set(this, false); + _MessageStream_errored.set(this, false); + _MessageStream_aborted.set(this, false); + _MessageStream_catchingPromiseCreated.set(this, false); + _MessageStream_response.set(this, void 0); + _MessageStream_request_id.set(this, void 0); + _MessageStream_logger.set(this, void 0); + _MessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); + if (isAbortError(error)) { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); + return this._emit("abort", error); + } + if (error instanceof AnthropicError) { + return this._emit("error", error); + } + if (error instanceof Error) { + const anthropicError = new AnthropicError(error.message); + anthropicError.cause = error; + return this._emit("error", anthropicError); + } + return this._emit("error", new AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve2, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve2, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { + }); + __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { + }); + __classPrivateFieldSet(this, _MessageStream_params, params, "f"); + __classPrivateFieldSet(this, _MessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _MessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); + if (!response) { + throw new Error("Could not resolve a `Response` object"); + } + return { + data: this, + response, + request_id: response.headers.get("request-id") + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream2) { + const runner = new _MessageStream(null); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + static createMessage(messages, params, options, { logger: logger2 } = {}) { + const runner = new _MessageStream(params, { logger: logger2 }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit("message", message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream2 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse(); + this._connected(response); + for await (const event of stream2) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_response, response, "f"); + __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get("request-id"), "f"); + __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet(this, _MessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _MessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index2 = listeners.findIndex((l5) => l5.listener === listener); + if (index2 >= 0) + listeners.splice(index2, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve2, reject) => { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + if (event !== "error") + this.once("error", reject); + this.once(event, resolve2); + }); + } + async done() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) + return; + if (event === "end") { + __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l5) => !l5.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + return; + } + if (event === "error") { + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit("finalMessage", __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener("abort", abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream2 = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream2) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } finally { + if (signal && abortHandler) { + signal.removeEventListener("abort", abortHandler); + } + } + } + [(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_params = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_logger = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + return this.receivedMessages.at(-1); + }, _MessageStream_getFinalText = function _MessageStream_getFinalText2() { + if (this.receivedMessages.length === 0) { + throw new AnthropicError("stream ended without producing a Message with role=assistant"); + } + const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text); + if (textBlocks.length === 0) { + throw new AnthropicError("stream ended without producing a content block with type=text"); + } + return textBlocks.join(" "); + }, _MessageStream_beginRequest = function _MessageStream_beginRequest2() { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f"); + }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); + this._emit("streamEvent", event, messageSnapshot); + switch (event.type) { + case "content_block_delta": { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case "text_delta": { + if (content.type === "text") { + this._emit("text", event.delta.text, content.text || ""); + } + break; + } + case "citations_delta": { + if (content.type === "text") { + this._emit("citation", event.delta.citation, content.citations ?? []); + } + break; + } + case "input_json_delta": { + if (tracksToolInput2(content) && content.input) { + this._emit("inputJson", event.delta.partial_json, content.input); + } + break; + } + case "thinking_delta": { + if (content.type === "thinking") { + this._emit("thinking", event.delta.thinking, content.thinking); + } + break; + } + case "signature_delta": { + if (content.type === "thinking") { + this._emit("signature", content.signature); + } + break; + } + default: + checkNever2(event.delta); + } + break; + } + case "message_stop": { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }), true); + break; + } + case "content_block_stop": { + this._emit("contentBlock", messageSnapshot.content.at(-1)); + break; + } + case "message_start": { + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case "content_block_start": + case "message_delta": + break; + } + }, _MessageStream_endRequest = function _MessageStream_endRequest2() { + if (this.ended) { + throw new AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, void 0, "f"); + return maybeParseMessage(snapshot, __classPrivateFieldGet(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _MessageStream_logger, "f") }); + }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) { + let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (event.type === "message_start") { + if (snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case "message_stop": + return snapshot; + case "message_delta": + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + return snapshot; + case "content_block_start": + snapshot.content.push({ ...event.content_block }); + return snapshot; + case "content_block_delta": { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case "text_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || "") + event.delta.text + }; + } + break; + } + case "citations_delta": { + if (snapshotContent?.type === "text") { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...snapshotContent.citations ?? [], event.delta.citation] + }; + } + break; + } + case "input_json_delta": { + if (snapshotContent && tracksToolInput2(snapshotContent)) { + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY2] || ""; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY2, { + value: jsonBuf, + enumerable: false, + writable: true + }); + if (jsonBuf) { + newContent.input = partialParse(jsonBuf); + } + snapshot.content[event.index] = newContent; + } + break; + } + case "thinking_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking + }; + } + break; + } + case "signature_delta": { + if (snapshotContent?.type === "thinking") { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature + }; + } + break; + } + default: + checkNever2(event.delta); + } + return snapshot; + } + case "content_block_stop": + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("streamEvent", (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } + }); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(void 0); + } + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: void 0, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: void 0, done: true }; + } + }; + } + toReadableStream() { + const stream2 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream2.toReadableStream(); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs +var Batches2; +var init_batches2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs"() { + init_process_shim(); + init_resource(); + init_pagination(); + init_headers(); + init_jsonl(); + init_error4(); + init_path(); + Batches2 = class extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-opus-4-6', + * }, + * }, + * ], + * }); + * ``` + */ + create(body, options) { + return this._client.post("/v1/messages/batches", { body, ...options }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, options) { + return this._client.get(path`/v1/messages/batches/${messageBatchID}`, options); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const messageBatch of client.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/v1/messages/batches", Page, { query, ...options }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const deletedMessageBatch = + * await client.messages.batches.delete('message_batch_id'); + * ``` + */ + delete(messageBatchID, options) { + return this._client.delete(path`/v1/messages/batches/${messageBatchID}`, options); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, options) { + return this._client.post(path`/v1/messages/batches/${messageBatchID}/cancel`, options); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatchIndividualResponse = + * await client.messages.batches.results('message_batch_id'); + * ``` + */ + async results(messageBatchID, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + return this._client.get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]), + stream: true, + __binaryResponse: true + })._thenUnwrap((_3, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +var Messages2, DEPRECATED_MODELS2, MODELS_TO_WARN_WITH_THINKING_ENABLED2; +var init_messages2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs"() { + init_process_shim(); + init_resource(); + init_headers(); + init_stainless_helper_header(); + init_MessageStream(); + init_parser2(); + init_batches2(); + init_batches2(); + init_constants(); + Messages2 = class extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches2(this._client); + } + create(body, options) { + if (body.model in DEPRECATED_MODELS2) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]} +Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + if (body.model in MODELS_TO_WARN_WITH_THINKING_ENABLED2 && body.thinking && body.thinking.type === "enabled") { + console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + const helperHeader = stainlessHelperHeader(body.tools, body.messages); + return this._client.post("/v1/messages", { + body, + timeout: timeout ?? 6e5, + ...options, + headers: buildHeaders([helperHeader, options?.headers]), + stream: body.stream ?? false + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.messages.parse({ + * model: 'claude-sonnet-4-5-20250929', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_config: { + * format: zodOutputFormat(z.object({ answer: z.number() })), + * }, + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream. + * + * If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`), + * the final message will include a `parsed_output` property with the parsed content. + * + * @example + * ```ts + * const stream = client.messages.stream({ + * model: 'claude-sonnet-4-5-20250929', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_config: { + * format: zodOutputFormat(z.object({ answer: z.number() })), + * }, + * }); + * + * const message = await stream.finalMessage(); + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + stream(body, options) { + return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console }); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const messageTokensCount = + * await client.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-opus-4-6', + * }); + * ``` + */ + countTokens(body, options) { + return this._client.post("/v1/messages/count_tokens", { body, ...options }); + } + }; + DEPRECATED_MODELS2 = { + "claude-1.3": "November 6th, 2024", + "claude-1.3-100k": "November 6th, 2024", + "claude-instant-1.1": "November 6th, 2024", + "claude-instant-1.1-100k": "November 6th, 2024", + "claude-instant-1.2": "November 6th, 2024", + "claude-3-sonnet-20240229": "July 21st, 2025", + "claude-3-opus-20240229": "January 5th, 2026", + "claude-2.1": "July 21st, 2025", + "claude-2.0": "July 21st, 2025", + "claude-3-7-sonnet-latest": "February 19th, 2026", + "claude-3-7-sonnet-20250219": "February 19th, 2026", + "claude-3-5-haiku-latest": "February 19th, 2026", + "claude-3-5-haiku-20241022": "February 19th, 2026" + }; + MODELS_TO_WARN_WITH_THINKING_ENABLED2 = ["claude-opus-4-6"]; + Messages2.Batches = Batches2; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/models.mjs +var Models2; +var init_models2 = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/models.mjs"() { + init_process_shim(); + init_resource(); + init_pagination(); + init_headers(); + init_path(); + Models2 = class extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path`/v1/models/${modelID}`, { + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, + options?.headers + ]) + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList("/v1/models", Page, { + query, + ...options, + headers: buildHeaders([ + { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 }, + options?.headers + ]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/resources/index.mjs +var init_resources = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/resources/index.mjs"() { + init_process_shim(); + init_shared(); + init_beta(); + init_completions(); + init_messages2(); + init_models2(); + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs +var readEnv; +var init_env = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"() { + init_process_shim(); + readEnv = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; + }; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/client.mjs +var _BaseAnthropic_instances, _a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden, HUMAN_PROMPT, AI_PROMPT, BaseAnthropic, Anthropic; +var init_client = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/client.mjs"() { + init_process_shim(); + init_tslib(); + init_uuid(); + init_values(); + init_sleep(); + init_errors(); + init_detect_platform(); + init_shims(); + init_request_options(); + init_version(); + init_error3(); + init_pagination(); + init_uploads2(); + init_resources(); + init_api_promise(); + init_completions(); + init_models2(); + init_beta(); + init_messages2(); + init_detect_platform(); + init_headers(); + init_env(); + init_log(); + init_values(); + HUMAN_PROMPT = "\\n\\nHuman:"; + AI_PROMPT = "\\n\\nAssistant:"; + BaseAnthropic = class { + /** + * API Client for interfacing with the Anthropic API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] + * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv("ANTHROPIC_BASE_URL"), apiKey = readEnv("ANTHROPIC_API_KEY") ?? null, authToken = readEnv("ANTHROPIC_AUTH_TOKEN") ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); + _BaseAnthropic_encoder.set(this, void 0); + const options = { + apiKey, + authToken, + ...opts, + baseURL: baseURL || `https://api.anthropic.com` + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = typeof apiKey === "string" ? apiKey : null; + this.authToken = authToken; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + authToken: this.authToken, + ...options + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values: values2, nulls }) { + if (values2.get("x-api-key") || values2.get("authorization")) { + return; + } + if (this.apiKey && values2.get("x-api-key")) { + return; + } + if (nulls.has("x-api-key")) { + return; + } + if (this.authToken && values2.get("authorization")) { + return; + } + if (nulls.has("authorization")) { + return; + } + throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); + } + async apiKeyAuth(opts) { + if (this.apiKey == null) { + return void 0; + } + return buildHeaders([{ "X-Api-Key": this.apiKey }]); + } + async bearerAuth(opts) { + if (this.authToken == null) { + return void 0; + } + return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + } + /** + * Basic re-implementation of `qs.stringify` for primitive types. + */ + stringifyQuery(query) { + return Object.entries(query).filter(([_3, value]) => typeof value !== "undefined").map(([key, value]) => { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new AnthropicError(`Cannot stringify type ${typeof value}; 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("&"); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path6, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + _calculateNonstreamingTimeout(maxTokens) { + const defaultTimeout = 10 * 60; + const expectedTimeout = 60 * 60 * maxTokens / 128e3; + if (expectedTimeout > defaultTimeout) { + throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details"); + } + return defaultTimeout * 1e3; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path6, opts) { + return this.methodRequest("get", path6, opts); + } + post(path6, opts) { + return this.methodRequest("post", path6, opts); + } + patch(path6, opts) { + return this.methodRequest("patch", path6, opts); + } + put(path6, opts) { + return this.methodRequest("put", path6, opts); + } + delete(path6, opts) { + return this.methodRequest("delete", path6, opts); + } + methodRequest(method, path6, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path6, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join(""); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError(err2).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path6, Page3, opts) { + return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path6, ...opts2 })) : { method: "get", path: path6, ...opts }); + } + requestAPIList(Page3, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise(this, request, Page3); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 60 * 60 * 1e3; + const defaultTime = 60 * 10 * 1e3; + const expectedTime = maxTime * maxTokens / 128e3; + if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) { + throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details"); + } + return defaultTime; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path6, query, defaultBaseURL } = options; + const url = this.buildURL(path6, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders(), + ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0, + "anthropic-version": "2023-06-01" + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom(body) }; + } else { + return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); + } + } + }; + _a = BaseAnthropic, _BaseAnthropic_encoder = /* @__PURE__ */ new WeakMap(), _BaseAnthropic_instances = /* @__PURE__ */ new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden2() { + return this.baseURL !== "https://api.anthropic.com"; + }; + BaseAnthropic.Anthropic = _a; + BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; + BaseAnthropic.AI_PROMPT = AI_PROMPT; + BaseAnthropic.DEFAULT_TIMEOUT = 6e5; + BaseAnthropic.AnthropicError = AnthropicError; + BaseAnthropic.APIError = APIError; + BaseAnthropic.APIConnectionError = APIConnectionError; + BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; + BaseAnthropic.APIUserAbortError = APIUserAbortError; + BaseAnthropic.NotFoundError = NotFoundError; + BaseAnthropic.ConflictError = ConflictError; + BaseAnthropic.RateLimitError = RateLimitError; + BaseAnthropic.BadRequestError = BadRequestError; + BaseAnthropic.AuthenticationError = AuthenticationError; + BaseAnthropic.InternalServerError = InternalServerError; + BaseAnthropic.PermissionDeniedError = PermissionDeniedError; + BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; + BaseAnthropic.toFile = toFile; + Anthropic = class extends BaseAnthropic { + constructor() { + super(...arguments); + this.completions = new Completions(this); + this.messages = new Messages2(this); + this.models = new Models2(this); + this.beta = new Beta(this); + } + }; + Anthropic.Completions = Completions; + Anthropic.Messages = Messages2; + Anthropic.Models = Models2; + Anthropic.Beta = Beta; + } +}); + +// ../pi-mono/node_modules/@anthropic-ai/sdk/index.mjs +var init_sdk = __esm({ + "../pi-mono/node_modules/@anthropic-ai/sdk/index.mjs"() { + init_process_shim(); + init_client(); + init_uploads2(); + init_api_promise(); + init_client(); + init_pagination(); + init_error3(); + } +}); + +// ../pi-mono/node_modules/partial-json/dist/options.js +var require_options = __commonJS({ + "../pi-mono/node_modules/partial-json/dist/options.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Allow = exports.ALL = exports.COLLECTION = exports.ATOM = exports.SPECIAL = exports.INF = exports._INFINITY = exports.INFINITY = exports.NAN = exports.BOOL = exports.NULL = exports.OBJ = exports.ARR = exports.NUM = exports.STR = void 0; + exports.STR = 1; + exports.NUM = 2; + exports.ARR = 4; + exports.OBJ = 8; + exports.NULL = 16; + exports.BOOL = 32; + exports.NAN = 64; + exports.INFINITY = 128; + exports._INFINITY = 256; + exports.INF = exports.INFINITY | exports._INFINITY; + exports.SPECIAL = exports.NULL | exports.BOOL | exports.INF | exports.NAN; + exports.ATOM = exports.STR | exports.NUM | exports.SPECIAL; + exports.COLLECTION = exports.ARR | exports.OBJ; + exports.ALL = exports.ATOM | exports.COLLECTION; + exports.Allow = { STR: exports.STR, NUM: exports.NUM, ARR: exports.ARR, OBJ: exports.OBJ, NULL: exports.NULL, BOOL: exports.BOOL, NAN: exports.NAN, INFINITY: exports.INFINITY, _INFINITY: exports._INFINITY, INF: exports.INF, SPECIAL: exports.SPECIAL, ATOM: exports.ATOM, COLLECTION: exports.COLLECTION, ALL: exports.ALL }; + exports.default = exports.Allow; + } +}); + +// ../pi-mono/node_modules/partial-json/dist/index.js +var require_dist = __commonJS({ + "../pi-mono/node_modules/partial-json/dist/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Allow = exports.MalformedJSON = exports.PartialJSON = exports.parseJSON = exports.parse = void 0; + var options_1 = require_options(); + Object.defineProperty(exports, "Allow", { enumerable: true, get: function() { + return options_1.Allow; + } }); + __exportStar(require_options(), exports); + var PartialJSON2 = class extends Error { + }; + exports.PartialJSON = PartialJSON2; + var MalformedJSON2 = class extends Error { + }; + exports.MalformedJSON = MalformedJSON2; + function parseJSON3(jsonString, allowPartial = options_1.Allow.ALL) { + if (typeof jsonString !== "string") { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON2(jsonString.trim(), allowPartial); + } + exports.parseJSON = parseJSON3; + var _parseJSON2 = (jsonString, allow) => { + const length = jsonString.length; + let index2 = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON2(`${msg} at position ${index2}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON2(`${msg} at position ${index2}`); + }; + const parseAny = () => { + skipBlank(); + if (index2 >= length) + markPartialJSON("Unexpected end of input"); + if (jsonString[index2] === '"') + return parseStr(); + if (jsonString[index2] === "{") + return parseObj(); + if (jsonString[index2] === "[") + return parseArr(); + if (jsonString.substring(index2, index2 + 4) === "null" || options_1.Allow.NULL & allow && length - index2 < 4 && "null".startsWith(jsonString.substring(index2))) { + index2 += 4; + return null; + } + if (jsonString.substring(index2, index2 + 4) === "true" || options_1.Allow.BOOL & allow && length - index2 < 4 && "true".startsWith(jsonString.substring(index2))) { + index2 += 4; + return true; + } + if (jsonString.substring(index2, index2 + 5) === "false" || options_1.Allow.BOOL & allow && length - index2 < 5 && "false".startsWith(jsonString.substring(index2))) { + index2 += 5; + return false; + } + if (jsonString.substring(index2, index2 + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index2 < 8 && "Infinity".startsWith(jsonString.substring(index2))) { + index2 += 8; + return Infinity; + } + if (jsonString.substring(index2, index2 + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index2 && length - index2 < 9 && "-Infinity".startsWith(jsonString.substring(index2))) { + index2 += 9; + return -Infinity; + } + if (jsonString.substring(index2, index2 + 3) === "NaN" || options_1.Allow.NAN & allow && length - index2 < 3 && "NaN".startsWith(jsonString.substring(index2))) { + index2 += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index2; + let escape4 = false; + index2++; + while (index2 < length && (jsonString[index2] !== '"' || escape4 && jsonString[index2 - 1] === "\\")) { + escape4 = jsonString[index2] === "\\" ? !escape4 : false; + index2++; + } + if (jsonString.charAt(index2) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index2 - Number(escape4))); + } catch (e9) { + throwMalformedError(String(e9)); + } + } else if (options_1.Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index2 - Number(escape4)) + '"'); + } catch (e9) { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"'); + } + } + markPartialJSON("Unterminated string literal"); + }; + const parseObj = () => { + index2++; + skipBlank(); + const obj = {}; + try { + while (jsonString[index2] !== "}") { + skipBlank(); + if (index2 >= length && options_1.Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index2++; + try { + const value = parseAny(); + obj[key] = value; + } catch (e9) { + if (options_1.Allow.OBJ & allow) + return obj; + else + throw e9; + } + skipBlank(); + if (jsonString[index2] === ",") + index2++; + } + } catch (e9) { + if (options_1.Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index2++; + return obj; + }; + const parseArr = () => { + index2++; + const arr = []; + try { + while (jsonString[index2] !== "]") { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index2] === ",") { + index2++; + } + } + } catch (e9) { + if (options_1.Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index2++; + return arr; + }; + const parseNum = () => { + if (index2 === 0) { + if (jsonString === "-") + throwMalformedError("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } catch (e9) { + if (options_1.Allow.NUM & allow) + try { + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e"))); + } catch (e10) { + } + throwMalformedError(String(e9)); + } + } + const start = index2; + if (jsonString[index2] === "-") + index2++; + while (jsonString[index2] && ",]}".indexOf(jsonString[index2]) === -1) + index2++; + if (index2 == length && !(options_1.Allow.NUM & allow)) + markPartialJSON("Unterminated number literal"); + try { + return JSON.parse(jsonString.substring(start, index2)); + } catch (e9) { + if (jsonString.substring(start, index2) === "-") + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e"))); + } catch (e10) { + throwMalformedError(String(e10)); + } + } + }; + const skipBlank = () => { + while (index2 < length && " \n\r ".includes(jsonString[index2])) { + index2++; + } + }; + return parseAny(); + }; + var parse3 = parseJSON3; + exports.parse = parse3; + } +}); + +// ../pi-mono/node_modules/openai/internal/tslib.mjs +function __classPrivateFieldSet2(receiver, state, value, kind, f4) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldGet2(receiver, state, kind, f4) { + if (kind === "a" && !f4) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); +} +var init_tslib2 = __esm({ + "../pi-mono/node_modules/openai/internal/tslib.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/uuid.mjs +var uuid42; +var init_uuid2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/uuid.mjs"() { + init_process_shim(); + uuid42 = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2?.randomUUID) { + uuid42 = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c6) => (+c6 ^ randomByte() & 15 >> +c6 / 4).toString(16)); + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/errors.mjs +function isAbortError2(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +var castToError2; +var init_errors2 = __esm({ + "../pi-mono/node_modules/openai/internal/errors.mjs"() { + init_process_shim(); + castToError2 = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch { + } + try { + return new Error(JSON.stringify(err)); + } catch { + } + } + return new Error(err); + }; + } +}); + +// ../pi-mono/node_modules/openai/core/error.mjs +var OpenAIError, APIError2, APIUserAbortError2, APIConnectionError2, APIConnectionTimeoutError2, BadRequestError2, AuthenticationError2, PermissionDeniedError2, NotFoundError2, ConflictError2, UnprocessableEntityError2, RateLimitError2, InternalServerError2, LengthFinishReasonError, ContentFilterFinishReasonError, InvalidWebhookSignatureError; +var init_error5 = __esm({ + "../pi-mono/node_modules/openai/core/error.mjs"() { + init_process_shim(); + init_errors2(); + OpenAIError = class extends Error { + }; + APIError2 = class _APIError extends OpenAIError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get("x-request-id"); + this.error = error; + const data = error; + this.code = data?.["code"]; + this.param = data?.["param"]; + this.type = data?.["type"]; + } + static makeMessage(status, error, message) { + const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError2({ message, cause: castToError2(errorResponse) }); + } + const error = errorResponse?.["error"]; + if (status === 400) { + return new BadRequestError2(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError2(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError2(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError2(status, error, message, headers); + } + if (status === 409) { + return new ConflictError2(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError2(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError2(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError2(status, error, message, headers); + } + return new _APIError(status, error, message, headers); + } + }; + APIUserAbortError2 = class extends APIError2 { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } + }; + APIConnectionError2 = class extends APIError2 { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } + }; + APIConnectionTimeoutError2 = class extends APIConnectionError2 { + constructor({ message } = {}) { + super({ message: message ?? "Request timed out." }); + } + }; + BadRequestError2 = class extends APIError2 { + }; + AuthenticationError2 = class extends APIError2 { + }; + PermissionDeniedError2 = class extends APIError2 { + }; + NotFoundError2 = class extends APIError2 { + }; + ConflictError2 = class extends APIError2 { + }; + UnprocessableEntityError2 = class extends APIError2 { + }; + RateLimitError2 = class extends APIError2 { + }; + InternalServerError2 = class extends APIError2 { + }; + LengthFinishReasonError = class extends OpenAIError { + constructor() { + super(`Could not parse response content as the length limit was reached`); + } + }; + ContentFilterFinishReasonError = class extends OpenAIError { + constructor() { + super(`Could not parse response content as the request was rejected by the content filter`); + } + }; + InvalidWebhookSignatureError = class extends Error { + constructor(message) { + super(message); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/values.mjs +function maybeObj2(x2) { + if (typeof x2 !== "object") { + return {}; + } + return x2 ?? {}; +} +function isEmptyObj2(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn2(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function isObj(obj) { + return obj != null && typeof obj === "object" && !Array.isArray(obj); +} +var startsWithSchemeRegexp2, isAbsoluteURL2, isArray2, isReadonlyArray2, validatePositiveInteger2, safeJSON2; +var init_values2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/values.mjs"() { + init_process_shim(); + init_error5(); + startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i; + isAbsoluteURL2 = (url) => { + return startsWithSchemeRegexp2.test(url); + }; + isArray2 = (val2) => (isArray2 = Array.isArray, isArray2(val2)); + isReadonlyArray2 = isArray2; + validatePositiveInteger2 = (name, n7) => { + if (typeof n7 !== "number" || !Number.isInteger(n7)) { + throw new OpenAIError(`${name} must be an integer`); + } + if (n7 < 0) { + throw new OpenAIError(`${name} must be a positive integer`); + } + return n7; + }; + safeJSON2 = (text3) => { + try { + return JSON.parse(text3); + } catch (err) { + return void 0; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/sleep.mjs +var sleep2; +var init_sleep2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/sleep.mjs"() { + init_process_shim(); + sleep2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); + } +}); + +// ../pi-mono/node_modules/openai/version.mjs +var VERSION2; +var init_version2 = __esm({ + "../pi-mono/node_modules/openai/version.mjs"() { + init_process_shim(); + VERSION2 = "6.26.0"; + } +}); + +// ../pi-mono/node_modules/openai/internal/detect-platform.mjs +function getDetectedPlatform2() { + if (typeof Deno !== "undefined" && Deno.build != null) { + return "deno"; + } + if (typeof EdgeRuntime !== "undefined") { + return "edge"; + } + if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") { + return "node"; + } + return "unknown"; +} +function getBrowserInfo2() { + if (typeof navigator === "undefined" || !navigator) { + return null; + } + const browserPatterns = [ + { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } + ]; + for (const { key, pattern } of browserPatterns) { + const match2 = pattern.exec(navigator.userAgent); + if (match2) { + const major = match2[1] || 0; + const minor = match2[2] || 0; + const patch = match2[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +var isRunningInBrowser2, getPlatformProperties2, normalizeArch2, normalizePlatform2, _platformHeaders2, getPlatformHeaders2; +var init_detect_platform2 = __esm({ + "../pi-mono/node_modules/openai/internal/detect-platform.mjs"() { + init_process_shim(); + init_version2(); + isRunningInBrowser2 = () => { + return ( + // @ts-ignore + typeof window !== "undefined" && // @ts-ignore + typeof window.document !== "undefined" && // @ts-ignore + typeof navigator !== "undefined" + ); + }; + getPlatformProperties2 = () => { + const detectedPlatform = getDetectedPlatform2(); + if (detectedPlatform === "deno") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": normalizePlatform2(Deno.build.os), + "X-Stainless-Arch": normalizeArch2(Deno.build.arch), + "X-Stainless-Runtime": "deno", + "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown" + }; + } + if (typeof EdgeRuntime !== "undefined") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": `other:${EdgeRuntime}`, + "X-Stainless-Runtime": "edge", + "X-Stainless-Runtime-Version": globalThis.process.version + }; + } + if (detectedPlatform === "node") { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"), + "X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"), + "X-Stainless-Runtime": "node", + "X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown" + }; + } + const browserInfo = getBrowserInfo2(); + if (browserInfo) { + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": `browser:${browserInfo.browser}`, + "X-Stainless-Runtime-Version": browserInfo.version + }; + } + return { + "X-Stainless-Lang": "js", + "X-Stainless-Package-Version": VERSION2, + "X-Stainless-OS": "Unknown", + "X-Stainless-Arch": "unknown", + "X-Stainless-Runtime": "unknown", + "X-Stainless-Runtime-Version": "unknown" + }; + }; + normalizeArch2 = (arch) => { + if (arch === "x32") + return "x32"; + if (arch === "x86_64" || arch === "x64") + return "x64"; + if (arch === "arm") + return "arm"; + if (arch === "aarch64" || arch === "arm64") + return "arm64"; + if (arch) + return `other:${arch}`; + return "unknown"; + }; + normalizePlatform2 = (platform) => { + platform = platform.toLowerCase(); + if (platform.includes("ios")) + return "iOS"; + if (platform === "android") + return "Android"; + if (platform === "darwin") + return "MacOS"; + if (platform === "win32") + return "Windows"; + if (platform === "freebsd") + return "FreeBSD"; + if (platform === "openbsd") + return "OpenBSD"; + if (platform === "linux") + return "Linux"; + if (platform) + return `Other:${platform}`; + return "Unknown"; + }; + getPlatformHeaders2 = () => { + return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2()); + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/shims.mjs +function getDefaultFetch2() { + if (typeof fetch !== "undefined") { + return fetch; + } + throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`"); +} +function makeReadableStream2(...args) { + const ReadableStream2 = globalThis.ReadableStream; + if (typeof ReadableStream2 === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream2(...args); +} +function ReadableStreamFrom2(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream2({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + } + }); +} +function ReadableStreamToAsyncIterable2(stream2) { + if (stream2[Symbol.asyncIterator]) + return stream2; + const reader = stream2.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); + return result; + } catch (e9) { + reader.releaseLock(); + throw e9; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: void 0 }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +async function CancelReadableStream2(stream2) { + if (stream2 === null || typeof stream2 !== "object") + return; + if (stream2[Symbol.asyncIterator]) { + await stream2[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream2.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +var init_shims2 = __esm({ + "../pi-mono/node_modules/openai/internal/shims.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/openai/internal/request-options.mjs +var FallbackEncoder2; +var init_request_options2 = __esm({ + "../pi-mono/node_modules/openai/internal/request-options.mjs"() { + init_process_shim(); + FallbackEncoder2 = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/qs/formats.mjs +var default_format, default_formatter, formatters, RFC1738; +var init_formats = __esm({ + "../pi-mono/node_modules/openai/internal/qs/formats.mjs"() { + init_process_shim(); + default_format = "RFC3986"; + default_formatter = (v4) => String(v4); + formatters = { + RFC1738: (v4) => String(v4).replace(/%20/g, "+"), + RFC3986: default_formatter + }; + RFC1738 = "RFC1738"; + } +}); + +// ../pi-mono/node_modules/openai/internal/qs/utils.mjs +function is_buffer(obj) { + if (!obj || typeof obj !== "object") { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function maybe_map(val2, fn) { + if (isArray2(val2)) { + const mapped = []; + for (let i7 = 0; i7 < val2.length; i7 += 1) { + mapped.push(fn(val2[i7])); + } + return mapped; + } + return fn(val2); +} +var has, hex_table, limit, encode; +var init_utils = __esm({ + "../pi-mono/node_modules/openai/internal/qs/utils.mjs"() { + init_process_shim(); + init_formats(); + init_values2(); + has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)); + hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i7 = 0; i7 < 256; ++i7) { + array.push("%" + ((i7 < 16 ? "0" : "") + i7.toString(16)).toUpperCase()); + } + return array; + })(); + limit = 1024; + encode = (str2, _defaultEncoder, charset, _kind, format2) => { + if (str2.length === 0) { + return str2; + } + let string = str2; + if (typeof str2 === "symbol") { + string = Symbol.prototype.toString.call(str2); + } else if (typeof str2 !== "string") { + string = String(str2); + } + if (charset === "iso-8859-1") { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function($0) { + return "%26%23" + parseInt($0.slice(2), 16) + "%3B"; + }); + } + let out = ""; + for (let j3 = 0; j3 < string.length; j3 += limit) { + const segment = string.length >= limit ? string.slice(j3, j3 + limit) : string; + const arr = []; + for (let i7 = 0; i7 < segment.length; ++i7) { + let c6 = segment.charCodeAt(i7); + if (c6 === 45 || // - + c6 === 46 || // . + c6 === 95 || // _ + c6 === 126 || // ~ + c6 >= 48 && c6 <= 57 || // 0-9 + c6 >= 65 && c6 <= 90 || // a-z + c6 >= 97 && c6 <= 122 || // A-Z + format2 === RFC1738 && (c6 === 40 || c6 === 41)) { + arr[arr.length] = segment.charAt(i7); + continue; + } + if (c6 < 128) { + arr[arr.length] = hex_table[c6]; + continue; + } + if (c6 < 2048) { + arr[arr.length] = hex_table[192 | c6 >> 6] + hex_table[128 | c6 & 63]; + continue; + } + if (c6 < 55296 || c6 >= 57344) { + arr[arr.length] = hex_table[224 | c6 >> 12] + hex_table[128 | c6 >> 6 & 63] + hex_table[128 | c6 & 63]; + continue; + } + i7 += 1; + c6 = 65536 + ((c6 & 1023) << 10 | segment.charCodeAt(i7) & 1023); + arr[arr.length] = hex_table[240 | c6 >> 18] + hex_table[128 | c6 >> 12 & 63] + hex_table[128 | c6 >> 6 & 63] + hex_table[128 | c6 & 63]; + } + out += arr.join(""); + } + return out; + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/qs/stringify.mjs +function is_non_nullish_primitive(v4) { + return typeof v4 === "string" || typeof v4 === "number" || typeof v4 === "boolean" || typeof v4 === "symbol" || typeof v4 === "bigint"; +} +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format2, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) { + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== "undefined") { + if (pos === step) { + throw new RangeError("Cyclic object value"); + } else { + find_flag = true; + } + } + if (typeof tmp_sc.get(sentinel) === "undefined") { + step = 0; + } + } + if (typeof filter2 === "function") { + obj = filter2(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } else if (generateArrayPrefix === "comma" && isArray2(obj)) { + obj = maybe_map(obj, function(value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? ( + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, "key", format2) + ) : prefix; + } + obj = ""; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format2); + return [ + formatter?.(key_value) + "=" + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, "value", format2)) + ]; + } + return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; + } + const values2 = []; + if (typeof obj === "undefined") { + return values2; + } + let obj_keys; + if (generateArrayPrefix === "comma" && isArray2(obj)) { + if (encodeValuesOnly && encoder) { + obj = maybe_map(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }]; + } else if (isArray2(filter2)) { + obj_keys = filter2; + } else { + const keys2 = Object.keys(obj); + obj_keys = sort ? keys2.sort(sort) : keys2; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); + const adjusted_prefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; + if (allowEmptyArrays && isArray2(obj) && obj.length === 0) { + return adjusted_prefix + "[]"; + } + for (let j3 = 0; j3 < obj_keys.length; ++j3) { + const key = obj_keys[j3]; + const value = ( + // @ts-ignore + typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key] + ); + if (skipNulls && value === null) { + continue; + } + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; + const key_prefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); + sideChannel.set(object, step); + const valueSideChannel = /* @__PURE__ */ new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values2, inner_stringify( + value, + key_prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder, + filter2, + sort, + allowDots, + serializeDate, + format2, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + return values2; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") { + throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); + } + if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") { + throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); + } + if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") { + throw new TypeError("Encoder has to be a function."); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") { + throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); + } + let format2 = default_format; + if (typeof opts.format !== "undefined") { + if (!has(formatters, opts.format)) { + throw new TypeError("Unknown format option provided."); + } + format2 = opts.format; + } + const formatter = formatters[format2]; + let filter2 = defaults.filter; + if (typeof opts.filter === "function" || isArray2(opts.filter)) { + filter2 = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } else if ("indices" in opts) { + arrayFormat = opts.indices ? "indices" : "repeat"; + } else { + arrayFormat = defaults.arrayFormat; + } + if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") { + throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); + } + const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat, + charset, + charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === "undefined" ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter2, + format: format2, + formatter, + serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === "function" ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling + }; +} +function stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter2; + if (typeof options.filter === "function") { + filter2 = options.filter; + obj = filter2("", obj); + } else if (isArray2(options.filter)) { + filter2 = options.filter; + obj_keys = filter2; + } + const keys2 = []; + if (typeof obj !== "object" || obj === null) { + return ""; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = /* @__PURE__ */ new WeakMap(); + for (let i7 = 0; i7 < obj_keys.length; ++i7) { + const key = obj_keys[i7]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys2, inner_stringify( + obj[key], + key, + // @ts-expect-error + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + const joined = keys2.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? "?" : ""; + if (options.charsetSentinel) { + if (options.charset === "iso-8859-1") { + prefix += "utf8=%26%2310003%3B&"; + } else { + prefix += "utf8=%E2%9C%93&"; + } + } + return joined.length > 0 ? prefix + joined : ""; +} +var array_prefix_generators, push_to_array, toISOString, defaults, sentinel; +var init_stringify = __esm({ + "../pi-mono/node_modules/openai/internal/qs/stringify.mjs"() { + init_process_shim(); + init_utils(); + init_formats(); + init_values2(); + array_prefix_generators = { + brackets(prefix) { + return String(prefix) + "[]"; + }, + comma: "comma", + indices(prefix, key) { + return String(prefix) + "[" + key + "]"; + }, + repeat(prefix) { + return String(prefix); + } + }; + push_to_array = function(arr, value_or_array) { + Array.prototype.push.apply(arr, isArray2(value_or_array) ? value_or_array : [value_or_array]); + }; + defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: "indices", + charset: "utf-8", + charsetSentinel: false, + delimiter: "&", + encode: true, + encodeDotInKeys: false, + encoder: encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false + }; + sentinel = {}; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/query.mjs +function stringifyQuery(query) { + return stringify(query, { arrayFormat: "brackets" }); +} +var init_query2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/query.mjs"() { + init_process_shim(); + init_stringify(); + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/bytes.mjs +function concatBytes2(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index2 = 0; + for (const buffer of buffers) { + output.set(buffer, index2); + index2 += buffer.length; + } + return output; +} +function encodeUTF82(str2) { + let encoder; + return (encodeUTF8_2 ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_2 = encoder.encode.bind(encoder)))(str2); +} +function decodeUTF82(bytes) { + let decoder; + return (decodeUTF8_2 ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_2 = decoder.decode.bind(decoder)))(bytes); +} +var encodeUTF8_2, decodeUTF8_2; +var init_bytes2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/bytes.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/openai/internal/decoders/line.mjs +function findNewlineIndex2(buffer, startIndex) { + const newline = 10; + const carriage = 13; + for (let i7 = startIndex ?? 0; i7 < buffer.length; i7++) { + if (buffer[i7] === newline) { + return { preceding: i7, index: i7 + 1, carriage: false }; + } + if (buffer[i7] === carriage) { + return { preceding: i7, index: i7 + 1, carriage: true }; + } + } + return null; +} +function findDoubleNewlineIndex2(buffer) { + const newline = 10; + const carriage = 13; + for (let i7 = 0; i7 < buffer.length - 1; i7++) { + if (buffer[i7] === newline && buffer[i7 + 1] === newline) { + return i7 + 2; + } + if (buffer[i7] === carriage && buffer[i7 + 1] === carriage) { + return i7 + 2; + } + if (buffer[i7] === carriage && buffer[i7 + 1] === newline && i7 + 3 < buffer.length && buffer[i7 + 2] === carriage && buffer[i7 + 3] === newline) { + return i7 + 4; + } + } + return -1; +} +var _LineDecoder_buffer2, _LineDecoder_carriageReturnIndex2, LineDecoder2; +var init_line2 = __esm({ + "../pi-mono/node_modules/openai/internal/decoders/line.mjs"() { + init_process_shim(); + init_tslib2(); + init_bytes2(); + LineDecoder2 = class { + constructor() { + _LineDecoder_buffer2.set(this, void 0); + _LineDecoder_carriageReturnIndex2.set(this, void 0); + __classPrivateFieldSet2(this, _LineDecoder_buffer2, new Uint8Array(), "f"); + __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF82(chunk) : chunk; + __classPrivateFieldSet2(this, _LineDecoder_buffer2, concatBytes2([__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex2(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f"), __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") == null) { + __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, patternIndex.index, "f"); + continue; + } + if (__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") != null && (patternIndex.index !== __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF82(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(0, __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") - 1))); + __classPrivateFieldSet2(this, _LineDecoder_buffer2, __classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f")), "f"); + __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex2, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF82(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet2(this, _LineDecoder_buffer2, __classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex2, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").length) { + return []; + } + return this.decode("\n"); + } + }; + _LineDecoder_buffer2 = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex2 = /* @__PURE__ */ new WeakMap(); + LineDecoder2.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]); + LineDecoder2.NEWLINE_REGEXP = /\r\n|[\n\r]/g; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/log.mjs +function noop2() { +} +function makeLogFn2(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) { + return noop2; + } else { + return logger2[fnLevel].bind(logger2); + } +} +function loggerFor2(client) { + const logger2 = client.logger; + const logLevel = client.logLevel ?? "off"; + if (!logger2) { + return noopLogger2; + } + const cachedLogger = cachedLoggers2.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn2("error", logger2, logLevel), + warn: makeLogFn2("warn", logger2, logLevel), + info: makeLogFn2("info", logger2, logLevel), + debug: makeLogFn2("debug", logger2, logLevel) + }; + cachedLoggers2.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +var levelNumbers2, parseLogLevel2, noopLogger2, cachedLoggers2, formatRequestDetails2; +var init_log2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/log.mjs"() { + init_process_shim(); + init_values2(); + levelNumbers2 = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 + }; + parseLogLevel2 = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn2(levelNumbers2, maybeLevel)) { + return maybeLevel; + } + loggerFor2(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`); + return void 0; + }; + noopLogger2 = { + error: noop2, + warn: noop2, + info: noop2, + debug: noop2 + }; + cachedLoggers2 = /* @__PURE__ */ new WeakMap(); + formatRequestDetails2 = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; + }; + } +}); + +// ../pi-mono/node_modules/openai/core/streaming.mjs +async function* _iterSSEMessages2(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { + throw new OpenAIError(`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 OpenAIError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder2(); + const lineDecoder = new LineDecoder2(); + const iter = ReadableStreamToAsyncIterable2(response.body); + for await (const sseChunk of iterSSEChunks2(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +async function* iterSSEChunks2(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF82(chunk) : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex2(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +function partition2(str2, delimiter2) { + const index2 = str2.indexOf(delimiter2); + if (index2 !== -1) { + return [str2.substring(0, index2), delimiter2, str2.substring(index2 + delimiter2.length)]; + } + return [str2, "", ""]; +} +var _Stream_client2, Stream2, SSEDecoder2; +var init_streaming3 = __esm({ + "../pi-mono/node_modules/openai/core/streaming.mjs"() { + init_process_shim(); + init_tslib2(); + init_error5(); + init_shims2(); + init_line2(); + init_shims2(); + init_errors2(); + init_bytes2(); + init_log2(); + init_error5(); + Stream2 = class _Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + _Stream_client2.set(this, void 0); + this.controller = controller; + __classPrivateFieldSet2(this, _Stream_client2, client, "f"); + } + static fromSSEResponse(response, controller, client, synthesizeEventData) { + let consumed2 = false; + const logger2 = client ? loggerFor2(client) : console; + async function* iterator() { + if (consumed2) { + throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed2 = true; + let done = false; + try { + for await (const sse of _iterSSEMessages2(response, controller)) { + if (done) + continue; + if (sse.data.startsWith("[DONE]")) { + done = true; + continue; + } + if (sse.event === null || !sse.event.startsWith("thread.")) { + let data; + try { + data = JSON.parse(sse.data); + } catch (e9) { + logger2.error(`Could not parse message into JSON:`, sse.data); + logger2.error(`From chunk:`, sse.raw); + throw e9; + } + if (data && data.error) { + throw new APIError2(void 0, data.error, void 0, response.headers); + } + yield synthesizeEventData ? { event: sse.event, data } : data; + } else { + let data; + try { + data = JSON.parse(sse.data); + } catch (e9) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e9; + } + if (sse.event == "error") { + throw new APIError2(void 0, data.error, data.message, void 0); + } + yield { event: sse.event, data }; + } + } + done = true; + } catch (e9) { + if (isAbortError2(e9)) + return; + throw e9; + } finally { + if (!done) + controller.abort(); + } + } + return new _Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed2 = false; + async function* iterLines() { + const lineDecoder = new LineDecoder2(); + const iter = ReadableStreamToAsyncIterable2(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed2) { + throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed2 = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } catch (e9) { + if (isAbortError2(e9)) + return; + throw e9; + } finally { + if (!done) + controller.abort(); + } + } + return new _Stream(iterator, controller, client); + } + [(_Stream_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + } + }; + }; + return [ + new _Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet2(this, _Stream_client2, "f")), + new _Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet2(this, _Stream_client2, "f")) + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self2 = this; + let iter; + return makeReadableStream2({ + async start() { + iter = self2[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encodeUTF82(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + } + }); + } + }; + SSEDecoder2 = class { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith("\r")) { + line = line.substring(0, line.length - 1); + } + if (!line) { + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join("\n"), + raw: this.chunks + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(":")) { + return null; + } + let [fieldname, _3, value] = partition2(line, ":"); + if (value.startsWith(" ")) { + value = value.substring(1); + } + if (fieldname === "event") { + this.event = value; + } else if (fieldname === "data") { + this.data.push(value); + } + return null; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/parse.mjs +async function defaultParseResponse2(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor2(client).debug("response", response.status, response.url, response.headers, response.body); + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData); + } + return Stream2.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData); + } + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = contentType?.split(";")[0]?.trim(); + const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json"); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; + } + const json2 = await response.json(); + return addRequestID2(json2, response); + } + const text3 = await response.text(); + return text3; + })(); + loggerFor2(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +function addRequestID2(value, response) { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return value; + } + return Object.defineProperty(value, "_request_id", { + value: response.headers.get("x-request-id"), + enumerable: false + }); +} +var init_parse3 = __esm({ + "../pi-mono/node_modules/openai/internal/parse.mjs"() { + init_process_shim(); + init_streaming3(); + init_log2(); + } +}); + +// ../pi-mono/node_modules/openai/core/api-promise.mjs +var _APIPromise_client2, APIPromise2; +var init_api_promise2 = __esm({ + "../pi-mono/node_modules/openai/core/api-promise.mjs"() { + init_process_shim(); + init_tslib2(); + init_parse3(); + APIPromise2 = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse2 = defaultParseResponse2) { + super((resolve2) => { + resolve2(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse2; + _APIPromise_client2.set(this, void 0); + __classPrivateFieldSet2(this, _APIPromise_client2, client, "f"); + } + _thenUnwrap(transform) { + return new _APIPromise(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => addRequestID2(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p4) => p4.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the X-Request-ID header which is useful for debugging requests and reporting + * issues to OpenAI. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get("x-request-id") }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } + }; + _APIPromise_client2 = /* @__PURE__ */ new WeakMap(); + } +}); + +// ../pi-mono/node_modules/openai/core/pagination.mjs +var _AbstractPage_client2, AbstractPage2, PagePromise2, Page2, CursorPage, ConversationCursorPage; +var init_pagination2 = __esm({ + "../pi-mono/node_modules/openai/core/pagination.mjs"() { + init_process_shim(); + init_tslib2(); + init_error5(); + init_parse3(); + init_api_promise2(); + init_values2(); + AbstractPage2 = class { + constructor(client, response, body, options) { + _AbstractPage_client2.set(this, void 0); + __classPrivateFieldSet2(this, _AbstractPage_client2, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); + } + return await __classPrivateFieldGet2(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } + }; + PagePromise2 = class extends APIPromise2 { + constructor(client, request, Page3) { + super(client, request, async (client2, props) => new Page3(client2, props.response, await defaultParseResponse2(client2, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } + }; + Page2 = class extends AbstractPage2 { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.object = body.object; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + return null; + } + }; + CursorPage = class extends AbstractPage2 { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const data = this.getPaginatedItems(); + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj2(this.options.query), + after: id + } + }; + } + }; + ConversationCursorPage = class extends AbstractPage2 { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.last_id = body.last_id || ""; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj2(this.options.query), + after: cursor + } + }; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/uploads.mjs +function makeFile2(fileBits, fileName, options) { + checkFileSupport2(); + return new File(fileBits, fileName ?? "unknown_file", options); +} +function getName2(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +function supportsFormData2(fetchObject) { + const fetch3 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap2.get(fetch3); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = "Response" in fetch3 ? fetch3.Response : (await fetch3("data:,")).constructor; + const data = new FormData(); + if (data.toString() === await new FetchResponse(data).text()) { + return false; + } + return true; + } catch { + return true; + } + })(); + supportsFormDataMap2.set(fetch3, promise); + return promise; +} +var checkFileSupport2, isAsyncIterable2, maybeMultipartFormRequestOptions, multipartFormRequestOptions2, supportsFormDataMap2, createForm2, isNamedBlob2, isUploadable, hasUploadableValue, addFormValue2; +var init_uploads3 = __esm({ + "../pi-mono/node_modules/openai/internal/uploads.mjs"() { + init_process_shim(); + init_shims2(); + checkFileSupport2 = () => { + if (typeof File === "undefined") { + const { process: process2 } = globalThis; + const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } + }; + isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + maybeMultipartFormRequestOptions = async (opts, fetch3) => { + if (!hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await createForm2(opts.body, fetch3) }; + }; + multipartFormRequestOptions2 = async (opts, fetch3) => { + return { ...opts, body: await createForm2(opts.body, fetch3) }; + }; + supportsFormDataMap2 = /* @__PURE__ */ new WeakMap(); + createForm2 = async (body, fetch3) => { + if (!await supportsFormData2(fetch3)) { + throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class."); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue2(form, key, value))); + return form; + }; + isNamedBlob2 = (value) => value instanceof Blob && "name" in value; + isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable2(value) || isNamedBlob2(value)); + hasUploadableValue = (value) => { + if (isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === "object") { + for (const k2 in value) { + if (hasUploadableValue(value[k2])) + return true; + } + } + return false; + }; + addFormValue2 = async (form, key, value) => { + if (value === void 0) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + form.append(key, String(value)); + } else if (value instanceof Response) { + form.append(key, makeFile2([await value.blob()], getName2(value))); + } else if (isAsyncIterable2(value)) { + form.append(key, makeFile2([await new Response(ReadableStreamFrom2(value)).blob()], getName2(value))); + } else if (isNamedBlob2(value)) { + form.append(key, value, getName2(value)); + } else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue2(form, key + "[]", entry))); + } else if (typeof value === "object") { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue2(form, `${key}[${name}]`, prop))); + } else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/to-file.mjs +async function toFile2(value, name, options) { + checkFileSupport2(); + value = await value; + if (isFileLike2(value)) { + if (value instanceof File) { + return value; + } + return makeFile2([await value.arrayBuffer()], value.name); + } + if (isResponseLike2(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile2(await getBytes2(blob), name, options); + } + const parts = await getBytes2(value); + name || (name = getName2(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = { ...options, type }; + } + } + return makeFile2(parts, name, options); +} +async function getBytes2(value) { + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike2(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable2(value)) { + for await (const chunk of value) { + parts.push(...await getBytes2(chunk)); + } + } else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError2(value)}`); + } + return parts; +} +function propsForError2(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`; +} +var isBlobLike2, isFileLike2, isResponseLike2; +var init_to_file2 = __esm({ + "../pi-mono/node_modules/openai/internal/to-file.mjs"() { + init_process_shim(); + init_uploads3(); + init_uploads3(); + isBlobLike2 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; + isFileLike2 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike2(value); + isResponseLike2 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; + } +}); + +// ../pi-mono/node_modules/openai/core/uploads.mjs +var init_uploads4 = __esm({ + "../pi-mono/node_modules/openai/core/uploads.mjs"() { + init_process_shim(); + init_to_file2(); + } +}); + +// ../pi-mono/node_modules/openai/core/resource.mjs +var APIResource2; +var init_resource2 = __esm({ + "../pi-mono/node_modules/openai/core/resource.mjs"() { + init_process_shim(); + APIResource2 = class { + constructor(client) { + this._client = client; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/path.mjs +function encodeURIPath2(str2) { + return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +var EMPTY2, createPathTagFunction2, path2; +var init_path2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/path.mjs"() { + init_process_shim(); + init_error5(); + EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); + createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path6(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path7 = statics.reduce((previousValue, currentValue, index2) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index2]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index2 !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index2 === params.length ? "" : encoded); + }, ""); + const pathOnly = path7.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match2; + while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match2.index, + length: match2[0].length, + error: `Value "${match2[0]}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a3, b4) => a3.start - b4.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new OpenAIError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e9) => e9.error).join("\n")} +${path7} +${underline}`); + } + return path7; + }; + path2 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2); + } +}); + +// ../pi-mono/node_modules/openai/resources/chat/completions/messages.mjs +var Messages3; +var init_messages3 = __esm({ + "../pi-mono/node_modules/openai/resources/chat/completions/messages.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + Messages3 = class extends APIResource2 { + /** + * Get the messages in a stored chat completion. Only Chat Completions that have + * been created with the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( + * 'completion_id', + * )) { + * // ... + * } + * ``` + */ + list(completionID, query = {}, options) { + return this._client.getAPIList(path2`/chat/completions/${completionID}/messages`, CursorPage, { query, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/error.mjs +var init_error6 = __esm({ + "../pi-mono/node_modules/openai/error.mjs"() { + init_process_shim(); + init_error5(); + } +}); + +// ../pi-mono/node_modules/openai/lib/parser.mjs +function isChatCompletionFunctionTool(tool) { + return tool !== void 0 && "function" in tool && tool.function !== void 0; +} +function isAutoParsableResponseFormat(response_format) { + return response_format?.["$brand"] === "auto-parseable-response-format"; +} +function isAutoParsableTool(tool) { + return tool?.["$brand"] === "auto-parseable-tool"; +} +function maybeParseChatCompletion(completion, params) { + if (!params || !hasAutoParseableInput(params)) { + return { + ...completion, + choices: completion.choices.map((choice) => { + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + parsed: null, + ...choice.message.tool_calls ? { + tool_calls: choice.message.tool_calls + } : void 0 + } + }; + }) + }; + } + return parseChatCompletion(completion, params); +} +function parseChatCompletion(completion, params) { + const choices = completion.choices.map((choice) => { + if (choice.finish_reason === "length") { + throw new LengthFinishReasonError(); + } + if (choice.finish_reason === "content_filter") { + throw new ContentFilterFinishReasonError(); + } + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + ...choice.message.tool_calls ? { + tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? void 0 + } : void 0, + parsed: choice.message.content && !choice.message.refusal ? parseResponseFormat(params, choice.message.content) : null + } + }; + }); + return { ...completion, choices }; +} +function parseResponseFormat(params, content) { + if (params.response_format?.type !== "json_schema") { + return null; + } + if (params.response_format?.type === "json_schema") { + if ("$parseRaw" in params.response_format) { + const response_format = params.response_format; + return response_format.$parseRaw(content); + } + return JSON.parse(content); + } + return null; +} +function parseToolCall(params, toolCall) { + const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name); + return { + ...toolCall, + function: { + ...toolCall.function, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) : null + } + }; +} +function shouldParseToolCall(params, toolCall) { + if (!params || !("tools" in params) || !params.tools) { + return false; + } + const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name); + return isChatCompletionFunctionTool(inputTool) && (isAutoParsableTool(inputTool) || inputTool?.function.strict || false); +} +function hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.response_format)) { + return true; + } + return params.tools?.some((t6) => isAutoParsableTool(t6) || t6.type === "function" && t6.function.strict === true) ?? false; +} +function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { + for (const toolCall of toolCalls || []) { + if (toolCall.type !== "function") { + throw new OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); + } + } +} +function validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== "function") { + throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); + } + if (tool.function.strict !== true) { + throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); + } + } +} +var init_parser3 = __esm({ + "../pi-mono/node_modules/openai/lib/parser.mjs"() { + init_process_shim(); + init_error6(); + } +}); + +// ../pi-mono/node_modules/openai/lib/chatCompletionUtils.mjs +var isAssistantMessage, isToolMessage; +var init_chatCompletionUtils = __esm({ + "../pi-mono/node_modules/openai/lib/chatCompletionUtils.mjs"() { + init_process_shim(); + isAssistantMessage = (message) => { + return message?.role === "assistant"; + }; + isToolMessage = (message) => { + return message?.role === "tool"; + }; + } +}); + +// ../pi-mono/node_modules/openai/lib/EventStream.mjs +var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError, EventStream2; +var init_EventStream = __esm({ + "../pi-mono/node_modules/openai/lib/EventStream.mjs"() { + init_process_shim(); + init_tslib2(); + init_error6(); + EventStream2 = class { + constructor() { + _EventStream_instances.add(this); + this.controller = new AbortController(); + _EventStream_connectedPromise.set(this, void 0); + _EventStream_resolveConnectedPromise.set(this, () => { + }); + _EventStream_rejectConnectedPromise.set(this, () => { + }); + _EventStream_endPromise.set(this, void 0); + _EventStream_resolveEndPromise.set(this, () => { + }); + _EventStream_rejectEndPromise.set(this, () => { + }); + _EventStream_listeners.set(this, {}); + _EventStream_ended.set(this, false); + _EventStream_errored.set(this, false); + _EventStream_aborted.set(this, false); + _EventStream_catchingPromiseCreated.set(this, false); + __classPrivateFieldSet2(this, _EventStream_connectedPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet2(this, _EventStream_resolveConnectedPromise, resolve2, "f"); + __classPrivateFieldSet2(this, _EventStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet2(this, _EventStream_endPromise, new Promise((resolve2, reject) => { + __classPrivateFieldSet2(this, _EventStream_resolveEndPromise, resolve2, "f"); + __classPrivateFieldSet2(this, _EventStream_rejectEndPromise, reject, "f"); + }), "f"); + __classPrivateFieldGet2(this, _EventStream_connectedPromise, "f").catch(() => { + }); + __classPrivateFieldGet2(this, _EventStream_endPromise, "f").catch(() => { + }); + } + _run(executor) { + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit("end"); + }, __classPrivateFieldGet2(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); + }, 0); + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet2(this, _EventStream_resolveConnectedPromise, "f").call(this); + this._emit("connect"); + } + get ended() { + return __classPrivateFieldGet2(this, _EventStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet2(this, _EventStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet2(this, _EventStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event]; + if (!listeners) + return this; + const index2 = listeners.findIndex((l5) => l5.listener === listener); + if (index2 >= 0) + listeners.splice(index2, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve2, reject) => { + __classPrivateFieldSet2(this, _EventStream_catchingPromiseCreated, true, "f"); + if (event !== "error") + this.once("error", reject); + this.once(event, resolve2); + }); + } + async done() { + __classPrivateFieldSet2(this, _EventStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet2(this, _EventStream_endPromise, "f"); + } + _emit(event, ...args) { + if (__classPrivateFieldGet2(this, _EventStream_ended, "f")) { + return; + } + if (event === "end") { + __classPrivateFieldSet2(this, _EventStream_ended, true, "f"); + __classPrivateFieldGet2(this, _EventStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = listeners.filter((l5) => !l5.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === "abort") { + const error = args[0]; + if (!__classPrivateFieldGet2(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet2(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet2(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + return; + } + if (event === "error") { + const error = args[0]; + if (!__classPrivateFieldGet2(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet2(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet2(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit("end"); + } + } + _emitFinal() { + } + }; + _EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_handleError = function _EventStream_handleError2(error) { + __classPrivateFieldSet2(this, _EventStream_errored, true, "f"); + if (error instanceof Error && error.name === "AbortError") { + error = new APIUserAbortError2(); + } + if (error instanceof APIUserAbortError2) { + __classPrivateFieldSet2(this, _EventStream_aborted, true, "f"); + return this._emit("abort", error); + } + if (error instanceof OpenAIError) { + return this._emit("error", error); + } + if (error instanceof Error) { + const openAIError = new OpenAIError(error.message); + openAIError.cause = error; + return this._emit("error", openAIError); + } + return this._emit("error", new OpenAIError(String(error))); + }; + } +}); + +// ../pi-mono/node_modules/openai/lib/RunnableFunction.mjs +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === "function"; +} +var init_RunnableFunction = __esm({ + "../pi-mono/node_modules/openai/lib/RunnableFunction.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/openai/lib/AbstractChatCompletionRunner.mjs +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS, AbstractChatCompletionRunner; +var init_AbstractChatCompletionRunner = __esm({ + "../pi-mono/node_modules/openai/lib/AbstractChatCompletionRunner.mjs"() { + init_process_shim(); + init_tslib2(); + init_error6(); + init_parser3(); + init_chatCompletionUtils(); + init_EventStream(); + init_RunnableFunction(); + DEFAULT_MAX_CHAT_COMPLETIONS = 10; + AbstractChatCompletionRunner = class extends EventStream2 { + constructor() { + super(...arguments); + _AbstractChatCompletionRunner_instances.add(this); + this._chatCompletions = []; + this.messages = []; + } + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit("chatCompletion", chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; + } + _addMessage(message, emit = true) { + if (!("content" in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit("message", message); + if (isToolMessage(message) && message.content) { + this._emit("functionToolCallResult", message.content); + } else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === "function") { + this._emit("functionToolCall", tool_call.function); + } + } + } + } + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new OpenAIError("stream ended without producing a ChatCompletion"); + return completion; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionToolCall() { + await this.done(); + return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + } + async finalFunctionToolCallResult() { + await this.done(); + return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit("finalChatCompletion", completion); + const finalMessage = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit("finalMessage", finalMessage); + const finalContent = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit("finalContent", finalContent); + const finalFunctionCall = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + if (finalFunctionCall) + this._emit("finalFunctionToolCall", finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit("finalFunctionToolCallResult", finalFunctionCallResult); + if (this._chatCompletions.some((c6) => c6.usage)) { + this._emit("totalUsage", __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(client, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); + } + async _runChatCompletion(client, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(client, params, options); + } + async _runTools(client, params, options) { + const role = "tool"; + const { tool_choice = "auto", stream: stream2, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const inputTools = params.tools.map((tool) => { + if (isAutoParsableTool(tool)) { + if (!tool.$callback) { + throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function"); + } + return { + type: "function", + function: { + function: tool.$callback, + name: tool.function.name, + description: tool.function.description || "", + parameters: tool.function.parameters, + parse: tool.$parseRaw, + strict: true + } + }; + } + return tool; + }); + const functionsByName = {}; + for (const f4 of inputTools) { + if (f4.type === "function") { + functionsByName[f4.function.name || f4.function.function.name] = f4.function; + } + } + const tools = "tools" in params ? inputTools.map((t6) => t6.type === "function" ? { + type: "function", + function: { + name: t6.function.name || t6.function.function.name, + parameters: t6.function.parameters, + description: t6.function.description, + strict: t6.function.strict + } + } : t6) : void 0; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i7 = 0; i7 < maxChatCompletions; ++i7) { + const chatCompletion = await this._createChatCompletion(client, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages] + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls?.length) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== "function") + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`; + this._addMessage({ role, tool_call_id, content: content2 }); + continue; + } else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content: content2 }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } catch (error) { + const content2 = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content: content2 }); + continue; + } + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } + } + } + return; + } + }; + _AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() { + return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; + }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() { + let i7 = this.messages.length; + while (i7-- > 0) { + const message = this.messages[i7]; + if (isAssistantMessage(message)) { + const ret = { + ...message, + content: message.content ?? null, + refusal: message.refusal ?? null + }; + return ret; + } + } + throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant"); + }, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall2() { + for (let i7 = this.messages.length - 1; i7 >= 0; i7--) { + const message = this.messages[i7]; + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.filter((x2) => x2.type === "function").at(-1)?.function; + } + } + return; + }, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult2() { + for (let i7 = this.messages.length - 1; i7 >= 0; i7--) { + const message = this.messages[i7]; + if (isToolMessage(message) && message.content != null && typeof message.content === "string" && this.messages.some((x2) => x2.role === "assistant" && x2.tool_calls?.some((y4) => y4.type === "function" && y4.id === message.tool_call_id))) { + return message.content; + } + } + return; + }, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0 + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; + }, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) { + if (params.n != null && params.n > 1) { + throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly."); + } + }, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) { + return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent); + }; + } +}); + +// ../pi-mono/node_modules/openai/lib/ChatCompletionRunner.mjs +var ChatCompletionRunner; +var init_ChatCompletionRunner = __esm({ + "../pi-mono/node_modules/openai/lib/ChatCompletionRunner.mjs"() { + init_process_shim(); + init_AbstractChatCompletionRunner(); + init_chatCompletionUtils(); + ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner { + static runTools(client, params, options) { + const runner = new _ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" } + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; + } + _addMessage(message, emit = true) { + super._addMessage(message, emit); + if (isAssistantMessage(message) && message.content) { + this._emit("content", message.content); + } + } + }; + } +}); + +// ../pi-mono/node_modules/openai/_vendor/partial-json-parser/parser.mjs +function parseJSON(jsonString, allowPartial = Allow.ALL) { + if (typeof jsonString !== "string") { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON(jsonString.trim(), allowPartial); +} +var STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, MINUS_INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL, Allow, PartialJSON, MalformedJSON, _parseJSON, partialParse3; +var init_parser4 = __esm({ + "../pi-mono/node_modules/openai/_vendor/partial-json-parser/parser.mjs"() { + init_process_shim(); + STR = 1; + NUM = 2; + ARR = 4; + OBJ = 8; + NULL = 16; + BOOL = 32; + NAN = 64; + INFINITY = 128; + MINUS_INFINITY = 256; + INF = INFINITY | MINUS_INFINITY; + SPECIAL = NULL | BOOL | INF | NAN; + ATOM = STR | NUM | SPECIAL; + COLLECTION = ARR | OBJ; + ALL = ATOM | COLLECTION; + Allow = { + STR, + NUM, + ARR, + OBJ, + NULL, + BOOL, + NAN, + INFINITY, + MINUS_INFINITY, + INF, + SPECIAL, + ATOM, + COLLECTION, + ALL + }; + PartialJSON = class extends Error { + }; + MalformedJSON = class extends Error { + }; + _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index2 = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index2}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index2}`); + }; + const parseAny = () => { + skipBlank(); + if (index2 >= length) + markPartialJSON("Unexpected end of input"); + if (jsonString[index2] === '"') + return parseStr(); + if (jsonString[index2] === "{") + return parseObj(); + if (jsonString[index2] === "[") + return parseArr(); + if (jsonString.substring(index2, index2 + 4) === "null" || Allow.NULL & allow && length - index2 < 4 && "null".startsWith(jsonString.substring(index2))) { + index2 += 4; + return null; + } + if (jsonString.substring(index2, index2 + 4) === "true" || Allow.BOOL & allow && length - index2 < 4 && "true".startsWith(jsonString.substring(index2))) { + index2 += 4; + return true; + } + if (jsonString.substring(index2, index2 + 5) === "false" || Allow.BOOL & allow && length - index2 < 5 && "false".startsWith(jsonString.substring(index2))) { + index2 += 5; + return false; + } + if (jsonString.substring(index2, index2 + 8) === "Infinity" || Allow.INFINITY & allow && length - index2 < 8 && "Infinity".startsWith(jsonString.substring(index2))) { + index2 += 8; + return Infinity; + } + if (jsonString.substring(index2, index2 + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && 1 < length - index2 && length - index2 < 9 && "-Infinity".startsWith(jsonString.substring(index2))) { + index2 += 9; + return -Infinity; + } + if (jsonString.substring(index2, index2 + 3) === "NaN" || Allow.NAN & allow && length - index2 < 3 && "NaN".startsWith(jsonString.substring(index2))) { + index2 += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index2; + let escape4 = false; + index2++; + while (index2 < length && (jsonString[index2] !== '"' || escape4 && jsonString[index2 - 1] === "\\")) { + escape4 = jsonString[index2] === "\\" ? !escape4 : false; + index2++; + } + if (jsonString.charAt(index2) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index2 - Number(escape4))); + } catch (e9) { + throwMalformedError(String(e9)); + } + } else if (Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index2 - Number(escape4)) + '"'); + } catch (e9) { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"'); + } + } + markPartialJSON("Unterminated string literal"); + }; + const parseObj = () => { + index2++; + skipBlank(); + const obj = {}; + try { + while (jsonString[index2] !== "}") { + skipBlank(); + if (index2 >= length && Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index2++; + try { + const value = parseAny(); + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + } catch (e9) { + if (Allow.OBJ & allow) + return obj; + else + throw e9; + } + skipBlank(); + if (jsonString[index2] === ",") + index2++; + } + } catch (e9) { + if (Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index2++; + return obj; + }; + const parseArr = () => { + index2++; + const arr = []; + try { + while (jsonString[index2] !== "]") { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index2] === ",") { + index2++; + } + } + } catch (e9) { + if (Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index2++; + return arr; + }; + const parseNum = () => { + if (index2 === 0) { + if (jsonString === "-" && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } catch (e9) { + if (Allow.NUM & allow) { + try { + if ("." === jsonString[jsonString.length - 1]) + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("."))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e"))); + } catch (e10) { + } + } + throwMalformedError(String(e9)); + } + } + const start = index2; + if (jsonString[index2] === "-") + index2++; + while (jsonString[index2] && !",]}".includes(jsonString[index2])) + index2++; + if (index2 == length && !(Allow.NUM & allow)) + markPartialJSON("Unterminated number literal"); + try { + return JSON.parse(jsonString.substring(start, index2)); + } catch (e9) { + if (jsonString.substring(start, index2) === "-" && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e"))); + } catch (e10) { + throwMalformedError(String(e10)); + } + } + }; + const skipBlank = () => { + while (index2 < length && " \n\r ".includes(jsonString[index2])) { + index2++; + } + }; + return parseAny(); + }; + partialParse3 = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); + } +}); + +// ../pi-mono/node_modules/openai/streaming.mjs +var init_streaming4 = __esm({ + "../pi-mono/node_modules/openai/streaming.mjs"() { + init_process_shim(); + init_streaming3(); + } +}); + +// ../pi-mono/node_modules/openai/lib/ChatCompletionStream.mjs +function finalizeChatCompletion(snapshot, params) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + const completion = { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index: index2, logprobs, ...choiceRest }) => { + if (!finish_reason) { + throw new OpenAIError(`missing finish_reason for choice ${index2}`); + } + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; + if (!role) { + throw new OpenAIError(`missing role for choice ${index2}`); + } + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) { + throw new OpenAIError(`missing function_call.arguments for choice ${index2}`); + } + if (!name) { + throw new OpenAIError(`missing function_call.name for choice ${index2}`); + } + return { + ...choiceRest, + message: { + content, + function_call: { arguments: args, name }, + role, + refusal: message.refusal ?? null + }, + finish_reason, + index: index2, + logprobs + }; + } + if (tool_calls) { + return { + ...choiceRest, + index: index2, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + refusal: message.refusal ?? null, + tool_calls: tool_calls.map((tool_call, i7) => { + const { function: fn, type, id: id2, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id2 == null) { + throw new OpenAIError(`missing choices[${index2}].tool_calls[${i7}].id +${str(snapshot)}`); + } + if (type == null) { + throw new OpenAIError(`missing choices[${index2}].tool_calls[${i7}].type +${str(snapshot)}`); + } + if (name == null) { + throw new OpenAIError(`missing choices[${index2}].tool_calls[${i7}].function.name +${str(snapshot)}`); + } + if (args == null) { + throw new OpenAIError(`missing choices[${index2}].tool_calls[${i7}].function.arguments +${str(snapshot)}`); + } + return { ...toolRest, id: id2, type, function: { ...fnRest, name, arguments: args } }; + }) + } + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role, refusal: message.refusal ?? null }, + finish_reason, + index: index2, + logprobs + }; + }), + created, + model, + object: "chat.completion", + ...system_fingerprint ? { system_fingerprint } : {} + }; + return maybeParseChatCompletion(completion, params); +} +function str(x2) { + return JSON.stringify(x2); +} +function assertIsEmpty(obj) { + return; +} +function assertNever(_x2) { +} +var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion, ChatCompletionStream; +var init_ChatCompletionStream = __esm({ + "../pi-mono/node_modules/openai/lib/ChatCompletionStream.mjs"() { + init_process_shim(); + init_tslib2(); + init_parser4(); + init_error6(); + init_parser3(); + init_streaming4(); + init_AbstractChatCompletionRunner(); + ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner { + constructor(params) { + super(); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_params.set(this, void 0); + _ChatCompletionStream_choiceEventStates.set(this, void 0); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + __classPrivateFieldSet2(this, _ChatCompletionStream_params, params, "f"); + __classPrivateFieldSet2(this, _ChatCompletionStream_choiceEventStates, [], "f"); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream2) { + const runner = new _ChatCompletionStream(null); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + static createChatCompletion(client, params, options) { + const runner = new _ChatCompletionStream(params); + runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } })); + return runner; + } + async _createChatCompletion(client, params, options) { + super._createChatCompletion; + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream2 = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream2) { + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream2 = Stream2.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream2) { + if (chatId && chatId !== chunk.id) { + this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() { + if (this.ended) + return; + __classPrivateFieldSet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); + }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) { + let state = __classPrivateFieldGet2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; + if (state) { + return state; + } + state = { + content_done: false, + refusal_done: false, + logprobs_content_done: false, + logprobs_refusal_done: false, + done_tool_calls: /* @__PURE__ */ new Set(), + current_tool_call_index: null + }; + __classPrivateFieldGet2(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; + return state; + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) { + if (this.ended) + return; + const completion = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit("chunk", chunk, completion); + for (const choice of chunk.choices) { + const choiceSnapshot = completion.choices[choice.index]; + if (choice.delta.content != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.content) { + this._emit("content", choice.delta.content, choiceSnapshot.message.content); + this._emit("content.delta", { + delta: choice.delta.content, + snapshot: choiceSnapshot.message.content, + parsed: choiceSnapshot.message.parsed + }); + } + if (choice.delta.refusal != null && choiceSnapshot.message?.role === "assistant" && choiceSnapshot.message?.refusal) { + this._emit("refusal.delta", { + delta: choice.delta.refusal, + snapshot: choiceSnapshot.message.refusal + }); + } + if (choice.logprobs?.content != null && choiceSnapshot.message?.role === "assistant") { + this._emit("logprobs.content.delta", { + content: choice.logprobs?.content, + snapshot: choiceSnapshot.logprobs?.content ?? [] + }); + } + if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === "assistant") { + this._emit("logprobs.refusal.delta", { + refusal: choice.logprobs?.refusal, + snapshot: choiceSnapshot.logprobs?.refusal ?? [] + }); + } + const state = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.finish_reason) { + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + if (state.current_tool_call_index != null) { + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + } + for (const toolCall of choice.delta.tool_calls ?? []) { + if (state.current_tool_call_index !== toolCall.index) { + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + if (state.current_tool_call_index != null) { + __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + } + state.current_tool_call_index = toolCall.index; + } + for (const toolCallDelta of choice.delta.tool_calls ?? []) { + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; + if (!toolCallSnapshot?.type) { + continue; + } + if (toolCallSnapshot?.type === "function") { + this._emit("tool_calls.function.arguments.delta", { + name: toolCallSnapshot.function?.name, + index: toolCallDelta.index, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: toolCallSnapshot.function.parsed_arguments, + arguments_delta: toolCallDelta.function?.arguments ?? "" + }); + } else { + assertNever(toolCallSnapshot?.type); + } + } + } + }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) { + const state = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (state.done_tool_calls.has(toolCallIndex)) { + return; + } + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; + if (!toolCallSnapshot) { + throw new Error("no tool call snapshot"); + } + if (!toolCallSnapshot.type) { + throw new Error("tool call snapshot missing `type`"); + } + if (toolCallSnapshot.type === "function") { + const inputTool = __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); + this._emit("tool_calls.function.arguments.done", { + name: toolCallSnapshot.function.name, + index: toolCallIndex, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) : null + }); + } else { + assertNever(toolCallSnapshot.type); + } + }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) { + const state = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.message.content && !state.content_done) { + state.content_done = true; + const responseFormat = __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); + this._emit("content.done", { + content: choiceSnapshot.message.content, + parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null + }); + } + if (choiceSnapshot.message.refusal && !state.refusal_done) { + state.refusal_done = true; + this._emit("refusal.done", { refusal: choiceSnapshot.message.refusal }); + } + if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { + state.logprobs_content_done = true; + this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content }); + } + if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { + state.logprobs_refusal_done = true; + this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal }); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new OpenAIError(`request ended without sending any chunks`); + } + __classPrivateFieldSet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); + __classPrivateFieldSet2(this, _ChatCompletionStream_choiceEventStates, [], "f"); + return finalizeChatCompletion(snapshot, __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f")); + }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat2() { + const responseFormat = __classPrivateFieldGet2(this, _ChatCompletionStream_params, "f")?.response_format; + if (isAutoParsableResponseFormat(responseFormat)) { + return responseFormat; + } + return null; + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) { + var _a7, _b, _c, _d; + let snapshot = __classPrivateFieldGet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = __classPrivateFieldSet2(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [] + }, "f"); + } else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index: index2, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index2]; + if (!choice) { + choice = snapshot.choices[index2] = { finish_reason, index: index2, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } else { + const { content: content2, refusal: refusal2, ...rest3 } = logprobs; + assertIsEmpty(rest3); + Object.assign(choice.logprobs, rest3); + if (content2) { + (_a7 = choice.logprobs).content ?? (_a7.content = []); + choice.logprobs.content.push(...content2); + } + if (refusal2) { + (_b = choice.logprobs).refusal ?? (_b.refusal = []); + choice.logprobs.refusal.push(...refusal2); + } + } + } + if (finish_reason) { + choice.finish_reason = finish_reason; + if (__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f"))) { + if (finish_reason === "length") { + throw new LengthFinishReasonError(); + } + if (finish_reason === "content_filter") { + throw new ContentFilterFinishReasonError(); + } + } + } + Object.assign(choice, other); + if (!delta) + continue; + const { content, refusal, function_call, role, tool_calls, ...rest2 } = delta; + assertIsEmpty(rest2); + Object.assign(choice.message, rest2); + if (refusal) { + choice.message.refusal = (choice.message.refusal || "") + refusal; + } + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_c = choice.message.function_call).arguments ?? (_c.arguments = ""); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (content) { + choice.message.content = (choice.message.content || "") + content; + if (!choice.message.refusal && __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { + choice.message.parsed = partialParse3(choice.message.content); + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index: index3, id, type, function: fn, ...rest3 } of tool_calls) { + const tool_call = (_d = choice.message.tool_calls)[index3] ?? (_d[index3] = {}); + Object.assign(tool_call, rest3); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { name: fn.name ?? "", arguments: "" }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) { + tool_call.function.arguments += fn.arguments; + if (shouldParseToolCall(__classPrivateFieldGet2(this, _ChatCompletionStream_params, "f"), tool_call)) { + tool_call.function.parsed_arguments = partialParse3(tool_call.function.arguments); + } + } + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("chunk", (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } else { + pushQueue.push(chunk); + } + }); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(void 0); + } + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: void 0, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: void 0, done: true }; + } + }; + } + toReadableStream() { + const stream2 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller); + return stream2.toReadableStream(); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +var ChatCompletionStreamingRunner; +var init_ChatCompletionStreamingRunner = __esm({ + "../pi-mono/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs"() { + init_process_shim(); + init_ChatCompletionStream(); + ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream { + static fromReadableStream(stream2) { + const runner = new _ChatCompletionStreamingRunner(null); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + static runTools(client, params, options) { + const runner = new _ChatCompletionStreamingRunner( + // @ts-expect-error TODO these types are incompatible + params + ); + const opts = { + ...options, + headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" } + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/chat/completions/completions.mjs +var Completions2; +var init_completions2 = __esm({ + "../pi-mono/node_modules/openai/resources/chat/completions/completions.mjs"() { + init_process_shim(); + init_resource2(); + init_messages3(); + init_messages3(); + init_pagination2(); + init_path2(); + init_ChatCompletionRunner(); + init_ChatCompletionStreamingRunner(); + init_ChatCompletionStream(); + init_parser3(); + init_ChatCompletionStreamingRunner(); + init_RunnableFunction(); + init_ChatCompletionStream(); + init_ChatCompletionRunner(); + Completions2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.messages = new Messages3(this._client); + } + create(body, options) { + return this._client.post("/chat/completions", { body, ...options, stream: body.stream ?? false }); + } + /** + * Get a stored chat completion. Only Chat Completions that have been created with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * const chatCompletion = + * await client.chat.completions.retrieve('completion_id'); + * ``` + */ + retrieve(completionID, options) { + return this._client.get(path2`/chat/completions/${completionID}`, options); + } + /** + * Modify a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be modified. Currently, the only + * supported modification is to update the `metadata` field. + * + * @example + * ```ts + * const chatCompletion = await client.chat.completions.update( + * 'completion_id', + * { metadata: { foo: 'string' } }, + * ); + * ``` + */ + update(completionID, body, options) { + return this._client.post(path2`/chat/completions/${completionID}`, { body, ...options }); + } + /** + * List stored Chat Completions. Only Chat Completions that have been stored with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletion of client.chat.completions.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/chat/completions", CursorPage, { query, ...options }); + } + /** + * Delete a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be deleted. + * + * @example + * ```ts + * const chatCompletionDeleted = + * await client.chat.completions.delete('completion_id'); + * ``` + */ + delete(completionID, options) { + return this._client.delete(path2`/chat/completions/${completionID}`, options); + } + parse(body, options) { + validateInputTools(body.tools); + return this._client.chat.completions.create(body, { + ...options, + headers: { + ...options?.headers, + "X-Stainless-Helper-Method": "chat.completions.parse" + } + })._thenUnwrap((completion) => parseChatCompletion(completion, body)); + } + runTools(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner.runTools(this._client, body, options); + } + return ChatCompletionRunner.runTools(this._client, body, options); + } + /** + * Creates a chat completion stream + */ + stream(body, options) { + return ChatCompletionStream.createChatCompletion(this._client, body, options); + } + }; + Completions2.Messages = Messages3; + } +}); + +// ../pi-mono/node_modules/openai/resources/chat/chat.mjs +var Chat; +var init_chat = __esm({ + "../pi-mono/node_modules/openai/resources/chat/chat.mjs"() { + init_process_shim(); + init_resource2(); + init_completions2(); + init_completions2(); + Chat = class extends APIResource2 { + constructor() { + super(...arguments); + this.completions = new Completions2(this._client); + } + }; + Chat.Completions = Completions2; + } +}); + +// ../pi-mono/node_modules/openai/resources/chat/completions/index.mjs +var init_completions3 = __esm({ + "../pi-mono/node_modules/openai/resources/chat/completions/index.mjs"() { + init_process_shim(); + init_completions2(); + init_completions2(); + init_messages3(); + } +}); + +// ../pi-mono/node_modules/openai/resources/chat/index.mjs +var init_chat2 = __esm({ + "../pi-mono/node_modules/openai/resources/chat/index.mjs"() { + init_process_shim(); + init_chat(); + init_completions3(); + } +}); + +// ../pi-mono/node_modules/openai/resources/shared.mjs +var init_shared2 = __esm({ + "../pi-mono/node_modules/openai/resources/shared.mjs"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/openai/internal/headers.mjs +function* iterateHeaders2(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders2 in headers) { + const { values: values2, nulls } = headers; + yield* values2.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray2(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values2 = isReadonlyArray2(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values2) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +var brand_privateNullableHeaders2, buildHeaders2; +var init_headers2 = __esm({ + "../pi-mono/node_modules/openai/internal/headers.mjs"() { + init_process_shim(); + init_values2(); + brand_privateNullableHeaders2 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); + buildHeaders2 = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders2(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders2]: true, values: targetHeaders, nulls: nullHeaders }; + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/audio/speech.mjs +var Speech; +var init_speech = __esm({ + "../pi-mono/node_modules/openai/resources/audio/speech.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + Speech = class extends APIResource2 { + /** + * Generates audio from the input text. + * + * Returns the audio file content, or a stream of audio events. + * + * @example + * ```ts + * const speech = await client.audio.speech.create({ + * input: 'input', + * model: 'string', + * voice: 'ash', + * }); + * + * const content = await speech.blob(); + * console.log(content); + * ``` + */ + create(body, options) { + return this._client.post("/audio/speech", { + body, + ...options, + headers: buildHeaders2([{ Accept: "application/octet-stream" }, options?.headers]), + __binaryResponse: true + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/audio/transcriptions.mjs +var Transcriptions; +var init_transcriptions = __esm({ + "../pi-mono/node_modules/openai/resources/audio/transcriptions.mjs"() { + init_process_shim(); + init_resource2(); + init_uploads3(); + Transcriptions = class extends APIResource2 { + create(body, options) { + return this._client.post("/audio/transcriptions", multipartFormRequestOptions2({ + body, + ...options, + stream: body.stream ?? false, + __metadata: { model: body.model } + }, this._client)); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/audio/translations.mjs +var Translations; +var init_translations = __esm({ + "../pi-mono/node_modules/openai/resources/audio/translations.mjs"() { + init_process_shim(); + init_resource2(); + init_uploads3(); + Translations = class extends APIResource2 { + create(body, options) { + return this._client.post("/audio/translations", multipartFormRequestOptions2({ body, ...options, __metadata: { model: body.model } }, this._client)); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/audio/audio.mjs +var Audio; +var init_audio = __esm({ + "../pi-mono/node_modules/openai/resources/audio/audio.mjs"() { + init_process_shim(); + init_resource2(); + init_speech(); + init_speech(); + init_transcriptions(); + init_transcriptions(); + init_translations(); + init_translations(); + Audio = class extends APIResource2 { + constructor() { + super(...arguments); + this.transcriptions = new Transcriptions(this._client); + this.translations = new Translations(this._client); + this.speech = new Speech(this._client); + } + }; + Audio.Transcriptions = Transcriptions; + Audio.Translations = Translations; + Audio.Speech = Speech; + } +}); + +// ../pi-mono/node_modules/openai/resources/batches.mjs +var Batches3; +var init_batches3 = __esm({ + "../pi-mono/node_modules/openai/resources/batches.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + Batches3 = class extends APIResource2 { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body, options) { + return this._client.post("/batches", { body, ...options }); + } + /** + * Retrieves a batch. + */ + retrieve(batchID, options) { + return this._client.get(path2`/batches/${batchID}`, options); + } + /** + * List your organization's batches. + */ + list(query = {}, options) { + return this._client.getAPIList("/batches", CursorPage, { query, ...options }); + } + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to + * 10 minutes, before changing to `cancelled`, where it will have partial results + * (if any) available in the output file. + */ + cancel(batchID, options) { + return this._client.post(path2`/batches/${batchID}/cancel`, options); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/assistants.mjs +var Assistants; +var init_assistants = __esm({ + "../pi-mono/node_modules/openai/resources/beta/assistants.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_path2(); + Assistants = class extends APIResource2 { + /** + * Create an assistant with a model and instructions. + * + * @deprecated + */ + create(body, options) { + return this._client.post("/assistants", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Retrieves an assistant. + * + * @deprecated + */ + retrieve(assistantID, options) { + return this._client.get(path2`/assistants/${assistantID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Modifies an assistant. + * + * @deprecated + */ + update(assistantID, body, options) { + return this._client.post(path2`/assistants/${assistantID}`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Returns a list of assistants. + * + * @deprecated + */ + list(query = {}, options) { + return this._client.getAPIList("/assistants", CursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Delete an assistant. + * + * @deprecated + */ + delete(assistantID, options) { + return this._client.delete(path2`/assistants/${assistantID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/realtime/sessions.mjs +var Sessions; +var init_sessions = __esm({ + "../pi-mono/node_modules/openai/resources/beta/realtime/sessions.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + Sessions = class extends APIResource2 { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API. Can be configured with the same session parameters as the + * `session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const session = + * await client.beta.realtime.sessions.create(); + * ``` + */ + create(body, options) { + return this._client.post("/realtime/sessions", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +var TranscriptionSessions; +var init_transcription_sessions = __esm({ + "../pi-mono/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + TranscriptionSessions = class extends APIResource2 { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API specifically for realtime transcriptions. Can be configured with + * the same session parameters as the `transcription_session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const transcriptionSession = + * await client.beta.realtime.transcriptionSessions.create(); + * ``` + */ + create(body, options) { + return this._client.post("/realtime/transcription_sessions", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/realtime/realtime.mjs +var Realtime; +var init_realtime = __esm({ + "../pi-mono/node_modules/openai/resources/beta/realtime/realtime.mjs"() { + init_process_shim(); + init_resource2(); + init_sessions(); + init_sessions(); + init_transcription_sessions(); + init_transcription_sessions(); + Realtime = class extends APIResource2 { + constructor() { + super(...arguments); + this.sessions = new Sessions(this._client); + this.transcriptionSessions = new TranscriptionSessions(this._client); + } + }; + Realtime.Sessions = Sessions; + Realtime.TranscriptionSessions = TranscriptionSessions; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/chatkit/sessions.mjs +var Sessions2; +var init_sessions2 = __esm({ + "../pi-mono/node_modules/openai/resources/beta/chatkit/sessions.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + init_path2(); + Sessions2 = class extends APIResource2 { + /** + * Create a ChatKit session. + * + * @example + * ```ts + * const chatSession = + * await client.beta.chatkit.sessions.create({ + * user: 'x', + * workflow: { id: 'id' }, + * }); + * ``` + */ + create(body, options) { + return this._client.post("/chatkit/sessions", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) + }); + } + /** + * Cancel an active ChatKit session and return its most recent metadata. + * + * Cancelling prevents new requests from using the issued client secret. + * + * @example + * ```ts + * const chatSession = + * await client.beta.chatkit.sessions.cancel('cksess_123'); + * ``` + */ + cancel(sessionID, options) { + return this._client.post(path2`/chatkit/sessions/${sessionID}/cancel`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/chatkit/threads.mjs +var Threads; +var init_threads = __esm({ + "../pi-mono/node_modules/openai/resources/beta/chatkit/threads.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_path2(); + Threads = class extends APIResource2 { + /** + * Retrieve a ChatKit thread by its identifier. + * + * @example + * ```ts + * const chatkitThread = + * await client.beta.chatkit.threads.retrieve('cthr_123'); + * ``` + */ + retrieve(threadID, options) { + return this._client.get(path2`/chatkit/threads/${threadID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) + }); + } + /** + * List ChatKit threads with optional pagination and user filters. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatkitThread of client.beta.chatkit.threads.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/chatkit/threads", ConversationCursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) + }); + } + /** + * Delete a ChatKit thread along with its items and stored attachments. + * + * @example + * ```ts + * const thread = await client.beta.chatkit.threads.delete( + * 'cthr_123', + * ); + * ``` + */ + delete(threadID, options) { + return this._client.delete(path2`/chatkit/threads/${threadID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) + }); + } + /** + * List items that belong to a ChatKit thread. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const thread of client.beta.chatkit.threads.listItems( + * 'cthr_123', + * )) { + * // ... + * } + * ``` + */ + listItems(threadID, query = {}, options) { + return this._client.getAPIList(path2`/chatkit/threads/${threadID}/items`, ConversationCursorPage, { query, ...options, headers: buildHeaders2([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]) }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/chatkit/chatkit.mjs +var ChatKit; +var init_chatkit = __esm({ + "../pi-mono/node_modules/openai/resources/beta/chatkit/chatkit.mjs"() { + init_process_shim(); + init_resource2(); + init_sessions2(); + init_sessions2(); + init_threads(); + init_threads(); + ChatKit = class extends APIResource2 { + constructor() { + super(...arguments); + this.sessions = new Sessions2(this._client); + this.threads = new Threads(this._client); + } + }; + ChatKit.Sessions = Sessions2; + ChatKit.Threads = Threads; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/threads/messages.mjs +var Messages4; +var init_messages4 = __esm({ + "../pi-mono/node_modules/openai/resources/beta/threads/messages.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_path2(); + Messages4 = class extends APIResource2 { + /** + * Create a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(threadID, body, options) { + return this._client.post(path2`/threads/${threadID}/messages`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Retrieve a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(messageID, params, options) { + const { thread_id } = params; + return this._client.get(path2`/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Modifies a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(messageID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path2`/threads/${thread_id}/messages/${messageID}`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Returns a list of messages for a given thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path2`/threads/${threadID}/messages`, CursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Deletes a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(messageID, params, options) { + const { thread_id } = params; + return this._client.delete(path2`/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/threads/runs/steps.mjs +var Steps; +var init_steps = __esm({ + "../pi-mono/node_modules/openai/resources/beta/threads/runs/steps.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_path2(); + Steps = class extends APIResource2 { + /** + * Retrieves a run step. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(stepID, params, options) { + const { thread_id, run_id, ...query } = params; + return this._client.get(path2`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Returns a list of run steps belonging to a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(runID, params, options) { + const { thread_id, ...query } = params; + return this._client.getAPIList(path2`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/base64.mjs +var toFloat32Array; +var init_base64 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/base64.mjs"() { + init_process_shim(); + init_error5(); + init_bytes2(); + toFloat32Array = (base64Str) => { + if (typeof Buffer !== "undefined") { + const buf = Buffer.from(base64Str, "base64"); + return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); + } else { + const binaryStr = atob(base64Str); + const len = binaryStr.length; + const bytes = new Uint8Array(len); + for (let i7 = 0; i7 < len; i7++) { + bytes[i7] = binaryStr.charCodeAt(i7); + } + return Array.from(new Float32Array(bytes.buffer)); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils/env.mjs +var readEnv2; +var init_env2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils/env.mjs"() { + init_process_shim(); + readEnv2 = (env) => { + if (typeof globalThis.process !== "undefined") { + return globalThis.process.env?.[env]?.trim() ?? void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return void 0; + }; + } +}); + +// ../pi-mono/node_modules/openai/internal/utils.mjs +var init_utils2 = __esm({ + "../pi-mono/node_modules/openai/internal/utils.mjs"() { + init_process_shim(); + init_values2(); + init_base64(); + init_env2(); + init_log2(); + init_uuid2(); + init_sleep2(); + init_query2(); + } +}); + +// ../pi-mono/node_modules/openai/lib/AssistantStream.mjs +function assertNever2(_x2) { +} +var _AssistantStream_instances, _a2, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun, AssistantStream; +var init_AssistantStream = __esm({ + "../pi-mono/node_modules/openai/lib/AssistantStream.mjs"() { + init_process_shim(); + init_tslib2(); + init_streaming4(); + init_error6(); + init_EventStream(); + init_utils2(); + AssistantStream = class extends EventStream2 { + constructor() { + super(...arguments); + _AssistantStream_instances.add(this); + _AssistantStream_events.set(this, []); + _AssistantStream_runStepSnapshots.set(this, {}); + _AssistantStream_messageSnapshots.set(this, {}); + _AssistantStream_messageSnapshot.set(this, void 0); + _AssistantStream_finalRun.set(this, void 0); + _AssistantStream_currentContentIndex.set(this, void 0); + _AssistantStream_currentContent.set(this, void 0); + _AssistantStream_currentToolCallIndex.set(this, void 0); + _AssistantStream_currentToolCall.set(this, void 0); + _AssistantStream_currentEvent.set(this, void 0); + _AssistantStream_currentRunSnapshot.set(this, void 0); + _AssistantStream_currentRunStepSnapshot.set(this, void 0); + } + [(_AssistantStream_events = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("event", (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } + }); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(void 0); + } + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: void 0, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: void 0, done: true }; + } + }; + } + static fromReadableStream(stream2) { + const runner = new _a2(); + runner._run(() => runner._fromReadableStream(stream2)); + return runner; + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + this._connected(); + const stream2 = Stream2.fromReadableStream(readableStream, this.controller); + for await (const event of stream2) { + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + toReadableStream() { + const stream2 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller); + return stream2.toReadableStream(); + } + static createToolAssistantStream(runId, runs, params, options) { + const runner = new _a2(); + runner._run(() => runner._runToolAssistantStream(runId, runs, params, { + ...options, + headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } + })); + return runner; + } + async _createToolAssistantStream(run, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream2 = await run.submitToolOutputs(runId, body, { + ...options, + signal: this.controller.signal + }); + this._connected(); + for await (const event of stream2) { + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static createThreadAssistantStream(params, thread, options) { + const runner = new _a2(); + runner._run(() => runner._threadAssistantStream(params, thread, { + ...options, + headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } + })); + return runner; + } + static createAssistantStream(threadId, runs, params, options) { + const runner = new _a2(); + runner._run(() => runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } + })); + return runner; + } + currentEvent() { + return __classPrivateFieldGet2(this, _AssistantStream_currentEvent, "f"); + } + currentRun() { + return __classPrivateFieldGet2(this, _AssistantStream_currentRunSnapshot, "f"); + } + currentMessageSnapshot() { + return __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f"); + } + currentRunStepSnapshot() { + return __classPrivateFieldGet2(this, _AssistantStream_currentRunStepSnapshot, "f"); + } + async finalRunSteps() { + await this.done(); + return Object.values(__classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")); + } + async finalMessages() { + await this.done(); + return Object.values(__classPrivateFieldGet2(this, _AssistantStream_messageSnapshots, "f")); + } + async finalRun() { + await this.done(); + if (!__classPrivateFieldGet2(this, _AssistantStream_finalRun, "f")) + throw Error("Final run was not received."); + return __classPrivateFieldGet2(this, _AssistantStream_finalRun, "f"); + } + async _createThreadAssistantStream(thread, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream2 = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream2) { + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream2 = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream2) { + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static accumulateDelta(acc, delta) { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; + } + let accValue = acc[key]; + if (accValue === null || accValue === void 0) { + acc[key] = deltaValue; + continue; + } + if (key === "index" || key === "type") { + acc[key] = deltaValue; + continue; + } + if (typeof accValue === "string" && typeof deltaValue === "string") { + accValue += deltaValue; + } else if (typeof accValue === "number" && typeof deltaValue === "number") { + accValue += deltaValue; + } else if (isObj(accValue) && isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue, deltaValue); + } else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x2) => typeof x2 === "string" || typeof x2 === "number")) { + accValue.push(...deltaValue); + continue; + } + for (const deltaEntry of deltaValue) { + if (!isObj(deltaEntry)) { + throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); + } + const index2 = deltaEntry["index"]; + if (index2 == null) { + console.error(deltaEntry); + throw new Error("Expected array delta entry to have an `index` property"); + } + if (typeof index2 !== "number") { + throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index2}`); + } + const accEntry = accValue[index2]; + if (accEntry == null) { + accValue.push(deltaEntry); + } else { + accValue[index2] = this.accumulateDelta(accEntry, deltaEntry); + } + } + continue; + } else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + } + acc[key] = accValue; + } + return acc; + } + _addRun(run) { + return run; + } + async _threadAssistantStream(params, thread, options) { + return await this._createThreadAssistantStream(thread, params, options); + } + async _runAssistantStream(threadId, runs, params, options) { + return await this._createAssistantStream(runs, threadId, params, options); + } + async _runToolAssistantStream(runId, runs, params, options) { + return await this._createToolAssistantStream(runs, runId, params, options); + } + }; + _a2 = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent2(event) { + if (this.ended) + return; + __classPrivateFieldSet2(this, _AssistantStream_currentEvent, event, "f"); + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + switch (event.event) { + case "thread.created": + break; + case "thread.run.created": + case "thread.run.queued": + case "thread.run.in_progress": + case "thread.run.requires_action": + case "thread.run.completed": + case "thread.run.incomplete": + case "thread.run.failed": + case "thread.run.cancelling": + case "thread.run.cancelled": + case "thread.run.expired": + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + break; + case "thread.run.step.created": + case "thread.run.step.in_progress": + case "thread.run.step.delta": + case "thread.run.step.completed": + case "thread.run.step.failed": + case "thread.run.step.cancelled": + case "thread.run.step.expired": + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + break; + case "thread.message.created": + case "thread.message.in_progress": + case "thread.message.delta": + case "thread.message.completed": + case "thread.message.incomplete": + __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + break; + case "error": + throw new Error("Encountered an error event in event processing - errors should be processed earlier"); + default: + assertNever2(event); + } + }, _AssistantStream_endRequest = function _AssistantStream_endRequest2() { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + if (!__classPrivateFieldGet2(this, _AssistantStream_finalRun, "f")) + throw Error("Final run has not been received"); + return __classPrivateFieldGet2(this, _AssistantStream_finalRun, "f"); + }, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event) { + const [accumulatedMessage, newContent] = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")); + __classPrivateFieldSet2(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + __classPrivateFieldGet2(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == "text") { + this._emit("textCreated", snapshotContent.text); + } + } + switch (event.event) { + case "thread.message.created": + this._emit("messageCreated", event.data); + break; + case "thread.message.in_progress": + break; + case "thread.message.delta": + this._emit("messageDelta", event.data.delta, accumulatedMessage); + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + if (content.type == "text" && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == "text") { + this._emit("textDelta", textDelta, snapshot.text); + } else { + throw Error("The snapshot associated with this text delta is not text or missing"); + } + } + if (content.index != __classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f")) { + if (__classPrivateFieldGet2(this, _AssistantStream_currentContent, "f")) { + switch (__classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").type) { + case "text": + this._emit("textDone", __classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")); + break; + case "image_file": + this._emit("imageFileDone", __classPrivateFieldGet2(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + __classPrivateFieldSet2(this, _AssistantStream_currentContentIndex, content.index, "f"); + } + __classPrivateFieldSet2(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); + } + } + break; + case "thread.message.completed": + case "thread.message.incomplete": + if (__classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f") !== void 0) { + const currentContent = event.data.content[__classPrivateFieldGet2(this, _AssistantStream_currentContentIndex, "f")]; + if (currentContent) { + switch (currentContent.type) { + case "image_file": + this._emit("imageFileDone", currentContent.image_file, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")); + break; + case "text": + this._emit("textDone", currentContent.text, __classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + } + if (__classPrivateFieldGet2(this, _AssistantStream_messageSnapshot, "f")) { + this._emit("messageDone", event.data); + } + __classPrivateFieldSet2(this, _AssistantStream_messageSnapshot, void 0, "f"); + } + }, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event) { + const accumulatedRunStep = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + __classPrivateFieldSet2(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + switch (event.event) { + case "thread.run.step.created": + this._emit("runStepCreated", event.data); + break; + case "thread.run.step.delta": + const delta = event.data.delta; + if (delta.step_details && delta.step_details.type == "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type == "tool_calls") { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == __classPrivateFieldGet2(this, _AssistantStream_currentToolCallIndex, "f")) { + this._emit("toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); + } else { + if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) { + this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")); + } + __classPrivateFieldSet2(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + __classPrivateFieldSet2(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) + this._emit("toolCallCreated", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")); + } + } + } + this._emit("runStepDelta", event.data.delta, accumulatedRunStep); + break; + case "thread.run.step.completed": + case "thread.run.step.failed": + case "thread.run.step.cancelled": + case "thread.run.step.expired": + __classPrivateFieldSet2(this, _AssistantStream_currentRunStepSnapshot, void 0, "f"); + const details = event.data.step_details; + if (details.type == "tool_calls") { + if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) { + this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet2(this, _AssistantStream_currentToolCall, void 0, "f"); + } + } + this._emit("runStepDone", event.data, accumulatedRunStep); + break; + case "thread.run.step.in_progress": + break; + } + }, _AssistantStream_handleEvent = function _AssistantStream_handleEvent2(event) { + __classPrivateFieldGet2(this, _AssistantStream_events, "f").push(event); + this._emit("event", event); + }, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event) { + switch (event.event) { + case "thread.run.step.created": + __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + return event.data; + case "thread.run.step.delta": + let snapshot = __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (!snapshot) { + throw Error("Received a RunStepDelta before creation of a snapshot"); + } + let data = event.data; + if (data.delta) { + const accumulated = _a2.accumulateDelta(snapshot, data.delta); + __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + } + return __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + case "thread.run.step.completed": + case "thread.run.step.failed": + case "thread.run.step.cancelled": + case "thread.run.step.expired": + case "thread.run.step.in_progress": + __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + break; + } + if (__classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) + return __classPrivateFieldGet2(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + throw new Error("No snapshot available"); + }, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage2(event, snapshot) { + let newContent = []; + switch (event.event) { + case "thread.message.created": + return [event.data, newContent]; + case "thread.message.delta": + if (!snapshot) { + throw Error("Received a delta with no existing snapshot (there should be one from message creation)"); + } + let data = event.data; + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = __classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); + } else { + snapshot.content[contentElement.index] = contentElement; + newContent.push(contentElement); + } + } + } + return [snapshot, newContent]; + case "thread.message.in_progress": + case "thread.message.completed": + case "thread.message.incomplete": + if (snapshot) { + return [snapshot, newContent]; + } else { + throw Error("Received thread message event with no existing snapshot"); + } + } + throw Error("Tried to accumulate a non-message event"); + }, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent2(contentElement, currentContent) { + return _a2.accumulateDelta(currentContent, contentElement); + }, _AssistantStream_handleRun = function _AssistantStream_handleRun2(event) { + __classPrivateFieldSet2(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.event) { + case "thread.run.created": + break; + case "thread.run.queued": + break; + case "thread.run.in_progress": + break; + case "thread.run.requires_action": + case "thread.run.cancelled": + case "thread.run.failed": + case "thread.run.completed": + case "thread.run.expired": + case "thread.run.incomplete": + __classPrivateFieldSet2(this, _AssistantStream_finalRun, event.data, "f"); + if (__classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")) { + this._emit("toolCallDone", __classPrivateFieldGet2(this, _AssistantStream_currentToolCall, "f")); + __classPrivateFieldSet2(this, _AssistantStream_currentToolCall, void 0, "f"); + } + break; + case "thread.run.cancelling": + break; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/threads/runs/runs.mjs +var Runs; +var init_runs = __esm({ + "../pi-mono/node_modules/openai/resources/beta/threads/runs/runs.mjs"() { + init_process_shim(); + init_resource2(); + init_steps(); + init_steps(); + init_pagination2(); + init_headers2(); + init_AssistantStream(); + init_sleep2(); + init_path2(); + Runs = class extends APIResource2 { + constructor() { + super(...arguments); + this.steps = new Steps(this._client); + } + create(threadID, params, options) { + const { include, ...body } = params; + return this._client.post(path2`/threads/${threadID}/runs`, { + query: { include }, + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + stream: params.stream ?? false, + __synthesizeEventData: true + }); + } + /** + * Retrieves a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(runID, params, options) { + const { thread_id } = params; + return this._client.get(path2`/threads/${thread_id}/runs/${runID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Modifies a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path2`/threads/${thread_id}/runs/${runID}`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Returns a list of runs belonging to a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path2`/threads/${threadID}/runs`, CursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Cancels a run that is `in_progress`. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + cancel(runID, params, options) { + const { thread_id } = params; + return this._client.post(path2`/threads/${thread_id}/runs/${runID}/cancel`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(run.id, { thread_id: threadId }, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(runId, params, options) { + const headers = buildHeaders2([ + options?.headers, + { + "X-Stainless-Poll-Helper": "true", + "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0 + } + ]); + while (true) { + const { data: run, response } = await this.retrieve(runId, params, { + ...options, + headers: { ...options?.headers, ...headers } + }).withResponse(); + switch (run.status) { + //If we are in any sort of intermediate state we poll + case "queued": + case "in_progress": + case "cancelling": + let sleepInterval = 5e3; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = response.headers.get("openai-poll-after-ms"); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep2(sleepInterval); + break; + //We return the run in any terminal state. + case "requires_action": + case "incomplete": + case "cancelled": + case "completed": + case "failed": + case "expired": + return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path2`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + stream: params.stream ?? false, + __synthesizeEventData: true + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(runId, params, options) { + const run = await this.submitToolOutputs(runId, params, options); + return await this.poll(run.id, params, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(runId, params, options) { + return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); + } + }; + Runs.Steps = Steps; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/threads/threads.mjs +var Threads2; +var init_threads2 = __esm({ + "../pi-mono/node_modules/openai/resources/beta/threads/threads.mjs"() { + init_process_shim(); + init_resource2(); + init_messages4(); + init_messages4(); + init_runs(); + init_runs(); + init_headers2(); + init_AssistantStream(); + init_path2(); + Threads2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.runs = new Runs(this._client); + this.messages = new Messages4(this._client); + } + /** + * Create a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(body = {}, options) { + return this._client.post("/threads", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Retrieves a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(threadID, options) { + return this._client.get(path2`/threads/${threadID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Modifies a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(threadID, body, options) { + return this._client.post(path2`/threads/${threadID}`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Delete a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(threadID, options) { + return this._client.delete(path2`/threads/${threadID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + createAndRun(body, options) { + return this._client.post("/threads/runs", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]), + stream: body.stream ?? false, + __synthesizeEventData: true + }); + } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } + }; + Threads2.Runs = Runs; + Threads2.Messages = Messages4; + } +}); + +// ../pi-mono/node_modules/openai/resources/beta/beta.mjs +var Beta2; +var init_beta2 = __esm({ + "../pi-mono/node_modules/openai/resources/beta/beta.mjs"() { + init_process_shim(); + init_resource2(); + init_assistants(); + init_assistants(); + init_realtime(); + init_realtime(); + init_chatkit(); + init_chatkit(); + init_threads2(); + init_threads2(); + Beta2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.realtime = new Realtime(this._client); + this.chatkit = new ChatKit(this._client); + this.assistants = new Assistants(this._client); + this.threads = new Threads2(this._client); + } + }; + Beta2.Realtime = Realtime; + Beta2.ChatKit = ChatKit; + Beta2.Assistants = Assistants; + Beta2.Threads = Threads2; + } +}); + +// ../pi-mono/node_modules/openai/resources/completions.mjs +var Completions3; +var init_completions4 = __esm({ + "../pi-mono/node_modules/openai/resources/completions.mjs"() { + init_process_shim(); + init_resource2(); + Completions3 = class extends APIResource2 { + create(body, options) { + return this._client.post("/completions", { body, ...options, stream: body.stream ?? false }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/containers/files/content.mjs +var Content; +var init_content = __esm({ + "../pi-mono/node_modules/openai/resources/containers/files/content.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + init_path2(); + Content = class extends APIResource2 { + /** + * Retrieve Container File Content + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path2`/containers/${container_id}/files/${fileID}/content`, { + ...options, + headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]), + __binaryResponse: true + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/containers/files/files.mjs +var Files2; +var init_files2 = __esm({ + "../pi-mono/node_modules/openai/resources/containers/files/files.mjs"() { + init_process_shim(); + init_resource2(); + init_content(); + init_content(); + init_pagination2(); + init_headers2(); + init_uploads3(); + init_path2(); + Files2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.content = new Content(this._client); + } + /** + * Create a Container File + * + * You can send either a multipart/form-data request with the raw file content, or + * a JSON request with a file ID. + */ + create(containerID, body, options) { + return this._client.post(path2`/containers/${containerID}/files`, maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Retrieve Container File + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path2`/containers/${container_id}/files/${fileID}`, options); + } + /** + * List Container files + */ + list(containerID, query = {}, options) { + return this._client.getAPIList(path2`/containers/${containerID}/files`, CursorPage, { + query, + ...options + }); + } + /** + * Delete Container File + */ + delete(fileID, params, options) { + const { container_id } = params; + return this._client.delete(path2`/containers/${container_id}/files/${fileID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + }; + Files2.Content = Content; + } +}); + +// ../pi-mono/node_modules/openai/resources/containers/containers.mjs +var Containers; +var init_containers = __esm({ + "../pi-mono/node_modules/openai/resources/containers/containers.mjs"() { + init_process_shim(); + init_resource2(); + init_files2(); + init_files2(); + init_pagination2(); + init_headers2(); + init_path2(); + Containers = class extends APIResource2 { + constructor() { + super(...arguments); + this.files = new Files2(this._client); + } + /** + * Create Container + */ + create(body, options) { + return this._client.post("/containers", { body, ...options }); + } + /** + * Retrieve Container + */ + retrieve(containerID, options) { + return this._client.get(path2`/containers/${containerID}`, options); + } + /** + * List Containers + */ + list(query = {}, options) { + return this._client.getAPIList("/containers", CursorPage, { query, ...options }); + } + /** + * Delete Container + */ + delete(containerID, options) { + return this._client.delete(path2`/containers/${containerID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + }; + Containers.Files = Files2; + } +}); + +// ../pi-mono/node_modules/openai/resources/conversations/items.mjs +var Items; +var init_items = __esm({ + "../pi-mono/node_modules/openai/resources/conversations/items.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + Items = class extends APIResource2 { + /** + * Create items in a conversation with the given ID. + */ + create(conversationID, params, options) { + const { include, ...body } = params; + return this._client.post(path2`/conversations/${conversationID}/items`, { + query: { include }, + body, + ...options + }); + } + /** + * Get a single item from a conversation with the given IDs. + */ + retrieve(itemID, params, options) { + const { conversation_id, ...query } = params; + return this._client.get(path2`/conversations/${conversation_id}/items/${itemID}`, { query, ...options }); + } + /** + * List all items for a conversation with the given ID. + */ + list(conversationID, query = {}, options) { + return this._client.getAPIList(path2`/conversations/${conversationID}/items`, ConversationCursorPage, { query, ...options }); + } + /** + * Delete an item from a conversation with the given IDs. + */ + delete(itemID, params, options) { + const { conversation_id } = params; + return this._client.delete(path2`/conversations/${conversation_id}/items/${itemID}`, options); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/conversations/conversations.mjs +var Conversations; +var init_conversations = __esm({ + "../pi-mono/node_modules/openai/resources/conversations/conversations.mjs"() { + init_process_shim(); + init_resource2(); + init_items(); + init_items(); + init_path2(); + Conversations = class extends APIResource2 { + constructor() { + super(...arguments); + this.items = new Items(this._client); + } + /** + * Create a conversation. + */ + create(body = {}, options) { + return this._client.post("/conversations", { body, ...options }); + } + /** + * Get a conversation + */ + retrieve(conversationID, options) { + return this._client.get(path2`/conversations/${conversationID}`, options); + } + /** + * Update a conversation + */ + update(conversationID, body, options) { + return this._client.post(path2`/conversations/${conversationID}`, { body, ...options }); + } + /** + * Delete a conversation. Items in the conversation will not be deleted. + */ + delete(conversationID, options) { + return this._client.delete(path2`/conversations/${conversationID}`, options); + } + }; + Conversations.Items = Items; + } +}); + +// ../pi-mono/node_modules/openai/resources/embeddings.mjs +var Embeddings; +var init_embeddings = __esm({ + "../pi-mono/node_modules/openai/resources/embeddings.mjs"() { + init_process_shim(); + init_resource2(); + init_utils2(); + Embeddings = class extends APIResource2 { + /** + * Creates an embedding vector representing the input text. + * + * @example + * ```ts + * const createEmbeddingResponse = + * await client.embeddings.create({ + * input: 'The quick brown fox jumped over the lazy dog', + * model: 'text-embedding-3-small', + * }); + * ``` + */ + create(body, options) { + const hasUserProvidedEncodingFormat = !!body.encoding_format; + let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : "base64"; + if (hasUserProvidedEncodingFormat) { + loggerFor2(this._client).debug("embeddings/user defined encoding_format:", body.encoding_format); + } + const response = this._client.post("/embeddings", { + body: { + ...body, + encoding_format + }, + ...options + }); + if (hasUserProvidedEncodingFormat) { + return response; + } + loggerFor2(this._client).debug("embeddings/decoding base64 embeddings from base64"); + return response._thenUnwrap((response2) => { + if (response2 && response2.data) { + response2.data.forEach((embeddingBase64Obj) => { + const embeddingBase64Str = embeddingBase64Obj.embedding; + embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); + }); + } + return response2; + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/evals/runs/output-items.mjs +var OutputItems; +var init_output_items = __esm({ + "../pi-mono/node_modules/openai/resources/evals/runs/output-items.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + OutputItems = class extends APIResource2 { + /** + * Get an evaluation run output item by ID. + */ + retrieve(outputItemID, params, options) { + const { eval_id, run_id } = params; + return this._client.get(path2`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); + } + /** + * Get a list of output items for an evaluation run. + */ + list(runID, params, options) { + const { eval_id, ...query } = params; + return this._client.getAPIList(path2`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { query, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/evals/runs/runs.mjs +var Runs2; +var init_runs2 = __esm({ + "../pi-mono/node_modules/openai/resources/evals/runs/runs.mjs"() { + init_process_shim(); + init_resource2(); + init_output_items(); + init_output_items(); + init_pagination2(); + init_path2(); + Runs2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.outputItems = new OutputItems(this._client); + } + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what + * model configuration to use to test. The datasource will be validated against the + * schema specified in the config of the evaluation. + */ + create(evalID, body, options) { + return this._client.post(path2`/evals/${evalID}/runs`, { body, ...options }); + } + /** + * Get an evaluation run by ID. + */ + retrieve(runID, params, options) { + const { eval_id } = params; + return this._client.get(path2`/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Get a list of runs for an evaluation. + */ + list(evalID, query = {}, options) { + return this._client.getAPIList(path2`/evals/${evalID}/runs`, CursorPage, { + query, + ...options + }); + } + /** + * Delete an eval run. + */ + delete(runID, params, options) { + const { eval_id } = params; + return this._client.delete(path2`/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Cancel an ongoing evaluation run. + */ + cancel(runID, params, options) { + const { eval_id } = params; + return this._client.post(path2`/evals/${eval_id}/runs/${runID}`, options); + } + }; + Runs2.OutputItems = OutputItems; + } +}); + +// ../pi-mono/node_modules/openai/resources/evals/evals.mjs +var Evals; +var init_evals = __esm({ + "../pi-mono/node_modules/openai/resources/evals/evals.mjs"() { + init_process_shim(); + init_resource2(); + init_runs2(); + init_runs2(); + init_pagination2(); + init_path2(); + Evals = class extends APIResource2 { + constructor() { + super(...arguments); + this.runs = new Runs2(this._client); + } + /** + * Create the structure of an evaluation that can be used to test a model's + * performance. An evaluation is a set of testing criteria and the config for a + * data source, which dictates the schema of the data used in the evaluation. After + * creating an evaluation, you can run it on different models and model parameters. + * We support several types of graders and datasources. For more information, see + * the [Evals guide](https://platform.openai.com/docs/guides/evals). + */ + create(body, options) { + return this._client.post("/evals", { body, ...options }); + } + /** + * Get an evaluation by ID. + */ + retrieve(evalID, options) { + return this._client.get(path2`/evals/${evalID}`, options); + } + /** + * Update certain properties of an evaluation. + */ + update(evalID, body, options) { + return this._client.post(path2`/evals/${evalID}`, { body, ...options }); + } + /** + * List evaluations for a project. + */ + list(query = {}, options) { + return this._client.getAPIList("/evals", CursorPage, { query, ...options }); + } + /** + * Delete an evaluation. + */ + delete(evalID, options) { + return this._client.delete(path2`/evals/${evalID}`, options); + } + }; + Evals.Runs = Runs2; + } +}); + +// ../pi-mono/node_modules/openai/resources/files.mjs +var Files3; +var init_files3 = __esm({ + "../pi-mono/node_modules/openai/resources/files.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_sleep2(); + init_error6(); + init_uploads3(); + init_path2(); + Files3 = class extends APIResource2 { + /** + * Upload a file that can be used across various endpoints. Individual files can be + * up to 512 MB, and each project can store up to 2.5 TB of files in total. There + * is no organization-wide storage limit. + * + * - The Assistants API supports files up to 2 million tokens and of specific file + * types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) + * for details. + * - The Fine-tuning API only supports `.jsonl` files. The input also has certain + * required formats for fine-tuning + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input + * also has a specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body, options) { + return this._client.post("/files", multipartFormRequestOptions2({ body, ...options }, this._client)); + } + /** + * Returns information about a specific file. + */ + retrieve(fileID, options) { + return this._client.get(path2`/files/${fileID}`, options); + } + /** + * Returns a list of files. + */ + list(query = {}, options) { + return this._client.getAPIList("/files", CursorPage, { query, ...options }); + } + /** + * Delete a file and remove it from all vector stores. + */ + delete(fileID, options) { + return this._client.delete(path2`/files/${fileID}`, options); + } + /** + * Returns the contents of the specified file. + */ + content(fileID, options) { + return this._client.get(path2`/files/${fileID}/content`, { + ...options, + headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]), + __binaryResponse: true + }); + } + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) { + const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep2(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new APIConnectionTimeoutError2({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.` + }); + } + } + return file; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/methods.mjs +var Methods; +var init_methods = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/methods.mjs"() { + init_process_shim(); + init_resource2(); + Methods = class extends APIResource2 { + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/alpha/graders.mjs +var Graders; +var init_graders = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/alpha/graders.mjs"() { + init_process_shim(); + init_resource2(); + Graders = class extends APIResource2 { + /** + * Run a grader. + * + * @example + * ```ts + * const response = await client.fineTuning.alpha.graders.run({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * model_sample: 'model_sample', + * }); + * ``` + */ + run(body, options) { + return this._client.post("/fine_tuning/alpha/graders/run", { body, ...options }); + } + /** + * Validate a grader. + * + * @example + * ```ts + * const response = + * await client.fineTuning.alpha.graders.validate({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * }); + * ``` + */ + validate(body, options) { + return this._client.post("/fine_tuning/alpha/graders/validate", { body, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +var Alpha; +var init_alpha = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs"() { + init_process_shim(); + init_resource2(); + init_graders(); + init_graders(); + Alpha = class extends APIResource2 { + constructor() { + super(...arguments); + this.graders = new Graders(this._client); + } + }; + Alpha.Graders = Graders; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +var Permissions; +var init_permissions = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + Permissions = class extends APIResource2 { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList(path2`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page2, { body, method: "post", ...options }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @deprecated Retrieve is deprecated. Please swap to the paginated list method instead. + */ + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get(path2`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTunedModelCheckpoint, query = {}, options) { + return this._client.getAPIList(path2`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, ConversationCursorPage, { query, ...options }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete(path2`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +var Checkpoints; +var init_checkpoints = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs"() { + init_process_shim(); + init_resource2(); + init_permissions(); + init_permissions(); + Checkpoints = class extends APIResource2 { + constructor() { + super(...arguments); + this.permissions = new Permissions(this._client); + } + }; + Checkpoints.Permissions = Permissions; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +var Checkpoints2; +var init_checkpoints2 = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + Checkpoints2 = class extends APIResource2 { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path2`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { query, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +var Jobs; +var init_jobs = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs"() { + init_process_shim(); + init_resource2(); + init_checkpoints2(); + init_checkpoints2(); + init_pagination2(); + init_path2(); + Jobs = class extends APIResource2 { + constructor() { + super(...arguments); + this.checkpoints = new Checkpoints2(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post("/fine_tuning/jobs", { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID, options) { + return this._client.get(path2`/fine_tuning/jobs/${fineTuningJobID}`, options); + } + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList("/fine_tuning/jobs", CursorPage, { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID, options) { + return this._client.post(path2`/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); + } + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path2`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { query, ...options }); + } + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID, options) { + return this._client.post(path2`/fine_tuning/jobs/${fineTuningJobID}/pause`, options); + } + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID, options) { + return this._client.post(path2`/fine_tuning/jobs/${fineTuningJobID}/resume`, options); + } + }; + Jobs.Checkpoints = Checkpoints2; + } +}); + +// ../pi-mono/node_modules/openai/resources/fine-tuning/fine-tuning.mjs +var FineTuning; +var init_fine_tuning = __esm({ + "../pi-mono/node_modules/openai/resources/fine-tuning/fine-tuning.mjs"() { + init_process_shim(); + init_resource2(); + init_methods(); + init_methods(); + init_alpha(); + init_alpha(); + init_checkpoints(); + init_checkpoints(); + init_jobs(); + init_jobs(); + FineTuning = class extends APIResource2 { + constructor() { + super(...arguments); + this.methods = new Methods(this._client); + this.jobs = new Jobs(this._client); + this.checkpoints = new Checkpoints(this._client); + this.alpha = new Alpha(this._client); + } + }; + FineTuning.Methods = Methods; + FineTuning.Jobs = Jobs; + FineTuning.Checkpoints = Checkpoints; + FineTuning.Alpha = Alpha; + } +}); + +// ../pi-mono/node_modules/openai/resources/graders/grader-models.mjs +var GraderModels; +var init_grader_models = __esm({ + "../pi-mono/node_modules/openai/resources/graders/grader-models.mjs"() { + init_process_shim(); + init_resource2(); + GraderModels = class extends APIResource2 { + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/graders/graders.mjs +var Graders2; +var init_graders2 = __esm({ + "../pi-mono/node_modules/openai/resources/graders/graders.mjs"() { + init_process_shim(); + init_resource2(); + init_grader_models(); + init_grader_models(); + Graders2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.graderModels = new GraderModels(this._client); + } + }; + Graders2.GraderModels = GraderModels; + } +}); + +// ../pi-mono/node_modules/openai/resources/images.mjs +var Images; +var init_images = __esm({ + "../pi-mono/node_modules/openai/resources/images.mjs"() { + init_process_shim(); + init_resource2(); + init_uploads3(); + Images = class extends APIResource2 { + /** + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. + * + * @example + * ```ts + * const imagesResponse = await client.images.createVariation({ + * image: fs.createReadStream('otter.png'), + * }); + * ``` + */ + createVariation(body, options) { + return this._client.post("/images/variations", multipartFormRequestOptions2({ body, ...options }, this._client)); + } + edit(body, options) { + return this._client.post("/images/edits", multipartFormRequestOptions2({ body, ...options, stream: body.stream ?? false }, this._client)); + } + generate(body, options) { + return this._client.post("/images/generations", { body, ...options, stream: body.stream ?? false }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/models.mjs +var Models3; +var init_models3 = __esm({ + "../pi-mono/node_modules/openai/resources/models.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + Models3 = class extends APIResource2 { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this._client.get(path2`/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this._client.getAPIList("/models", Page2, options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + delete(model, options) { + return this._client.delete(path2`/models/${model}`, options); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/moderations.mjs +var Moderations; +var init_moderations = __esm({ + "../pi-mono/node_modules/openai/resources/moderations.mjs"() { + init_process_shim(); + init_resource2(); + Moderations = class extends APIResource2 { + /** + * Classifies if text and/or image inputs are potentially harmful. Learn more in + * the [moderation guide](https://platform.openai.com/docs/guides/moderation). + */ + create(body, options) { + return this._client.post("/moderations", { body, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/realtime/calls.mjs +var Calls; +var init_calls = __esm({ + "../pi-mono/node_modules/openai/resources/realtime/calls.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + init_path2(); + Calls = class extends APIResource2 { + /** + * Accept an incoming SIP call and configure the realtime session that will handle + * it. + * + * @example + * ```ts + * await client.realtime.calls.accept('call_id', { + * type: 'realtime', + * }); + * ``` + */ + accept(callID, body, options) { + return this._client.post(path2`/realtime/calls/${callID}/accept`, { + body, + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * End an active Realtime API call, whether it was initiated over SIP or WebRTC. + * + * @example + * ```ts + * await client.realtime.calls.hangup('call_id'); + * ``` + */ + hangup(callID, options) { + return this._client.post(path2`/realtime/calls/${callID}/hangup`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Transfer an active SIP call to a new destination using the SIP REFER verb. + * + * @example + * ```ts + * await client.realtime.calls.refer('call_id', { + * target_uri: 'tel:+14155550123', + * }); + * ``` + */ + refer(callID, body, options) { + return this._client.post(path2`/realtime/calls/${callID}/refer`, { + body, + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + /** + * Decline an incoming SIP call by returning a SIP status code to the caller. + * + * @example + * ```ts + * await client.realtime.calls.reject('call_id'); + * ``` + */ + reject(callID, body = {}, options) { + return this._client.post(path2`/realtime/calls/${callID}/reject`, { + body, + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/realtime/client-secrets.mjs +var ClientSecrets; +var init_client_secrets = __esm({ + "../pi-mono/node_modules/openai/resources/realtime/client-secrets.mjs"() { + init_process_shim(); + init_resource2(); + ClientSecrets = class extends APIResource2 { + /** + * Create a Realtime client secret with an associated session configuration. + * + * Client secrets are short-lived tokens that can be passed to a client app, such + * as a web frontend or mobile client, which grants access to the Realtime API + * without leaking your main API key. You can configure a custom TTL for each + * client secret. + * + * You can also attach session configuration options to the client secret, which + * will be applied to any sessions created using that client secret, but these can + * also be overridden by the client connection. + * + * [Learn more about authentication with client secrets over WebRTC](https://platform.openai.com/docs/guides/realtime-webrtc). + * + * Returns the created client secret and the effective session object. The client + * secret is a string that looks like `ek_1234`. + * + * @example + * ```ts + * const clientSecret = + * await client.realtime.clientSecrets.create(); + * ``` + */ + create(body, options) { + return this._client.post("/realtime/client_secrets", { body, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/realtime/realtime.mjs +var Realtime2; +var init_realtime2 = __esm({ + "../pi-mono/node_modules/openai/resources/realtime/realtime.mjs"() { + init_process_shim(); + init_resource2(); + init_calls(); + init_calls(); + init_client_secrets(); + init_client_secrets(); + Realtime2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.clientSecrets = new ClientSecrets(this._client); + this.calls = new Calls(this._client); + } + }; + Realtime2.ClientSecrets = ClientSecrets; + Realtime2.Calls = Calls; + } +}); + +// ../pi-mono/node_modules/openai/lib/ResponsesParser.mjs +function maybeParseResponse(response, params) { + if (!params || !hasAutoParseableInput2(params)) { + return { + ...response, + output_parsed: null, + output: response.output.map((item) => { + if (item.type === "function_call") { + return { + ...item, + parsed_arguments: null + }; + } + if (item.type === "message") { + return { + ...item, + content: item.content.map((content) => ({ + ...content, + parsed: null + })) + }; + } else { + return item; + } + }) + }; + } + return parseResponse(response, params); +} +function parseResponse(response, params) { + const output = response.output.map((item) => { + if (item.type === "function_call") { + return { + ...item, + parsed_arguments: parseToolCall2(params, item) + }; + } + if (item.type === "message") { + const content = item.content.map((content2) => { + if (content2.type === "output_text") { + return { + ...content2, + parsed: parseTextFormat(params, content2.text) + }; + } + return content2; + }); + return { + ...item, + content + }; + } + return item; + }); + const parsed = Object.assign({}, response, { output }); + if (!Object.getOwnPropertyDescriptor(response, "output_text")) { + addOutputText(parsed); + } + Object.defineProperty(parsed, "output_parsed", { + enumerable: true, + get() { + for (const output2 of parsed.output) { + if (output2.type !== "message") { + continue; + } + for (const content of output2.content) { + if (content.type === "output_text" && content.parsed !== null) { + return content.parsed; + } + } + } + return null; + } + }); + return parsed; +} +function parseTextFormat(params, content) { + if (params.text?.format?.type !== "json_schema") { + return null; + } + if ("$parseRaw" in params.text?.format) { + const text_format = params.text?.format; + return text_format.$parseRaw(content); + } + return JSON.parse(content); +} +function hasAutoParseableInput2(params) { + if (isAutoParsableResponseFormat(params.text?.format)) { + return true; + } + return false; +} +function isAutoParsableTool2(tool) { + return tool?.["$brand"] === "auto-parseable-tool"; +} +function getInputToolByName(input_tools, name) { + return input_tools.find((tool) => tool.type === "function" && tool.name === name); +} +function parseToolCall2(params, toolCall) { + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return { + ...toolCall, + ...toolCall, + parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null + }; +} +function addOutputText(rsp) { + const texts = []; + for (const output of rsp.output) { + if (output.type !== "message") { + continue; + } + for (const content of output.content) { + if (content.type === "output_text") { + texts.push(content.text); + } + } + } + rsp.output_text = texts.join(""); +} +var init_ResponsesParser = __esm({ + "../pi-mono/node_modules/openai/lib/ResponsesParser.mjs"() { + init_process_shim(); + init_error6(); + init_parser3(); + } +}); + +// ../pi-mono/node_modules/openai/lib/responses/ResponseStream.mjs +function finalizeResponse(snapshot, params) { + return maybeParseResponse(snapshot, params); +} +var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse, ResponseStream; +var init_ResponseStream = __esm({ + "../pi-mono/node_modules/openai/lib/responses/ResponseStream.mjs"() { + init_process_shim(); + init_tslib2(); + init_error6(); + init_EventStream(); + init_ResponsesParser(); + ResponseStream = class _ResponseStream extends EventStream2 { + constructor(params) { + super(); + _ResponseStream_instances.add(this); + _ResponseStream_params.set(this, void 0); + _ResponseStream_currentResponseSnapshot.set(this, void 0); + _ResponseStream_finalResponse.set(this, void 0); + __classPrivateFieldSet2(this, _ResponseStream_params, params, "f"); + } + static createResponse(client, params, options) { + const runner = new _ResponseStream(params); + runner._run(() => runner._createOrRetrieveResponse(client, params, { + ...options, + headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } + })); + return runner; + } + async _createOrRetrieveResponse(client, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener("abort", () => this.controller.abort()); + } + __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); + let stream2; + let starting_after = null; + if ("response_id" in params) { + stream2 = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true }); + starting_after = params.starting_after ?? null; + } else { + stream2 = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + } + this._connected(); + for await (const event of stream2) { + __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); + } + if (stream2.controller.signal?.aborted) { + throw new APIUserAbortError2(); + } + return __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + } + [(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest2() { + if (this.ended) + return; + __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, void 0, "f"); + }, _ResponseStream_addEvent = function _ResponseStream_addEvent2(event, starting_after) { + if (this.ended) + return; + const maybeEmit = (name, event2) => { + if (starting_after == null || event2.sequence_number > starting_after) { + this._emit(name, event2); + } + }; + const response = __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); + maybeEmit("event", event); + switch (event.type) { + case "response.output_text.delta": { + const output = response.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === "message") { + const content = output.content[event.content_index]; + if (!content) { + throw new OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== "output_text") { + throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + maybeEmit("response.output_text.delta", { + ...event, + snapshot: content.text + }); + } + break; + } + case "response.function_call_arguments.delta": { + const output = response.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === "function_call") { + maybeEmit("response.function_call_arguments.delta", { + ...event, + snapshot: output.arguments + }); + } + break; + } + default: + maybeEmit(event.type, event); + break; + } + }, _ResponseStream_endRequest = function _ResponseStream_endRequest2() { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet2(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) { + throw new OpenAIError(`request ended without sending any events`); + } + __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, void 0, "f"); + const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet2(this, _ResponseStream_params, "f")); + __classPrivateFieldSet2(this, _ResponseStream_finalResponse, parsedResponse, "f"); + return parsedResponse; + }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse2(event) { + let snapshot = __classPrivateFieldGet2(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) { + if (event.type !== "response.created") { + throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); + } + snapshot = __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + return snapshot; + } + switch (event.type) { + case "response.output_item.added": { + snapshot.output.push(event.item); + break; + } + case "response.content_part.added": { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + const type = output.type; + const part = event.part; + if (type === "message" && part.type !== "reasoning_text") { + output.content.push(part); + } else if (type === "reasoning" && part.type === "reasoning_text") { + if (!output.content) { + output.content = []; + } + output.content.push(part); + } + break; + } + case "response.output_text.delta": { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === "message") { + const content = output.content[event.content_index]; + if (!content) { + throw new OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== "output_text") { + throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case "response.function_call_arguments.delta": { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === "function_call") { + output.arguments += event.delta; + } + break; + } + case "response.reasoning_text.delta": { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === "reasoning") { + const content = output.content?.[event.content_index]; + if (!content) { + throw new OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== "reasoning_text") { + throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case "response.completed": { + __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + break; + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on("event", (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } else { + pushQueue.push(event); + } + }); + this.on("end", () => { + done = true; + for (const reader of readQueue) { + reader.resolve(void 0); + } + readQueue.length = 0; + }); + this.on("abort", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on("error", (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: void 0, done: true }; + } + return new Promise((resolve2, reject) => readQueue.push({ resolve: resolve2, reject })).then((event2) => event2 ? { value: event2, done: false } : { value: void 0, done: true }); + } + const event = pushQueue.shift(); + return { value: event, done: false }; + }, + return: async () => { + this.abort(); + return { value: void 0, done: true }; + } + }; + } + /** + * @returns a promise that resolves with the final Response, or rejects + * if an error occurred or the stream ended prematurely without producing a REsponse. + */ + async finalResponse() { + await this.done(); + const response = __classPrivateFieldGet2(this, _ResponseStream_finalResponse, "f"); + if (!response) + throw new OpenAIError("stream ended without producing a ChatCompletion"); + return response; + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/responses/input-items.mjs +var InputItems; +var init_input_items = __esm({ + "../pi-mono/node_modules/openai/resources/responses/input-items.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_path2(); + InputItems = class extends APIResource2 { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const responseItem of client.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list(responseID, query = {}, options) { + return this._client.getAPIList(path2`/responses/${responseID}/input_items`, CursorPage, { query, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/responses/input-tokens.mjs +var InputTokens; +var init_input_tokens = __esm({ + "../pi-mono/node_modules/openai/resources/responses/input-tokens.mjs"() { + init_process_shim(); + init_resource2(); + InputTokens = class extends APIResource2 { + /** + * Returns input token counts of the request. + * + * Returns an object with `object` set to `response.input_tokens` and an + * `input_tokens` count. + * + * @example + * ```ts + * const response = await client.responses.inputTokens.count(); + * ``` + */ + count(body = {}, options) { + return this._client.post("/responses/input_tokens", { body, ...options }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/responses/responses.mjs +var Responses; +var init_responses = __esm({ + "../pi-mono/node_modules/openai/resources/responses/responses.mjs"() { + init_process_shim(); + init_ResponsesParser(); + init_ResponseStream(); + init_resource2(); + init_input_items(); + init_input_items(); + init_input_tokens(); + init_input_tokens(); + init_headers2(); + init_path2(); + Responses = class extends APIResource2 { + constructor() { + super(...arguments); + this.inputItems = new InputItems(this._client); + this.inputTokens = new InputTokens(this._client); + } + create(body, options) { + return this._client.post("/responses", { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => { + if ("object" in rsp && rsp.object === "response") { + addOutputText(rsp); + } + return rsp; + }); + } + retrieve(responseID, query = {}, options) { + return this._client.get(path2`/responses/${responseID}`, { + query, + ...options, + stream: query?.stream ?? false + })._thenUnwrap((rsp) => { + if ("object" in rsp && rsp.object === "response") { + addOutputText(rsp); + } + return rsp; + }); + } + /** + * Deletes a model response with the given ID. + * + * @example + * ```ts + * await client.responses.delete( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + delete(responseID, options) { + return this._client.delete(path2`/responses/${responseID}`, { + ...options, + headers: buildHeaders2([{ Accept: "*/*" }, options?.headers]) + }); + } + parse(body, options) { + return this._client.responses.create(body, options)._thenUnwrap((response) => parseResponse(response, body)); + } + /** + * Creates a model response stream + */ + stream(body, options) { + return ResponseStream.createResponse(this._client, body, options); + } + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const response = await client.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID, options) { + return this._client.post(path2`/responses/${responseID}/cancel`, options); + } + /** + * Compact a conversation. Returns a compacted response object. + * + * Learn when and how to compact long-running conversations in the + * [conversation state guide](https://platform.openai.com/docs/guides/conversation-state#managing-the-context-window). + * For ZDR-compatible compaction details, see + * [Compaction (advanced)](https://platform.openai.com/docs/guides/conversation-state#compaction-advanced). + * + * @example + * ```ts + * const compactedResponse = await client.responses.compact({ + * model: 'gpt-5.4', + * }); + * ``` + */ + compact(body, options) { + return this._client.post("/responses/compact", { body, ...options }); + } + }; + Responses.InputItems = InputItems; + Responses.InputTokens = InputTokens; + } +}); + +// ../pi-mono/node_modules/openai/resources/skills/content.mjs +var Content2; +var init_content2 = __esm({ + "../pi-mono/node_modules/openai/resources/skills/content.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + init_path2(); + Content2 = class extends APIResource2 { + /** + * Download a skill zip bundle by its ID. + */ + retrieve(skillID, options) { + return this._client.get(path2`/skills/${skillID}/content`, { + ...options, + headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]), + __binaryResponse: true + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/skills/versions/content.mjs +var Content3; +var init_content3 = __esm({ + "../pi-mono/node_modules/openai/resources/skills/versions/content.mjs"() { + init_process_shim(); + init_resource2(); + init_headers2(); + init_path2(); + Content3 = class extends APIResource2 { + /** + * Download a skill version zip bundle. + */ + retrieve(version6, params, options) { + const { skill_id } = params; + return this._client.get(path2`/skills/${skill_id}/versions/${version6}/content`, { + ...options, + headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]), + __binaryResponse: true + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/skills/versions/versions.mjs +var Versions2; +var init_versions2 = __esm({ + "../pi-mono/node_modules/openai/resources/skills/versions/versions.mjs"() { + init_process_shim(); + init_resource2(); + init_content3(); + init_content3(); + init_pagination2(); + init_uploads3(); + init_path2(); + Versions2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.content = new Content3(this._client); + } + /** + * Create a new immutable skill version. + */ + create(skillID, body = {}, options) { + return this._client.post(path2`/skills/${skillID}/versions`, maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Get a specific skill version. + */ + retrieve(version6, params, options) { + const { skill_id } = params; + return this._client.get(path2`/skills/${skill_id}/versions/${version6}`, options); + } + /** + * List skill versions for a skill. + */ + list(skillID, query = {}, options) { + return this._client.getAPIList(path2`/skills/${skillID}/versions`, CursorPage, { + query, + ...options + }); + } + /** + * Delete a skill version. + */ + delete(version6, params, options) { + const { skill_id } = params; + return this._client.delete(path2`/skills/${skill_id}/versions/${version6}`, options); + } + }; + Versions2.Content = Content3; + } +}); + +// ../pi-mono/node_modules/openai/resources/skills/skills.mjs +var Skills2; +var init_skills2 = __esm({ + "../pi-mono/node_modules/openai/resources/skills/skills.mjs"() { + init_process_shim(); + init_resource2(); + init_content2(); + init_content2(); + init_versions2(); + init_versions2(); + init_pagination2(); + init_uploads3(); + init_path2(); + Skills2 = class extends APIResource2 { + constructor() { + super(...arguments); + this.content = new Content2(this._client); + this.versions = new Versions2(this._client); + } + /** + * Create a new skill. + */ + create(body = {}, options) { + return this._client.post("/skills", maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Get a skill by its ID. + */ + retrieve(skillID, options) { + return this._client.get(path2`/skills/${skillID}`, options); + } + /** + * Update the default version pointer for a skill. + */ + update(skillID, body, options) { + return this._client.post(path2`/skills/${skillID}`, { body, ...options }); + } + /** + * List all skills for the current project. + */ + list(query = {}, options) { + return this._client.getAPIList("/skills", CursorPage, { query, ...options }); + } + /** + * Delete a skill by its ID. + */ + delete(skillID, options) { + return this._client.delete(path2`/skills/${skillID}`, options); + } + }; + Skills2.Content = Content2; + Skills2.Versions = Versions2; + } +}); + +// ../pi-mono/node_modules/openai/resources/uploads/parts.mjs +var Parts; +var init_parts = __esm({ + "../pi-mono/node_modules/openai/resources/uploads/parts.mjs"() { + init_process_shim(); + init_resource2(); + init_uploads3(); + init_path2(); + Parts = class extends APIResource2 { + /** + * Adds a + * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + * A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + * maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended + * order of the Parts when you + * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + */ + create(uploadID, body, options) { + return this._client.post(path2`/uploads/${uploadID}/parts`, multipartFormRequestOptions2({ body, ...options }, this._client)); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/uploads/uploads.mjs +var Uploads; +var init_uploads5 = __esm({ + "../pi-mono/node_modules/openai/resources/uploads/uploads.mjs"() { + init_process_shim(); + init_resource2(); + init_parts(); + init_parts(); + init_path2(); + Uploads = class extends APIResource2 { + constructor() { + super(...arguments); + this.parts = new Parts(this._client); + } + /** + * Creates an intermediate + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + * that you can add + * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an hour + * after you create it. + * + * Once you complete the Upload, we will create a + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * contains all the parts you uploaded. This File is usable in the rest of our + * platform as a regular File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. Please + * refer to documentation for the + * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please follow + * the documentation on + * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + * + * Returns the Upload object with status `pending`. + */ + create(body, options) { + return this._client.post("/uploads", { body, ...options }); + } + /** + * Cancels the Upload. No Parts may be added after an Upload is cancelled. + * + * Returns the Upload object with status `cancelled`. + */ + cancel(uploadID, options) { + return this._client.post(path2`/uploads/${uploadID}/cancel`, options); + } + /** + * Completes the + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part + * IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes + * initially specified when creating the Upload object. No Parts may be added after + * an Upload is completed. Returns the Upload object with status `completed`, + * including an additional `file` property containing the created usable File + * object. + */ + complete(uploadID, body, options) { + return this._client.post(path2`/uploads/${uploadID}/complete`, { body, ...options }); + } + }; + Uploads.Parts = Parts; + } +}); + +// ../pi-mono/node_modules/openai/lib/Util.mjs +var allSettledWithThrow; +var init_Util = __esm({ + "../pi-mono/node_modules/openai/lib/Util.mjs"() { + init_process_shim(); + allSettledWithThrow = async (promises) => { + const results = await Promise.allSettled(promises); + const rejected = results.filter((result) => result.status === "rejected"); + if (rejected.length) { + for (const result of rejected) { + console.error(result.reason); + } + throw new Error(`${rejected.length} promise(s) failed - see the above errors`); + } + const values2 = []; + for (const result of results) { + if (result.status === "fulfilled") { + values2.push(result.value); + } + } + return values2; + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/vector-stores/file-batches.mjs +var FileBatches; +var init_file_batches = __esm({ + "../pi-mono/node_modules/openai/resources/vector-stores/file-batches.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_sleep2(); + init_Util(); + init_path2(); + FileBatches = class extends APIResource2 { + /** + * Create a vector store file batch. + */ + create(vectorStoreID, body, options) { + return this._client.post(path2`/vector_stores/${vectorStoreID}/file_batches`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Retrieves a vector store file batch. + */ + retrieve(batchID, params, options) { + const { vector_store_id } = params; + return this._client.get(path2`/vector_stores/${vector_store_id}/file_batches/${batchID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Cancel a vector store file batch. This attempts to cancel the processing of + * files in this batch as soon as possible. + */ + cancel(batchID, params, options) { + const { vector_store_id } = params; + return this._client.post(path2`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Create a vector store batch and poll until all files have been processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const batch = await this.create(vectorStoreId, body); + return await this.poll(vectorStoreId, batch.id, options); + } + /** + * Returns a list of vector store files in a batch. + */ + listFiles(batchID, params, options) { + const { vector_store_id, ...query } = params; + return this._client.getAPIList(path2`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, { query, ...options, headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) }); + } + /** + * Wait for the given file batch to be processed. + * + * Note: this will return even if one of the files failed to process, you need to + * check batch.file_counts.failed_count to handle this case. + */ + async poll(vectorStoreID, batchID, options) { + const headers = buildHeaders2([ + options?.headers, + { + "X-Stainless-Poll-Helper": "true", + "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0 + } + ]); + while (true) { + const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { + ...options, + headers + }).withResponse(); + switch (batch.status) { + case "in_progress": + let sleepInterval = 5e3; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = response.headers.get("openai-poll-after-ms"); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep2(sleepInterval); + break; + case "failed": + case "cancelled": + case "completed": + return batch; + } + } + } + /** + * Uploads the given files concurrently and then creates a vector store file batch. + * + * The concurrency limit is configurable using the `maxConcurrency` parameter. + */ + async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { + if (files == null || files.length == 0) { + throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); + } + const configuredConcurrency = options?.maxConcurrency ?? 5; + const concurrencyLimit = Math.min(configuredConcurrency, files.length); + const client = this._client; + const fileIterator = files.values(); + const allFileIds = [...fileIds]; + async function processFiles(iterator) { + for (let item of iterator) { + const fileObj = await client.files.create({ file: item, purpose: "assistants" }, options); + allFileIds.push(fileObj.id); + } + } + const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); + await allSettledWithThrow(workers); + return await this.createAndPoll(vectorStoreId, { + file_ids: allFileIds + }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/vector-stores/files.mjs +var Files4; +var init_files4 = __esm({ + "../pi-mono/node_modules/openai/resources/vector-stores/files.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_utils2(); + init_path2(); + Files4 = class extends APIResource2 { + /** + * Create a vector store file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). + */ + create(vectorStoreID, body, options) { + return this._client.post(path2`/vector_stores/${vectorStoreID}/files`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Retrieves a vector store file. + */ + retrieve(fileID, params, options) { + const { vector_store_id } = params; + return this._client.get(path2`/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Update attributes on a vector store file. + */ + update(fileID, params, options) { + const { vector_store_id, ...body } = params; + return this._client.post(path2`/vector_stores/${vector_store_id}/files/${fileID}`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Returns a list of vector store files. + */ + list(vectorStoreID, query = {}, options) { + return this._client.getAPIList(path2`/vector_stores/${vectorStoreID}/files`, CursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Delete a vector store file. This will remove the file from the vector store but + * the file itself will not be deleted. To delete the file, use the + * [delete file](https://platform.openai.com/docs/api-reference/files/delete) + * endpoint. + */ + delete(fileID, params, options) { + const { vector_store_id } = params; + return this._client.delete(path2`/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Attach a file to the given vector store and wait for it to be processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const file = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file.id, options); + } + /** + * Wait for the vector store file to finish processing. + * + * Note: this will return even if the file failed to process, you need to check + * file.last_error and file.status to handle these cases + */ + async poll(vectorStoreID, fileID, options) { + const headers = buildHeaders2([ + options?.headers, + { + "X-Stainless-Poll-Helper": "true", + "X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0 + } + ]); + while (true) { + const fileResponse = await this.retrieve(fileID, { + vector_store_id: vectorStoreID + }, { ...options, headers }).withResponse(); + const file = fileResponse.data; + switch (file.status) { + case "in_progress": + let sleepInterval = 5e3; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } else { + const headerInterval = fileResponse.response.headers.get("openai-poll-after-ms"); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep2(sleepInterval); + break; + case "failed": + case "completed": + return file; + } + } + } + /** + * Upload a file to the `files` API and then attach it to the given vector store. + * + * Note the file will be asynchronously processed (you can use the alternative + * polling helper method to wait for processing to complete). + */ + async upload(vectorStoreId, file, options) { + const fileInfo = await this._client.files.create({ file, purpose: "assistants" }, options); + return this.create(vectorStoreId, { file_id: fileInfo.id }, options); + } + /** + * Add a file to a vector store and poll until processing is complete. + */ + async uploadAndPoll(vectorStoreId, file, options) { + const fileInfo = await this.upload(vectorStoreId, file, options); + return await this.poll(vectorStoreId, fileInfo.id, options); + } + /** + * Retrieve the parsed contents of a vector store file. + */ + content(fileID, params, options) { + const { vector_store_id } = params; + return this._client.getAPIList(path2`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page2, { ...options, headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) }); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/vector-stores/vector-stores.mjs +var VectorStores; +var init_vector_stores = __esm({ + "../pi-mono/node_modules/openai/resources/vector-stores/vector-stores.mjs"() { + init_process_shim(); + init_resource2(); + init_file_batches(); + init_file_batches(); + init_files4(); + init_files4(); + init_pagination2(); + init_headers2(); + init_path2(); + VectorStores = class extends APIResource2 { + constructor() { + super(...arguments); + this.files = new Files4(this._client); + this.fileBatches = new FileBatches(this._client); + } + /** + * Create a vector store. + */ + create(body, options) { + return this._client.post("/vector_stores", { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Retrieves a vector store. + */ + retrieve(vectorStoreID, options) { + return this._client.get(path2`/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Modifies a vector store. + */ + update(vectorStoreID, body, options) { + return this._client.post(path2`/vector_stores/${vectorStoreID}`, { + body, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Returns a list of vector stores. + */ + list(query = {}, options) { + return this._client.getAPIList("/vector_stores", CursorPage, { + query, + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Delete a vector store. + */ + delete(vectorStoreID, options) { + return this._client.delete(path2`/vector_stores/${vectorStoreID}`, { + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + /** + * Search a vector store for relevant chunks based on a query and file attributes + * filter. + */ + search(vectorStoreID, body, options) { + return this._client.getAPIList(path2`/vector_stores/${vectorStoreID}/search`, Page2, { + body, + method: "post", + ...options, + headers: buildHeaders2([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]) + }); + } + }; + VectorStores.Files = Files4; + VectorStores.FileBatches = FileBatches; + } +}); + +// ../pi-mono/node_modules/openai/resources/videos.mjs +var Videos; +var init_videos = __esm({ + "../pi-mono/node_modules/openai/resources/videos.mjs"() { + init_process_shim(); + init_resource2(); + init_pagination2(); + init_headers2(); + init_uploads3(); + init_path2(); + Videos = class extends APIResource2 { + /** + * Create a new video generation job from a prompt and optional reference assets. + */ + create(body, options) { + return this._client.post("/videos", maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Fetch the latest metadata for a generated video. + */ + retrieve(videoID, options) { + return this._client.get(path2`/videos/${videoID}`, options); + } + /** + * List recently generated videos for the current project. + */ + list(query = {}, options) { + return this._client.getAPIList("/videos", ConversationCursorPage, { query, ...options }); + } + /** + * Permanently delete a completed or failed video and its stored assets. + */ + delete(videoID, options) { + return this._client.delete(path2`/videos/${videoID}`, options); + } + /** + * Download the generated video bytes or a derived preview asset. + * + * Streams the rendered video content for the specified video job. + */ + downloadContent(videoID, query = {}, options) { + return this._client.get(path2`/videos/${videoID}/content`, { + query, + ...options, + headers: buildHeaders2([{ Accept: "application/binary" }, options?.headers]), + __binaryResponse: true + }); + } + /** + * Create a remix of a completed video using a refreshed prompt. + */ + remix(videoID, body, options) { + return this._client.post(path2`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/webhooks/webhooks.mjs +var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader, Webhooks; +var init_webhooks = __esm({ + "../pi-mono/node_modules/openai/resources/webhooks/webhooks.mjs"() { + init_process_shim(); + init_tslib2(); + init_error6(); + init_resource2(); + init_headers2(); + Webhooks = class extends APIResource2 { + constructor() { + super(...arguments); + _Webhooks_instances.add(this); + } + /** + * Validates that the given payload was sent by OpenAI and parses the payload. + */ + async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + await this.verifySignature(payload, headers, secret, tolerance); + return JSON.parse(payload); + } + /** + * Validates whether or not the webhook payload was sent by OpenAI. + * + * An error will be raised if the webhook payload was not sent by OpenAI. + * + * @param payload - The webhook payload + * @param headers - The webhook headers + * @param secret - The webhook secret (optional, will use client secret if not provided) + * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) + */ + async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + if (typeof crypto === "undefined" || typeof crypto.subtle.importKey !== "function" || typeof crypto.subtle.verify !== "function") { + throw new Error("Webhook signature verification is only supported when the `crypto` global is defined"); + } + __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); + const headersObj = buildHeaders2([headers]).values; + const signatureHeader = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature"); + const timestamp = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp"); + const webhookId = __classPrivateFieldGet2(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id"); + const timestampSeconds = parseInt(timestamp, 10); + if (isNaN(timestampSeconds)) { + throw new InvalidWebhookSignatureError("Invalid webhook timestamp format"); + } + const nowSeconds = Math.floor(Date.now() / 1e3); + if (nowSeconds - timestampSeconds > tolerance) { + throw new InvalidWebhookSignatureError("Webhook timestamp is too old"); + } + if (timestampSeconds > nowSeconds + tolerance) { + throw new InvalidWebhookSignatureError("Webhook timestamp is too new"); + } + const signatures = signatureHeader.split(" ").map((part) => part.startsWith("v1,") ? part.substring(3) : part); + const decodedSecret = secret.startsWith("whsec_") ? Buffer.from(secret.replace("whsec_", ""), "base64") : Buffer.from(secret, "utf-8"); + const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]); + for (const signature of signatures) { + try { + const signatureBytes = Buffer.from(signature, "base64"); + const isValid3 = await crypto.subtle.verify("HMAC", key, signatureBytes, new TextEncoder().encode(signedPayload)); + if (isValid3) { + return; + } + } catch { + continue; + } + } + throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature"); + } + }; + _Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) { + if (typeof secret !== "string" || secret.length === 0) { + throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); + } + }, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader2(headers, name) { + if (!headers) { + throw new Error(`Headers are required`); + } + const value = headers.get(name); + if (value === null || value === void 0) { + throw new Error(`Missing required header: ${name}`); + } + return value; + }; + } +}); + +// ../pi-mono/node_modules/openai/resources/webhooks/index.mjs +var init_webhooks2 = __esm({ + "../pi-mono/node_modules/openai/resources/webhooks/index.mjs"() { + init_process_shim(); + init_webhooks(); + } +}); + +// ../pi-mono/node_modules/openai/resources/webhooks.mjs +var init_webhooks3 = __esm({ + "../pi-mono/node_modules/openai/resources/webhooks.mjs"() { + init_process_shim(); + init_webhooks2(); + } +}); + +// ../pi-mono/node_modules/openai/resources/index.mjs +var init_resources2 = __esm({ + "../pi-mono/node_modules/openai/resources/index.mjs"() { + init_process_shim(); + init_chat2(); + init_shared2(); + init_audio(); + init_batches3(); + init_beta2(); + init_completions4(); + init_containers(); + init_conversations(); + init_embeddings(); + init_evals(); + init_files3(); + init_fine_tuning(); + init_graders2(); + init_images(); + init_models3(); + init_moderations(); + init_realtime2(); + init_responses(); + init_skills2(); + init_uploads5(); + init_vector_stores(); + init_videos(); + init_webhooks3(); + } +}); + +// ../pi-mono/node_modules/openai/client.mjs +var _OpenAI_instances, _a3, _OpenAI_encoder, _OpenAI_baseURLOverridden, OpenAI; +var init_client2 = __esm({ + "../pi-mono/node_modules/openai/client.mjs"() { + init_process_shim(); + init_tslib2(); + init_uuid2(); + init_values2(); + init_sleep2(); + init_errors2(); + init_detect_platform2(); + init_shims2(); + init_request_options2(); + init_query2(); + init_version2(); + init_error5(); + init_pagination2(); + init_uploads4(); + init_resources2(); + init_api_promise2(); + init_batches3(); + init_completions4(); + init_embeddings(); + init_files3(); + init_images(); + init_models3(); + init_moderations(); + init_videos(); + init_audio(); + init_beta2(); + init_chat(); + init_containers(); + init_conversations(); + init_evals(); + init_fine_tuning(); + init_graders2(); + init_realtime2(); + init_responses(); + init_skills2(); + init_uploads5(); + init_vector_stores(); + init_webhooks(); + init_detect_platform2(); + init_headers2(); + init_env2(); + init_log2(); + init_values2(); + OpenAI = class { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] + * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv2("OPENAI_BASE_URL"), apiKey = readEnv2("OPENAI_API_KEY"), organization = readEnv2("OPENAI_ORG_ID") ?? null, project = readEnv2("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv2("OPENAI_WEBHOOK_SECRET") ?? null, ...opts } = {}) { + _OpenAI_instances.add(this); + _OpenAI_encoder.set(this, void 0); + this.completions = new Completions3(this); + this.chat = new Chat(this); + this.embeddings = new Embeddings(this); + this.files = new Files3(this); + this.images = new Images(this); + this.audio = new Audio(this); + this.moderations = new Moderations(this); + this.models = new Models3(this); + this.fineTuning = new FineTuning(this); + this.graders = new Graders2(this); + this.vectorStores = new VectorStores(this); + this.webhooks = new Webhooks(this); + this.beta = new Beta2(this); + this.batches = new Batches3(this); + this.uploads = new Uploads(this); + this.responses = new Responses(this); + this.realtime = new Realtime2(this); + this.conversations = new Conversations(this); + this.evals = new Evals(this); + this.containers = new Containers(this); + this.skills = new Skills2(this); + this.videos = new Videos(this); + if (apiKey === void 0) { + throw new OpenAIError("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable."); + } + const options = { + apiKey, + organization, + project, + webhookSecret, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1` + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser2()) { + throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? _a3.DEFAULT_TIMEOUT; + this.logger = options.logger ?? console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel2(readEnv2("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch2(); + __classPrivateFieldSet2(this, _OpenAI_encoder, FallbackEncoder2, "f"); + this._options = options; + this.apiKey = typeof apiKey === "string" ? apiKey : "Missing Key"; + this.organization = organization; + this.project = project; + this.webhookSecret = webhookSecret; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + organization: this.organization, + project: this.project, + webhookSecret: this.webhookSecret, + ...options + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values: values2, nulls }) { + return; + } + async authHeaders(opts) { + return buildHeaders2([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringifyQuery(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION2}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid42()}`; + } + makeStatusError(status, error, message, headers) { + return APIError2.generate(status, error, message, headers); + } + async _callApiKey() { + const apiKey = this._options.apiKey; + if (typeof apiKey !== "function") + return false; + let token; + try { + token = await apiKey(); + } catch (err) { + if (err instanceof OpenAIError) + throw err; + throw new OpenAIError( + `Failed to get token from 'apiKey' function: ${err.message}`, + // @ts-ignore + { cause: err } + ); + } + if (typeof token !== "string" || !token) { + throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`); + } + this.apiKey = token; + return true; + } + buildURL(path6, query, defaultBaseURL) { + const baseURL = !__classPrivateFieldGet2(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL2(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj2(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + await this._callApiKey(); + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path6, opts) { + return this.methodRequest("get", path6, opts); + } + post(path6, opts) { + return this.methodRequest("post", path6, opts); + } + patch(path6, opts) { + return this.methodRequest("patch", path6, opts); + } + put(path6, opts) { + return this.methodRequest("put", path6, opts); + } + delete(path6, opts) { + return this.methodRequest("delete", path6, opts); + } + methodRequest(method, path6, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return { method, path: path6, ...opts2 }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor2(this).debug(`[${requestLogID}] sending request`, formatRequestDetails2({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if (options.signal?.aborted) { + throw new APIUserAbortError2(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError2); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError2(); + } + const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails2({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError2(); + } + throw new APIConnectionError2({ cause: response }); + } + const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join(""); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream2(response.body); + loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor2(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError2(err2).message); + const errJSON = safeJSON2(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor2(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor2(this).info(responseInfo); + loggerFor2(this).debug(`[${requestLogID}] response start`, formatRequestDetails2({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path6, Page3, opts) { + return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path6, ...opts2 })) : { method: "get", path: path6, ...opts }); + } + requestAPIList(Page3, options) { + const request = this.makeRequest(options, null, void 0); + return new PagePromise2(this, request, Page3); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = { + signal: controller.signal, + ...isReadableBody ? { duplex: "half" } : {}, + method: "GET", + ...options + }; + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders?.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (timeoutMillis === void 0) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep2(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path: path6, query, defaultBaseURL } = options; + const url = this.buildURL(path6, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger2("timeout", options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...options.signal && { signal: options.signal }, + ...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }, + ...body && { body }, + ...this.fetchOptions ?? {}, + ...options.fetchOptions ?? {} + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders2([ + idempotencyHeaders, + { + Accept: "application/json", + "User-Agent": this.getUserAgent(), + "X-Stainless-Retry-Count": String(retryCount), + ...options.timeout ? { "X-Stainless-Timeout": String(Math.trunc(options.timeout / 1e3)) } : {}, + ...getPlatformHeaders2(), + "OpenAI-Organization": this.organization, + "OpenAI-Project": this.project + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders2([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return __classPrivateFieldGet2(this, _OpenAI_encoder, "f").call(this, { body, headers }); + } + } + }; + _a3 = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() { + return this.baseURL !== "https://api.openai.com/v1"; + }; + OpenAI.OpenAI = _a3; + OpenAI.DEFAULT_TIMEOUT = 6e5; + OpenAI.OpenAIError = OpenAIError; + OpenAI.APIError = APIError2; + OpenAI.APIConnectionError = APIConnectionError2; + OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError2; + OpenAI.APIUserAbortError = APIUserAbortError2; + OpenAI.NotFoundError = NotFoundError2; + OpenAI.ConflictError = ConflictError2; + OpenAI.RateLimitError = RateLimitError2; + OpenAI.BadRequestError = BadRequestError2; + OpenAI.AuthenticationError = AuthenticationError2; + OpenAI.InternalServerError = InternalServerError2; + OpenAI.PermissionDeniedError = PermissionDeniedError2; + OpenAI.UnprocessableEntityError = UnprocessableEntityError2; + OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; + OpenAI.toFile = toFile2; + OpenAI.Completions = Completions3; + OpenAI.Chat = Chat; + OpenAI.Embeddings = Embeddings; + OpenAI.Files = Files3; + OpenAI.Images = Images; + OpenAI.Audio = Audio; + OpenAI.Moderations = Moderations; + OpenAI.Models = Models3; + OpenAI.FineTuning = FineTuning; + OpenAI.Graders = Graders2; + OpenAI.VectorStores = VectorStores; + OpenAI.Webhooks = Webhooks; + OpenAI.Beta = Beta2; + OpenAI.Batches = Batches3; + OpenAI.Uploads = Uploads; + OpenAI.Responses = Responses; + OpenAI.Realtime = Realtime2; + OpenAI.Conversations = Conversations; + OpenAI.Evals = Evals; + OpenAI.Containers = Containers; + OpenAI.Skills = Skills2; + OpenAI.Videos = Videos; + } +}); + +// ../pi-mono/node_modules/openai/azure.mjs +var AzureOpenAI, _deployments_endpoints; +var init_azure = __esm({ + "../pi-mono/node_modules/openai/azure.mjs"() { + init_process_shim(); + init_headers2(); + init_error6(); + init_utils2(); + init_client2(); + AzureOpenAI = class extends OpenAI { + /** + * API Client for interfacing with the Azure OpenAI API. + * + * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] + * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` + * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] + * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv2("OPENAI_BASE_URL"), apiKey = readEnv2("AZURE_OPENAI_API_KEY"), apiVersion = readEnv2("OPENAI_API_VERSION"), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { + if (!apiVersion) { + throw new OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); + } + if (typeof azureADTokenProvider === "function") { + dangerouslyAllowBrowser = true; + } + if (!azureADTokenProvider && !apiKey) { + throw new OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable."); + } + if (azureADTokenProvider && apiKey) { + throw new OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time."); + } + opts.defaultQuery = { ...opts.defaultQuery, "api-version": apiVersion }; + if (!baseURL) { + if (!endpoint) { + endpoint = process.env["AZURE_OPENAI_ENDPOINT"]; + } + if (!endpoint) { + throw new OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable"); + } + baseURL = `${endpoint}/openai`; + } else { + if (endpoint) { + throw new OpenAIError("baseURL and endpoint are mutually exclusive"); + } + } + super({ + apiKey: azureADTokenProvider ?? apiKey, + baseURL, + ...opts, + ...dangerouslyAllowBrowser !== void 0 ? { dangerouslyAllowBrowser } : {} + }); + this.apiVersion = ""; + this.apiVersion = apiVersion; + this.deploymentName = deployment; + } + async buildRequest(options, props = {}) { + if (_deployments_endpoints.has(options.path) && options.method === "post" && options.body !== void 0) { + if (!isObj(options.body)) { + throw new Error("Expected request body to be an object"); + } + const model = this.deploymentName || options.body["model"] || options.__metadata?.["model"]; + if (model !== void 0 && !this.baseURL.includes("/deployments")) { + options.path = `/deployments/${model}${options.path}`; + } + } + return super.buildRequest(options, props); + } + async authHeaders(opts) { + if (typeof this._options.apiKey === "string") { + return buildHeaders2([{ "api-key": this.apiKey }]); + } + return super.authHeaders(opts); + } + }; + _deployments_endpoints = /* @__PURE__ */ new Set([ + "/completions", + "/chat/completions", + "/embeddings", + "/audio/transcriptions", + "/audio/translations", + "/audio/speech", + "/images/generations", + "/batches", + "/images/edits" + ]); + } +}); + +// ../pi-mono/node_modules/openai/index.mjs +var init_openai = __esm({ + "../pi-mono/node_modules/openai/index.mjs"() { + init_process_shim(); + init_client2(); + init_uploads4(); + init_api_promise2(); + init_client2(); + init_pagination2(); + init_error5(); + init_azure(); + } +}); + +// ../pi-mono/node_modules/retry/lib/retry_operation.js +var require_retry_operation = __commonJS({ + "../pi-mono/node_modules/retry/lib/retry_operation.js"(exports, module) { + init_process_shim(); + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.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); + } + } + module.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = function(fn) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i7 = 0; i7 < this._errors.length; i7++) { + var error = this._errors[i7]; + var message = error.message; + var count = (counts[message] || 0) + 1; + counts[message] = count; + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; + } + } + return mainError; + }; + } +}); + +// ../pi-mono/node_modules/retry/lib/retry.js +var require_retry = __commonJS({ + "../pi-mono/node_modules/retry/lib/retry.js"(exports) { + init_process_shim(); + var RetryOperation = require_retry_operation(); + exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); + }; + exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i7 = 0; i7 < opts.retries; i7++) { + timeouts.push(this.createTimeout(i7, opts)); + } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i7, opts)); + } + timeouts.sort(function(a3, b4) { + return a3 - b4; + }); + return timeouts; + }; + exports.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports.wrap = function(obj, options, methods2) { + if (options instanceof Array) { + methods2 = options; + options = null; + } + if (!methods2) { + methods2 = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods2.push(key); + } + } + } + for (var i7 = 0; i7 < methods2.length; i7++) { + var method = methods2[i7]; + var original = obj[method]; + obj[method] = function retryWrapper(original2) { + var op2 = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback2 = args.pop(); + args.push(function(err) { + if (op2.retry(err)) { + return; + } + if (err) { + arguments[0] = op2.mainError(); + } + callback2.apply(this, arguments); + }); + op2.attempt(function() { + original2.apply(obj, args); + }); + }.bind(obj, original); + obj[method].options = options; + } + }; + } +}); + +// ../pi-mono/node_modules/retry/index.js +var require_retry2 = __commonJS({ + "../pi-mono/node_modules/retry/index.js"(exports, module) { + init_process_shim(); + module.exports = require_retry(); + } +}); + +// ../pi-mono/node_modules/p-retry/index.js +var require_p_retry = __commonJS({ + "../pi-mono/node_modules/p-retry/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var retry = require_retry2(); + var networkErrorMsgs = [ + "Failed to fetch", + // Chrome + "NetworkError when attempting to fetch resource.", + // Firefox + "The Internet connection appears to be offline.", + // Safari + "Network request failed" + // `cross-fetch` + ]; + var AbortError2 = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } + }; + var decorateErrorWithCounts = (error, attemptNumber, options) => { + const retriesLeft = options.retries - (attemptNumber - 1); + error.attemptNumber = attemptNumber; + error.retriesLeft = retriesLeft; + return error; + }; + var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); + var pRetry2 = (input, options) => new Promise((resolve2, reject) => { + options = { + onFailedAttempt: () => { + }, + retries: 10, + ...options + }; + const operation = retry.operation(options); + operation.attempt(async (attemptNumber) => { + try { + resolve2(await input(attemptNumber)); + } catch (error) { + if (!(error instanceof Error)) { + reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); + return; + } + if (error instanceof AbortError2) { + operation.stop(); + reject(error.originalError); + } else if (error instanceof TypeError && !isNetworkError(error.message)) { + operation.stop(); + reject(error); + } else { + decorateErrorWithCounts(error, attemptNumber, options); + try { + await options.onFailedAttempt(error); + } catch (error2) { + reject(error2); + return; + } + if (!operation.retry(error)) { + reject(operation.mainError()); + } + } + } + }); + }); + module.exports = pRetry2; + module.exports.default = pRetry2; + module.exports.AbortError = AbortError2; + } +}); + +// ../pi-mono/node_modules/@google/genai/dist/web/index.mjs +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl + }; +} +function getBaseUrl(httpOptions, vertexai, vertexBaseUrlFromEnv, geminiBaseUrlFromEnv) { + var _a7, _b; + if (!(httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.baseUrl)) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a7 = defaultBaseUrls.vertexUrl) !== null && _a7 !== void 0 ? _a7 : vertexBaseUrlFromEnv; + } else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 ? _b : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} +function formatMap(templateString, valueMap) { + const regex = /\{([^}]+)\}/g; + return templateString.replace(regex, (match2, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + return value !== void 0 && value !== null ? String(value) : ""; + } else { + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys2, value) { + for (let i7 = 0; i7 < keys2.length - 1; i7++) { + const key = keys2[i7]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j3 = 0; j3 < arrayData.length; j3++) { + const entry = arrayData[j3]; + setValueByPath(entry, keys2.slice(i7 + 1), value[j3]); + } + } else { + for (const d4 of arrayData) { + setValueByPath(d4, keys2.slice(i7 + 1), value); + } + } + } + return; + } else if (key.endsWith("[0]")) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys2.slice(i7 + 1), value); + return; + } + if (!data[key] || typeof data[key] !== "object") { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys2[keys2.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== void 0) { + if (!value || typeof value === "object" && Object.keys(value).length === 0) { + return; + } + if (value === existingData) { + return; + } + if (typeof existingData === "object" && typeof value === "object" && existingData !== null && value !== null) { + Object.assign(existingData, value); + } else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } else { + if (keyToSet === "_self" && typeof value === "object" && value !== null && !Array.isArray(value)) { + const valueAsRecord = value; + Object.assign(data, valueAsRecord); + } else { + data[keyToSet] = value; + } + } +} +function getValueByPath(data, keys2, defaultValue = void 0) { + try { + if (keys2.length === 1 && keys2[0] === "_self") { + return data; + } + for (let i7 = 0; i7 < keys2.length; i7++) { + if (typeof data !== "object" || data === null) { + return defaultValue; + } + const key = keys2[i7]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return defaultValue; + } + return arrayData.map((d4) => getValueByPath(d4, keys2.slice(i7 + 1), defaultValue)); + } else { + return defaultValue; + } + } else { + data = data[key]; + } + } + return data; + } catch (error) { + if (error instanceof TypeError) { + return defaultValue; + } + throw error; + } +} +function moveValueByPath(data, paths) { + for (const [sourcePath, destPath] of Object.entries(paths)) { + const sourceKeys = sourcePath.split("."); + const destKeys = destPath.split("."); + const excludeKeys = /* @__PURE__ */ new Set(); + let wildcardIdx = -1; + for (let i7 = 0; i7 < sourceKeys.length; i7++) { + if (sourceKeys[i7] === "*") { + wildcardIdx = i7; + break; + } + } + if (wildcardIdx !== -1 && destKeys.length > wildcardIdx) { + for (let i7 = wildcardIdx; i7 < destKeys.length; i7++) { + const key = destKeys[i7]; + if (key !== "*" && !key.endsWith("[]") && !key.endsWith("[0]")) { + excludeKeys.add(key); + } + } + } + _moveValueRecursive(data, sourceKeys, destKeys, 0, excludeKeys); + } +} +function _moveValueRecursive(data, sourceKeys, destKeys, keyIdx, excludeKeys) { + if (keyIdx >= sourceKeys.length) { + return; + } + if (typeof data !== "object" || data === null) { + return; + } + const key = sourceKeys[keyIdx]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + const dataRecord = data; + if (keyName in dataRecord && Array.isArray(dataRecord[keyName])) { + for (const item of dataRecord[keyName]) { + _moveValueRecursive(item, sourceKeys, destKeys, keyIdx + 1, excludeKeys); + } + } + } else if (key === "*") { + if (typeof data === "object" && data !== null && !Array.isArray(data)) { + const dataRecord = data; + const keysToMove = Object.keys(dataRecord).filter((k2) => !k2.startsWith("_") && !excludeKeys.has(k2)); + const valuesToMove = {}; + for (const k2 of keysToMove) { + valuesToMove[k2] = dataRecord[k2]; + } + for (const [k2, v4] of Object.entries(valuesToMove)) { + const newDestKeys = []; + for (const dk of destKeys.slice(keyIdx)) { + if (dk === "*") { + newDestKeys.push(k2); + } else { + newDestKeys.push(dk); + } + } + setValueByPath(dataRecord, newDestKeys, v4); + } + for (const k2 of keysToMove) { + delete dataRecord[k2]; + } + } + } else { + const dataRecord = data; + if (key in dataRecord) { + _moveValueRecursive(dataRecord[key], sourceKeys, destKeys, keyIdx + 1, excludeKeys); + } + } +} +function tBytes$1(fromBytes) { + if (typeof fromBytes !== "string") { + throw new Error("fromImageBytes must be a string"); + } + return fromBytes; +} +function fetchPredictOperationParametersToVertex(fromObject2) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject2, [ + "operationName" + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ["operationName"], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject2, ["resourceName"]); + if (fromResourceName != null) { + setValueByPath(toObject, ["_url", "resourceName"], fromResourceName); + } + return toObject; +} +function generateVideosOperationFromMldev$1(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, [ + "response", + "generateVideoResponse" + ]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], generateVideosResponseFromMldev$1(fromResponse)); + } + return toObject; +} +function generateVideosOperationFromVertex$1(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], generateVideosResponseFromVertex$1(fromResponse)); + } + return toObject; +} +function generateVideosResponseFromMldev$1(fromObject2) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject2, [ + "generatedSamples" + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev$1(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [ + "raiMediaFilteredCount" + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [ + "raiMediaFilteredReasons" + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosResponseFromVertex$1(fromObject2) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject2, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex$1(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [ + "raiMediaFilteredCount" + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [ + "raiMediaFilteredReasons" + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generatedVideoFromMldev$1(fromObject2) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev$1(fromVideo)); + } + return toObject; +} +function generatedVideoFromVertex$1(fromObject2) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject2, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex$1(fromVideo)); + } + return toObject; +} +function getOperationParametersToMldev(fromObject2) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject2, [ + "operationName" + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + return toObject; +} +function getOperationParametersToVertex(fromObject2) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject2, [ + "operationName" + ]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + return toObject; +} +function importFileOperationFromMldev$1(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], importFileResponseFromMldev$1(fromResponse)); + } + return toObject; +} +function importFileResponseFromMldev$1(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromParent = getValueByPath(fromObject2, ["parent"]); + if (fromParent != null) { + setValueByPath(toObject, ["parent"], fromParent); + } + const fromDocumentName = getValueByPath(fromObject2, ["documentName"]); + if (fromDocumentName != null) { + setValueByPath(toObject, ["documentName"], fromDocumentName); + } + return toObject; +} +function uploadToFileSearchStoreOperationFromMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], uploadToFileSearchStoreResponseFromMldev(fromResponse)); + } + return toObject; +} +function uploadToFileSearchStoreResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromParent = getValueByPath(fromObject2, ["parent"]); + if (fromParent != null) { + setValueByPath(toObject, ["parent"], fromParent); + } + const fromDocumentName = getValueByPath(fromObject2, ["documentName"]); + if (fromDocumentName != null) { + setValueByPath(toObject, ["documentName"], fromDocumentName); + } + return toObject; +} +function videoFromMldev$1(fromObject2) { + const toObject = {}; + const fromUri = getValueByPath(fromObject2, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject2, ["encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function videoFromVertex$1(fromObject2) { + const toObject = {}; + const fromUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject2, [ + "bytesBase64Encoded" + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes$1(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function tModel(apiClient, model) { + if (!model || typeof model !== "string") { + throw new Error("model is required and must be a string"); + } + if (model.includes("..") || model.includes("?") || model.includes("&")) { + throw new Error("invalid model parameter"); + } + if (apiClient.isVertexAI()) { + if (model.startsWith("publishers/") || model.startsWith("projects/") || model.startsWith("models/")) { + return model; + } else if (model.indexOf("/") >= 0) { + const parts = model.split("/", 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } else { + return `publishers/google/models/${model}`; + } + } else { + if (model.startsWith("models/") || model.startsWith("tunedModels/")) { + return model; + } else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ""; + } + if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === "object" && blob !== null) { + return blob; + } + throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof blob}`); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("image/")) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if (transformedBlob.mimeType && transformedBlob.mimeType.startsWith("audio/")) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === void 0) { + throw new Error("PartUnion is required"); + } + if (typeof origin === "object") { + return origin; + } + if (typeof origin === "string") { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) { + throw new Error("PartListUnion is required"); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return origin !== null && origin !== void 0 && typeof origin === "object" && "parts" in origin && Array.isArray(origin.parts); +} +function _isFunctionCallPart(origin) { + return origin !== null && origin !== void 0 && typeof origin === "object" && "functionCall" in origin; +} +function _isFunctionResponsePart(origin) { + return origin !== null && origin !== void 0 && typeof origin === "object" && "functionResponse" in origin; +} +function tContent(origin) { + if (origin === null || origin === void 0) { + throw new Error("ContentUnion is required"); + } + if (_isContent(origin)) { + return origin; + } + return { + role: "user", + parts: tParts(origin) + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) { + return [content.parts[0].text]; + } + return []; + }); + } else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if (content.parts && content.parts.length > 0 && content.parts[0].text !== void 0) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if (origin === null || origin === void 0 || Array.isArray(origin) && origin.length === 0) { + throw new Error("contents are required"); + } + if (!Array.isArray(origin)) { + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them"); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + 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 (isContent) { + result.push(item); + } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + 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 { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: "user", parts: tParts(accumulatedParts) }); + } + return result; +} +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes("null")) { + resultingSchema["nullable"] = true; + } + const listWithoutNull = typeList.filter((type) => type !== "null"); + if (listWithoutNull.length === 1) { + resultingSchema["type"] = Object.values(Type2).includes(listWithoutNull[0].toUpperCase()) ? listWithoutNull[0].toUpperCase() : Type2.TYPE_UNSPECIFIED; + } else { + resultingSchema["anyOf"] = []; + for (const i7 of listWithoutNull) { + resultingSchema["anyOf"].push({ + "type": Object.values(Type2).includes(i7.toUpperCase()) ? i7.toUpperCase() : Type2.TYPE_UNSPECIFIED + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ["items"]; + const listSchemaFieldNames = ["anyOf"]; + const dictSchemaFieldNames = ["properties"]; + if (_jsonSchema["type"] && _jsonSchema["anyOf"]) { + throw new Error("type and anyOf cannot be both populated."); + } + const incomingAnyOf = _jsonSchema["anyOf"]; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[1]; + } else if (incomingAnyOf[1]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema["type"] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + if (fieldValue == null) { + continue; + } + if (fieldName == "type") { + if (fieldValue === "null") { + throw new Error("type: null can not be the only possible type for the field."); + } + if (fieldValue instanceof Array) { + continue; + } + genAISchema["type"] = Object.values(Type2).includes(fieldValue.toUpperCase()) ? fieldValue.toUpperCase() : Type2.TYPE_UNSPECIFIED; + } else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = processJsonSchema(fieldValue); + } else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item["type"] == "null") { + genAISchema["nullable"] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = listSchemaFieldValue; + } else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = dictSchemaFieldValue; + } else { + if (fieldName === "additionalProperties") { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === "object") { + return speechConfig; + } else if (typeof speechConfig === "string") { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig + } + } + }; + } else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ("multiSpeakerVoiceConfig" in speechConfig) { + throw new Error("multiSpeakerVoiceConfig is not supported in the live API."); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes("$schema")) { + functionDeclaration.parameters = processJsonSchema(functionDeclaration.parameters); + } else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes("$schema")) { + functionDeclaration.response = processJsonSchema(functionDeclaration.response); + } else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + if (tools === void 0 || tools === null) { + throw new Error("tools is required"); + } + if (!Array.isArray(tools)) { + throw new Error("tools is required and must be an array of Tools"); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +function resourceName(client, resourceName2, resourcePrefix, splitsAfterPrefix = 1) { + const shouldAppendPrefix = !resourceName2.startsWith(`${resourcePrefix}/`) && resourceName2.split("/").length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName2.startsWith("projects/")) { + return resourceName2; + } else if (resourceName2.startsWith("locations/")) { + return `projects/${client.getProject()}/${resourceName2}`; + } else if (resourceName2.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName2}`; + } else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName2}`; + } else { + return resourceName2; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName2}`; + } + return resourceName2; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== "string") { + throw new Error("name must be a string"); + } + return resourceName(apiClient, name, "cachedContents"); +} +function tTuningJobStatus(status) { + switch (status) { + 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 status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return origin !== null && origin !== void 0 && typeof origin === "object" && "name" in origin; +} +function isGeneratedVideo(origin) { + return origin !== null && origin !== void 0 && typeof origin === "object" && "video" in origin; +} +function isVideo(origin) { + return origin !== null && origin !== void 0 && typeof origin === "object" && "uri" in origin; +} +function tFileName(fromName) { + var _a7; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === void 0) { + return void 0; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a7 = fromName.video) === null || _a7 === void 0 ? void 0 : _a7.uri; + if (name === void 0) { + return void 0; + } + } + if (typeof fromName === "string") { + name = fromName; + } + if (name === void 0) { + throw new Error("Could not extract file name from the provided input."); + } + if (name.startsWith("https://")) { + const suffix = name.split("files/")[1]; + const match2 = suffix.match(/[a-z0-9]+/); + if (match2 === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match2[0]; + } else if (name.startsWith("files/")) { + name = name.split("files/")[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? "publishers/google/models" : "models"; + } else { + res = baseModels ? "models" : "tunedModels"; + } + return res; +} +function tExtractModels(response) { + for (const key of ["models", "tunedModels", "publisherModels"]) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === "object" && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema["name"], + description: mcpToolSchema["description"], + parametersJsonSchema: mcpToolSchema["inputSchema"] + }; + if (mcpToolSchema["outputSchema"]) { + functionDeclaration["responseJsonSchema"] = mcpToolSchema["outputSchema"]; + } + if (config.behavior) { + functionDeclaration["behavior"] = config.behavior; + } + const geminiTool = { + functionDeclarations: [ + functionDeclaration + ] + }; + return geminiTool; +} +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = /* @__PURE__ */ new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations }; +} +function tBatchJobSource(client, src) { + let sourceObj; + if (typeof src === "string") { + if (client.isVertexAI()) { + if (src.startsWith("gs://")) { + sourceObj = { format: "jsonl", gcsUri: [src] }; + } else if (src.startsWith("bq://")) { + sourceObj = { format: "bigquery", bigqueryUri: src }; + } else { + throw new Error(`Unsupported string source for Vertex AI: ${src}`); + } + } else { + if (src.startsWith("files/")) { + sourceObj = { fileName: src }; + } else { + throw new Error(`Unsupported string source for Gemini API: ${src}`); + } + } + } else if (Array.isArray(src)) { + if (client.isVertexAI()) { + throw new Error("InlinedRequest[] is not supported in Vertex AI."); + } + sourceObj = { inlinedRequests: src }; + } else { + sourceObj = src; + } + const vertexSourcesCount = [sourceObj.gcsUri, sourceObj.bigqueryUri].filter(Boolean).length; + const mldevSourcesCount = [ + sourceObj.inlinedRequests, + sourceObj.fileName + ].filter(Boolean).length; + if (client.isVertexAI()) { + if (mldevSourcesCount > 0 || vertexSourcesCount !== 1) { + throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI."); + } + } else { + if (vertexSourcesCount > 0 || mldevSourcesCount !== 1) { + throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API."); + } + } + return sourceObj; +} +function tBatchJobDestination(dest) { + if (typeof dest !== "string") { + return dest; + } + const destString = dest; + if (destString.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: destString + }; + } else if (destString.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: destString + }; + } else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tRecvBatchJobDestination(dest) { + if (typeof dest !== "object" || dest === null) { + return {}; + } + const obj = dest; + const inlineResponsesVal = obj["inlinedResponses"]; + if (typeof inlineResponsesVal !== "object" || inlineResponsesVal === null) { + return dest; + } + const inlineResponsesObj = inlineResponsesVal; + const responsesArray = inlineResponsesObj["inlinedResponses"]; + if (!Array.isArray(responsesArray) || responsesArray.length === 0) { + return dest; + } + let hasEmbedding = false; + for (const responseItem of responsesArray) { + if (typeof responseItem !== "object" || responseItem === null) { + continue; + } + const responseItemObj = responseItem; + const responseVal = responseItemObj["response"]; + if (typeof responseVal !== "object" || responseVal === null) { + continue; + } + const responseObj = responseVal; + if (responseObj["embedding"] !== void 0) { + hasEmbedding = true; + break; + } + } + if (hasEmbedding) { + obj["inlinedEmbedContentResponses"] = obj["inlinedResponses"]; + delete obj["inlinedResponses"]; + } + return dest; +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split("/").pop(); + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split("/").pop(); + } else if (/^\d+$/.test(nameString)) { + return nameString; + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === "BATCH_STATE_UNSPECIFIED") { + return "JOB_STATE_UNSPECIFIED"; + } else if (stateString === "BATCH_STATE_PENDING") { + return "JOB_STATE_PENDING"; + } else if (stateString === "BATCH_STATE_RUNNING") { + return "JOB_STATE_RUNNING"; + } else if (stateString === "BATCH_STATE_SUCCEEDED") { + return "JOB_STATE_SUCCEEDED"; + } else if (stateString === "BATCH_STATE_FAILED") { + return "JOB_STATE_FAILED"; + } else if (stateString === "BATCH_STATE_CANCELLED") { + return "JOB_STATE_CANCELLED"; + } else if (stateString === "BATCH_STATE_EXPIRED") { + return "JOB_STATE_EXPIRED"; + } else { + return stateString; + } +} +function tIsVertexEmbedContentModel(model) { + return model.includes("gemini") && model !== "gemini-embedding-001" || model.includes("maas"); +} +function authConfigToMldev$4(fromObject2) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject2, ["apiKey"]); + if (fromApiKey != null) { + setValueByPath(toObject, ["apiKey"], fromApiKey); + } + if (getValueByPath(fromObject2, ["apiKeyConfig"]) !== void 0) { + throw new Error("apiKeyConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["authType"]) !== void 0) { + throw new Error("authType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["googleServiceAccountConfig"]) !== void 0) { + throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["httpBasicAuthConfig"]) !== void 0) { + throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oauthConfig"]) !== void 0) { + throw new Error("oauthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oidcConfig"]) !== void 0) { + throw new Error("oidcConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject2) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject2, ["responsesFile"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject2, [ + "inlinedResponses", + "inlinedResponses" + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ["inlinedResponses"], transformedList); + } + const fromInlinedEmbedContentResponses = getValueByPath(fromObject2, [ + "inlinedEmbedContentResponses", + "inlinedResponses" + ]); + if (fromInlinedEmbedContentResponses != null) { + let transformedList = fromInlinedEmbedContentResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["inlinedEmbedContentResponses"], transformedList); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject2) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject2, ["predictionsFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject2, [ + "gcsDestination", + "outputUriPrefix" + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject2, [ + "bigqueryDestination", + "outputUri" + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject2) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject2, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["predictionsFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject2, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryDestination", "outputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject2, ["fileName"]) !== void 0) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject2, ["inlinedResponses"]) !== void 0) { + throw new Error("inlinedResponses parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject2, ["inlinedEmbedContentResponses"]) !== void 0) { + throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI."); + } + return toObject; +} +function batchJobFromMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject2, [ + "metadata", + "displayName" + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject2, ["metadata", "state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject2, [ + "metadata", + "createTime" + ]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject2, [ + "metadata", + "endTime" + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject2, [ + "metadata", + "updateTime" + ]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject2, ["metadata", "model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromDest = getValueByPath(fromObject2, ["metadata", "output"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(tRecvBatchJobDestination(fromDest))); + } + return toObject; +} +function batchJobFromVertex(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject2, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromCreateTime = getValueByPath(fromObject2, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject2, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject2, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromSrc = getValueByPath(fromObject2, ["inputConfig"]); + if (fromSrc != null) { + setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject2, ["outputConfig"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(tRecvBatchJobDestination(fromDest))); + } + const fromCompletionStats = getValueByPath(fromObject2, [ + "completionStats" + ]); + if (fromCompletionStats != null) { + setValueByPath(toObject, ["completionStats"], fromCompletionStats); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject2) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject2, ["instancesFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject2, ["gcsSource", "uris"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject2, [ + "bigquerySource", + "inputUri" + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["format"]) !== void 0) { + throw new Error("format parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["gcsUri"]) !== void 0) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["bigqueryUri"]) !== void 0) { + throw new Error("bigqueryUri parameter is not supported in Gemini API."); + } + const fromFileName = getValueByPath(fromObject2, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject2, [ + "inlinedRequests" + ]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ["requests", "requests"], transformedList); + } + return toObject; +} +function batchJobSourceToVertex(fromObject2) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject2, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["instancesFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject2, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject2, ["fileName"]) !== void 0) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject2, ["inlinedRequests"]) !== void 0) { + throw new Error("inlinedRequests parameter is not supported in Vertex AI."); + } + return toObject; +} +function blobToMldev$4(fromObject2) { + const toObject = {}; + const fromData = getValueByPath(fromObject2, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function candidateFromMldev$1(fromObject2) { + const toObject = {}; + const fromContent = getValueByPath(fromObject2, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], fromContent); + } + const fromCitationMetadata = getValueByPath(fromObject2, [ + "citationMetadata" + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev$1(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject2, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromGroundingMetadata = getValueByPath(fromObject2, [ + "groundingMetadata" + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromAvgLogprobs = getValueByPath(fromObject2, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromIndex = getValueByPath(fromObject2, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject2, [ + "logprobsResult" + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject2, [ + "safetyRatings" + ]); + if (fromSafetyRatings != null) { + let transformedList = fromSafetyRatings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["safetyRatings"], transformedList); + } + const fromUrlContextMetadata = getValueByPath(fromObject2, [ + "urlContextMetadata" + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ["urlContextMetadata"], fromUrlContextMetadata); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject2) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject2, ["citationSources"]); + if (fromCitations != null) { + let transformedList = fromCitations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["citations"], transformedList); + } + return toObject; +} +function contentToMldev$4(fromObject2) { + const toObject = {}; + const fromParts = getValueByPath(fromObject2, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject2, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + if (getValueByPath(fromObject2, ["dest"]) !== void 0) { + throw new Error("dest parameter is not supported in Gemini API."); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject2, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDest = getValueByPath(fromObject2, ["dest"]); + if (parentObject !== void 0 && fromDest != null) { + setValueByPath(parentObject, ["outputConfig"], batchJobDestinationToVertex(tBatchJobDestination(fromDest))); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject2, ["src"]); + if (fromSrc != null) { + setValueByPath(toObject, ["batch", "inputConfig"], batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createBatchJobConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject2, ["src"]); + if (fromSrc != null) { + setValueByPath(toObject, ["inputConfig"], batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc))); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createBatchJobConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function createEmbeddingsBatchJobConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + return toObject; +} +function createEmbeddingsBatchJobParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject2, ["src"]); + if (fromSrc != null) { + setValueByPath(toObject, ["batch", "inputConfig"], embeddingsBatchJobSourceToMldev(apiClient, fromSrc)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createEmbeddingsBatchJobConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function embedContentBatchToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContentsForEmbed(apiClient, fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["requests[]", "request", "content"], transformedList); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["_self"], embedContentConfigToMldev$1(fromConfig, toObject)); + moveValueByPath(toObject, { "requests[].*": "requests[].request.*" }); + } + return toObject; +} +function embedContentConfigToMldev$1(fromObject2, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject2, ["taskType"]); + if (parentObject !== void 0 && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject2, ["title"]); + if (parentObject !== void 0 && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject2, [ + "outputDimensionality" + ]); + if (parentObject !== void 0 && fromOutputDimensionality != null) { + setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality); + } + if (getValueByPath(fromObject2, ["mimeType"]) !== void 0) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["autoTruncate"]) !== void 0) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embeddingsBatchJobSourceToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject2, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["file_name"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject2, [ + "inlinedRequests" + ]); + if (fromInlinedRequests != null) { + setValueByPath(toObject, ["requests"], embedContentBatchToMldev(apiClient, fromInlinedRequests)); + } + return toObject; +} +function fileDataToMldev$4(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject2, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function functionCallToMldev$4(fromObject2) { + const toObject = {}; + const fromId = getValueByPath(fromObject2, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject2, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + if (getValueByPath(fromObject2, ["partialArgs"]) !== void 0) { + throw new Error("partialArgs parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["willContinue"]) !== void 0) { + throw new Error("willContinue parameter is not supported in Gemini API."); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject2) { + const toObject = {}; + const fromAllowedFunctionNames = getValueByPath(fromObject2, [ + "allowedFunctionNames" + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames); + } + const fromMode = getValueByPath(fromObject2, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + if (getValueByPath(fromObject2, ["streamFunctionCallArguments"]) !== void 0) { + throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API."); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject2, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["systemInstruction"], contentToMldev$4(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject2, [ + "candidateCount" + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject2, [ + "stopSequences" + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject2, [ + "responseLogprobs" + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject2, [ + "presencePenalty" + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject2, [ + "frequencyPenalty" + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject2, [ + "responseMimeType" + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject2, [ + "responseSchema" + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ["responseSchema"], tSchema(fromResponseSchema)); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject2, ["routingConfig"]) !== void 0) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["modelSelectionConfig"]) !== void 0) { + throw new Error("modelSelectionConfig parameter is not supported in Gemini API."); + } + const fromSafetySettings = getValueByPath(fromObject2, [ + "safetySettings" + ]); + if (parentObject !== void 0 && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]); + if (parentObject !== void 0 && fromToolConfig != null) { + setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$2(fromToolConfig)); + } + if (getValueByPath(fromObject2, ["labels"]) !== void 0) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject2, [ + "cachedContent" + ]); + if (parentObject !== void 0 && fromCachedContent != null) { + setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ["speechConfig"], tSpeechConfig(fromSpeechConfig)); + } + if (getValueByPath(fromObject2, ["audioTimestamp"]) !== void 0) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig); + } + const fromImageConfig = getValueByPath(fromObject2, ["imageConfig"]); + if (fromImageConfig != null) { + setValueByPath(toObject, ["imageConfig"], imageConfigToMldev$1(fromImageConfig)); + } + const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject2, [ + "enableEnhancedCivicAnswers" + ]); + if (fromEnableEnhancedCivicAnswers != null) { + setValueByPath(toObject, ["enableEnhancedCivicAnswers"], fromEnableEnhancedCivicAnswers); + } + if (getValueByPath(fromObject2, ["modelArmorConfig"]) !== void 0) { + throw new Error("modelArmorConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject2, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject2, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject2, [ + "promptFeedback" + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject2, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject2, [ + "usageMetadata" + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tBatchJobName(apiClient, fromName)); + } + return toObject; +} +function googleMapsToMldev$4(fromObject2) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath(toObject, ["authConfig"], authConfigToMldev$4(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject2, ["enableWidget"]); + if (fromEnableWidget != null) { + setValueByPath(toObject, ["enableWidget"], fromEnableWidget); + } + return toObject; +} +function googleSearchToMldev$4(fromObject2) { + const toObject = {}; + const fromSearchTypes = getValueByPath(fromObject2, ["searchTypes"]); + if (fromSearchTypes != null) { + setValueByPath(toObject, ["searchTypes"], fromSearchTypes); + } + if (getValueByPath(fromObject2, ["blockingConfidence"]) !== void 0) { + throw new Error("blockingConfidence parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) { + throw new Error("excludeDomains parameter is not supported in Gemini API."); + } + const fromTimeRangeFilter = getValueByPath(fromObject2, [ + "timeRangeFilter" + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter); + } + return toObject; +} +function imageConfigToMldev$1(fromObject2) { + const toObject = {}; + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (fromAspectRatio != null) { + setValueByPath(toObject, ["aspectRatio"], fromAspectRatio); + } + const fromImageSize = getValueByPath(fromObject2, ["imageSize"]); + if (fromImageSize != null) { + setValueByPath(toObject, ["imageSize"], fromImageSize); + } + if (getValueByPath(fromObject2, ["personGeneration"]) !== void 0) { + throw new Error("personGeneration parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["prominentPeople"]) !== void 0) { + throw new Error("prominentPeople parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["outputMimeType"]) !== void 0) { + throw new Error("outputMimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["outputCompressionQuality"]) !== void 0) { + throw new Error("outputCompressionQuality parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["imageOutputOptions"]) !== void 0) { + throw new Error("imageOutputOptions parameter is not supported in Gemini API."); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["request", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ["request", "contents"], transformedList); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["request", "generationConfig"], generateContentConfigToMldev$1(apiClient, fromConfig, getValueByPath(toObject, ["request"], {}))); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject2) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], generateContentResponseFromMldev$1(fromResponse)); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + if (getValueByPath(fromObject2, ["filter"]) !== void 0) { + throw new Error("filter parameter is not supported in Gemini API."); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject2, ["filter"]); + if (parentObject !== void 0 && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listBatchJobsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listBatchJobsConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject2, ["operations"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject2, [ + "batchPredictionJobs" + ]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function partToMldev$4(fromObject2) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromCodeExecutionResult = getValueByPath(fromObject2, [ + "codeExecutionResult" + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject2, [ + "executableCode" + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject2, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], functionCallToMldev$4(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject2, [ + "functionResponse" + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject2, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData)); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromThought = getValueByPath(fromObject2, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject2, [ + "thoughtSignature" + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject2, [ + "videoMetadata" + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + return toObject; +} +function safetySettingToMldev$1(fromObject2) { + const toObject = {}; + const fromCategory = getValueByPath(fromObject2, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + if (getValueByPath(fromObject2, ["method"]) !== void 0) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromThreshold = getValueByPath(fromObject2, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function toolConfigToMldev$2(fromObject2) { + const toObject = {}; + const fromRetrievalConfig = getValueByPath(fromObject2, [ + "retrievalConfig" + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ["retrievalConfig"], fromRetrievalConfig); + } + const fromFunctionCallingConfig = getValueByPath(fromObject2, [ + "functionCallingConfig" + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$2(fromFunctionCallingConfig)); + } + return toObject; +} +function toolToMldev$4(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + const fromFileSearch = getValueByPath(fromObject2, ["fileSearch"]); + if (fromFileSearch != null) { + setValueByPath(toObject, ["fileSearch"], fromFileSearch); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$4(fromGoogleSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$4(fromGoogleMaps)); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) { + throw new Error("enterpriseWebSearch parameter is not supported in Gemini API."); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject2, ["parallelAiSearch"]) !== void 0) { + throw new Error("parallelAiSearch parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + const fromMcpServers = getValueByPath(fromObject2, ["mcpServers"]); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["mcpServers"], transformedList); + } + return toObject; +} +function authConfigToMldev$3(fromObject2) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject2, ["apiKey"]); + if (fromApiKey != null) { + setValueByPath(toObject, ["apiKey"], fromApiKey); + } + if (getValueByPath(fromObject2, ["apiKeyConfig"]) !== void 0) { + throw new Error("apiKeyConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["authType"]) !== void 0) { + throw new Error("authType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["googleServiceAccountConfig"]) !== void 0) { + throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["httpBasicAuthConfig"]) !== void 0) { + throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oauthConfig"]) !== void 0) { + throw new Error("oauthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oidcConfig"]) !== void 0) { + throw new Error("oidcConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function blobToMldev$3(fromObject2) { + const toObject = {}; + const fromData = getValueByPath(fromObject2, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function contentToMldev$3(fromObject2) { + const toObject = {}; + const fromParts = getValueByPath(fromObject2, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject2, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject2, ["ttl"]); + if (parentObject !== void 0 && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]); + if (parentObject !== void 0 && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (parentObject !== void 0 && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["systemInstruction"], contentToMldev$3(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]); + if (parentObject !== void 0 && fromToolConfig != null) { + setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev$1(fromToolConfig)); + } + if (getValueByPath(fromObject2, ["kmsKeyName"]) !== void 0) { + throw new Error("kmsKeyName parameter is not supported in Gemini API."); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject2, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject2, ["ttl"]); + if (parentObject !== void 0 && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]); + if (parentObject !== void 0 && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (parentObject !== void 0 && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["systemInstruction"], tContent(fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]); + if (parentObject !== void 0 && fromToolConfig != null) { + setValueByPath(parentObject, ["toolConfig"], fromToolConfig); + } + const fromKmsKeyName = getValueByPath(fromObject2, ["kmsKeyName"]); + if (parentObject !== void 0 && fromKmsKeyName != null) { + setValueByPath(parentObject, ["encryption_spec", "kmsKeyName"], fromKmsKeyName); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createCachedContentConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createCachedContentConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function deleteCachedContentResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteCachedContentResponseFromVertex(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function fileDataToMldev$3(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject2, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function functionCallToMldev$3(fromObject2) { + const toObject = {}; + const fromId = getValueByPath(fromObject2, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject2, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + if (getValueByPath(fromObject2, ["partialArgs"]) !== void 0) { + throw new Error("partialArgs parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["willContinue"]) !== void 0) { + throw new Error("willContinue parameter is not supported in Gemini API."); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject2) { + const toObject = {}; + const fromAllowedFunctionNames = getValueByPath(fromObject2, [ + "allowedFunctionNames" + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames); + } + const fromMode = getValueByPath(fromObject2, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + if (getValueByPath(fromObject2, ["streamFunctionCallArguments"]) !== void 0) { + throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API."); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject2) { + const toObject = {}; + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject2, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject2, [ + "parametersJsonSchema" + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject2, ["behavior"]) !== void 0) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName)); + } + return toObject; +} +function googleMapsToMldev$3(fromObject2) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath(toObject, ["authConfig"], authConfigToMldev$3(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject2, ["enableWidget"]); + if (fromEnableWidget != null) { + setValueByPath(toObject, ["enableWidget"], fromEnableWidget); + } + return toObject; +} +function googleSearchToMldev$3(fromObject2) { + const toObject = {}; + const fromSearchTypes = getValueByPath(fromObject2, ["searchTypes"]); + if (fromSearchTypes != null) { + setValueByPath(toObject, ["searchTypes"], fromSearchTypes); + } + if (getValueByPath(fromObject2, ["blockingConfidence"]) !== void 0) { + throw new Error("blockingConfidence parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) { + throw new Error("excludeDomains parameter is not supported in Gemini API."); + } + const fromTimeRangeFilter = getValueByPath(fromObject2, [ + "timeRangeFilter" + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listCachedContentsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listCachedContentsConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject2, [ + "cachedContents" + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject2, [ + "cachedContents" + ]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function partToMldev$3(fromObject2) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromCodeExecutionResult = getValueByPath(fromObject2, [ + "codeExecutionResult" + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject2, [ + "executableCode" + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject2, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], functionCallToMldev$3(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject2, [ + "functionResponse" + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject2, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData)); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromThought = getValueByPath(fromObject2, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject2, [ + "thoughtSignature" + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject2, [ + "videoMetadata" + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + return toObject; +} +function toolConfigToMldev$1(fromObject2) { + const toObject = {}; + const fromRetrievalConfig = getValueByPath(fromObject2, [ + "retrievalConfig" + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ["retrievalConfig"], fromRetrievalConfig); + } + const fromFunctionCallingConfig = getValueByPath(fromObject2, [ + "functionCallingConfig" + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev$1(fromFunctionCallingConfig)); + } + return toObject; +} +function toolToMldev$3(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + const fromFileSearch = getValueByPath(fromObject2, ["fileSearch"]); + if (fromFileSearch != null) { + setValueByPath(toObject, ["fileSearch"], fromFileSearch); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$3(fromGoogleSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$3(fromGoogleMaps)); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) { + throw new Error("enterpriseWebSearch parameter is not supported in Gemini API."); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject2, ["parallelAiSearch"]) !== void 0) { + throw new Error("parallelAiSearch parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + const fromMcpServers = getValueByPath(fromObject2, ["mcpServers"]); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["mcpServers"], transformedList); + } + return toObject; +} +function toolToVertex$2(fromObject2) { + const toObject = {}; + const fromRetrieval = getValueByPath(fromObject2, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + if (getValueByPath(fromObject2, ["fileSearch"]) !== void 0) { + throw new Error("fileSearch parameter is not supported in Vertex AI."); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], fromGoogleSearch); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], fromGoogleMaps); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject2, [ + "enterpriseWebSearch" + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + const fromParallelAiSearch = getValueByPath(fromObject2, [ + "parallelAiSearch" + ]); + if (fromParallelAiSearch != null) { + setValueByPath(toObject, ["parallelAiSearch"], fromParallelAiSearch); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + if (getValueByPath(fromObject2, ["mcpServers"]) !== void 0) { + throw new Error("mcpServers parameter is not supported in Vertex AI."); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject2, ["ttl"]); + if (parentObject !== void 0 && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]); + if (parentObject !== void 0 && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject2, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject2, ["ttl"]); + if (parentObject !== void 0 && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]); + if (parentObject !== void 0 && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + updateCachedContentConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], tCachedContentName(apiClient, fromName)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + updateCachedContentConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function __rest(s6, e9) { + var t6 = {}; + for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4) && e9.indexOf(p4) < 0) + t6[p4] = s6[p4]; + if (s6 != null && typeof Object.getOwnPropertySymbols === "function") + for (var i7 = 0, p4 = Object.getOwnPropertySymbols(s6); i7 < p4.length; i7++) { + if (e9.indexOf(p4[i7]) < 0 && Object.prototype.propertyIsEnumerable.call(s6, p4[i7])) + t6[p4[i7]] = s6[p4[i7]]; + } + return t6; +} +function __values(o9) { + var s6 = typeof Symbol === "function" && Symbol.iterator, m4 = s6 && o9[s6], i7 = 0; + if (m4) return m4.call(o9); + if (o9 && typeof o9.length === "number") return { + next: function() { + if (o9 && i7 >= o9.length) o9 = void 0; + return { value: o9 && o9[i7++], done: !o9 }; + } + }; + throw new TypeError(s6 ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __await(v4) { + return this instanceof __await ? (this.v = v4, this) : new __await(v4); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g3 = generator.apply(thisArg, _arguments || []), i7, q2 = []; + return i7 = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i7[Symbol.asyncIterator] = function() { + return this; + }, i7; + function awaitReturn(f4) { + return function(v4) { + return Promise.resolve(v4).then(f4, reject); + }; + } + function verb(n7, f4) { + if (g3[n7]) { + i7[n7] = function(v4) { + return new Promise(function(a3, b4) { + q2.push([n7, v4, a3, b4]) > 1 || resume(n7, v4); + }); + }; + if (f4) i7[n7] = f4(i7[n7]); + } + } + function resume(n7, v4) { + try { + step(g3[n7](v4)); + } catch (e9) { + settle(q2[0][3], e9); + } + } + function step(r8) { + r8.value instanceof __await ? Promise.resolve(r8.value.v).then(fulfill, reject) : settle(q2[0][2], r8); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f4, v4) { + if (f4(v4), q2.shift(), q2.length) resume(q2[0][0], q2[0][1]); + } +} +function __asyncValues(o9) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m4 = o9[Symbol.asyncIterator], i7; + return m4 ? m4.call(o9) : (o9 = typeof __values === "function" ? __values(o9) : o9[Symbol.iterator](), i7 = {}, verb("next"), verb("throw"), verb("return"), i7[Symbol.asyncIterator] = function() { + return this; + }, i7); + function verb(n7) { + i7[n7] = o9[n7] && function(v4) { + return new Promise(function(resolve2, reject) { + v4 = o9[n7](v4), settle(resolve2, reject, v4.done, v4.value); + }); + }; + } + function settle(resolve2, reject, d4, v4) { + Promise.resolve(v4).then(function(v5) { + resolve2({ value: v5, done: d4 }); + }, reject); + } +} +function isValidResponse(response) { + var _a7; + if (response.candidates == void 0 || response.candidates.length === 0) { + return false; + } + const content = (_a7 = response.candidates[0]) === null || _a7 === void 0 ? void 0 : _a7.content; + if (content === void 0) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === void 0 || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === void 0 || Object.keys(part).length === 0) { + return false; + } + } + return true; +} +function validateHistory(history) { + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== "user" && content.role !== "model") { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === void 0 || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i7 = 0; + while (i7 < length) { + if (comprehensiveHistory[i7].role === "user") { + curatedHistory.push(comprehensiveHistory[i7]); + i7++; + } else { + const modelOutput = []; + let isValid3 = true; + while (i7 < length && comprehensiveHistory[i7].role === "model") { + modelOutput.push(comprehensiveHistory[i7]); + if (isValid3 && !isValidContent(comprehensiveHistory[i7])) { + isValid3 = false; + } + i7++; + } + if (isValid3) { + curatedHistory.push(...modelOutput); + } else { + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +function createFileParametersToMldev(fromObject2) { + const toObject = {}; + const fromFile = getValueByPath(fromObject2, ["file"]); + if (fromFile != null) { + setValueByPath(toObject, ["file"], fromFile); + } + return toObject; +} +function createFileResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + return toObject; +} +function deleteFileResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function getFileParametersToMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + return toObject; +} +function internalRegisterFilesParametersToMldev(fromObject2) { + const toObject = {}; + const fromUris = getValueByPath(fromObject2, ["uris"]); + if (fromUris != null) { + setValueByPath(toObject, ["uris"], fromUris); + } + return toObject; +} +function listFilesConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listFilesConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject2, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function registerFilesResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromFiles = getValueByPath(fromObject2, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["languageCodes"]) !== void 0) { + throw new Error("languageCodes parameter is not supported in Gemini API."); + } + return toObject; +} +function authConfigToMldev$2(fromObject2) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject2, ["apiKey"]); + if (fromApiKey != null) { + setValueByPath(toObject, ["apiKey"], fromApiKey); + } + if (getValueByPath(fromObject2, ["apiKeyConfig"]) !== void 0) { + throw new Error("apiKeyConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["authType"]) !== void 0) { + throw new Error("authType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["googleServiceAccountConfig"]) !== void 0) { + throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["httpBasicAuthConfig"]) !== void 0) { + throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oauthConfig"]) !== void 0) { + throw new Error("oauthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oidcConfig"]) !== void 0) { + throw new Error("oidcConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function blobToMldev$2(fromObject2) { + const toObject = {}; + const fromData = getValueByPath(fromObject2, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function contentToMldev$2(fromObject2) { + const toObject = {}; + const fromParts = getValueByPath(fromObject2, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject2, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function fileDataToMldev$2(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject2, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function functionCallToMldev$2(fromObject2) { + const toObject = {}; + const fromId = getValueByPath(fromObject2, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject2, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + if (getValueByPath(fromObject2, ["partialArgs"]) !== void 0) { + throw new Error("partialArgs parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["willContinue"]) !== void 0) { + throw new Error("willContinue parameter is not supported in Gemini API."); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject2) { + const toObject = {}; + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject2, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject2, [ + "parametersJsonSchema" + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject2, ["behavior"]) !== void 0) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + return toObject; +} +function generationConfigToVertex$1(fromObject2) { + const toObject = {}; + const fromModelSelectionConfig = getValueByPath(fromObject2, [ + "modelSelectionConfig" + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromAudioTimestamp = getValueByPath(fromObject2, [ + "audioTimestamp" + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromCandidateCount = getValueByPath(fromObject2, [ + "candidateCount" + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject2, [ + "enableAffectiveDialog" + ]); + if (fromEnableAffectiveDialog != null) { + setValueByPath(toObject, ["enableAffectiveDialog"], fromEnableAffectiveDialog); + } + const fromFrequencyPenalty = getValueByPath(fromObject2, [ + "frequencyPenalty" + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromPresencePenalty = getValueByPath(fromObject2, [ + "presencePenalty" + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromResponseLogprobs = getValueByPath(fromObject2, [ + "responseLogprobs" + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromResponseMimeType = getValueByPath(fromObject2, [ + "responseMimeType" + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromResponseSchema = getValueByPath(fromObject2, [ + "responseSchema" + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ["responseSchema"], fromResponseSchema); + } + const fromRoutingConfig = getValueByPath(fromObject2, [ + "routingConfig" + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ["speechConfig"], fromSpeechConfig); + } + const fromStopSequences = getValueByPath(fromObject2, [ + "stopSequences" + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + if (getValueByPath(fromObject2, ["enableEnhancedCivicAnswers"]) !== void 0) { + throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI."); + } + return toObject; +} +function googleMapsToMldev$2(fromObject2) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath(toObject, ["authConfig"], authConfigToMldev$2(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject2, ["enableWidget"]); + if (fromEnableWidget != null) { + setValueByPath(toObject, ["enableWidget"], fromEnableWidget); + } + return toObject; +} +function googleSearchToMldev$2(fromObject2) { + const toObject = {}; + const fromSearchTypes = getValueByPath(fromObject2, ["searchTypes"]); + if (fromSearchTypes != null) { + setValueByPath(toObject, ["searchTypes"], fromSearchTypes); + } + if (getValueByPath(fromObject2, ["blockingConfidence"]) !== void 0) { + throw new Error("blockingConfidence parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) { + throw new Error("excludeDomains parameter is not supported in Gemini API."); + } + const fromTimeRangeFilter = getValueByPath(fromObject2, [ + "timeRangeFilter" + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject2, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject2, [ + "generationConfig" + ]); + if (parentObject !== void 0 && fromGenerationConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (parentObject !== void 0 && fromResponseModalities != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (parentObject !== void 0 && fromTemperature != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (parentObject !== void 0 && fromTopP != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (parentObject !== void 0 && fromTopK != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (parentObject !== void 0 && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (parentObject !== void 0 && fromMediaResolution != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (parentObject !== void 0 && fromSpeechConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], tLiveSpeechConfig(fromSpeechConfig)); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (parentObject !== void 0 && fromThinkingConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject2, [ + "enableAffectiveDialog" + ]); + if (parentObject !== void 0 && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev$2(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject2, [ + "sessionResumption" + ]); + if (parentObject !== void 0 && fromSessionResumption != null) { + setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev$1(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject2, [ + "inputAudioTranscription" + ]); + if (parentObject !== void 0 && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev$1(fromInputAudioTranscription)); + } + const fromOutputAudioTranscription = getValueByPath(fromObject2, [ + "outputAudioTranscription" + ]); + if (parentObject !== void 0 && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev$1(fromOutputAudioTranscription)); + } + const fromRealtimeInputConfig = getValueByPath(fromObject2, [ + "realtimeInputConfig" + ]); + if (parentObject !== void 0 && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig); + } + const fromContextWindowCompression = getValueByPath(fromObject2, [ + "contextWindowCompression" + ]); + if (parentObject !== void 0 && fromContextWindowCompression != null) { + setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression); + } + const fromProactivity = getValueByPath(fromObject2, ["proactivity"]); + if (parentObject !== void 0 && fromProactivity != null) { + setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity); + } + if (getValueByPath(fromObject2, ["explicitVadSignal"]) !== void 0) { + throw new Error("explicitVadSignal parameter is not supported in Gemini API."); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject2, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject2, [ + "generationConfig" + ]); + if (parentObject !== void 0 && fromGenerationConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig"], generationConfigToVertex$1(fromGenerationConfig)); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (parentObject !== void 0 && fromResponseModalities != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (parentObject !== void 0 && fromTemperature != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (parentObject !== void 0 && fromTopP != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (parentObject !== void 0 && fromTopK != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (parentObject !== void 0 && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (parentObject !== void 0 && fromMediaResolution != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (parentObject !== void 0 && fromSpeechConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], tLiveSpeechConfig(fromSpeechConfig)); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (parentObject !== void 0 && fromThinkingConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject2, [ + "enableAffectiveDialog" + ]); + if (parentObject !== void 0 && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["setup", "systemInstruction"], tContent(fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject2, [ + "sessionResumption" + ]); + if (parentObject !== void 0 && fromSessionResumption != null) { + setValueByPath(parentObject, ["setup", "sessionResumption"], fromSessionResumption); + } + const fromInputAudioTranscription = getValueByPath(fromObject2, [ + "inputAudioTranscription" + ]); + if (parentObject !== void 0 && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ["setup", "inputAudioTranscription"], fromInputAudioTranscription); + } + const fromOutputAudioTranscription = getValueByPath(fromObject2, [ + "outputAudioTranscription" + ]); + if (parentObject !== void 0 && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ["setup", "outputAudioTranscription"], fromOutputAudioTranscription); + } + const fromRealtimeInputConfig = getValueByPath(fromObject2, [ + "realtimeInputConfig" + ]); + if (parentObject !== void 0 && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig); + } + const fromContextWindowCompression = getValueByPath(fromObject2, [ + "contextWindowCompression" + ]); + if (parentObject !== void 0 && fromContextWindowCompression != null) { + setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression); + } + const fromProactivity = getValueByPath(fromObject2, ["proactivity"]); + if (parentObject !== void 0 && fromProactivity != null) { + setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity); + } + const fromExplicitVadSignal = getValueByPath(fromObject2, [ + "explicitVadSignal" + ]); + if (parentObject !== void 0 && fromExplicitVadSignal != null) { + setValueByPath(parentObject, ["setup", "explicitVadSignal"], fromExplicitVadSignal); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], liveConnectConfigToMldev$1(fromConfig, toObject)); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], liveConnectConfigToVertex(fromConfig, toObject)); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject2) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject2, [ + "musicGenerationConfig" + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath(toObject, ["musicGenerationConfig"], fromMusicGenerationConfig); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject2) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject2, [ + "weightedPrompts" + ]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject2) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject2, ["media"]); + if (fromMedia != null) { + let transformedList = tBlobs(fromMedia); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return blobToMldev$2(item); + }); + } + setValueByPath(toObject, ["mediaChunks"], transformedList); + } + const fromAudio = getValueByPath(fromObject2, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], blobToMldev$2(tAudioBlob(fromAudio))); + } + const fromAudioStreamEnd = getValueByPath(fromObject2, [ + "audioStreamEnd" + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], blobToMldev$2(tImageBlob(fromVideo))); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject2, [ + "activityStart" + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], fromActivityStart); + } + const fromActivityEnd = getValueByPath(fromObject2, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], fromActivityEnd); + } + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject2) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject2, ["media"]); + if (fromMedia != null) { + let transformedList = tBlobs(fromMedia); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["mediaChunks"], transformedList); + } + const fromAudio = getValueByPath(fromObject2, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject2, [ + "audioStreamEnd" + ]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject2, [ + "activityStart" + ]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], fromActivityStart); + } + const fromActivityEnd = getValueByPath(fromObject2, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], fromActivityEnd); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject2) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject2, [ + "setupComplete" + ]); + if (fromSetupComplete != null) { + setValueByPath(toObject, ["setupComplete"], fromSetupComplete); + } + const fromServerContent = getValueByPath(fromObject2, [ + "serverContent" + ]); + if (fromServerContent != null) { + setValueByPath(toObject, ["serverContent"], fromServerContent); + } + const fromToolCall = getValueByPath(fromObject2, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath(toObject, ["toolCall"], fromToolCall); + } + const fromToolCallCancellation = getValueByPath(fromObject2, [ + "toolCallCancellation" + ]); + if (fromToolCallCancellation != null) { + setValueByPath(toObject, ["toolCallCancellation"], fromToolCallCancellation); + } + const fromUsageMetadata = getValueByPath(fromObject2, [ + "usageMetadata" + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], usageMetadataFromVertex(fromUsageMetadata)); + } + const fromGoAway = getValueByPath(fromObject2, ["goAway"]); + if (fromGoAway != null) { + setValueByPath(toObject, ["goAway"], fromGoAway); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject2, [ + "sessionResumptionUpdate" + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath(toObject, ["sessionResumptionUpdate"], fromSessionResumptionUpdate); + } + const fromVoiceActivityDetectionSignal = getValueByPath(fromObject2, [ + "voiceActivityDetectionSignal" + ]); + if (fromVoiceActivityDetectionSignal != null) { + setValueByPath(toObject, ["voiceActivityDetectionSignal"], fromVoiceActivityDetectionSignal); + } + const fromVoiceActivity = getValueByPath(fromObject2, [ + "voiceActivity" + ]); + if (fromVoiceActivity != null) { + setValueByPath(toObject, ["voiceActivity"], voiceActivityFromVertex(fromVoiceActivity)); + } + return toObject; +} +function partToMldev$2(fromObject2) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromCodeExecutionResult = getValueByPath(fromObject2, [ + "codeExecutionResult" + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject2, [ + "executableCode" + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject2, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], functionCallToMldev$2(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject2, [ + "functionResponse" + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject2, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData)); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromThought = getValueByPath(fromObject2, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject2, [ + "thoughtSignature" + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject2, [ + "videoMetadata" + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject2) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject2, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject2, ["transparent"]) !== void 0) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function toolToMldev$2(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + const fromFileSearch = getValueByPath(fromObject2, ["fileSearch"]); + if (fromFileSearch != null) { + setValueByPath(toObject, ["fileSearch"], fromFileSearch); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$2(fromGoogleSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$2(fromGoogleMaps)); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) { + throw new Error("enterpriseWebSearch parameter is not supported in Gemini API."); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject2, ["parallelAiSearch"]) !== void 0) { + throw new Error("parallelAiSearch parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + const fromMcpServers = getValueByPath(fromObject2, ["mcpServers"]); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["mcpServers"], transformedList); + } + return toObject; +} +function toolToVertex$1(fromObject2) { + const toObject = {}; + const fromRetrieval = getValueByPath(fromObject2, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + if (getValueByPath(fromObject2, ["fileSearch"]) !== void 0) { + throw new Error("fileSearch parameter is not supported in Vertex AI."); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], fromGoogleSearch); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], fromGoogleMaps); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject2, [ + "enterpriseWebSearch" + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + const fromParallelAiSearch = getValueByPath(fromObject2, [ + "parallelAiSearch" + ]); + if (fromParallelAiSearch != null) { + setValueByPath(toObject, ["parallelAiSearch"], fromParallelAiSearch); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + if (getValueByPath(fromObject2, ["mcpServers"]) !== void 0) { + throw new Error("mcpServers parameter is not supported in Vertex AI."); + } + return toObject; +} +function usageMetadataFromVertex(fromObject2) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject2, [ + "promptTokenCount" + ]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject2, [ + "cachedContentTokenCount" + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount); + } + const fromResponseTokenCount = getValueByPath(fromObject2, [ + "candidatesTokenCount" + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject2, [ + "toolUsePromptTokenCount" + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath(toObject, ["toolUsePromptTokenCount"], fromToolUsePromptTokenCount); + } + const fromThoughtsTokenCount = getValueByPath(fromObject2, [ + "thoughtsTokenCount" + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject2, [ + "totalTokenCount" + ]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject2, [ + "promptTokensDetails" + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject2, [ + "cacheTokensDetails" + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject2, [ + "candidatesTokensDetails" + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject2, [ + "toolUsePromptTokensDetails" + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + const fromTrafficType = getValueByPath(fromObject2, ["trafficType"]); + if (fromTrafficType != null) { + setValueByPath(toObject, ["trafficType"], fromTrafficType); + } + return toObject; +} +function voiceActivityFromVertex(fromObject2) { + const toObject = {}; + const fromVoiceActivityType = getValueByPath(fromObject2, ["type"]); + if (fromVoiceActivityType != null) { + setValueByPath(toObject, ["voiceActivityType"], fromVoiceActivityType); + } + return toObject; +} +function authConfigToMldev$1(fromObject2, _rootObject) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject2, ["apiKey"]); + if (fromApiKey != null) { + setValueByPath(toObject, ["apiKey"], fromApiKey); + } + if (getValueByPath(fromObject2, ["apiKeyConfig"]) !== void 0) { + throw new Error("apiKeyConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["authType"]) !== void 0) { + throw new Error("authType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["googleServiceAccountConfig"]) !== void 0) { + throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["httpBasicAuthConfig"]) !== void 0) { + throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oauthConfig"]) !== void 0) { + throw new Error("oauthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oidcConfig"]) !== void 0) { + throw new Error("oidcConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function blobToMldev$1(fromObject2, _rootObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject2, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function candidateFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject2, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], fromContent); + } + const fromCitationMetadata = getValueByPath(fromObject2, [ + "citationMetadata" + ]); + if (fromCitationMetadata != null) { + setValueByPath(toObject, ["citationMetadata"], citationMetadataFromMldev(fromCitationMetadata)); + } + const fromTokenCount = getValueByPath(fromObject2, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject2, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromGroundingMetadata = getValueByPath(fromObject2, [ + "groundingMetadata" + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromAvgLogprobs = getValueByPath(fromObject2, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromIndex = getValueByPath(fromObject2, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject2, [ + "logprobsResult" + ]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject2, [ + "safetyRatings" + ]); + if (fromSafetyRatings != null) { + let transformedList = fromSafetyRatings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["safetyRatings"], transformedList); + } + const fromUrlContextMetadata = getValueByPath(fromObject2, [ + "urlContextMetadata" + ]); + if (fromUrlContextMetadata != null) { + setValueByPath(toObject, ["urlContextMetadata"], fromUrlContextMetadata); + } + return toObject; +} +function citationMetadataFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject2, ["citationSources"]); + if (fromCitations != null) { + let transformedList = fromCitations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["citations"], transformedList); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject2, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject2, ["tokensInfo"]); + if (fromTokensInfo != null) { + let transformedList = fromTokensInfo; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["tokensInfo"], transformedList); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject2, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + const fromStatistics = getValueByPath(fromObject2, ["statistics"]); + if (fromStatistics != null) { + setValueByPath(toObject, ["statistics"], contentEmbeddingStatisticsFromVertex(fromStatistics)); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject2, ["truncated"]); + if (fromTruncated != null) { + setValueByPath(toObject, ["truncated"], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject2, ["token_count"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function contentToMldev$1(fromObject2, rootObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject2, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject2, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject2, ["controlType"]); + if (fromControlType != null) { + setValueByPath(toObject, ["controlType"], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject2, [ + "enableControlImageComputation" + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath(toObject, ["computeControl"], fromEnableControlImageComputation); + } + return toObject; +} +function countTokensConfigToMldev(fromObject2, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["systemInstruction"]) !== void 0) { + throw new Error("systemInstruction parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["tools"]) !== void 0) { + throw new Error("tools parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["generationConfig"]) !== void 0) { + throw new Error("generationConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function countTokensConfigToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["systemInstruction"], tContent(fromSystemInstruction)); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject2, [ + "generationConfig" + ]); + if (parentObject !== void 0 && fromGenerationConfig != null) { + setValueByPath(parentObject, ["generationConfig"], generationConfigToVertex(fromGenerationConfig)); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + countTokensConfigToMldev(fromConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + countTokensConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function countTokensResponseFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject2, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject2, [ + "cachedContentTokenCount" + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath(toObject, ["cachedContentTokenCount"], fromCachedContentTokenCount); + } + return toObject; +} +function countTokensResponseFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject2, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject2, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject2, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + return toObject; +} +function deleteModelResponseFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteModelResponseFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function editImageConfigToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]); + if (parentObject !== void 0 && fromOutputGcsUri != null) { + setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject2, [ + "negativePrompt" + ]); + if (parentObject !== void 0 && fromNegativePrompt != null) { + setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject2, [ + "numberOfImages" + ]); + if (parentObject !== void 0 && fromNumberOfImages != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (parentObject !== void 0 && fromAspectRatio != null) { + setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject2, [ + "guidanceScale" + ]); + if (parentObject !== void 0 && fromGuidanceScale != null) { + setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject2, [ + "safetyFilterLevel" + ]); + if (parentObject !== void 0 && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject2, [ + "includeSafetyAttributes" + ]); + if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject2, [ + "includeRaiReason" + ]); + if (parentObject !== void 0 && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject2, ["language"]); + if (parentObject !== void 0 && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject2, [ + "outputMimeType" + ]); + if (parentObject !== void 0 && fromOutputMimeType != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject2, [ + "outputCompressionQuality" + ]); + if (parentObject !== void 0 && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject2, ["addWatermark"]); + if (parentObject !== void 0 && fromAddWatermark != null) { + setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromEditMode = getValueByPath(fromObject2, ["editMode"]); + if (parentObject !== void 0 && fromEditMode != null) { + setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject2, ["baseSteps"]); + if (parentObject !== void 0 && fromBaseSteps != null) { + setValueByPath(parentObject, ["parameters", "editConfig", "baseSteps"], fromBaseSteps); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject2, [ + "referenceImages" + ]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath(toObject, ["instances[0]", "referenceImages"], transformedList); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + editImageConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function editImageResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject2, [ + "predictions" + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function embedContentConfigToMldev(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject2, ["taskType"]); + if (parentObject !== void 0 && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject2, ["title"]); + if (parentObject !== void 0 && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject2, [ + "outputDimensionality" + ]); + if (parentObject !== void 0 && fromOutputDimensionality != null) { + setValueByPath(parentObject, ["requests[]", "outputDimensionality"], fromOutputDimensionality); + } + if (getValueByPath(fromObject2, ["mimeType"]) !== void 0) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["autoTruncate"]) !== void 0) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embedContentConfigToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + let discriminatorTaskType = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorTaskType === void 0) { + discriminatorTaskType = "PREDICT"; + } + if (discriminatorTaskType === "PREDICT") { + const fromTaskType = getValueByPath(fromObject2, ["taskType"]); + if (parentObject !== void 0 && fromTaskType != null) { + setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType); + } + } else if (discriminatorTaskType === "EMBED_CONTENT") { + const fromTaskType = getValueByPath(fromObject2, ["taskType"]); + if (parentObject !== void 0 && fromTaskType != null) { + setValueByPath(parentObject, ["taskType"], fromTaskType); + } + } + let discriminatorTitle = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorTitle === void 0) { + discriminatorTitle = "PREDICT"; + } + if (discriminatorTitle === "PREDICT") { + const fromTitle = getValueByPath(fromObject2, ["title"]); + if (parentObject !== void 0 && fromTitle != null) { + setValueByPath(parentObject, ["instances[]", "title"], fromTitle); + } + } else if (discriminatorTitle === "EMBED_CONTENT") { + const fromTitle = getValueByPath(fromObject2, ["title"]); + if (parentObject !== void 0 && fromTitle != null) { + setValueByPath(parentObject, ["title"], fromTitle); + } + } + let discriminatorOutputDimensionality = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorOutputDimensionality === void 0) { + discriminatorOutputDimensionality = "PREDICT"; + } + if (discriminatorOutputDimensionality === "PREDICT") { + const fromOutputDimensionality = getValueByPath(fromObject2, [ + "outputDimensionality" + ]); + if (parentObject !== void 0 && fromOutputDimensionality != null) { + setValueByPath(parentObject, ["parameters", "outputDimensionality"], fromOutputDimensionality); + } + } else if (discriminatorOutputDimensionality === "EMBED_CONTENT") { + const fromOutputDimensionality = getValueByPath(fromObject2, [ + "outputDimensionality" + ]); + if (parentObject !== void 0 && fromOutputDimensionality != null) { + setValueByPath(parentObject, ["outputDimensionality"], fromOutputDimensionality); + } + } + let discriminatorMimeType = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorMimeType === void 0) { + discriminatorMimeType = "PREDICT"; + } + if (discriminatorMimeType === "PREDICT") { + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (parentObject !== void 0 && fromMimeType != null) { + setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType); + } + } + let discriminatorAutoTruncate = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorAutoTruncate === void 0) { + discriminatorAutoTruncate = "PREDICT"; + } + if (discriminatorAutoTruncate === "PREDICT") { + const fromAutoTruncate = getValueByPath(fromObject2, [ + "autoTruncate" + ]); + if (parentObject !== void 0 && fromAutoTruncate != null) { + setValueByPath(parentObject, ["parameters", "autoTruncate"], fromAutoTruncate); + } + } else if (discriminatorAutoTruncate === "EMBED_CONTENT") { + const fromAutoTruncate = getValueByPath(fromObject2, [ + "autoTruncate" + ]); + if (parentObject !== void 0 && fromAutoTruncate != null) { + setValueByPath(parentObject, ["autoTruncate"], fromAutoTruncate); + } + } + return toObject; +} +function embedContentParametersPrivateToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContentsForEmbed(apiClient, fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["requests[]", "content"], transformedList); + } + const fromContent = getValueByPath(fromObject2, ["content"]); + if (fromContent != null) { + contentToMldev$1(tContent(fromContent)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + embedContentConfigToMldev(fromConfig, toObject); + } + const fromModelForEmbedContent = getValueByPath(fromObject2, ["model"]); + if (fromModelForEmbedContent !== void 0) { + setValueByPath(toObject, ["requests[]", "model"], tModel(apiClient, fromModelForEmbedContent)); + } + return toObject; +} +function embedContentParametersPrivateToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + let discriminatorContents = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorContents === void 0) { + discriminatorContents = "PREDICT"; + } + if (discriminatorContents === "PREDICT") { + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContentsForEmbed(apiClient, fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["instances[]", "content"], transformedList); + } + } + let discriminatorContent = getValueByPath(rootObject, [ + "embeddingApiType" + ]); + if (discriminatorContent === void 0) { + discriminatorContent = "PREDICT"; + } + if (discriminatorContent === "EMBED_CONTENT") { + const fromContent = getValueByPath(fromObject2, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], tContent(fromContent)); + } + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + embedContentConfigToVertex(fromConfig, toObject, rootObject); + } + return toObject; +} +function embedContentResponseFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject2, ["embeddings"]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject2, [ + "predictions[]", + "embeddings" + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + if (rootObject && getValueByPath(rootObject, ["embeddingApiType"]) === "EMBED_CONTENT") { + const embedding = getValueByPath(fromObject2, ["embedding"]); + const usageMetadata = getValueByPath(fromObject2, ["usageMetadata"]); + const truncated = getValueByPath(fromObject2, ["truncated"]); + if (embedding) { + const stats = {}; + if (usageMetadata && usageMetadata["promptTokenCount"]) { + stats.tokenCount = usageMetadata["promptTokenCount"]; + } + if (truncated) { + stats.truncated = truncated; + } + embedding.statistics = stats; + setValueByPath(toObject, ["embeddings"], [embedding]); + } + } + return toObject; +} +function endpointFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["endpoint"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject2, [ + "deployedModelId" + ]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId); + } + return toObject; +} +function fileDataToMldev$1(fromObject2, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject2, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function functionCallToMldev$1(fromObject2, _rootObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject2, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject2, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + if (getValueByPath(fromObject2, ["partialArgs"]) !== void 0) { + throw new Error("partialArgs parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["willContinue"]) !== void 0) { + throw new Error("willContinue parameter is not supported in Gemini API."); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromAllowedFunctionNames = getValueByPath(fromObject2, [ + "allowedFunctionNames" + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath(toObject, ["allowedFunctionNames"], fromAllowedFunctionNames); + } + const fromMode = getValueByPath(fromObject2, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + if (getValueByPath(fromObject2, ["streamFunctionCallArguments"]) !== void 0) { + throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API."); + } + return toObject; +} +function functionDeclarationToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject2, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject2, [ + "parametersJsonSchema" + ]); + if (fromParametersJsonSchema != null) { + setValueByPath(toObject, ["parametersJsonSchema"], fromParametersJsonSchema); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject2, ["behavior"]) !== void 0) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["systemInstruction"], contentToMldev$1(tContent(fromSystemInstruction))); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject2, [ + "candidateCount" + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject2, [ + "stopSequences" + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject2, [ + "responseLogprobs" + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject2, [ + "presencePenalty" + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject2, [ + "frequencyPenalty" + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject2, [ + "responseMimeType" + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject2, [ + "responseSchema" + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ["responseSchema"], tSchema(fromResponseSchema)); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject2, ["routingConfig"]) !== void 0) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["modelSelectionConfig"]) !== void 0) { + throw new Error("modelSelectionConfig parameter is not supported in Gemini API."); + } + const fromSafetySettings = getValueByPath(fromObject2, [ + "safetySettings" + ]); + if (parentObject !== void 0 && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]); + if (parentObject !== void 0 && fromToolConfig != null) { + setValueByPath(parentObject, ["toolConfig"], toolConfigToMldev(fromToolConfig)); + } + if (getValueByPath(fromObject2, ["labels"]) !== void 0) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject2, [ + "cachedContent" + ]); + if (parentObject !== void 0 && fromCachedContent != null) { + setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ["speechConfig"], tSpeechConfig(fromSpeechConfig)); + } + if (getValueByPath(fromObject2, ["audioTimestamp"]) !== void 0) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig); + } + const fromImageConfig = getValueByPath(fromObject2, ["imageConfig"]); + if (fromImageConfig != null) { + setValueByPath(toObject, ["imageConfig"], imageConfigToMldev(fromImageConfig)); + } + const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject2, [ + "enableEnhancedCivicAnswers" + ]); + if (fromEnableEnhancedCivicAnswers != null) { + setValueByPath(toObject, ["enableEnhancedCivicAnswers"], fromEnableEnhancedCivicAnswers); + } + if (getValueByPath(fromObject2, ["modelArmorConfig"]) !== void 0) { + throw new Error("modelArmorConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["systemInstruction"], tContent(fromSystemInstruction)); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject2, [ + "candidateCount" + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject2, [ + "stopSequences" + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject2, [ + "responseLogprobs" + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject2, [ + "presencePenalty" + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject2, [ + "frequencyPenalty" + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject2, [ + "responseMimeType" + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject2, [ + "responseSchema" + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ["responseSchema"], tSchema(fromResponseSchema)); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject2, [ + "routingConfig" + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject2, [ + "modelSelectionConfig" + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig); + } + const fromSafetySettings = getValueByPath(fromObject2, [ + "safetySettings" + ]); + if (parentObject !== void 0 && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject2, ["toolConfig"]); + if (parentObject !== void 0 && fromToolConfig != null) { + setValueByPath(parentObject, ["toolConfig"], fromToolConfig); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject2, [ + "cachedContent" + ]); + if (parentObject !== void 0 && fromCachedContent != null) { + setValueByPath(parentObject, ["cachedContent"], tCachedContentName(apiClient, fromCachedContent)); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ["speechConfig"], tSpeechConfig(fromSpeechConfig)); + } + const fromAudioTimestamp = getValueByPath(fromObject2, [ + "audioTimestamp" + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig); + } + const fromImageConfig = getValueByPath(fromObject2, ["imageConfig"]); + if (fromImageConfig != null) { + setValueByPath(toObject, ["imageConfig"], imageConfigToVertex(fromImageConfig)); + } + if (getValueByPath(fromObject2, ["enableEnhancedCivicAnswers"]) !== void 0) { + throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI."); + } + const fromModelArmorConfig = getValueByPath(fromObject2, [ + "modelArmorConfig" + ]); + if (parentObject !== void 0 && fromModelArmorConfig != null) { + setValueByPath(parentObject, ["modelArmorConfig"], fromModelArmorConfig); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["generationConfig"], generateContentConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject2, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["generationConfig"], generateContentConfigToVertex(apiClient, fromConfig, toObject)); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject2, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject2, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject2, [ + "promptFeedback" + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject2, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject2, [ + "usageMetadata" + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject2, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromCreateTime = getValueByPath(fromObject2, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromModelVersion = getValueByPath(fromObject2, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject2, [ + "promptFeedback" + ]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromResponseId = getValueByPath(fromObject2, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromUsageMetadata = getValueByPath(fromObject2, [ + "usageMetadata" + ]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject2, parentObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["outputGcsUri"]) !== void 0) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["negativePrompt"]) !== void 0) { + throw new Error("negativePrompt parameter is not supported in Gemini API."); + } + const fromNumberOfImages = getValueByPath(fromObject2, [ + "numberOfImages" + ]); + if (parentObject !== void 0 && fromNumberOfImages != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (parentObject !== void 0 && fromAspectRatio != null) { + setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject2, [ + "guidanceScale" + ]); + if (parentObject !== void 0 && fromGuidanceScale != null) { + setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale); + } + if (getValueByPath(fromObject2, ["seed"]) !== void 0) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromSafetyFilterLevel = getValueByPath(fromObject2, [ + "safetyFilterLevel" + ]); + if (parentObject !== void 0 && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject2, [ + "includeSafetyAttributes" + ]); + if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject2, [ + "includeRaiReason" + ]); + if (parentObject !== void 0 && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject2, ["language"]); + if (parentObject !== void 0 && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject2, [ + "outputMimeType" + ]); + if (parentObject !== void 0 && fromOutputMimeType != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject2, [ + "outputCompressionQuality" + ]); + if (parentObject !== void 0 && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality); + } + if (getValueByPath(fromObject2, ["addWatermark"]) !== void 0) { + throw new Error("addWatermark parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["labels"]) !== void 0) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromImageSize = getValueByPath(fromObject2, ["imageSize"]); + if (parentObject !== void 0 && fromImageSize != null) { + setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize); + } + if (getValueByPath(fromObject2, ["enhancePrompt"]) !== void 0) { + throw new Error("enhancePrompt parameter is not supported in Gemini API."); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]); + if (parentObject !== void 0 && fromOutputGcsUri != null) { + setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri); + } + const fromNegativePrompt = getValueByPath(fromObject2, [ + "negativePrompt" + ]); + if (parentObject !== void 0 && fromNegativePrompt != null) { + setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt); + } + const fromNumberOfImages = getValueByPath(fromObject2, [ + "numberOfImages" + ]); + if (parentObject !== void 0 && fromNumberOfImages != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages); + } + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (parentObject !== void 0 && fromAspectRatio != null) { + setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio); + } + const fromGuidanceScale = getValueByPath(fromObject2, [ + "guidanceScale" + ]); + if (parentObject !== void 0 && fromGuidanceScale != null) { + setValueByPath(parentObject, ["parameters", "guidanceScale"], fromGuidanceScale); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject2, [ + "safetyFilterLevel" + ]); + if (parentObject !== void 0 && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject2, [ + "includeSafetyAttributes" + ]); + if (parentObject !== void 0 && fromIncludeSafetyAttributes != null) { + setValueByPath(parentObject, ["parameters", "includeSafetyAttributes"], fromIncludeSafetyAttributes); + } + const fromIncludeRaiReason = getValueByPath(fromObject2, [ + "includeRaiReason" + ]); + if (parentObject !== void 0 && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason); + } + const fromLanguage = getValueByPath(fromObject2, ["language"]); + if (parentObject !== void 0 && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject2, [ + "outputMimeType" + ]); + if (parentObject !== void 0 && fromOutputMimeType != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject2, [ + "outputCompressionQuality" + ]); + if (parentObject !== void 0 && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality); + } + const fromAddWatermark = getValueByPath(fromObject2, ["addWatermark"]); + if (parentObject !== void 0 && fromAddWatermark != null) { + setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromImageSize = getValueByPath(fromObject2, ["imageSize"]); + if (parentObject !== void 0 && fromImageSize != null) { + setValueByPath(parentObject, ["parameters", "sampleImageSize"], fromImageSize); + } + const fromEnhancePrompt = getValueByPath(fromObject2, [ + "enhancePrompt" + ]); + if (parentObject !== void 0 && fromEnhancePrompt != null) { + setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + generateImagesConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + generateImagesConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject2, [ + "predictions" + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject2, [ + "positivePromptSafetyAttributes" + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromMldev(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject2, [ + "predictions" + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject2, [ + "positivePromptSafetyAttributes" + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath(toObject, ["positivePromptSafetyAttributes"], safetyAttributesFromVertex(fromPositivePromptSafetyAttributes)); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject2, [ + "numberOfVideos" + ]); + if (parentObject !== void 0 && fromNumberOfVideos != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos); + } + if (getValueByPath(fromObject2, ["outputGcsUri"]) !== void 0) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["fps"]) !== void 0) { + throw new Error("fps parameter is not supported in Gemini API."); + } + const fromDurationSeconds = getValueByPath(fromObject2, [ + "durationSeconds" + ]); + if (parentObject !== void 0 && fromDurationSeconds != null) { + setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds); + } + if (getValueByPath(fromObject2, ["seed"]) !== void 0) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (parentObject !== void 0 && fromAspectRatio != null) { + setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject2, ["resolution"]); + if (parentObject !== void 0 && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + if (getValueByPath(fromObject2, ["pubsubTopic"]) !== void 0) { + throw new Error("pubsubTopic parameter is not supported in Gemini API."); + } + const fromNegativePrompt = getValueByPath(fromObject2, [ + "negativePrompt" + ]); + if (parentObject !== void 0 && fromNegativePrompt != null) { + setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject2, [ + "enhancePrompt" + ]); + if (parentObject !== void 0 && fromEnhancePrompt != null) { + setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt); + } + if (getValueByPath(fromObject2, ["generateAudio"]) !== void 0) { + throw new Error("generateAudio parameter is not supported in Gemini API."); + } + const fromLastFrame = getValueByPath(fromObject2, ["lastFrame"]); + if (parentObject !== void 0 && fromLastFrame != null) { + setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToMldev(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject2, [ + "referenceImages" + ]); + if (parentObject !== void 0 && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToMldev(item); + }); + } + setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList); + } + if (getValueByPath(fromObject2, ["mask"]) !== void 0) { + throw new Error("mask parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["compressionQuality"]) !== void 0) { + throw new Error("compressionQuality parameter is not supported in Gemini API."); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject2, [ + "numberOfVideos" + ]); + if (parentObject !== void 0 && fromNumberOfVideos != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfVideos); + } + const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]); + if (parentObject !== void 0 && fromOutputGcsUri != null) { + setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri); + } + const fromFps = getValueByPath(fromObject2, ["fps"]); + if (parentObject !== void 0 && fromFps != null) { + setValueByPath(parentObject, ["parameters", "fps"], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject2, [ + "durationSeconds" + ]); + if (parentObject !== void 0 && fromDurationSeconds != null) { + setValueByPath(parentObject, ["parameters", "durationSeconds"], fromDurationSeconds); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (parentObject !== void 0 && fromAspectRatio != null) { + setValueByPath(parentObject, ["parameters", "aspectRatio"], fromAspectRatio); + } + const fromResolution = getValueByPath(fromObject2, ["resolution"]); + if (parentObject !== void 0 && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + const fromPubsubTopic = getValueByPath(fromObject2, ["pubsubTopic"]); + if (parentObject !== void 0 && fromPubsubTopic != null) { + setValueByPath(parentObject, ["parameters", "pubsubTopic"], fromPubsubTopic); + } + const fromNegativePrompt = getValueByPath(fromObject2, [ + "negativePrompt" + ]); + if (parentObject !== void 0 && fromNegativePrompt != null) { + setValueByPath(parentObject, ["parameters", "negativePrompt"], fromNegativePrompt); + } + const fromEnhancePrompt = getValueByPath(fromObject2, [ + "enhancePrompt" + ]); + if (parentObject !== void 0 && fromEnhancePrompt != null) { + setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt); + } + const fromGenerateAudio = getValueByPath(fromObject2, [ + "generateAudio" + ]); + if (parentObject !== void 0 && fromGenerateAudio != null) { + setValueByPath(parentObject, ["parameters", "generateAudio"], fromGenerateAudio); + } + const fromLastFrame = getValueByPath(fromObject2, ["lastFrame"]); + if (parentObject !== void 0 && fromLastFrame != null) { + setValueByPath(parentObject, ["instances[0]", "lastFrame"], imageToVertex(fromLastFrame)); + } + const fromReferenceImages = getValueByPath(fromObject2, [ + "referenceImages" + ]); + if (parentObject !== void 0 && fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return videoGenerationReferenceImageToVertex(item); + }); + } + setValueByPath(parentObject, ["instances[0]", "referenceImages"], transformedList); + } + const fromMask = getValueByPath(fromObject2, ["mask"]); + if (parentObject !== void 0 && fromMask != null) { + setValueByPath(parentObject, ["instances[0]", "mask"], videoGenerationMaskToVertex(fromMask)); + } + const fromCompressionQuality = getValueByPath(fromObject2, [ + "compressionQuality" + ]); + if (parentObject !== void 0 && fromCompressionQuality != null) { + setValueByPath(parentObject, ["parameters", "compressionQuality"], fromCompressionQuality); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, [ + "response", + "generateVideoResponse" + ]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], generateVideosResponseFromMldev(fromResponse)); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], generateVideosResponseFromVertex(fromResponse)); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["instances[0]", "image"], imageToMldev(fromImage)); + } + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["instances[0]", "video"], videoToMldev(fromVideo)); + } + const fromSource = getValueByPath(fromObject2, ["source"]); + if (fromSource != null) { + generateVideosSourceToMldev(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + generateVideosConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["instances[0]", "video"], videoToVertex(fromVideo)); + } + const fromSource = getValueByPath(fromObject2, ["source"]); + if (fromSource != null) { + generateVideosSourceToVertex(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + generateVideosConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject2, [ + "generatedSamples" + ]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [ + "raiMediaFilteredCount" + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [ + "raiMediaFilteredReasons" + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject2, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject2, [ + "raiMediaFilteredCount" + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath(toObject, ["raiMediaFilteredCount"], fromRaiMediaFilteredCount); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject2, [ + "raiMediaFilteredReasons" + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath(toObject, ["raiMediaFilteredReasons"], fromRaiMediaFilteredReasons); + } + return toObject; +} +function generateVideosSourceToMldev(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (parentObject !== void 0 && fromPrompt != null) { + setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject2, ["image"]); + if (parentObject !== void 0 && fromImage != null) { + setValueByPath(parentObject, ["instances[0]", "image"], imageToMldev(fromImage)); + } + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (parentObject !== void 0 && fromVideo != null) { + setValueByPath(parentObject, ["instances[0]", "video"], videoToMldev(fromVideo)); + } + return toObject; +} +function generateVideosSourceToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (parentObject !== void 0 && fromPrompt != null) { + setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject2, ["image"]); + if (parentObject !== void 0 && fromImage != null) { + setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage)); + } + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (parentObject !== void 0 && fromVideo != null) { + setValueByPath(parentObject, ["instances[0]", "video"], videoToVertex(fromVideo)); + } + return toObject; +} +function generatedImageFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject2, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject2, [ + "raiFilteredReason" + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject2, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromMldev(fromSafetyAttributes)); + } + return toObject; +} +function generatedImageFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject2, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject2, [ + "raiFilteredReason" + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject2, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath(toObject, ["safetyAttributes"], safetyAttributesFromVertex(fromSafetyAttributes)); + } + const fromEnhancedPrompt = getValueByPath(fromObject2, ["prompt"]); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt); + } + return toObject; +} +function generatedImageMaskFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromMask = getValueByPath(fromObject2, ["_self"]); + if (fromMask != null) { + setValueByPath(toObject, ["mask"], imageFromVertex(fromMask)); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (fromLabels != null) { + let transformedList = fromLabels; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["labels"], transformedList); + } + return toObject; +} +function generatedVideoFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject2, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev(fromVideo)); + } + return toObject; +} +function generatedVideoFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject2, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex(fromVideo)); + } + return toObject; +} +function generationConfigToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromModelSelectionConfig = getValueByPath(fromObject2, [ + "modelSelectionConfig" + ]); + if (fromModelSelectionConfig != null) { + setValueByPath(toObject, ["modelConfig"], fromModelSelectionConfig); + } + const fromResponseJsonSchema = getValueByPath(fromObject2, [ + "responseJsonSchema" + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromAudioTimestamp = getValueByPath(fromObject2, [ + "audioTimestamp" + ]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromCandidateCount = getValueByPath(fromObject2, [ + "candidateCount" + ]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject2, [ + "enableAffectiveDialog" + ]); + if (fromEnableAffectiveDialog != null) { + setValueByPath(toObject, ["enableAffectiveDialog"], fromEnableAffectiveDialog); + } + const fromFrequencyPenalty = getValueByPath(fromObject2, [ + "frequencyPenalty" + ]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromLogprobs = getValueByPath(fromObject2, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromPresencePenalty = getValueByPath(fromObject2, [ + "presencePenalty" + ]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromResponseLogprobs = getValueByPath(fromObject2, [ + "responseLogprobs" + ]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromResponseMimeType = getValueByPath(fromObject2, [ + "responseMimeType" + ]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromResponseSchema = getValueByPath(fromObject2, [ + "responseSchema" + ]); + if (fromResponseSchema != null) { + setValueByPath(toObject, ["responseSchema"], fromResponseSchema); + } + const fromRoutingConfig = getValueByPath(fromObject2, [ + "routingConfig" + ]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath(toObject, ["speechConfig"], fromSpeechConfig); + } + const fromStopSequences = getValueByPath(fromObject2, [ + "stopSequences" + ]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (fromThinkingConfig != null) { + setValueByPath(toObject, ["thinkingConfig"], fromThinkingConfig); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + if (getValueByPath(fromObject2, ["enableEnhancedCivicAnswers"]) !== void 0) { + throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI."); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject2, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject2, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + return toObject; +} +function googleMapsToMldev$1(fromObject2, rootObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath(toObject, ["authConfig"], authConfigToMldev$1(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject2, ["enableWidget"]); + if (fromEnableWidget != null) { + setValueByPath(toObject, ["enableWidget"], fromEnableWidget); + } + return toObject; +} +function googleSearchToMldev$1(fromObject2, _rootObject) { + const toObject = {}; + const fromSearchTypes = getValueByPath(fromObject2, ["searchTypes"]); + if (fromSearchTypes != null) { + setValueByPath(toObject, ["searchTypes"], fromSearchTypes); + } + if (getValueByPath(fromObject2, ["blockingConfidence"]) !== void 0) { + throw new Error("blockingConfidence parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) { + throw new Error("excludeDomains parameter is not supported in Gemini API."); + } + const fromTimeRangeFilter = getValueByPath(fromObject2, [ + "timeRangeFilter" + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter); + } + return toObject; +} +function imageConfigToMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (fromAspectRatio != null) { + setValueByPath(toObject, ["aspectRatio"], fromAspectRatio); + } + const fromImageSize = getValueByPath(fromObject2, ["imageSize"]); + if (fromImageSize != null) { + setValueByPath(toObject, ["imageSize"], fromImageSize); + } + if (getValueByPath(fromObject2, ["personGeneration"]) !== void 0) { + throw new Error("personGeneration parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["prominentPeople"]) !== void 0) { + throw new Error("prominentPeople parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["outputMimeType"]) !== void 0) { + throw new Error("outputMimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["outputCompressionQuality"]) !== void 0) { + throw new Error("outputCompressionQuality parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["imageOutputOptions"]) !== void 0) { + throw new Error("imageOutputOptions parameter is not supported in Gemini API."); + } + return toObject; +} +function imageConfigToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromAspectRatio = getValueByPath(fromObject2, ["aspectRatio"]); + if (fromAspectRatio != null) { + setValueByPath(toObject, ["aspectRatio"], fromAspectRatio); + } + const fromImageSize = getValueByPath(fromObject2, ["imageSize"]); + if (fromImageSize != null) { + setValueByPath(toObject, ["imageSize"], fromImageSize); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (fromPersonGeneration != null) { + setValueByPath(toObject, ["personGeneration"], fromPersonGeneration); + } + const fromProminentPeople = getValueByPath(fromObject2, [ + "prominentPeople" + ]); + if (fromProminentPeople != null) { + setValueByPath(toObject, ["prominentPeople"], fromProminentPeople); + } + const fromOutputMimeType = getValueByPath(fromObject2, [ + "outputMimeType" + ]); + if (fromOutputMimeType != null) { + setValueByPath(toObject, ["imageOutputOptions", "mimeType"], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject2, [ + "outputCompressionQuality" + ]); + if (fromOutputCompressionQuality != null) { + setValueByPath(toObject, ["imageOutputOptions", "compressionQuality"], fromOutputCompressionQuality); + } + const fromImageOutputOptions = getValueByPath(fromObject2, [ + "imageOutputOptions" + ]); + if (fromImageOutputOptions != null) { + setValueByPath(toObject, ["imageOutputOptions"], fromImageOutputOptions); + } + return toObject; +} +function imageFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject2, [ + "bytesBase64Encoded" + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function imageFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject2, [ + "bytesBase64Encoded" + ]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function imageToMldev(fromObject2, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["gcsUri"]) !== void 0) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + const fromImageBytes = getValueByPath(fromObject2, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function imageToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject2, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject2, ["filter"]); + if (parentObject !== void 0 && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject2, ["queryBase"]); + if (parentObject !== void 0 && fromQueryBase != null) { + setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject2, ["filter"]); + if (parentObject !== void 0 && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject2, ["queryBase"]); + if (parentObject !== void 0 && fromQueryBase != null) { + setValueByPath(parentObject, ["_url", "models_url"], tModelsUrl(apiClient, fromQueryBase)); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listModelsConfigToMldev(apiClient, fromConfig, toObject); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listModelsConfigToVertex(apiClient, fromConfig, toObject); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject2, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject2, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject2, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject2, [ + "segmentationClasses" + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject2, ["maskDilation"]); + if (fromMaskDilation != null) { + setValueByPath(toObject, ["dilation"], fromMaskDilation); + } + return toObject; +} +function modelFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject2, ["version"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject2, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromMldev(fromTunedModelInfo)); + } + const fromInputTokenLimit = getValueByPath(fromObject2, [ + "inputTokenLimit" + ]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject2, [ + "outputTokenLimit" + ]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject2, [ + "supportedGenerationMethods" + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ["supportedActions"], fromSupportedActions); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromMaxTemperature = getValueByPath(fromObject2, [ + "maxTemperature" + ]); + if (fromMaxTemperature != null) { + setValueByPath(toObject, ["maxTemperature"], fromMaxTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromThinking = getValueByPath(fromObject2, ["thinking"]); + if (fromThinking != null) { + setValueByPath(toObject, ["thinking"], fromThinking); + } + return toObject; +} +function modelFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject2, ["versionId"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject2, ["deployedModels"]); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ["endpoints"], transformedList); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject2, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath(toObject, ["tunedModelInfo"], tunedModelInfoFromVertex(fromTunedModelInfo)); + } + const fromDefaultCheckpointId = getValueByPath(fromObject2, [ + "defaultCheckpointId" + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject2, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function partToMldev$1(fromObject2, rootObject) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromCodeExecutionResult = getValueByPath(fromObject2, [ + "codeExecutionResult" + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject2, [ + "executableCode" + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject2, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], functionCallToMldev$1(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject2, [ + "functionResponse" + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject2, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData)); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromThought = getValueByPath(fromObject2, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject2, [ + "thoughtSignature" + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject2, [ + "videoMetadata" + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + return toObject; +} +function productImageToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromProductImage = getValueByPath(fromObject2, ["productImage"]); + if (fromProductImage != null) { + setValueByPath(toObject, ["image"], imageToVertex(fromProductImage)); + } + return toObject; +} +function recontextImageConfigToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromNumberOfImages = getValueByPath(fromObject2, [ + "numberOfImages" + ]); + if (parentObject !== void 0 && fromNumberOfImages != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages); + } + const fromBaseSteps = getValueByPath(fromObject2, ["baseSteps"]); + if (parentObject !== void 0 && fromBaseSteps != null) { + setValueByPath(parentObject, ["parameters", "baseSteps"], fromBaseSteps); + } + const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]); + if (parentObject !== void 0 && fromOutputGcsUri != null) { + setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject2, [ + "safetyFilterLevel" + ]); + if (parentObject !== void 0 && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + const fromAddWatermark = getValueByPath(fromObject2, ["addWatermark"]); + if (parentObject !== void 0 && fromAddWatermark != null) { + setValueByPath(parentObject, ["parameters", "addWatermark"], fromAddWatermark); + } + const fromOutputMimeType = getValueByPath(fromObject2, [ + "outputMimeType" + ]); + if (parentObject !== void 0 && fromOutputMimeType != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject2, [ + "outputCompressionQuality" + ]); + if (parentObject !== void 0 && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality); + } + const fromEnhancePrompt = getValueByPath(fromObject2, [ + "enhancePrompt" + ]); + if (parentObject !== void 0 && fromEnhancePrompt != null) { + setValueByPath(parentObject, ["parameters", "enhancePrompt"], fromEnhancePrompt); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + return toObject; +} +function recontextImageParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject2, ["source"]); + if (fromSource != null) { + recontextImageSourceToVertex(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + recontextImageConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function recontextImageResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromGeneratedImages = getValueByPath(fromObject2, [ + "predictions" + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function recontextImageSourceToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (parentObject !== void 0 && fromPrompt != null) { + setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromPersonImage = getValueByPath(fromObject2, ["personImage"]); + if (parentObject !== void 0 && fromPersonImage != null) { + setValueByPath(parentObject, ["instances[0]", "personImage", "image"], imageToVertex(fromPersonImage)); + } + const fromProductImages = getValueByPath(fromObject2, [ + "productImages" + ]); + if (parentObject !== void 0 && fromProductImages != null) { + let transformedList = fromProductImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return productImageToVertex(item); + }); + } + setValueByPath(parentObject, ["instances[0]", "productImages"], transformedList); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject2, [ + "referenceImage" + ]); + if (fromReferenceImage != null) { + setValueByPath(toObject, ["referenceImage"], imageToVertex(fromReferenceImage)); + } + const fromReferenceId = getValueByPath(fromObject2, ["referenceId"]); + if (fromReferenceId != null) { + setValueByPath(toObject, ["referenceId"], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject2, [ + "referenceType" + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject2, [ + "maskImageConfig" + ]); + if (fromMaskImageConfig != null) { + setValueByPath(toObject, ["maskImageConfig"], maskReferenceConfigToVertex(fromMaskImageConfig)); + } + const fromControlImageConfig = getValueByPath(fromObject2, [ + "controlImageConfig" + ]); + if (fromControlImageConfig != null) { + setValueByPath(toObject, ["controlImageConfig"], controlReferenceConfigToVertex(fromControlImageConfig)); + } + const fromStyleImageConfig = getValueByPath(fromObject2, [ + "styleImageConfig" + ]); + if (fromStyleImageConfig != null) { + setValueByPath(toObject, ["styleImageConfig"], fromStyleImageConfig); + } + const fromSubjectImageConfig = getValueByPath(fromObject2, [ + "subjectImageConfig" + ]); + if (fromSubjectImageConfig != null) { + setValueByPath(toObject, ["subjectImageConfig"], fromSubjectImageConfig); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject2, [ + "safetyAttributes", + "categories" + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject2, [ + "safetyAttributes", + "scores" + ]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject2, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject2, [ + "safetyAttributes", + "categories" + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject2, [ + "safetyAttributes", + "scores" + ]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject2, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function safetySettingToMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromCategory = getValueByPath(fromObject2, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + if (getValueByPath(fromObject2, ["method"]) !== void 0) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromThreshold = getValueByPath(fromObject2, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function scribbleImageToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageToVertex(fromImage)); + } + return toObject; +} +function segmentImageConfigToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject2, ["mode"]); + if (parentObject !== void 0 && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + const fromMaxPredictions = getValueByPath(fromObject2, [ + "maxPredictions" + ]); + if (parentObject !== void 0 && fromMaxPredictions != null) { + setValueByPath(parentObject, ["parameters", "maxPredictions"], fromMaxPredictions); + } + const fromConfidenceThreshold = getValueByPath(fromObject2, [ + "confidenceThreshold" + ]); + if (parentObject !== void 0 && fromConfidenceThreshold != null) { + setValueByPath(parentObject, ["parameters", "confidenceThreshold"], fromConfidenceThreshold); + } + const fromMaskDilation = getValueByPath(fromObject2, ["maskDilation"]); + if (parentObject !== void 0 && fromMaskDilation != null) { + setValueByPath(parentObject, ["parameters", "maskDilation"], fromMaskDilation); + } + const fromBinaryColorThreshold = getValueByPath(fromObject2, [ + "binaryColorThreshold" + ]); + if (parentObject !== void 0 && fromBinaryColorThreshold != null) { + setValueByPath(parentObject, ["parameters", "binaryColorThreshold"], fromBinaryColorThreshold); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + return toObject; +} +function segmentImageParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSource = getValueByPath(fromObject2, ["source"]); + if (fromSource != null) { + segmentImageSourceToVertex(fromSource, toObject); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + segmentImageConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function segmentImageResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromGeneratedMasks = getValueByPath(fromObject2, ["predictions"]); + if (fromGeneratedMasks != null) { + let transformedList = fromGeneratedMasks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageMaskFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedMasks"], transformedList); + } + return toObject; +} +function segmentImageSourceToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + const fromPrompt = getValueByPath(fromObject2, ["prompt"]); + if (parentObject !== void 0 && fromPrompt != null) { + setValueByPath(parentObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject2, ["image"]); + if (parentObject !== void 0 && fromImage != null) { + setValueByPath(parentObject, ["instances[0]", "image"], imageToVertex(fromImage)); + } + const fromScribbleImage = getValueByPath(fromObject2, [ + "scribbleImage" + ]); + if (parentObject !== void 0 && fromScribbleImage != null) { + setValueByPath(parentObject, ["instances[0]", "scribble"], scribbleImageToVertex(fromScribbleImage)); + } + return toObject; +} +function toolConfigToMldev(fromObject2, rootObject) { + const toObject = {}; + const fromRetrievalConfig = getValueByPath(fromObject2, [ + "retrievalConfig" + ]); + if (fromRetrievalConfig != null) { + setValueByPath(toObject, ["retrievalConfig"], fromRetrievalConfig); + } + const fromFunctionCallingConfig = getValueByPath(fromObject2, [ + "functionCallingConfig" + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath(toObject, ["functionCallingConfig"], functionCallingConfigToMldev(fromFunctionCallingConfig)); + } + return toObject; +} +function toolToMldev$1(fromObject2, rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + const fromFileSearch = getValueByPath(fromObject2, ["fileSearch"]); + if (fromFileSearch != null) { + setValueByPath(toObject, ["fileSearch"], fromFileSearch); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], googleSearchToMldev$1(fromGoogleSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], googleMapsToMldev$1(fromGoogleMaps)); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) { + throw new Error("enterpriseWebSearch parameter is not supported in Gemini API."); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject2, ["parallelAiSearch"]) !== void 0) { + throw new Error("parallelAiSearch parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + const fromMcpServers = getValueByPath(fromObject2, ["mcpServers"]); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["mcpServers"], transformedList); + } + return toObject; +} +function toolToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromRetrieval = getValueByPath(fromObject2, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + if (getValueByPath(fromObject2, ["fileSearch"]) !== void 0) { + throw new Error("fileSearch parameter is not supported in Vertex AI."); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], fromGoogleSearch); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], fromGoogleMaps); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject2, [ + "enterpriseWebSearch" + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath(toObject, ["enterpriseWebSearch"], fromEnterpriseWebSearch); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + const fromParallelAiSearch = getValueByPath(fromObject2, [ + "parallelAiSearch" + ]); + if (fromParallelAiSearch != null) { + setValueByPath(toObject, ["parallelAiSearch"], fromParallelAiSearch); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + if (getValueByPath(fromObject2, ["mcpServers"]) !== void 0) { + throw new Error("mcpServers parameter is not supported in Vertex AI."); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject2, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject2, [ + "labels", + "google-vertex-llm-tuning-base-model-id" + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject2, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function updateModelConfigToMldev(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (parentObject !== void 0 && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject2, [ + "defaultCheckpointId" + ]); + if (parentObject !== void 0 && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelConfigToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (parentObject !== void 0 && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject2, [ + "defaultCheckpointId" + ]); + if (parentObject !== void 0 && fromDefaultCheckpointId != null) { + setValueByPath(parentObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + updateModelConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + updateModelConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject2, ["outputGcsUri"]); + if (parentObject !== void 0 && fromOutputGcsUri != null) { + setValueByPath(parentObject, ["parameters", "storageUri"], fromOutputGcsUri); + } + const fromSafetyFilterLevel = getValueByPath(fromObject2, [ + "safetyFilterLevel" + ]); + if (parentObject !== void 0 && fromSafetyFilterLevel != null) { + setValueByPath(parentObject, ["parameters", "safetySetting"], fromSafetyFilterLevel); + } + const fromPersonGeneration = getValueByPath(fromObject2, [ + "personGeneration" + ]); + if (parentObject !== void 0 && fromPersonGeneration != null) { + setValueByPath(parentObject, ["parameters", "personGeneration"], fromPersonGeneration); + } + const fromIncludeRaiReason = getValueByPath(fromObject2, [ + "includeRaiReason" + ]); + if (parentObject !== void 0 && fromIncludeRaiReason != null) { + setValueByPath(parentObject, ["parameters", "includeRaiReason"], fromIncludeRaiReason); + } + const fromOutputMimeType = getValueByPath(fromObject2, [ + "outputMimeType" + ]); + if (parentObject !== void 0 && fromOutputMimeType != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "mimeType"], fromOutputMimeType); + } + const fromOutputCompressionQuality = getValueByPath(fromObject2, [ + "outputCompressionQuality" + ]); + if (parentObject !== void 0 && fromOutputCompressionQuality != null) { + setValueByPath(parentObject, ["parameters", "outputOptions", "compressionQuality"], fromOutputCompressionQuality); + } + const fromEnhanceInputImage = getValueByPath(fromObject2, [ + "enhanceInputImage" + ]); + if (parentObject !== void 0 && fromEnhanceInputImage != null) { + setValueByPath(parentObject, ["parameters", "upscaleConfig", "enhanceInputImage"], fromEnhanceInputImage); + } + const fromImagePreservationFactor = getValueByPath(fromObject2, [ + "imagePreservationFactor" + ]); + if (parentObject !== void 0 && fromImagePreservationFactor != null) { + setValueByPath(parentObject, ["parameters", "upscaleConfig", "imagePreservationFactor"], fromImagePreservationFactor); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromNumberOfImages = getValueByPath(fromObject2, [ + "numberOfImages" + ]); + if (parentObject !== void 0 && fromNumberOfImages != null) { + setValueByPath(parentObject, ["parameters", "sampleCount"], fromNumberOfImages); + } + const fromMode = getValueByPath(fromObject2, ["mode"]); + if (parentObject !== void 0 && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject2, rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["instances[0]", "image"], imageToVertex(fromImage)); + } + const fromUpscaleFactor = getValueByPath(fromObject2, [ + "upscaleFactor" + ]); + if (fromUpscaleFactor != null) { + setValueByPath(toObject, ["parameters", "upscaleConfig", "upscaleFactor"], fromUpscaleFactor); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject2, [ + "predictions" + ]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function videoFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject2, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject2, ["encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function videoFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject2, [ + "bytesBase64Encoded" + ]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function videoGenerationMaskToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["_self"], imageToVertex(fromImage)); + } + const fromMaskMode = getValueByPath(fromObject2, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + return toObject; +} +function videoGenerationReferenceImageToMldev(fromObject2, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageToMldev(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject2, [ + "referenceType" + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + return toObject; +} +function videoGenerationReferenceImageToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject2, ["image"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageToVertex(fromImage)); + } + const fromReferenceType = getValueByPath(fromObject2, [ + "referenceType" + ]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + return toObject; +} +function videoToMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject2, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject2, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["encodedVideo"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["encoding"], fromMimeType); + } + return toObject; +} +function videoToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject2, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["gcsUri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject2, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function createFileSearchStoreConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + return toObject; +} +function createFileSearchStoreParametersToMldev(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createFileSearchStoreConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function deleteFileSearchStoreConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromForce = getValueByPath(fromObject2, ["force"]); + if (parentObject !== void 0 && fromForce != null) { + setValueByPath(parentObject, ["_query", "force"], fromForce); + } + return toObject; +} +function deleteFileSearchStoreParametersToMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + deleteFileSearchStoreConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function getFileSearchStoreParametersToMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + return toObject; +} +function importFileConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromCustomMetadata = getValueByPath(fromObject2, [ + "customMetadata" + ]); + if (parentObject !== void 0 && fromCustomMetadata != null) { + let transformedList = fromCustomMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ["customMetadata"], transformedList); + } + const fromChunkingConfig = getValueByPath(fromObject2, [ + "chunkingConfig" + ]); + if (parentObject !== void 0 && fromChunkingConfig != null) { + setValueByPath(parentObject, ["chunkingConfig"], fromChunkingConfig); + } + return toObject; +} +function importFileOperationFromMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject2, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], importFileResponseFromMldev(fromResponse)); + } + return toObject; +} +function importFileParametersToMldev(fromObject2) { + const toObject = {}; + const fromFileSearchStoreName = getValueByPath(fromObject2, [ + "fileSearchStoreName" + ]); + if (fromFileSearchStoreName != null) { + setValueByPath(toObject, ["_url", "file_search_store_name"], fromFileSearchStoreName); + } + const fromFileName = getValueByPath(fromObject2, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + importFileConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function importFileResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromParent = getValueByPath(fromObject2, ["parent"]); + if (fromParent != null) { + setValueByPath(toObject, ["parent"], fromParent); + } + const fromDocumentName = getValueByPath(fromObject2, ["documentName"]); + if (fromDocumentName != null) { + setValueByPath(toObject, ["documentName"], fromDocumentName); + } + return toObject; +} +function listFileSearchStoresConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFileSearchStoresParametersToMldev(fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listFileSearchStoresConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listFileSearchStoresResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFileSearchStores = getValueByPath(fromObject2, [ + "fileSearchStores" + ]); + if (fromFileSearchStores != null) { + let transformedList = fromFileSearchStores; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["fileSearchStores"], transformedList); + } + return toObject; +} +function uploadToFileSearchStoreConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (parentObject !== void 0 && fromMimeType != null) { + setValueByPath(parentObject, ["mimeType"], fromMimeType); + } + const fromDisplayName = getValueByPath(fromObject2, ["displayName"]); + if (parentObject !== void 0 && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromCustomMetadata = getValueByPath(fromObject2, [ + "customMetadata" + ]); + if (parentObject !== void 0 && fromCustomMetadata != null) { + let transformedList = fromCustomMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(parentObject, ["customMetadata"], transformedList); + } + const fromChunkingConfig = getValueByPath(fromObject2, [ + "chunkingConfig" + ]); + if (parentObject !== void 0 && fromChunkingConfig != null) { + setValueByPath(parentObject, ["chunkingConfig"], fromChunkingConfig); + } + return toObject; +} +function uploadToFileSearchStoreParametersToMldev(fromObject2) { + const toObject = {}; + const fromFileSearchStoreName = getValueByPath(fromObject2, [ + "fileSearchStoreName" + ]); + if (fromFileSearchStoreName != null) { + setValueByPath(toObject, ["_url", "file_search_store_name"], fromFileSearchStoreName); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + uploadToFileSearchStoreConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function uploadToFileSearchStoreResumableResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +async function throwErrorIfNotOK(response) { + var _a7; + if (response === void 0) { + throw new Error("response is undefined"); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ((_a7 = response.headers.get("content-type")) === null || _a7 === void 0 ? void 0 : _a7.includes("application/json")) { + errorBody = await response.json(); + } else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText + } + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.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 currentBodyObject = {}; + if (typeof requestInit.body === "string" && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if (typeof parsedBody === "object" && parsedBody !== null && !Array.isArray(parsedBody)) { + currentBodyObject = parsedBody; + } 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 (e9) { + console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body."); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if (sourceValue && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue && typeof targetValue === "object" && !Array.isArray(targetValue)) { + output[key] = deepMerge(targetValue, sourceValue); + } else { + if (targetValue && sourceValue && typeof targetValue !== typeof sourceValue) { + console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === "object" && "inputSchema" in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +function setMcpUsageHeader(headers) { + var _a7; + const existingHeader = (_a7 = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a7 !== void 0 ? _a7 : ""; + headers[GOOGLE_API_CLIENT_HEADER] = (existingHeader + ` ${MCP_LABEL}`).trimStart(); +} +function isMcpCallableTool(object) { + return object !== null && typeof object === "object" && object instanceof McpCallableTool; +} +function listAllTools(mcpClient_1) { + return __asyncGenerator(this, arguments, function* listAllTools_1(mcpClient, maxTools = 100) { + let cursor = void 0; + let numTools = 0; + while (numTools < maxTools) { + const t6 = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t6.tools) { + yield yield __await(tool); + numTools++; + } + if (!t6.nextCursor) { + break; + } + cursor = t6.nextCursor; + } + }); +} +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } else { + data = JSON.parse(event.data); + } + Object.assign(serverMessage, data); + onmessage(serverMessage); +} +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +function mapToHeaders$1(map3) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map3)) { + headers.append(key, value); + } + return headers; +} +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } else { + const resp = data; + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +function mapToHeaders(map3) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map3)) { + headers.append(key, value); + } + return headers; +} +function shouldDisableAfc(config) { + var _a7, _b, _c; + if ((_a7 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a7 === void 0 ? void 0 : _a7.disable) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = config === null || config === void 0 ? void 0 : config.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = (_c = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _c === void 0 ? void 0 : _c.maximumRemoteCalls; + if (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls)) || maxCalls == 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:", maxCalls); + return true; + } + return false; +} +function isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; +} +function hasCallableTools(params) { + var _a7, _b, _c; + return (_c = (_b = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools) === null || _b === void 0 ? void 0 : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 ? _c : false; +} +function findAfcIncompatibleToolIndexes(params) { + var _a7; + const afcIncompatibleToolIndexes = []; + if (!((_a7 = params === null || params === void 0 ? void 0 : params.config) === null || _a7 === void 0 ? void 0 : _a7.tools)) { + return afcIncompatibleToolIndexes; + } + params.config.tools.forEach((tool, index2) => { + if (isCallableTool(tool)) { + return; + } + const geminiTool = tool; + if (geminiTool.functionDeclarations && geminiTool.functionDeclarations.length > 0) { + afcIncompatibleToolIndexes.push(index2); + } + }); + return afcIncompatibleToolIndexes; +} +function shouldAppendAfcHistory(config) { + var _a7; + return !((_a7 = config === null || config === void 0 ? void 0 : config.automaticFunctionCalling) === null || _a7 === void 0 ? void 0 : _a7.ignoreCallHistory); +} +function audioTranscriptionConfigToMldev(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["languageCodes"]) !== void 0) { + throw new Error("languageCodes parameter is not supported in Gemini API."); + } + return toObject; +} +function authConfigToMldev(fromObject2) { + const toObject = {}; + const fromApiKey = getValueByPath(fromObject2, ["apiKey"]); + if (fromApiKey != null) { + setValueByPath(toObject, ["apiKey"], fromApiKey); + } + if (getValueByPath(fromObject2, ["apiKeyConfig"]) !== void 0) { + throw new Error("apiKeyConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["authType"]) !== void 0) { + throw new Error("authType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["googleServiceAccountConfig"]) !== void 0) { + throw new Error("googleServiceAccountConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["httpBasicAuthConfig"]) !== void 0) { + throw new Error("httpBasicAuthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oauthConfig"]) !== void 0) { + throw new Error("oauthConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["oidcConfig"]) !== void 0) { + throw new Error("oidcConfig parameter is not supported in Gemini API."); + } + return toObject; +} +function blobToMldev(fromObject2) { + const toObject = {}; + const fromData = getValueByPath(fromObject2, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function contentToMldev(fromObject2) { + const toObject = {}; + const fromParts = getValueByPath(fromObject2, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject2, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject2, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject2, ["expireTime"]); + if (parentObject !== void 0 && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject2, [ + "newSessionExpireTime" + ]); + if (parentObject !== void 0 && fromNewSessionExpireTime != null) { + setValueByPath(parentObject, ["newSessionExpireTime"], fromNewSessionExpireTime); + } + const fromUses = getValueByPath(fromObject2, ["uses"]); + if (parentObject !== void 0 && fromUses != null) { + setValueByPath(parentObject, ["uses"], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject2, [ + "liveConnectConstraints" + ]); + if (parentObject !== void 0 && fromLiveConnectConstraints != null) { + setValueByPath(parentObject, ["bidiGenerateContentSetup"], liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints)); + } + const fromLockAdditionalFields = getValueByPath(fromObject2, [ + "lockAdditionalFields" + ]); + if (parentObject !== void 0 && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], createAuthTokenConfigToMldev(apiClient, fromConfig, toObject)); + } + return toObject; +} +function fileDataToMldev(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["displayName"]) !== void 0) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject2, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject2, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function functionCallToMldev(fromObject2) { + const toObject = {}; + const fromId = getValueByPath(fromObject2, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject2, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + if (getValueByPath(fromObject2, ["partialArgs"]) !== void 0) { + throw new Error("partialArgs parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["willContinue"]) !== void 0) { + throw new Error("willContinue parameter is not supported in Gemini API."); + } + return toObject; +} +function googleMapsToMldev(fromObject2) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject2, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath(toObject, ["authConfig"], authConfigToMldev(fromAuthConfig)); + } + const fromEnableWidget = getValueByPath(fromObject2, ["enableWidget"]); + if (fromEnableWidget != null) { + setValueByPath(toObject, ["enableWidget"], fromEnableWidget); + } + return toObject; +} +function googleSearchToMldev(fromObject2) { + const toObject = {}; + const fromSearchTypes = getValueByPath(fromObject2, ["searchTypes"]); + if (fromSearchTypes != null) { + setValueByPath(toObject, ["searchTypes"], fromSearchTypes); + } + if (getValueByPath(fromObject2, ["blockingConfidence"]) !== void 0) { + throw new Error("blockingConfidence parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["excludeDomains"]) !== void 0) { + throw new Error("excludeDomains parameter is not supported in Gemini API."); + } + const fromTimeRangeFilter = getValueByPath(fromObject2, [ + "timeRangeFilter" + ]); + if (fromTimeRangeFilter != null) { + setValueByPath(toObject, ["timeRangeFilter"], fromTimeRangeFilter); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject2, [ + "generationConfig" + ]); + if (parentObject !== void 0 && fromGenerationConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig"], fromGenerationConfig); + } + const fromResponseModalities = getValueByPath(fromObject2, [ + "responseModalities" + ]); + if (parentObject !== void 0 && fromResponseModalities != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "responseModalities"], fromResponseModalities); + } + const fromTemperature = getValueByPath(fromObject2, ["temperature"]); + if (parentObject !== void 0 && fromTemperature != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject2, ["topP"]); + if (parentObject !== void 0 && fromTopP != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject2, ["topK"]); + if (parentObject !== void 0 && fromTopK != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "topK"], fromTopK); + } + const fromMaxOutputTokens = getValueByPath(fromObject2, [ + "maxOutputTokens" + ]); + if (parentObject !== void 0 && fromMaxOutputTokens != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "maxOutputTokens"], fromMaxOutputTokens); + } + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (parentObject !== void 0 && fromMediaResolution != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "mediaResolution"], fromMediaResolution); + } + const fromSeed = getValueByPath(fromObject2, ["seed"]); + if (parentObject !== void 0 && fromSeed != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "seed"], fromSeed); + } + const fromSpeechConfig = getValueByPath(fromObject2, ["speechConfig"]); + if (parentObject !== void 0 && fromSpeechConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "speechConfig"], tLiveSpeechConfig(fromSpeechConfig)); + } + const fromThinkingConfig = getValueByPath(fromObject2, [ + "thinkingConfig" + ]); + if (parentObject !== void 0 && fromThinkingConfig != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "thinkingConfig"], fromThinkingConfig); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject2, [ + "enableAffectiveDialog" + ]); + if (parentObject !== void 0 && fromEnableAffectiveDialog != null) { + setValueByPath(parentObject, ["setup", "generationConfig", "enableAffectiveDialog"], fromEnableAffectiveDialog); + } + const fromSystemInstruction = getValueByPath(fromObject2, [ + "systemInstruction" + ]); + if (parentObject !== void 0 && fromSystemInstruction != null) { + setValueByPath(parentObject, ["setup", "systemInstruction"], contentToMldev(tContent(fromSystemInstruction))); + } + const fromTools = getValueByPath(fromObject2, ["tools"]); + if (parentObject !== void 0 && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject2, [ + "sessionResumption" + ]); + if (parentObject !== void 0 && fromSessionResumption != null) { + setValueByPath(parentObject, ["setup", "sessionResumption"], sessionResumptionConfigToMldev(fromSessionResumption)); + } + const fromInputAudioTranscription = getValueByPath(fromObject2, [ + "inputAudioTranscription" + ]); + if (parentObject !== void 0 && fromInputAudioTranscription != null) { + setValueByPath(parentObject, ["setup", "inputAudioTranscription"], audioTranscriptionConfigToMldev(fromInputAudioTranscription)); + } + const fromOutputAudioTranscription = getValueByPath(fromObject2, [ + "outputAudioTranscription" + ]); + if (parentObject !== void 0 && fromOutputAudioTranscription != null) { + setValueByPath(parentObject, ["setup", "outputAudioTranscription"], audioTranscriptionConfigToMldev(fromOutputAudioTranscription)); + } + const fromRealtimeInputConfig = getValueByPath(fromObject2, [ + "realtimeInputConfig" + ]); + if (parentObject !== void 0 && fromRealtimeInputConfig != null) { + setValueByPath(parentObject, ["setup", "realtimeInputConfig"], fromRealtimeInputConfig); + } + const fromContextWindowCompression = getValueByPath(fromObject2, [ + "contextWindowCompression" + ]); + if (parentObject !== void 0 && fromContextWindowCompression != null) { + setValueByPath(parentObject, ["setup", "contextWindowCompression"], fromContextWindowCompression); + } + const fromProactivity = getValueByPath(fromObject2, ["proactivity"]); + if (parentObject !== void 0 && fromProactivity != null) { + setValueByPath(parentObject, ["setup", "proactivity"], fromProactivity); + } + if (getValueByPath(fromObject2, ["explicitVadSignal"]) !== void 0) { + throw new Error("explicitVadSignal parameter is not supported in Gemini API."); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject2) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], liveConnectConfigToMldev(fromConfig, toObject)); + } + return toObject; +} +function partToMldev(fromObject2) { + const toObject = {}; + const fromMediaResolution = getValueByPath(fromObject2, [ + "mediaResolution" + ]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromCodeExecutionResult = getValueByPath(fromObject2, [ + "codeExecutionResult" + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject2, [ + "executableCode" + ]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFileData = getValueByPath(fromObject2, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData)); + } + const fromFunctionCall = getValueByPath(fromObject2, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], functionCallToMldev(fromFunctionCall)); + } + const fromFunctionResponse = getValueByPath(fromObject2, [ + "functionResponse" + ]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromInlineData = getValueByPath(fromObject2, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData)); + } + const fromText = getValueByPath(fromObject2, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromThought = getValueByPath(fromObject2, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromThoughtSignature = getValueByPath(fromObject2, [ + "thoughtSignature" + ]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromVideoMetadata = getValueByPath(fromObject2, [ + "videoMetadata" + ]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject2) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject2, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject2, ["transparent"]) !== void 0) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function toolToMldev(fromObject2) { + const toObject = {}; + if (getValueByPath(fromObject2, ["retrieval"]) !== void 0) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromComputerUse = getValueByPath(fromObject2, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath(toObject, ["computerUse"], fromComputerUse); + } + const fromFileSearch = getValueByPath(fromObject2, ["fileSearch"]); + if (fromFileSearch != null) { + setValueByPath(toObject, ["fileSearch"], fromFileSearch); + } + const fromGoogleSearch = getValueByPath(fromObject2, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath(toObject, ["googleSearch"], googleSearchToMldev(fromGoogleSearch)); + } + const fromGoogleMaps = getValueByPath(fromObject2, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath(toObject, ["googleMaps"], googleMapsToMldev(fromGoogleMaps)); + } + const fromCodeExecution = getValueByPath(fromObject2, [ + "codeExecution" + ]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + if (getValueByPath(fromObject2, ["enterpriseWebSearch"]) !== void 0) { + throw new Error("enterpriseWebSearch parameter is not supported in Gemini API."); + } + const fromFunctionDeclarations = getValueByPath(fromObject2, [ + "functionDeclarations" + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject2, [ + "googleSearchRetrieval" + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath(toObject, ["googleSearchRetrieval"], fromGoogleSearchRetrieval); + } + if (getValueByPath(fromObject2, ["parallelAiSearch"]) !== void 0) { + throw new Error("parallelAiSearch parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject2, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], fromUrlContext); + } + const fromMcpServers = getValueByPath(fromObject2, ["mcpServers"]); + if (fromMcpServers != null) { + let transformedList = fromMcpServers; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["mcpServers"], transformedList); + } + return toObject; +} +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + if (typeof value === "object" && value != null && Object.keys(value).length > 0) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } else { + fields.push(key); + } + } + } + return fields.join(","); +} +function convertBidiSetupToTokenSetup(requestDict, config) { + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"]; + if (typeof bidiGenerateContentSetupValue === "object" && bidiGenerateContentSetupValue !== null && "setup" in bidiGenerateContentSetupValue) { + const innerSetup = bidiGenerateContentSetupValue.setup; + if (typeof innerSetup === "object" && innerSetup !== null) { + requestDict["bidiGenerateContentSetup"] = innerSetup; + setupForMaskGeneration = innerSetup; + } else { + delete requestDict["bidiGenerateContentSetup"]; + } + } else if (bidiGenerateContentSetupValue !== void 0) { + delete requestDict["bidiGenerateContentSetup"]; + } + const preExistingFieldMask = requestDict["fieldMask"]; + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if (Array.isArray(config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && (config === null || config === void 0 ? void 0 : config.lockAdditionalFields.length) === 0) { + if (generatedMaskFromBidi) { + requestDict["fieldMask"] = generatedMaskFromBidi; + } else { + delete requestDict["fieldMask"]; + } + } else if ((config === null || config === void 0 ? void 0 : config.lockAdditionalFields) && config.lockAdditionalFields.length > 0 && preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) { + const generationConfigFields = [ + "temperature", + "topK", + "topP", + "maxOutputTokens", + "responseModalities", + "seed", + "speechConfig" + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict["fieldMask"] = finalMaskParts.join(","); + } else { + delete requestDict["fieldMask"]; + } + } else { + delete requestDict["fieldMask"]; + } + } else { + if (preExistingFieldMask !== null && Array.isArray(preExistingFieldMask) && preExistingFieldMask.length > 0) { + requestDict["fieldMask"] = preExistingFieldMask.join(","); + } else { + delete requestDict["fieldMask"]; + } + } + return requestDict; +} +function deleteDocumentConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromForce = getValueByPath(fromObject2, ["force"]); + if (parentObject !== void 0 && fromForce != null) { + setValueByPath(parentObject, ["_query", "force"], fromForce); + } + return toObject; +} +function deleteDocumentParametersToMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + deleteDocumentConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function getDocumentParametersToMldev(fromObject2) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + return toObject; +} +function listDocumentsConfigToMldev(fromObject2, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listDocumentsParametersToMldev(fromObject2) { + const toObject = {}; + const fromParent = getValueByPath(fromObject2, ["parent"]); + if (fromParent != null) { + setValueByPath(toObject, ["_url", "parent"], fromParent); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listDocumentsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listDocumentsResponseFromMldev(fromObject2) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromDocuments = getValueByPath(fromObject2, ["documents"]); + if (fromDocuments != null) { + let transformedList = fromDocuments; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["documents"], transformedList); + } + return toObject; +} +function isAbortError3(err) { + return typeof err === "object" && err !== null && // Spec-compliant fetch implementations + ("name" in err && err.name === "AbortError" || // Expo fetch + "message" in err && String(err.message).includes("FetchRequestCanceledException")); +} +function isEmptyObj3(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +function hasOwn3(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function getDefaultFetch3() { + 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 makeReadableStream3(...args) { + const ReadableStream2 = globalThis.ReadableStream; + if (typeof ReadableStream2 === "undefined") { + throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`"); + } + return new ReadableStream2(...args); +} +function ReadableStreamFrom3(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream3({ + start() { + }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } else { + controller.enqueue(value); + } + }, + async cancel() { + var _a7; + await ((_a7 = iter.return) === null || _a7 === void 0 ? void 0 : _a7.call(iter)); + } + }); +} +function ReadableStreamToAsyncIterable3(stream2) { + if (stream2[Symbol.asyncIterator]) + return stream2; + const reader = stream2.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result === null || result === void 0 ? void 0 : result.done) + reader.releaseLock(); + return result; + } catch (e9) { + reader.releaseLock(); + throw e9; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: void 0 }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; +} +async function CancelReadableStream3(stream2) { + var _a7, _b; + if (stream2 === null || typeof stream2 !== "object") + return; + if (stream2[Symbol.asyncIterator]) { + await ((_b = (_a7 = stream2[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a7)); + return; + } + const reader = stream2.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +function stringifyQuery2(query) { + return Object.entries(query).filter(([_3, value]) => typeof value !== "undefined").map(([key, value]) => { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; 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("&"); +} +function makeFile3(fileBits, fileName, options) { + checkFileSupport3(); + return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : "unknown_file", options); +} +function getName3(value) { + return (typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "").split(/[\\/]/).pop() || void 0; +} +async function toFile3(value, name, options) { + checkFileSupport3(); + value = await value; + if (isFileLike3(value)) { + if (value instanceof File) { + return value; + } + return makeFile3([await value.arrayBuffer()], value.name); + } + if (isResponseLike3(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile3(await getBytes3(blob), name, options); + } + const parts = await getBytes3(value); + name || (name = getName3(value)); + if (!(options === null || options === void 0 ? void 0 : options.type)) { + const type = parts.find((part) => typeof part === "object" && "type" in part && part.type); + if (typeof type === "string") { + options = Object.assign(Object.assign({}, options), { type }); + } + } + return makeFile3(parts, name, options); +} +async function getBytes3(value) { + var _a7, e_1, _b, _c; + var _d; + let parts = []; + if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } else if (isBlobLike3(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } else if (isAsyncIterable3(value)) { + try { + for (var _e2 = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a7 = value_1_1.done, !_a7; _e2 = true) { + _c = value_1_1.value; + _e2 = false; + const chunk = _c; + parts.push(...await getBytes3(chunk)); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_e2 && !_a7 && (_b = value_1.return)) await _b.call(value_1); + } finally { + if (e_1) throw e_1.error; + } + } + } else { + const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError3(value)}`); + } + return parts; +} +function propsForError3(value) { + if (typeof value !== "object" || value === null) + return ""; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p4) => `"${p4}"`).join(", ")}]`; +} +function encodeURIPath3(str2) { + return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +function concatBytes3(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index2 = 0; + for (const buffer of buffers) { + output.set(buffer, index2); + index2 += buffer.length; + } + return output; +} +function encodeUTF83(str2) { + let encoder; + return (encodeUTF8_3 !== null && encodeUTF8_3 !== void 0 ? encodeUTF8_3 : (encoder = new globalThis.TextEncoder(), encodeUTF8_3 = encoder.encode.bind(encoder)))(str2); +} +function decodeUTF83(bytes) { + let decoder; + return (decodeUTF8_3 !== null && decodeUTF8_3 !== void 0 ? decodeUTF8_3 : (decoder = new globalThis.TextDecoder(), decodeUTF8_3 = decoder.decode.bind(decoder)))(bytes); +} +function findNewlineIndex3(buffer, startIndex) { + const newline = 10; + const carriage = 13; + const start = startIndex !== null && startIndex !== void 0 ? startIndex : 0; + const nextNewline = buffer.indexOf(newline, start); + const nextCarriage = buffer.indexOf(carriage, start); + if (nextNewline === -1 && nextCarriage === -1) { + return null; + } + let i7; + if (nextNewline !== -1 && nextCarriage !== -1) { + i7 = Math.min(nextNewline, nextCarriage); + } else { + i7 = nextNewline !== -1 ? nextNewline : nextCarriage; + } + if (buffer[i7] === newline) { + return { preceding: i7, index: i7 + 1, carriage: false }; + } + return { preceding: i7, index: i7 + 1, carriage: true }; +} +function noop3() { +} +function makeLogFn3(fnLevel, logger2, logLevel) { + if (!logger2 || levelNumbers3[fnLevel] > levelNumbers3[logLevel]) { + return noop3; + } else { + return logger2[fnLevel].bind(logger2); + } +} +function loggerFor3(client) { + var _a7; + const logger2 = client.logger; + const logLevel = (_a7 = client.logLevel) !== null && _a7 !== void 0 ? _a7 : "off"; + if (!logger2) { + return noopLogger3; + } + const cachedLogger = cachedLoggers3.get(logger2); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn3("error", logger2, logLevel), + warn: makeLogFn3("warn", logger2, logLevel), + info: makeLogFn3("info", logger2, logLevel), + debug: makeLogFn3("debug", logger2, logLevel) + }; + cachedLoggers3.set(logger2, [logLevel, levelLogger]); + return levelLogger; +} +function _iterSSEMessages3(response, controller) { + return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() { + var _a7, e_4, _b, _c; + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") { + throw new GeminiNextGenAPIClientError(`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 GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder3(); + const lineDecoder = new LineDecoder3(); + const iter = ReadableStreamToAsyncIterable3(response.body); + try { + for (var _d = true, _e2 = __asyncValues(iterBinaryChunks(iter)), _f; _f = yield __await(_e2.next()), _a7 = _f.done, !_a7; _d = true) { + _c = _f.value; + _d = false; + const sseChunk = _c; + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield yield __await(sse); + } + } + } catch (e_4_1) { + e_4 = { error: e_4_1 }; + } finally { + try { + if (!_d && !_a7 && (_b = _e2.return)) yield __await(_b.call(_e2)); + } finally { + if (e_4) throw e_4.error; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield yield __await(sse); + } + }); +} +function iterBinaryChunks(iterator) { + return __asyncGenerator(this, arguments, function* iterBinaryChunks_1() { + var _a7, e_5, _b, _c; + try { + for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a7 = iterator_3_1.done, !_a7; _d = true) { + _c = iterator_3_1.value; + _d = false; + const chunk = _c; + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF83(chunk) : chunk; + yield yield __await(binaryChunk); + } + } catch (e_5_1) { + e_5 = { error: e_5_1 }; + } finally { + try { + if (!_d && !_a7 && (_b = iterator_3.return)) yield __await(_b.call(iterator_3)); + } finally { + if (e_5) throw e_5.error; + } + } + }); +} +function partition3(str2, delimiter2) { + const index2 = str2.indexOf(delimiter2); + if (index2 !== -1) { + return [str2.substring(0, index2), delimiter2, str2.substring(index2 + delimiter2.length)]; + } + return [str2, "", ""]; +} +async function defaultParseResponse3(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + var _a7; + if (props.options.stream) { + loggerFor3(client).debug("response", response.status, response.url, response.headers, response.body); + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller, client); + } + return Stream3.fromSSEResponse(response, props.controller, client); + } + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get("content-type"); + const mediaType = (_a7 = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0]) === null || _a7 === void 0 ? void 0 : _a7.trim(); + const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes("application/json")) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith("+json")); + if (isJSON) { + const contentLength = response.headers.get("content-length"); + if (contentLength === "0") { + return void 0; + } + const json2 = await response.json(); + return json2; + } + const text3 = await response.text(); + return text3; + })(); + loggerFor3(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime + })); + return body; +} +function* iterateHeaders3(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders3 in headers) { + const { values: values2, nulls } = headers; + yield* values2.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } else if (isReadonlyArray3(headers)) { + iter = headers; + } else { + shouldClear = true; + iter = Object.entries(headers !== null && headers !== void 0 ? headers : {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== "string") + throw new TypeError("expected header name to be a string"); + const values2 = isReadonlyArray3(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values2) { + if (value === void 0) + continue; + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +function cancelTuningJobParametersToMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + return toObject; +} +function cancelTuningJobParametersToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + return toObject; +} +function cancelTuningJobResponseFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function cancelTuningJobResponseFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject2, parentObject, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["validationDataset"]) !== void 0) { + throw new Error("validationDataset parameter is not supported in Gemini API."); + } + const fromTunedModelDisplayName = getValueByPath(fromObject2, [ + "tunedModelDisplayName" + ]); + if (parentObject !== void 0 && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject2, ["description"]) !== void 0) { + throw new Error("description parameter is not supported in Gemini API."); + } + const fromEpochCount = getValueByPath(fromObject2, ["epochCount"]); + if (parentObject !== void 0 && fromEpochCount != null) { + setValueByPath(parentObject, ["tuningTask", "hyperparameters", "epochCount"], fromEpochCount); + } + const fromLearningRateMultiplier = getValueByPath(fromObject2, [ + "learningRateMultiplier" + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath(toObject, ["tuningTask", "hyperparameters", "learningRateMultiplier"], fromLearningRateMultiplier); + } + if (getValueByPath(fromObject2, ["exportLastCheckpointOnly"]) !== void 0) { + throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["preTunedModelCheckpointId"]) !== void 0) { + throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["adapterSize"]) !== void 0) { + throw new Error("adapterSize parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["tuningMode"]) !== void 0) { + throw new Error("tuningMode parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["customBaseModel"]) !== void 0) { + throw new Error("customBaseModel parameter is not supported in Gemini API."); + } + const fromBatchSize = getValueByPath(fromObject2, ["batchSize"]); + if (parentObject !== void 0 && fromBatchSize != null) { + setValueByPath(parentObject, ["tuningTask", "hyperparameters", "batchSize"], fromBatchSize); + } + const fromLearningRate = getValueByPath(fromObject2, ["learningRate"]); + if (parentObject !== void 0 && fromLearningRate != null) { + setValueByPath(parentObject, ["tuningTask", "hyperparameters", "learningRate"], fromLearningRate); + } + if (getValueByPath(fromObject2, ["labels"]) !== void 0) { + throw new Error("labels parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["beta"]) !== void 0) { + throw new Error("beta parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["baseTeacherModel"]) !== void 0) { + throw new Error("baseTeacherModel parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["tunedTeacherModelSource"]) !== void 0) { + throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["sftLossWeightMultiplier"]) !== void 0) { + throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["outputUri"]) !== void 0) { + throw new Error("outputUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["encryptionSpec"]) !== void 0) { + throw new Error("encryptionSpec parameter is not supported in Gemini API."); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + let discriminatorValidationDataset = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorValidationDataset === void 0) { + discriminatorValidationDataset = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorValidationDataset === "SUPERVISED_FINE_TUNING") { + const fromValidationDataset = getValueByPath(fromObject2, [ + "validationDataset" + ]); + if (parentObject !== void 0 && fromValidationDataset != null) { + setValueByPath(parentObject, ["supervisedTuningSpec"], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } else if (discriminatorValidationDataset === "PREFERENCE_TUNING") { + const fromValidationDataset = getValueByPath(fromObject2, [ + "validationDataset" + ]); + if (parentObject !== void 0 && fromValidationDataset != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec"], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } else if (discriminatorValidationDataset === "DISTILLATION") { + const fromValidationDataset = getValueByPath(fromObject2, [ + "validationDataset" + ]); + if (parentObject !== void 0 && fromValidationDataset != null) { + setValueByPath(parentObject, ["distillationSpec"], tuningValidationDatasetToVertex(fromValidationDataset)); + } + } + const fromTunedModelDisplayName = getValueByPath(fromObject2, [ + "tunedModelDisplayName" + ]); + if (parentObject !== void 0 && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["tunedModelDisplayName"], fromTunedModelDisplayName); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (parentObject !== void 0 && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + let discriminatorEpochCount = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorEpochCount === void 0) { + discriminatorEpochCount = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorEpochCount === "SUPERVISED_FINE_TUNING") { + const fromEpochCount = getValueByPath(fromObject2, ["epochCount"]); + if (parentObject !== void 0 && fromEpochCount != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "epochCount"], fromEpochCount); + } + } else if (discriminatorEpochCount === "PREFERENCE_TUNING") { + const fromEpochCount = getValueByPath(fromObject2, ["epochCount"]); + if (parentObject !== void 0 && fromEpochCount != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "epochCount"], fromEpochCount); + } + } else if (discriminatorEpochCount === "DISTILLATION") { + const fromEpochCount = getValueByPath(fromObject2, ["epochCount"]); + if (parentObject !== void 0 && fromEpochCount != null) { + setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "epochCount"], fromEpochCount); + } + } + let discriminatorLearningRateMultiplier = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorLearningRateMultiplier === void 0) { + discriminatorLearningRateMultiplier = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorLearningRateMultiplier === "SUPERVISED_FINE_TUNING") { + const fromLearningRateMultiplier = getValueByPath(fromObject2, [ + "learningRateMultiplier" + ]); + if (parentObject !== void 0 && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier); + } + } else if (discriminatorLearningRateMultiplier === "PREFERENCE_TUNING") { + const fromLearningRateMultiplier = getValueByPath(fromObject2, [ + "learningRateMultiplier" + ]); + if (parentObject !== void 0 && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, [ + "preferenceOptimizationSpec", + "hyperParameters", + "learningRateMultiplier" + ], fromLearningRateMultiplier); + } + } else if (discriminatorLearningRateMultiplier === "DISTILLATION") { + const fromLearningRateMultiplier = getValueByPath(fromObject2, [ + "learningRateMultiplier" + ]); + if (parentObject !== void 0 && fromLearningRateMultiplier != null) { + setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "learningRateMultiplier"], fromLearningRateMultiplier); + } + } + let discriminatorExportLastCheckpointOnly = getValueByPath(rootObject, ["config", "method"]); + if (discriminatorExportLastCheckpointOnly === void 0) { + discriminatorExportLastCheckpointOnly = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorExportLastCheckpointOnly === "SUPERVISED_FINE_TUNING") { + const fromExportLastCheckpointOnly = getValueByPath(fromObject2, [ + "exportLastCheckpointOnly" + ]); + if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly); + } + } else if (discriminatorExportLastCheckpointOnly === "PREFERENCE_TUNING") { + const fromExportLastCheckpointOnly = getValueByPath(fromObject2, [ + "exportLastCheckpointOnly" + ]); + if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly); + } + } else if (discriminatorExportLastCheckpointOnly === "DISTILLATION") { + const fromExportLastCheckpointOnly = getValueByPath(fromObject2, [ + "exportLastCheckpointOnly" + ]); + if (parentObject !== void 0 && fromExportLastCheckpointOnly != null) { + setValueByPath(parentObject, ["distillationSpec", "exportLastCheckpointOnly"], fromExportLastCheckpointOnly); + } + } + let discriminatorAdapterSize = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorAdapterSize === void 0) { + discriminatorAdapterSize = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorAdapterSize === "SUPERVISED_FINE_TUNING") { + const fromAdapterSize = getValueByPath(fromObject2, ["adapterSize"]); + if (parentObject !== void 0 && fromAdapterSize != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "adapterSize"], fromAdapterSize); + } + } else if (discriminatorAdapterSize === "PREFERENCE_TUNING") { + const fromAdapterSize = getValueByPath(fromObject2, ["adapterSize"]); + if (parentObject !== void 0 && fromAdapterSize != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "adapterSize"], fromAdapterSize); + } + } else if (discriminatorAdapterSize === "DISTILLATION") { + const fromAdapterSize = getValueByPath(fromObject2, ["adapterSize"]); + if (parentObject !== void 0 && fromAdapterSize != null) { + setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "adapterSize"], fromAdapterSize); + } + } + let discriminatorTuningMode = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorTuningMode === void 0) { + discriminatorTuningMode = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorTuningMode === "SUPERVISED_FINE_TUNING") { + const fromTuningMode = getValueByPath(fromObject2, ["tuningMode"]); + if (parentObject !== void 0 && fromTuningMode != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "tuningMode"], fromTuningMode); + } + } + const fromCustomBaseModel = getValueByPath(fromObject2, [ + "customBaseModel" + ]); + if (parentObject !== void 0 && fromCustomBaseModel != null) { + setValueByPath(parentObject, ["customBaseModel"], fromCustomBaseModel); + } + let discriminatorBatchSize = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorBatchSize === void 0) { + discriminatorBatchSize = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorBatchSize === "SUPERVISED_FINE_TUNING") { + const fromBatchSize = getValueByPath(fromObject2, ["batchSize"]); + if (parentObject !== void 0 && fromBatchSize != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "batchSize"], fromBatchSize); + } + } + let discriminatorLearningRate = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorLearningRate === void 0) { + discriminatorLearningRate = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorLearningRate === "SUPERVISED_FINE_TUNING") { + const fromLearningRate = getValueByPath(fromObject2, [ + "learningRate" + ]); + if (parentObject !== void 0 && fromLearningRate != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "hyperParameters", "learningRate"], fromLearningRate); + } + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (parentObject !== void 0 && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromBeta = getValueByPath(fromObject2, ["beta"]); + if (parentObject !== void 0 && fromBeta != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec", "hyperParameters", "beta"], fromBeta); + } + const fromBaseTeacherModel = getValueByPath(fromObject2, [ + "baseTeacherModel" + ]); + if (parentObject !== void 0 && fromBaseTeacherModel != null) { + setValueByPath(parentObject, ["distillationSpec", "baseTeacherModel"], fromBaseTeacherModel); + } + const fromTunedTeacherModelSource = getValueByPath(fromObject2, [ + "tunedTeacherModelSource" + ]); + if (parentObject !== void 0 && fromTunedTeacherModelSource != null) { + setValueByPath(parentObject, ["distillationSpec", "tunedTeacherModelSource"], fromTunedTeacherModelSource); + } + const fromSftLossWeightMultiplier = getValueByPath(fromObject2, [ + "sftLossWeightMultiplier" + ]); + if (parentObject !== void 0 && fromSftLossWeightMultiplier != null) { + setValueByPath(parentObject, ["distillationSpec", "hyperParameters", "sftLossWeightMultiplier"], fromSftLossWeightMultiplier); + } + const fromOutputUri = getValueByPath(fromObject2, ["outputUri"]); + if (parentObject !== void 0 && fromOutputUri != null) { + setValueByPath(parentObject, ["outputUri"], fromOutputUri); + } + const fromEncryptionSpec = getValueByPath(fromObject2, [ + "encryptionSpec" + ]); + if (parentObject !== void 0 && fromEncryptionSpec != null) { + setValueByPath(parentObject, ["encryptionSpec"], fromEncryptionSpec); + } + return toObject; +} +function createTuningJobParametersPrivateToMldev(fromObject2, rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject2, [ + "preTunedModel" + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject2, [ + "trainingDataset" + ]); + if (fromTrainingDataset != null) { + tuningDatasetToMldev(fromTrainingDataset); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createTuningJobConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function createTuningJobParametersPrivateToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromPreTunedModel = getValueByPath(fromObject2, [ + "preTunedModel" + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel); + } + const fromTrainingDataset = getValueByPath(fromObject2, [ + "trainingDataset" + ]); + if (fromTrainingDataset != null) { + tuningDatasetToVertex(fromTrainingDataset, toObject, rootObject); + } + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + createTuningJobConfigToVertex(fromConfig, toObject, rootObject); + } + return toObject; +} +function getTuningJobParametersToMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject2, ["filter"]); + if (parentObject !== void 0 && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject2, parentObject, _rootObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject2, ["pageSize"]); + if (parentObject !== void 0 && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject2, ["pageToken"]); + if (parentObject !== void 0 && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject2, ["filter"]); + if (parentObject !== void 0 && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject2, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listTuningJobsConfigToMldev(fromConfig, toObject); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject2, rootObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject2, ["config"]); + if (fromConfig != null) { + listTuningJobsConfigToVertex(fromConfig, toObject); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject2, ["tunedModels"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject2, [ + "nextPageToken" + ]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject2, ["tuningJobs"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function tunedModelFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject2, ["name"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject2, ["name"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tuningDatasetToMldev(fromObject2, _rootObject) { + const toObject = {}; + if (getValueByPath(fromObject2, ["gcsUri"]) !== void 0) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject2, ["vertexDatasetResource"]) !== void 0) { + throw new Error("vertexDatasetResource parameter is not supported in Gemini API."); + } + const fromExamples = getValueByPath(fromObject2, ["examples"]); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["examples", "examples"], transformedList); + } + return toObject; +} +function tuningDatasetToVertex(fromObject2, parentObject, rootObject) { + const toObject = {}; + let discriminatorGcsUri = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorGcsUri === void 0) { + discriminatorGcsUri = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorGcsUri === "SUPERVISED_FINE_TUNING") { + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (parentObject !== void 0 && fromGcsUri != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromGcsUri); + } + } else if (discriminatorGcsUri === "PREFERENCE_TUNING") { + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (parentObject !== void 0 && fromGcsUri != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec", "trainingDatasetUri"], fromGcsUri); + } + } else if (discriminatorGcsUri === "DISTILLATION") { + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (parentObject !== void 0 && fromGcsUri != null) { + setValueByPath(parentObject, ["distillationSpec", "promptDatasetUri"], fromGcsUri); + } + } + let discriminatorVertexDatasetResource = getValueByPath(rootObject, [ + "config", + "method" + ]); + if (discriminatorVertexDatasetResource === void 0) { + discriminatorVertexDatasetResource = "SUPERVISED_FINE_TUNING"; + } + if (discriminatorVertexDatasetResource === "SUPERVISED_FINE_TUNING") { + const fromVertexDatasetResource = getValueByPath(fromObject2, [ + "vertexDatasetResource" + ]); + if (parentObject !== void 0 && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ["supervisedTuningSpec", "trainingDatasetUri"], fromVertexDatasetResource); + } + } else if (discriminatorVertexDatasetResource === "PREFERENCE_TUNING") { + const fromVertexDatasetResource = getValueByPath(fromObject2, [ + "vertexDatasetResource" + ]); + if (parentObject !== void 0 && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ["preferenceOptimizationSpec", "trainingDatasetUri"], fromVertexDatasetResource); + } + } else if (discriminatorVertexDatasetResource === "DISTILLATION") { + const fromVertexDatasetResource = getValueByPath(fromObject2, [ + "vertexDatasetResource" + ]); + if (parentObject !== void 0 && fromVertexDatasetResource != null) { + setValueByPath(parentObject, ["distillationSpec", "promptDatasetUri"], fromVertexDatasetResource); + } + } + if (getValueByPath(fromObject2, ["examples"]) !== void 0) { + throw new Error("examples parameter is not supported in Vertex AI."); + } + return toObject; +} +function tuningJobFromMldev(fromObject2, rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject2, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject2, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject2, [ + "tuningTask", + "startTime" + ]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject2, [ + "tuningTask", + "completeTime" + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject2, ["_self"]); + if (fromTunedModel != null) { + setValueByPath(toObject, ["tunedModel"], tunedModelFromMldev(fromTunedModel)); + } + return toObject; +} +function tuningJobFromVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject2, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject2, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject2, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject2, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject2, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromDescription = getValueByPath(fromObject2, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject2, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject2, ["tunedModel"]); + if (fromTunedModel != null) { + setValueByPath(toObject, ["tunedModel"], fromTunedModel); + } + const fromPreTunedModel = getValueByPath(fromObject2, [ + "preTunedModel" + ]); + if (fromPreTunedModel != null) { + setValueByPath(toObject, ["preTunedModel"], fromPreTunedModel); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject2, [ + "supervisedTuningSpec" + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath(toObject, ["supervisedTuningSpec"], fromSupervisedTuningSpec); + } + const fromPreferenceOptimizationSpec = getValueByPath(fromObject2, [ + "preferenceOptimizationSpec" + ]); + if (fromPreferenceOptimizationSpec != null) { + setValueByPath(toObject, ["preferenceOptimizationSpec"], fromPreferenceOptimizationSpec); + } + const fromDistillationSpec = getValueByPath(fromObject2, [ + "distillationSpec" + ]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromTuningDataStats = getValueByPath(fromObject2, [ + "tuningDataStats" + ]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject2, [ + "encryptionSpec" + ]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject2, [ + "partnerModelTuningSpec" + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath(toObject, ["partnerModelTuningSpec"], fromPartnerModelTuningSpec); + } + const fromCustomBaseModel = getValueByPath(fromObject2, [ + "customBaseModel" + ]); + if (fromCustomBaseModel != null) { + setValueByPath(toObject, ["customBaseModel"], fromCustomBaseModel); + } + const fromEvaluateDatasetRuns = getValueByPath(fromObject2, [ + "evaluateDatasetRuns" + ]); + if (fromEvaluateDatasetRuns != null) { + let transformedList = fromEvaluateDatasetRuns; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return item; + }); + } + setValueByPath(toObject, ["evaluateDatasetRuns"], transformedList); + } + const fromExperiment = getValueByPath(fromObject2, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromFullFineTuningSpec = getValueByPath(fromObject2, [ + "fullFineTuningSpec" + ]); + if (fromFullFineTuningSpec != null) { + setValueByPath(toObject, ["fullFineTuningSpec"], fromFullFineTuningSpec); + } + const fromLabels = getValueByPath(fromObject2, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromOutputUri = getValueByPath(fromObject2, ["outputUri"]); + if (fromOutputUri != null) { + setValueByPath(toObject, ["outputUri"], fromOutputUri); + } + const fromPipelineJob = getValueByPath(fromObject2, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromServiceAccount = getValueByPath(fromObject2, [ + "serviceAccount" + ]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject2, [ + "tunedModelDisplayName" + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath(toObject, ["tunedModelDisplayName"], fromTunedModelDisplayName); + } + const fromTuningJobState = getValueByPath(fromObject2, [ + "tuningJobState" + ]); + if (fromTuningJobState != null) { + setValueByPath(toObject, ["tuningJobState"], fromTuningJobState); + } + const fromVeoTuningSpec = getValueByPath(fromObject2, [ + "veoTuningSpec" + ]); + if (fromVeoTuningSpec != null) { + setValueByPath(toObject, ["veoTuningSpec"], fromVeoTuningSpec); + } + return toObject; +} +function tuningOperationFromMldev(fromObject2, _rootObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject2, [ + "sdkHttpResponse" + ]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject2, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject2, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject2, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject2, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject2, _rootObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject2, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject2, [ + "vertexDatasetResource" + ]); + if (fromVertexDatasetResource != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromVertexDatasetResource); + } + return toObject; +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a7; + const response = await uploadBlobInternal(file, uploadUrl, apiClient); + const responseJson = await (response === null || response === void 0 ? void 0 : response.json()); + if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + return responseJson["file"]; +} +async function uploadBlobToFileSearchStore(file, uploadUrl, apiClient) { + var _a7; + const response = await uploadBlobInternal(file, uploadUrl, apiClient); + const responseJson = await (response === null || response === void 0 ? void 0 : response.json()); + if (((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final") { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + const resp = uploadToFileSearchStoreOperationFromMldev(responseJson); + const typedResp = new UploadToFileSearchStoreOperation(); + Object.assign(typedResp, resp); + return typedResp; +} +async function uploadBlobInternal(file, uploadUrl, apiClient) { + var _a7, _b; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(chunkSize) + } + } + }); + if ((_a7 = response === null || response === void 0 ? void 0 : response.headers) === null || _a7 === void 0 ? void 0 : _a7[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) { + break; + } + retryCount++; + await sleep3(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active") { + break; + } + if (fileSize <= offset) { + throw new Error("All content has been uploaded, but the upload status is not finalized."); + } + } + return response; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep3(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} +var import_p_retry, _defaultBaseGeminiUrl, _defaultBaseVertexUrl, BaseModule, Outcome, Language, FunctionResponseScheduling, Type2, PhishBlockThreshold, AuthType, HttpElementLocation, ApiSpec, Behavior, DynamicRetrievalConfigMode, FunctionCallingConfigMode, ThinkingLevel, PersonGeneration, HarmCategory, HarmBlockMethod, HarmBlockThreshold, FinishReason, HarmProbability, HarmSeverity, UrlRetrievalStatus, BlockedReason, TrafficType, Modality, MediaResolution, TuningMode, AdapterSize, JobState, TuningJobState, AggregationMetric, PairwiseChoice, TuningTask, PartMediaResolutionLevel, ResourceScope, FeatureSelectionPreference, Environment, ProminentPeople, EmbeddingApiType, SafetyFilterLevel, ImagePromptLanguage, MaskReferenceMode, ControlReferenceType, SubjectReferenceType, EditMode, SegmentMode, VideoGenerationReferenceType, VideoGenerationMaskMode, VideoCompressionQuality, TuningMethod, DocumentState, FileState, FileSource, TurnCompleteReason, MediaModality, VadSignalType, VoiceActivityType, StartSensitivity, EndSensitivity, ActivityHandling, TurnCoverage, Scale, MusicGenerationMode, LiveMusicPlaybackControl, HttpResponse, GenerateContentResponse, EmbedContentResponse, GenerateImagesResponse, EditImageResponse, UpscaleImageResponse, RecontextImageResponse, SegmentImageResponse, ListModelsResponse, DeleteModelResponse, CountTokensResponse, ComputeTokensResponse, GenerateVideosOperation, ListTuningJobsResponse, CancelTuningJobResponse, DeleteCachedContentResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, UploadToFileSearchStoreResumableResponse, ImportFileOperation, ListFilesResponse, CreateFileResponse, DeleteFileResponse, RegisterFilesResponse, ListBatchJobsResponse, LiveServerMessage, LiveMusicServerMessage, UploadToFileSearchStoreOperation, PagedItem, Pager, Batches4, Caches, Chats, Chat2, ApiError, Files5, CONTENT_TYPE_HEADER, SERVER_TIMEOUT_HEADER, USER_AGENT_HEADER, GOOGLE_API_CLIENT_HEADER, SDK_VERSION, LIBRARY_LABEL, VERTEX_AI_API_DEFAULT_VERSION, GOOGLE_AI_API_DEFAULT_VERSION, DEFAULT_RETRY_ATTEMPTS, DEFAULT_RETRY_HTTP_STATUS_CODES, ApiClient, MCP_LABEL, hasMcpToolUsageFromMcpToTool, McpCallableTool, LiveMusic, LiveMusicSession, FUNCTION_RESPONSE_REQUIRES_ID, Live, defaultLiveSendClientContentParamerters, Session, DEFAULT_MAX_REMOTE_CALLS, Models4, Operations, Tokens, Documents, FileSearchStores, uuid4Internal, uuid43, castToError3, GeminiNextGenAPIClientError, APIError3, APIUserAbortError3, APIConnectionError3, APIConnectionTimeoutError3, BadRequestError3, AuthenticationError3, PermissionDeniedError3, NotFoundError3, ConflictError3, UnprocessableEntityError3, RateLimitError3, InternalServerError3, startsWithSchemeRegexp3, isAbsoluteURL3, isArrayInternal, isArray3, isReadonlyArrayInternal, isReadonlyArray3, validatePositiveInteger3, safeJSON3, sleep$1, FallbackEncoder3, VERSION3, checkFileSupport3, isAsyncIterable3, isBlobLike3, isFileLike3, isResponseLike3, APIResource3, EMPTY3, createPathTagFunction3, path3, BaseInteractions, Interactions, encodeUTF8_3, decodeUTF8_3, LineDecoder3, levelNumbers3, parseLogLevel3, noopLogger3, cachedLoggers3, formatRequestDetails3, Stream3, SSEDecoder3, APIPromise3, brand_privateNullableHeaders3, buildHeaders3, readEnv3, _a4, BaseGeminiNextGenAPIClient, GeminiNextGenAPIClient, Tunings, BrowserDownloader, MAX_CHUNK_SIZE, MAX_RETRY_COUNT, INITIAL_RETRY_DELAY_MS, DELAY_MULTIPLIER, X_GOOG_UPLOAD_STATUS_HEADER_FIELD, BrowserUploader, BrowserWebSocketFactory, BrowserWebSocket, GOOGLE_API_KEY_HEADER, WebAuth, LANGUAGE_LABEL_PREFIX, GoogleGenAI; +var init_web = __esm({ + "../pi-mono/node_modules/@google/genai/dist/web/index.mjs"() { + init_process_shim(); + import_p_retry = __toESM(require_p_retry(), 1); + _defaultBaseGeminiUrl = void 0; + _defaultBaseVertexUrl = void 0; + BaseModule = class { + }; + (function(Outcome2) { + Outcome2["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + Outcome2["OUTCOME_OK"] = "OUTCOME_OK"; + Outcome2["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; + })(Outcome || (Outcome = {})); + (function(Language2) { + Language2["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + Language2["PYTHON"] = "PYTHON"; + })(Language || (Language = {})); + (function(FunctionResponseScheduling2) { + FunctionResponseScheduling2["SCHEDULING_UNSPECIFIED"] = "SCHEDULING_UNSPECIFIED"; + FunctionResponseScheduling2["SILENT"] = "SILENT"; + FunctionResponseScheduling2["WHEN_IDLE"] = "WHEN_IDLE"; + FunctionResponseScheduling2["INTERRUPT"] = "INTERRUPT"; + })(FunctionResponseScheduling || (FunctionResponseScheduling = {})); + (function(Type4) { + Type4["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + Type4["STRING"] = "STRING"; + Type4["NUMBER"] = "NUMBER"; + Type4["INTEGER"] = "INTEGER"; + Type4["BOOLEAN"] = "BOOLEAN"; + Type4["ARRAY"] = "ARRAY"; + Type4["OBJECT"] = "OBJECT"; + Type4["NULL"] = "NULL"; + })(Type2 || (Type2 = {})); + (function(PhishBlockThreshold2) { + PhishBlockThreshold2["PHISH_BLOCK_THRESHOLD_UNSPECIFIED"] = "PHISH_BLOCK_THRESHOLD_UNSPECIFIED"; + PhishBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + PhishBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + PhishBlockThreshold2["BLOCK_HIGH_AND_ABOVE"] = "BLOCK_HIGH_AND_ABOVE"; + PhishBlockThreshold2["BLOCK_HIGHER_AND_ABOVE"] = "BLOCK_HIGHER_AND_ABOVE"; + PhishBlockThreshold2["BLOCK_VERY_HIGH_AND_ABOVE"] = "BLOCK_VERY_HIGH_AND_ABOVE"; + PhishBlockThreshold2["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH"; + })(PhishBlockThreshold || (PhishBlockThreshold = {})); + (function(AuthType2) { + AuthType2["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + AuthType2["NO_AUTH"] = "NO_AUTH"; + AuthType2["API_KEY_AUTH"] = "API_KEY_AUTH"; + AuthType2["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + AuthType2["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + AuthType2["OAUTH"] = "OAUTH"; + AuthType2["OIDC_AUTH"] = "OIDC_AUTH"; + })(AuthType || (AuthType = {})); + (function(HttpElementLocation2) { + HttpElementLocation2["HTTP_IN_UNSPECIFIED"] = "HTTP_IN_UNSPECIFIED"; + HttpElementLocation2["HTTP_IN_QUERY"] = "HTTP_IN_QUERY"; + HttpElementLocation2["HTTP_IN_HEADER"] = "HTTP_IN_HEADER"; + HttpElementLocation2["HTTP_IN_PATH"] = "HTTP_IN_PATH"; + HttpElementLocation2["HTTP_IN_BODY"] = "HTTP_IN_BODY"; + HttpElementLocation2["HTTP_IN_COOKIE"] = "HTTP_IN_COOKIE"; + })(HttpElementLocation || (HttpElementLocation = {})); + (function(ApiSpec2) { + ApiSpec2["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + ApiSpec2["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + ApiSpec2["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; + })(ApiSpec || (ApiSpec = {})); + (function(Behavior2) { + Behavior2["UNSPECIFIED"] = "UNSPECIFIED"; + Behavior2["BLOCKING"] = "BLOCKING"; + Behavior2["NON_BLOCKING"] = "NON_BLOCKING"; + })(Behavior || (Behavior = {})); + (function(DynamicRetrievalConfigMode2) { + DynamicRetrievalConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + DynamicRetrievalConfigMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC"; + })(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); + (function(FunctionCallingConfigMode2) { + FunctionCallingConfigMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + FunctionCallingConfigMode2["AUTO"] = "AUTO"; + FunctionCallingConfigMode2["ANY"] = "ANY"; + FunctionCallingConfigMode2["NONE"] = "NONE"; + FunctionCallingConfigMode2["VALIDATED"] = "VALIDATED"; + })(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); + (function(ThinkingLevel2) { + ThinkingLevel2["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED"; + ThinkingLevel2["LOW"] = "LOW"; + ThinkingLevel2["MEDIUM"] = "MEDIUM"; + ThinkingLevel2["HIGH"] = "HIGH"; + ThinkingLevel2["MINIMAL"] = "MINIMAL"; + })(ThinkingLevel || (ThinkingLevel = {})); + (function(PersonGeneration2) { + PersonGeneration2["DONT_ALLOW"] = "DONT_ALLOW"; + PersonGeneration2["ALLOW_ADULT"] = "ALLOW_ADULT"; + PersonGeneration2["ALLOW_ALL"] = "ALLOW_ALL"; + })(PersonGeneration || (PersonGeneration = {})); + (function(HarmCategory2) { + HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; + HarmCategory2["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + HarmCategory2["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + HarmCategory2["HARM_CATEGORY_IMAGE_HARASSMENT"] = "HARM_CATEGORY_IMAGE_HARASSMENT"; + HarmCategory2["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; + HarmCategory2["HARM_CATEGORY_JAILBREAK"] = "HARM_CATEGORY_JAILBREAK"; + })(HarmCategory || (HarmCategory = {})); + (function(HarmBlockMethod2) { + HarmBlockMethod2["HARM_BLOCK_METHOD_UNSPECIFIED"] = "HARM_BLOCK_METHOD_UNSPECIFIED"; + HarmBlockMethod2["SEVERITY"] = "SEVERITY"; + HarmBlockMethod2["PROBABILITY"] = "PROBABILITY"; + })(HarmBlockMethod || (HarmBlockMethod = {})); + (function(HarmBlockThreshold2) { + HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE"; + HarmBlockThreshold2["OFF"] = "OFF"; + })(HarmBlockThreshold || (HarmBlockThreshold = {})); + (function(FinishReason2) { + FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + FinishReason2["STOP"] = "STOP"; + FinishReason2["MAX_TOKENS"] = "MAX_TOKENS"; + FinishReason2["SAFETY"] = "SAFETY"; + FinishReason2["RECITATION"] = "RECITATION"; + FinishReason2["LANGUAGE"] = "LANGUAGE"; + FinishReason2["OTHER"] = "OTHER"; + FinishReason2["BLOCKLIST"] = "BLOCKLIST"; + FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + FinishReason2["SPII"] = "SPII"; + FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + FinishReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + FinishReason2["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; + FinishReason2["IMAGE_PROHIBITED_CONTENT"] = "IMAGE_PROHIBITED_CONTENT"; + FinishReason2["NO_IMAGE"] = "NO_IMAGE"; + FinishReason2["IMAGE_RECITATION"] = "IMAGE_RECITATION"; + FinishReason2["IMAGE_OTHER"] = "IMAGE_OTHER"; + })(FinishReason || (FinishReason = {})); + (function(HarmProbability2) { + HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE"; + HarmProbability2["LOW"] = "LOW"; + HarmProbability2["MEDIUM"] = "MEDIUM"; + HarmProbability2["HIGH"] = "HIGH"; + })(HarmProbability || (HarmProbability = {})); + (function(HarmSeverity2) { + HarmSeverity2["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + HarmSeverity2["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + HarmSeverity2["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + HarmSeverity2["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + HarmSeverity2["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; + })(HarmSeverity || (HarmSeverity = {})); + (function(UrlRetrievalStatus2) { + UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_SUCCESS"] = "URL_RETRIEVAL_STATUS_SUCCESS"; + UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_ERROR"] = "URL_RETRIEVAL_STATUS_ERROR"; + UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_PAYWALL"] = "URL_RETRIEVAL_STATUS_PAYWALL"; + UrlRetrievalStatus2["URL_RETRIEVAL_STATUS_UNSAFE"] = "URL_RETRIEVAL_STATUS_UNSAFE"; + })(UrlRetrievalStatus || (UrlRetrievalStatus = {})); + (function(BlockedReason2) { + BlockedReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + BlockedReason2["SAFETY"] = "SAFETY"; + BlockedReason2["OTHER"] = "OTHER"; + BlockedReason2["BLOCKLIST"] = "BLOCKLIST"; + BlockedReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + BlockedReason2["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + BlockedReason2["MODEL_ARMOR"] = "MODEL_ARMOR"; + BlockedReason2["JAILBREAK"] = "JAILBREAK"; + })(BlockedReason || (BlockedReason = {})); + (function(TrafficType2) { + TrafficType2["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + TrafficType2["ON_DEMAND"] = "ON_DEMAND"; + TrafficType2["ON_DEMAND_PRIORITY"] = "ON_DEMAND_PRIORITY"; + TrafficType2["ON_DEMAND_FLEX"] = "ON_DEMAND_FLEX"; + TrafficType2["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; + })(TrafficType || (TrafficType = {})); + (function(Modality2) { + Modality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + Modality2["TEXT"] = "TEXT"; + Modality2["IMAGE"] = "IMAGE"; + Modality2["AUDIO"] = "AUDIO"; + })(Modality || (Modality = {})); + (function(MediaResolution2) { + MediaResolution2["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + MediaResolution2["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + MediaResolution2["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + MediaResolution2["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; + })(MediaResolution || (MediaResolution = {})); + (function(TuningMode2) { + TuningMode2["TUNING_MODE_UNSPECIFIED"] = "TUNING_MODE_UNSPECIFIED"; + TuningMode2["TUNING_MODE_FULL"] = "TUNING_MODE_FULL"; + TuningMode2["TUNING_MODE_PEFT_ADAPTER"] = "TUNING_MODE_PEFT_ADAPTER"; + })(TuningMode || (TuningMode = {})); + (function(AdapterSize2) { + AdapterSize2["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + AdapterSize2["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + AdapterSize2["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + AdapterSize2["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + AdapterSize2["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + AdapterSize2["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + AdapterSize2["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; + })(AdapterSize || (AdapterSize = {})); + (function(JobState2) { + JobState2["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + JobState2["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + JobState2["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + JobState2["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + JobState2["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + JobState2["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + JobState2["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + JobState2["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + JobState2["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + JobState2["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + JobState2["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + JobState2["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; + })(JobState || (JobState = {})); + (function(TuningJobState2) { + TuningJobState2["TUNING_JOB_STATE_UNSPECIFIED"] = "TUNING_JOB_STATE_UNSPECIFIED"; + TuningJobState2["TUNING_JOB_STATE_WAITING_FOR_QUOTA"] = "TUNING_JOB_STATE_WAITING_FOR_QUOTA"; + TuningJobState2["TUNING_JOB_STATE_PROCESSING_DATASET"] = "TUNING_JOB_STATE_PROCESSING_DATASET"; + TuningJobState2["TUNING_JOB_STATE_WAITING_FOR_CAPACITY"] = "TUNING_JOB_STATE_WAITING_FOR_CAPACITY"; + TuningJobState2["TUNING_JOB_STATE_TUNING"] = "TUNING_JOB_STATE_TUNING"; + TuningJobState2["TUNING_JOB_STATE_POST_PROCESSING"] = "TUNING_JOB_STATE_POST_PROCESSING"; + })(TuningJobState || (TuningJobState = {})); + (function(AggregationMetric2) { + AggregationMetric2["AGGREGATION_METRIC_UNSPECIFIED"] = "AGGREGATION_METRIC_UNSPECIFIED"; + AggregationMetric2["AVERAGE"] = "AVERAGE"; + AggregationMetric2["MODE"] = "MODE"; + AggregationMetric2["STANDARD_DEVIATION"] = "STANDARD_DEVIATION"; + AggregationMetric2["VARIANCE"] = "VARIANCE"; + AggregationMetric2["MINIMUM"] = "MINIMUM"; + AggregationMetric2["MAXIMUM"] = "MAXIMUM"; + AggregationMetric2["MEDIAN"] = "MEDIAN"; + AggregationMetric2["PERCENTILE_P90"] = "PERCENTILE_P90"; + AggregationMetric2["PERCENTILE_P95"] = "PERCENTILE_P95"; + AggregationMetric2["PERCENTILE_P99"] = "PERCENTILE_P99"; + })(AggregationMetric || (AggregationMetric = {})); + (function(PairwiseChoice2) { + PairwiseChoice2["PAIRWISE_CHOICE_UNSPECIFIED"] = "PAIRWISE_CHOICE_UNSPECIFIED"; + PairwiseChoice2["BASELINE"] = "BASELINE"; + PairwiseChoice2["CANDIDATE"] = "CANDIDATE"; + PairwiseChoice2["TIE"] = "TIE"; + })(PairwiseChoice || (PairwiseChoice = {})); + (function(TuningTask2) { + TuningTask2["TUNING_TASK_UNSPECIFIED"] = "TUNING_TASK_UNSPECIFIED"; + TuningTask2["TUNING_TASK_I2V"] = "TUNING_TASK_I2V"; + TuningTask2["TUNING_TASK_T2V"] = "TUNING_TASK_T2V"; + TuningTask2["TUNING_TASK_R2V"] = "TUNING_TASK_R2V"; + })(TuningTask || (TuningTask = {})); + (function(PartMediaResolutionLevel2) { + PartMediaResolutionLevel2["MEDIA_RESOLUTION_UNSPECIFIED"] = "MEDIA_RESOLUTION_UNSPECIFIED"; + PartMediaResolutionLevel2["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + PartMediaResolutionLevel2["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + PartMediaResolutionLevel2["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; + PartMediaResolutionLevel2["MEDIA_RESOLUTION_ULTRA_HIGH"] = "MEDIA_RESOLUTION_ULTRA_HIGH"; + })(PartMediaResolutionLevel || (PartMediaResolutionLevel = {})); + (function(ResourceScope2) { + ResourceScope2["COLLECTION"] = "COLLECTION"; + })(ResourceScope || (ResourceScope = {})); + (function(FeatureSelectionPreference2) { + FeatureSelectionPreference2["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference2["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference2["BALANCED"] = "BALANCED"; + FeatureSelectionPreference2["PRIORITIZE_COST"] = "PRIORITIZE_COST"; + })(FeatureSelectionPreference || (FeatureSelectionPreference = {})); + (function(Environment2) { + Environment2["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + Environment2["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; + })(Environment || (Environment = {})); + (function(ProminentPeople2) { + ProminentPeople2["PROMINENT_PEOPLE_UNSPECIFIED"] = "PROMINENT_PEOPLE_UNSPECIFIED"; + ProminentPeople2["ALLOW_PROMINENT_PEOPLE"] = "ALLOW_PROMINENT_PEOPLE"; + ProminentPeople2["BLOCK_PROMINENT_PEOPLE"] = "BLOCK_PROMINENT_PEOPLE"; + })(ProminentPeople || (ProminentPeople = {})); + (function(EmbeddingApiType2) { + EmbeddingApiType2["PREDICT"] = "PREDICT"; + EmbeddingApiType2["EMBED_CONTENT"] = "EMBED_CONTENT"; + })(EmbeddingApiType || (EmbeddingApiType = {})); + (function(SafetyFilterLevel2) { + SafetyFilterLevel2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel2["BLOCK_NONE"] = "BLOCK_NONE"; + })(SafetyFilterLevel || (SafetyFilterLevel = {})); + (function(ImagePromptLanguage2) { + ImagePromptLanguage2["auto"] = "auto"; + ImagePromptLanguage2["en"] = "en"; + ImagePromptLanguage2["ja"] = "ja"; + ImagePromptLanguage2["ko"] = "ko"; + ImagePromptLanguage2["hi"] = "hi"; + ImagePromptLanguage2["zh"] = "zh"; + ImagePromptLanguage2["pt"] = "pt"; + ImagePromptLanguage2["es"] = "es"; + })(ImagePromptLanguage || (ImagePromptLanguage = {})); + (function(MaskReferenceMode2) { + MaskReferenceMode2["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode2["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode2["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode2["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode2["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; + })(MaskReferenceMode || (MaskReferenceMode = {})); + (function(ControlReferenceType2) { + ControlReferenceType2["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType2["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType2["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType2["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; + })(ControlReferenceType || (ControlReferenceType = {})); + (function(SubjectReferenceType2) { + SubjectReferenceType2["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType2["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType2["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType2["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; + })(SubjectReferenceType || (SubjectReferenceType = {})); + (function(EditMode2) { + EditMode2["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode2["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode2["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode2["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode2["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode2["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode2["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode2["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; + })(EditMode || (EditMode = {})); + (function(SegmentMode2) { + SegmentMode2["FOREGROUND"] = "FOREGROUND"; + SegmentMode2["BACKGROUND"] = "BACKGROUND"; + SegmentMode2["PROMPT"] = "PROMPT"; + SegmentMode2["SEMANTIC"] = "SEMANTIC"; + SegmentMode2["INTERACTIVE"] = "INTERACTIVE"; + })(SegmentMode || (SegmentMode = {})); + (function(VideoGenerationReferenceType2) { + VideoGenerationReferenceType2["ASSET"] = "ASSET"; + VideoGenerationReferenceType2["STYLE"] = "STYLE"; + })(VideoGenerationReferenceType || (VideoGenerationReferenceType = {})); + (function(VideoGenerationMaskMode2) { + VideoGenerationMaskMode2["INSERT"] = "INSERT"; + VideoGenerationMaskMode2["REMOVE"] = "REMOVE"; + VideoGenerationMaskMode2["REMOVE_STATIC"] = "REMOVE_STATIC"; + VideoGenerationMaskMode2["OUTPAINT"] = "OUTPAINT"; + })(VideoGenerationMaskMode || (VideoGenerationMaskMode = {})); + (function(VideoCompressionQuality2) { + VideoCompressionQuality2["OPTIMIZED"] = "OPTIMIZED"; + VideoCompressionQuality2["LOSSLESS"] = "LOSSLESS"; + })(VideoCompressionQuality || (VideoCompressionQuality = {})); + (function(TuningMethod2) { + TuningMethod2["SUPERVISED_FINE_TUNING"] = "SUPERVISED_FINE_TUNING"; + TuningMethod2["PREFERENCE_TUNING"] = "PREFERENCE_TUNING"; + TuningMethod2["DISTILLATION"] = "DISTILLATION"; + })(TuningMethod || (TuningMethod = {})); + (function(DocumentState2) { + DocumentState2["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + DocumentState2["STATE_PENDING"] = "STATE_PENDING"; + DocumentState2["STATE_ACTIVE"] = "STATE_ACTIVE"; + DocumentState2["STATE_FAILED"] = "STATE_FAILED"; + })(DocumentState || (DocumentState = {})); + (function(FileState2) { + FileState2["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState2["PROCESSING"] = "PROCESSING"; + FileState2["ACTIVE"] = "ACTIVE"; + FileState2["FAILED"] = "FAILED"; + })(FileState || (FileState = {})); + (function(FileSource2) { + FileSource2["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource2["UPLOADED"] = "UPLOADED"; + FileSource2["GENERATED"] = "GENERATED"; + FileSource2["REGISTERED"] = "REGISTERED"; + })(FileSource || (FileSource = {})); + (function(TurnCompleteReason2) { + TurnCompleteReason2["TURN_COMPLETE_REASON_UNSPECIFIED"] = "TURN_COMPLETE_REASON_UNSPECIFIED"; + TurnCompleteReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + TurnCompleteReason2["RESPONSE_REJECTED"] = "RESPONSE_REJECTED"; + TurnCompleteReason2["NEED_MORE_INPUT"] = "NEED_MORE_INPUT"; + })(TurnCompleteReason || (TurnCompleteReason = {})); + (function(MediaModality2) { + MediaModality2["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + MediaModality2["TEXT"] = "TEXT"; + MediaModality2["IMAGE"] = "IMAGE"; + MediaModality2["VIDEO"] = "VIDEO"; + MediaModality2["AUDIO"] = "AUDIO"; + MediaModality2["DOCUMENT"] = "DOCUMENT"; + })(MediaModality || (MediaModality = {})); + (function(VadSignalType2) { + VadSignalType2["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED"; + VadSignalType2["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS"; + VadSignalType2["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS"; + })(VadSignalType || (VadSignalType = {})); + (function(VoiceActivityType2) { + VoiceActivityType2["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + VoiceActivityType2["ACTIVITY_START"] = "ACTIVITY_START"; + VoiceActivityType2["ACTIVITY_END"] = "ACTIVITY_END"; + })(VoiceActivityType || (VoiceActivityType = {})); + (function(StartSensitivity2) { + StartSensitivity2["START_SENSITIVITY_UNSPECIFIED"] = "START_SENSITIVITY_UNSPECIFIED"; + StartSensitivity2["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + StartSensitivity2["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; + })(StartSensitivity || (StartSensitivity = {})); + (function(EndSensitivity2) { + EndSensitivity2["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + EndSensitivity2["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + EndSensitivity2["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; + })(EndSensitivity || (EndSensitivity = {})); + (function(ActivityHandling2) { + ActivityHandling2["ACTIVITY_HANDLING_UNSPECIFIED"] = "ACTIVITY_HANDLING_UNSPECIFIED"; + ActivityHandling2["START_OF_ACTIVITY_INTERRUPTS"] = "START_OF_ACTIVITY_INTERRUPTS"; + ActivityHandling2["NO_INTERRUPTION"] = "NO_INTERRUPTION"; + })(ActivityHandling || (ActivityHandling = {})); + (function(TurnCoverage2) { + TurnCoverage2["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + TurnCoverage2["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + TurnCoverage2["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; + })(TurnCoverage || (TurnCoverage = {})); + (function(Scale3) { + Scale3["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + Scale3["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + Scale3["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + Scale3["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + Scale3["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + Scale3["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + Scale3["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + Scale3["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + Scale3["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + Scale3["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + Scale3["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + Scale3["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + Scale3["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; + })(Scale || (Scale = {})); + (function(MusicGenerationMode2) { + MusicGenerationMode2["MUSIC_GENERATION_MODE_UNSPECIFIED"] = "MUSIC_GENERATION_MODE_UNSPECIFIED"; + MusicGenerationMode2["QUALITY"] = "QUALITY"; + MusicGenerationMode2["DIVERSITY"] = "DIVERSITY"; + MusicGenerationMode2["VOCALIZATION"] = "VOCALIZATION"; + })(MusicGenerationMode || (MusicGenerationMode = {})); + (function(LiveMusicPlaybackControl2) { + LiveMusicPlaybackControl2["PLAYBACK_CONTROL_UNSPECIFIED"] = "PLAYBACK_CONTROL_UNSPECIFIED"; + LiveMusicPlaybackControl2["PLAY"] = "PLAY"; + LiveMusicPlaybackControl2["PAUSE"] = "PAUSE"; + LiveMusicPlaybackControl2["STOP"] = "STOP"; + LiveMusicPlaybackControl2["RESET_CONTEXT"] = "RESET_CONTEXT"; + })(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); + HttpResponse = class { + constructor(response) { + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } + }; + GenerateContentResponse = class { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a7, _b, _c, _d, _e2, _f, _g, _h; + if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.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 text3 = ""; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "text" && fieldName !== "thought" && fieldName !== "thoughtSignature" && (fieldValue !== null || fieldValue !== void 0)) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartText = true; + text3 += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + return anyTextPartText ? text3 : void 0; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a7, _b, _c, _d, _e2, _f, _g, _h; + if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.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 data = ""; + const nonDataParts = []; + for (const part of (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) !== null && _h !== void 0 ? _h : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && (fieldValue !== null || fieldValue !== void 0)) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : void 0; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a7, _b, _c, _d, _e2, _f, _g, _h; + if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.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 functionCalls = (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.functionCall).map((part) => part.functionCall).filter((functionCall) => functionCall !== void 0); + if ((functionCalls === null || functionCalls === void 0 ? void 0 : functionCalls.length) === 0) { + return void 0; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.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 executableCode = (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.executableCode).map((part) => part.executableCode).filter((executableCode2) => executableCode2 !== void 0); + if ((executableCode === null || executableCode === void 0 ? void 0 : executableCode.length) === 0) { + return void 0; + } + return (_j = executableCode === null || executableCode === void 0 ? void 0 : executableCode[0]) === null || _j === void 0 ? void 0 : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _j; + if (((_d = (_c = (_b = (_a7 = this.candidates) === null || _a7 === void 0 ? void 0 : _a7[0]) === null || _b === void 0 ? void 0 : _b.content) === null || _c === void 0 ? void 0 : _c.parts) === null || _d === void 0 ? void 0 : _d.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 codeExecutionResult = (_h = (_g = (_f = (_e2 = this.candidates) === null || _e2 === void 0 ? void 0 : _e2[0]) === null || _f === void 0 ? void 0 : _f.content) === null || _g === void 0 ? void 0 : _g.parts) === null || _h === void 0 ? void 0 : _h.filter((part) => part.codeExecutionResult).map((part) => part.codeExecutionResult).filter((codeExecutionResult2) => codeExecutionResult2 !== void 0); + if ((codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult.length) === 0) { + return void 0; + } + return (_j = codeExecutionResult === null || codeExecutionResult === void 0 ? void 0 : codeExecutionResult[0]) === null || _j === void 0 ? void 0 : _j.output; + } + }; + EmbedContentResponse = class { + }; + GenerateImagesResponse = class { + }; + EditImageResponse = class { + }; + UpscaleImageResponse = class { + }; + RecontextImageResponse = class { + }; + SegmentImageResponse = class { + }; + ListModelsResponse = class { + }; + DeleteModelResponse = class { + }; + CountTokensResponse = class { + }; + ComputeTokensResponse = class { + }; + GenerateVideosOperation = class _GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, _isVertexAI }) { + const operation = new _GenerateVideosOperation(); + let response; + const op2 = apiResponse; + if (_isVertexAI) { + response = generateVideosOperationFromVertex$1(op2); + } else { + response = generateVideosOperationFromMldev$1(op2); + } + Object.assign(operation, response); + return operation; + } + }; + ListTuningJobsResponse = class { + }; + CancelTuningJobResponse = class { + }; + DeleteCachedContentResponse = class { + }; + ListCachedContentsResponse = class { + }; + ListDocumentsResponse = class { + }; + ListFileSearchStoresResponse = class { + }; + UploadToFileSearchStoreResumableResponse = class { + }; + ImportFileOperation = class _ImportFileOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, _isVertexAI }) { + const operation = new _ImportFileOperation(); + const op2 = apiResponse; + const response = importFileOperationFromMldev$1(op2); + Object.assign(operation, response); + return operation; + } + }; + ListFilesResponse = class { + }; + CreateFileResponse = class { + }; + DeleteFileResponse = class { + }; + RegisterFilesResponse = class { + }; + ListBatchJobsResponse = class { + }; + LiveServerMessage = class { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a7, _b, _c; + let text3 = ""; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = (_b = (_a7 = this.serverContent) === null || _a7 === void 0 ? void 0 : _a7.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "text" && fieldName !== "thought" && fieldValue !== null) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartFound = true; + text3 += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn(`there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`); + } + return anyTextPartFound ? text3 : void 0; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a7, _b, _c; + let data = ""; + const nonDataParts = []; + for (const part of (_c = (_b = (_a7 = this.serverContent) === null || _a7 === void 0 ? void 0 : _a7.modelTurn) === null || _b === void 0 ? void 0 : _b.parts) !== null && _c !== void 0 ? _c : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn(`there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`); + } + return data.length > 0 ? btoa(data) : void 0; + } + }; + LiveMusicServerMessage = class { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if (this.serverContent && this.serverContent.audioChunks && this.serverContent.audioChunks.length > 0) { + return this.serverContent.audioChunks[0]; + } + return void 0; + } + }; + UploadToFileSearchStoreOperation = class _UploadToFileSearchStoreOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, _isVertexAI }) { + const operation = new _UploadToFileSearchStoreOperation(); + const op2 = apiResponse; + const response = uploadToFileSearchStoreOperationFromMldev(op2); + Object.assign(operation, response); + return operation; + } + }; + (function(PagedItem2) { + PagedItem2["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem2["PAGED_ITEM_MODELS"] = "models"; + PagedItem2["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem2["PAGED_ITEM_FILES"] = "files"; + PagedItem2["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; + PagedItem2["PAGED_ITEM_FILE_SEARCH_STORES"] = "fileSearchStores"; + PagedItem2["PAGED_ITEM_DOCUMENTS"] = "documents"; + })(PagedItem || (PagedItem = {})); + Pager = class { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a7, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = response === null || response === void 0 ? void 0 : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } else if (typeof params === "object") { + requestParams = Object.assign({}, params); + } else { + requestParams = params; + } + if (requestParams["config"]) { + requestParams["config"]["pageToken"] = response["nextPageToken"]; + } + this.paramsInternal = requestParams; + this.pageInternalSize = (_b = (_a7 = requestParams["config"]) === null || _a7 === void 0 ? void 0 : _a7["pageSize"]) !== null && _b !== void 0 ? _b : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index2) { + return this.pageInternal[index2]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } else { + return { value: void 0, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: void 0, done: true }; + } + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error("No more pages to fetch."); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a7; + if (((_a7 = this.params["config"]) === null || _a7 === void 0 ? void 0 : _a7["pageToken"]) !== void 0) { + return true; + } + return false; + } + }; + Batches4 = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x2) => this.listInternal(x2), await this.listInternal(params), params); + }; + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + params.config = this.formatDestination(params.src, params.config); + } + return this.createInternal(params); + }; + this.createEmbeddings = async (params) => { + console.warn("batches.createEmbeddings() is experimental and may change without notice."); + if (this.apiClient.isVertexAI()) { + throw new Error("Vertex AI does not support batches.createEmbeddings."); + } + return this.createEmbeddingsInternal(params); + }; + } + // Helper function to handle inlined generate content requests + createInlinedGenerateContentRequest(params) { + const body = createBatchJobParametersToMldev( + this.apiClient, + // Use instance apiClient + params + ); + const urlParams = body["_url"]; + const path6 = formatMap("{model}:batchGenerateContent", urlParams); + const batch = body["batch"]; + const inputConfig = batch["inputConfig"]; + const requestsWrapper = inputConfig["requests"]; + const requests = requestsWrapper["requests"]; + const newRequests = []; + for (const request of requests) { + const requestDict = Object.assign({}, request); + if (requestDict["systemInstruction"]) { + const systemInstructionValue = requestDict["systemInstruction"]; + delete requestDict["systemInstruction"]; + const requestContent = requestDict["request"]; + requestContent["systemInstruction"] = systemInstructionValue; + requestDict["request"] = requestContent; + } + newRequests.push(requestDict); + } + requestsWrapper["requests"] = newRequests; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + return { path: path6, body }; + } + // Helper function to get the first GCS URI + getGcsUri(src) { + if (typeof src === "string") { + return src.startsWith("gs://") ? src : void 0; + } + if (!Array.isArray(src) && src.gcsUri && src.gcsUri.length > 0) { + return src.gcsUri[0]; + } + return void 0; + } + // Helper function to get the BigQuery URI + getBigqueryUri(src) { + if (typeof src === "string") { + return src.startsWith("bq://") ? src : void 0; + } + if (!Array.isArray(src)) { + return src.bigqueryUri; + } + return void 0; + } + // Function to format the destination configuration for Vertex AI + formatDestination(src, config) { + const newConfig = config ? Object.assign({}, config) : {}; + const timestampStr = Date.now().toString(); + if (!newConfig.displayName) { + newConfig.displayName = `genaiBatchJob_${timestampStr}`; + } + if (newConfig.dest === void 0) { + const gcsUri = this.getGcsUri(src); + const bigqueryUri = this.getBigqueryUri(src); + if (gcsUri) { + if (gcsUri.endsWith(".jsonl")) { + newConfig.dest = `${gcsUri.slice(0, -6)}/dest`; + } else { + newConfig.dest = `${gcsUri}_dest_${timestampStr}`; + } + } else if (bigqueryUri) { + newConfig.dest = `${bigqueryUri}_dest_${timestampStr}`; + } else { + throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found."); + } + } + return newConfig; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path6 = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:batchGenerateContent", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createEmbeddingsInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = createEmbeddingsBatchJobParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:asyncBatchEmbedContent", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path6 = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path6 = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a7, _b, _c, _d; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path6 = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }); + } else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path6 = formatMap("batches/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }); + } + } + async listInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path6 = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listBatchJobsParametersToMldev(params); + path6 = formatMap("batches", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path6 = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path6 = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } + }; + Caches = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_CACHED_CONTENTS, (x2) => this.listInternal(x2), await this.listInternal(params), params); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex(this.apiClient, params); + path6 = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path6 = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromVertex(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteCachedContentResponseFromMldev(apiResponse); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + async listInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path6 = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listCachedContentsParametersToMldev(params); + path6 = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + }; + Chats = class { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat2( + this.apiClient, + this.modelsModule, + params.model, + params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history) + ); + } + }; + Chat2 = class { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a7; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a7 = params.config) !== null && _a7 !== void 0 ? _a7 : this.config + }); + this.sendPromise = (async () => { + var _a8, _b, _c; + const response = await responsePromise; + const outputContent = (_b = (_a8 = response.candidates) === null || _a8 === void 0 ? void 0 : _a8[0]) === null || _b === void 0 ? void 0 : _b.content; + const fullAutomaticFunctionCallingHistory = response.automaticFunctionCallingHistory; + const index2 = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = (_c = fullAutomaticFunctionCallingHistory.slice(index2)) !== null && _c !== void 0 ? _c : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory(inputContent, modelOutput, automaticFunctionCallingHistory); + return; + })(); + await this.sendPromise.catch(() => { + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a7; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a7 = params.config) !== null && _a7 !== void 0 ? _a7 : this.config + }); + this.sendPromise = streamResponse.then(() => void 0).catch(() => void 0); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated ? extractCuratedHistory(this.history) : this.history; + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _a7, e_1, _b, _c; + var _d, _e2; + const outputContent = []; + try { + for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _a7 = streamResponse_1_1.done, !_a7; _f = true) { + _c = streamResponse_1_1.value; + _f = false; + const chunk = _c; + if (isValidResponse(chunk)) { + const content = (_e2 = (_d = chunk.candidates) === null || _d === void 0 ? void 0 : _d[0]) === null || _e2 === void 0 ? void 0 : _e2.content; + if (content !== void 0) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_a7 && (_b = streamResponse_1.return)) yield __await(_b.call(streamResponse_1)); + } finally { + if (e_1) throw e_1.error; + } + } + this.recordHistory(inputContent, outputContent); + }); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if (modelOutput.length > 0 && modelOutput.every((content) => content.role !== void 0)) { + outputContents = modelOutput; + } else { + outputContents.push({ + role: "model", + parts: [] + }); + } + if (automaticFunctionCallingHistory && automaticFunctionCallingHistory.length > 0) { + this.history.push(...extractCuratedHistory(automaticFunctionCallingHistory)); + } else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } + }; + ApiError = class _ApiError extends Error { + constructor(options) { + super(options.message); + this.name = "ApiError"; + this.status = options.status; + Object.setPrototypeOf(this, _ApiError.prototype); + } + }; + Files5 = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILES, (x2) => this.listInternal(x2), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket."); + } + return this.apiClient.uploadFile(params.file, params.config).then((resp) => { + return resp; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + /** + * Registers Google Cloud Storage files for use with the API. + * This method is only available in Node.js environments. + */ + async registerFiles(params) { + throw new Error("registerFiles is only supported in Node.js environments."); + } + async _registerFiles(params) { + return this.registerFilesInternal(params); + } + async listInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = listFilesParametersToMldev(params); + path6 = formatMap("files", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = createFileParametersToMldev(params); + path6 = formatMap("upload/v1beta/files", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = getFileParametersToMldev(params); + path6 = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = deleteFileParametersToMldev(params); + path6 = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteFileResponseFromMldev(apiResponse); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async registerFilesInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = internalRegisterFilesParametersToMldev(params); + path6 = formatMap("files:register", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = registerFilesResponseFromMldev(apiResponse); + const typedResp = new RegisterFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + }; + CONTENT_TYPE_HEADER = "Content-Type"; + SERVER_TIMEOUT_HEADER = "X-Server-Timeout"; + USER_AGENT_HEADER = "User-Agent"; + GOOGLE_API_CLIENT_HEADER = "x-goog-api-client"; + SDK_VERSION = "1.45.0"; + LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; + VERTEX_AI_API_DEFAULT_VERSION = "v1beta1"; + GOOGLE_AI_API_DEFAULT_VERSION = "v1beta"; + DEFAULT_RETRY_ATTEMPTS = 5; + DEFAULT_RETRY_HTTP_STATUS_CODES = [ + 408, + // Request timeout + 429, + // Too many requests + 500, + // Internal server error + 502, + // Bad gateway + 503, + // Service unavailable + 504 + // Gateway timeout + ]; + ApiClient = class { + constructor(opts) { + var _a7, _b, _c; + this.clientOptions = Object.assign({}, opts); + this.customBaseUrl = (_a7 = opts.httpOptions) === null || _a7 === void 0 ? void 0 : _a7.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 initHttpOptions = {}; + if (this.clientOptions.vertexai) { + if (!this.clientOptions.location && !this.clientOptions.apiKey && !this.customBaseUrl) { + this.clientOptions.location = "global"; + } + const hasSufficientAuth = this.clientOptions.project && this.clientOptions.location || this.clientOptions.apiKey; + if (!hasSufficientAuth && !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 hasConstructorAuth = opts.project && opts.location || !!opts.apiKey; + if (this.customBaseUrl && !hasConstructorAuth) { + initHttpOptions.baseUrl = this.customBaseUrl; + this.clientOptions.project = void 0; + this.clientOptions.location = void 0; + } else if (this.clientOptions.apiKey || this.clientOptions.location === "global") { + initHttpOptions.baseUrl = "https://aiplatform.googleapis.com/"; + } else if (this.clientOptions.project && this.clientOptions.location) { + initHttpOptions.baseUrl = `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + initHttpOptions.apiVersion = (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : VERTEX_AI_API_DEFAULT_VERSION; + } else { + if (!this.clientOptions.apiKey) { + console.warn("API key should be set when using the Gemini API."); + } + initHttpOptions.apiVersion = (_c = this.clientOptions.apiVersion) !== null && _c !== void 0 ? _c : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions); + } + } + isVertexAI() { + var _a7; + return (_a7 = this.clientOptions.vertexai) !== null && _a7 !== void 0 ? _a7 : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getCustomBaseUrl() { + return this.customBaseUrl; + } + async getAuthHeaders() { + const headers = new Headers(); + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + 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(httpOptions) { + if (!httpOptions || httpOptions.baseUrl === void 0 || httpOptions.apiVersion === void 0) { + throw new Error("HTTP options are not correctly set."); + } + const baseUrl = httpOptions.baseUrl.endsWith("/") ? httpOptions.baseUrl.slice(0, -1) : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== "") { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join("/"); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss"; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } else { + throw new Error("HTTP options are not correctly set."); + } + } + constructUrl(path6, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path6 !== "") { + urlElement.push(path6); + } + const url = new URL(`${urlElement.join("/")}`); + return url; + } + shouldPrependVertexProjectPath(request, httpOptions) { + if (httpOptions.baseUrl && httpOptions.baseUrlResourceScope === ResourceScope.COLLECTION) { + return false; + } + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith("projects/")) { + return false; + } + if (request.httpMethod === "GET" && request.path.startsWith("publishers/google/models")) { + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === "GET") { + if (request.body && request.body !== "{}") { + throw new Error("Request body should be empty for GET request, but got non empty request body"); + } + } else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + if (typeof value === "object") { + patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value); + } else if (value !== void 0) { + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request, patchedHttpOptions); + const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation); + if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") { + url.searchParams.set("alt", "sse"); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url, abortSignal) { + if (httpOptions && httpOptions.timeout || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) { + const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout); + if (timeoutHandle && typeof timeoutHandle.unref === "function") { + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener("abort", () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions, url); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }).catch((e9) => { + if (e9 instanceof Error) { + throw e9; + } else { + throw new Error(JSON.stringify(e9)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod })).then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }).catch((e9) => { + if (e9 instanceof Error) { + throw e9; + } else { + throw new Error(JSON.stringify(e9)); + } + }); + } + processStreamResponse(response) { + return __asyncGenerator(this, arguments, function* processStreamResponse_1() { + var _a7; + const reader = (_a7 = response === null || response === void 0 ? void 0 : response.body) === null || _a7 === void 0 ? void 0 : _a7.getReader(); + const decoder = new TextDecoder("utf-8"); + if (!reader) { + throw new Error("Response body is empty"); + } + try { + let buffer = ""; + const dataPrefix = "data:"; + const delimiters2 = ["\n\n", "\r\r", "\r\n\r\n"]; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error("Incomplete JSON segment at the end"); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + try { + const chunkJson = JSON.parse(chunkString); + if ("error" in chunkJson) { + const errorJson = JSON.parse(JSON.stringify(chunkJson["error"])); + const status = errorJson["status"]; + const code = errorJson["code"]; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code + }); + throw apiError; + } + } + } catch (e9) { + const error = e9; + if (error.name === "ApiError") { + throw e9; + } + } + buffer += chunkString; + let delimiterIndex = -1; + let delimiterLength = 0; + while (true) { + delimiterIndex = -1; + delimiterLength = 0; + for (const delimiter2 of delimiters2) { + const index2 = buffer.indexOf(delimiter2); + if (index2 !== -1 && (delimiterIndex === -1 || index2 < delimiterIndex)) { + delimiterIndex = index2; + delimiterLength = delimiter2.length; + } + } + if (delimiterIndex === -1) { + break; + } + const eventString = buffer.substring(0, delimiterIndex); + buffer = buffer.substring(delimiterIndex + delimiterLength); + const trimmedEvent = eventString.trim(); + if (trimmedEvent.startsWith(dataPrefix)) { + const processedChunkString = trimmedEvent.substring(dataPrefix.length).trim(); + try { + const partialResponse = new Response(processedChunkString, { + headers: response === null || response === void 0 ? void 0 : response.headers, + status: response === null || response === void 0 ? void 0 : response.status, + statusText: response === null || response === void 0 ? void 0 : response.statusText + }); + yield yield __await(new HttpResponse(partialResponse)); + } catch (e9) { + throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e9}`); + } + } + } + } + } finally { + reader.releaseLock(); + } + }); + } + async apiCall(url, requestInit) { + var _a7; + if (!this.clientOptions.httpOptions || !this.clientOptions.httpOptions.retryOptions) { + return fetch(url, requestInit); + } + const retryOptions = this.clientOptions.httpOptions.retryOptions; + const runFetch = async () => { + const response = await fetch(url, requestInit); + if (response.ok) { + return response; + } + if (DEFAULT_RETRY_HTTP_STATUS_CODES.includes(response.status)) { + throw new Error(`Retryable HTTP Error: ${response.statusText}`); + } + throw new import_p_retry.AbortError(`Non-retryable exception ${response.statusText} sending request`); + }; + return (0, import_p_retry.default)(runFetch, { + // Retry attempts is one less than the number of total attempts. + retries: ((_a7 = retryOptions.attempts) !== null && _a7 !== void 0 ? _a7 : DEFAULT_RETRY_ATTEMPTS) - 1 + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = "application/json"; + return headers; + } + async getHeadersInternal(httpOptions, url) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1e3))); + } + } + await this.clientOptions.auth.addAuthHeaders(headers, url); + return headers; + } + getFileName(file) { + var _a7; + let fileName = ""; + if (typeof file === "string") { + fileName = file.replace(/[/\\]+$/, ""); + fileName = (_a7 = fileName.split(/[/\\]/).pop()) !== null && _a7 !== void 0 ? _a7 : ""; + } + return fileName; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link types.UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a7; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = (_a7 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a7 !== void 0 ? _a7 : fileStat.type; + if (mimeType === void 0 || mimeType === "") { + throw new Error("Can not determine mimeType. Please provide mimeType in the config."); + } + fileToUpload.mimeType = mimeType; + const body = { + file: fileToUpload + }; + const fileName = this.getFileName(file); + const path6 = formatMap("upload/v1beta/files", body["_url"]); + const uploadUrl = await this.fetchUploadUrl(path6, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions); + return uploader.upload(file, uploadUrl, this); + } + /** + * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param fileSearchStoreName The name of the file search store to upload the file to. + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFileToFileSearchStore(fileSearchStoreName, file, config) { + var _a7; + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + const sizeBytes = String(fileStat.size); + const mimeType = (_a7 = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a7 !== void 0 ? _a7 : fileStat.type; + if (mimeType === void 0 || mimeType === "") { + throw new Error("Can not determine mimeType. Please provide mimeType in the config."); + } + const path6 = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`; + const fileName = this.getFileName(file); + const body = {}; + if (config != null) { + uploadToFileSearchStoreConfigToMldev(config, body); + } + const uploadUrl = await this.fetchUploadUrl(path6, sizeBytes, mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions); + return uploader.uploadToFileSearchStore(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * types.DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(path6, sizeBytes, mimeType, fileName, body, configHttpOptions) { + var _a7; + let httpOptions = {}; + if (configHttpOptions) { + httpOptions = configHttpOptions; + } else { + httpOptions = { + apiVersion: "", + // api-version is set in the path. + headers: Object.assign({ "Content-Type": "application/json", "X-Goog-Upload-Protocol": "resumable", "X-Goog-Upload-Command": "start", "X-Goog-Upload-Header-Content-Length": `${sizeBytes}`, "X-Goog-Upload-Header-Content-Type": `${mimeType}` }, fileName ? { "X-Goog-Upload-File-Name": fileName } : {}) + }; + } + const httpResponse = await this.request({ + path: path6, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions + }); + if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) { + throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers."); + } + const uploadUrl = (_a7 = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a7 === void 0 ? void 0 : _a7["x-goog-upload-url"]; + if (uploadUrl === void 0) { + throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers"); + } + return uploadUrl; + } + }; + MCP_LABEL = "mcp_used/unknown"; + hasMcpToolUsageFromMcpToTool = false; + McpCallableTool = class _McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new _McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a7, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for (var _d = true, _e2 = (e_1 = void 0, __asyncValues(listAllTools(mcpClient))), _f; _f = await _e2.next(), _a7 = _f.done, !_a7; _d = true) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error(`Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`); + } + functionMap[mcpToolName] = mcpClient; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a7 && (_b = _e2.return)) await _b.call(_e2); + } finally { + if (e_1) throw e_1.error; + } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = void 0; + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout + }; + } + const callToolResponse = await mcpClient.callTool( + { + name: functionCall.name, + arguments: functionCall.args + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + void 0, + requestOptions + ); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError ? { error: callToolResponse } : callToolResponse + } + }); + } + } + return functionCallResponseParts; + } + }; + LiveMusic = class { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a7, _b; + 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 websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => { + }; + const onopenPromise = new Promise((resolve2) => { + onopenResolve = resolve2; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function() { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a7 !== void 0 ? _a7 : function(e9) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function(e9) { + } + }; + const conn = this.webSocketFactory.create(url, headersToMap$1(headers), websocketCallbacks); + conn.connect(); + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = { model }; + const clientMessage = { setup }; + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } + }; + LiveMusicSession = class { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if (!params.weightedPrompts || Object.keys(params.weightedPrompts).length === 0) { + throw new Error("Weighted prompts must be set and contain at least one entry."); + } + const clientContent = liveMusicSetWeightedPromptsParametersToMldev(params); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + this.conn.send(JSON.stringify(setConfigParameters)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = { playbackControl }; + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } + }; + FUNCTION_RESPONSE_REQUIRES_ID = "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI."; + Live = class { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic(this.apiClient, this.auth, this.webSocketFactory); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a7, _b, _c, _d, _e2, _f; + if (params.config && params.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 websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const clientHeaders = this.apiClient.getHeaders(); + if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) { + setMcpUsageHeader(clientHeaders); + } + const headers = mapToHeaders(clientHeaders); + if (this.apiClient.isVertexAI()) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + const apiKey = this.apiClient.getApiKey(); + const hasStandardAuth = !!project && !!location || !!apiKey; + if (this.apiClient.getCustomBaseUrl() && !hasStandardAuth) { + url = websocketBaseUrl; + } else { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers, url); + } + } else { + const apiKey = this.apiClient.getApiKey(); + let method = "BidiGenerateContent"; + let keyName = "key"; + if (apiKey === null || apiKey === void 0 ? void 0 : apiKey.startsWith("auth_tokens/")) { + console.warn("Warning: Ephemeral token support is experimental and may change in future versions."); + if (apiVersion !== "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."); + } + method = "BidiGenerateContentConstrained"; + keyName = "access_token"; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => { + }; + const onopenPromise = new Promise((resolve2) => { + onopenResolve = resolve2; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function() { + var _a8; + (_a8 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onopen) === null || _a8 === void 0 ? void 0 : _a8.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: (_a7 = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onerror) !== null && _a7 !== void 0 ? _a7 : function(e9) { + }, + onclose: (_b = callbacks === null || callbacks === void 0 ? void 0 : callbacks.onclose) !== null && _b !== void 0 ? _b : function(e9) { + } + }; + const conn = this.webSocketFactory.create(url, headersToMap(headers), websocketCallbacks); + conn.connect(); + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if (this.apiClient.isVertexAI() && transformedModel.startsWith("publishers/")) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + if (project && location) { + transformedModel = `projects/${project}/locations/${location}/` + transformedModel; + } + } + let clientMessage = {}; + if (this.apiClient.isVertexAI() && ((_c = params.config) === null || _c === void 0 ? void 0 : _c.responseModalities) === void 0) { + if (params.config === void 0) { + params.config = { responseModalities: [Modality.AUDIO] }; + } else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ((_d = params.config) === null || _d === void 0 ? void 0 : _d.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 inputTools = (_f = (_e2 = params.config) === null || _e2 === void 0 ? void 0 : _e2.tools) !== null && _f !== void 0 ? _f : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex(this.apiClient, liveConnectParameters); + } else { + clientMessage = liveConnectParametersToMldev(this.apiClient, liveConnectParameters); + } + delete clientMessage["config"]; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; + } + }; + defaultLiveSendClientContentParamerters = { + turnComplete: true + }; + Session = class { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== void 0) { + let contents = []; + try { + contents = tContents(params.turns); + if (!apiClient.isVertexAI()) { + contents = contents.map((item) => contentToMldev$1(item)); + } + } catch (_a7) { + throw new Error(`Failed to parse client content "turns", type: '${typeof params.turns}'`); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete } + }; + } + return { + clientContent: { turnComplete: params.turnComplete } + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error("functionResponses is required."); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error("functionResponses is required."); + } + for (const functionResponse of functionResponses) { + if (typeof functionResponse !== "object" || functionResponse === null || !("name" in functionResponse) || !("response" in functionResponse)) { + throw new Error(`Could not parse function response, type '${typeof functionResponse}'.`); + } + if (!apiClient.isVertexAI() && !("id" in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses } + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign(Object.assign({}, defaultLiveSendClientContentParamerters), params); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + "realtimeInput": liveSendRealtimeInputParametersToVertex(params) + }; + } else { + clientMessage = { + "realtimeInput": liveSendRealtimeInputParametersToMldev(params) + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error("Tool response parameters are required."); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } + }; + DEFAULT_MAX_REMOTE_CALLS = 10; + Models4 = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + this.embedContent = async (params) => { + if (!this.apiClient.isVertexAI()) { + return await this.embedContentInternal(params); + } + const isVertexEmbedContentModel = params.model.includes("gemini") && params.model !== "gemini-embedding-001" || params.model.includes("maas"); + if (isVertexEmbedContentModel) { + const contents = tContents(params.contents); + if (contents.length > 1) { + throw new Error("The embedContent API for this model only supports one content at a time."); + } + const paramsPrivate = Object.assign(Object.assign({}, params), { content: contents[0], embeddingApiType: EmbeddingApiType.EMBED_CONTENT }); + return await this.embedContentInternal(paramsPrivate); + } else { + const paramsPrivate = Object.assign(Object.assign({}, params), { embeddingApiType: EmbeddingApiType.PREDICT }); + return await this.embedContentInternal(paramsPrivate); + } + }; + this.generateContent = async (params) => { + var _a7, _b, _c, _d, _e2; + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params); + if (incompatibleToolIndexes.length > 0) { + const formattedIndexes = incompatibleToolIndexes.map((index2) => `tools[${index2}]`).join(", "); + throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${formattedIndexes}.`); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents(transformedParams.contents); + const maxRemoteCalls = (_c = (_b = (_a7 = transformedParams.config) === null || _a7 === void 0 ? void 0 : _a7.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e2 = (_d = params.config) === null || _d === void 0 ? void 0 : _d.tools) !== null && _e2 !== void 0 ? _e2 : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: "user", + parts: functionResponseParts + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = automaticFunctionCallingHistory; + } + return response; + }; + this.generateContentStream = async (params) => { + var _a7, _b, _c, _d, _e2; + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } + const incompatibleToolIndexes = findAfcIncompatibleToolIndexes(params); + if (incompatibleToolIndexes.length > 0) { + const formattedIndexes = incompatibleToolIndexes.map((index2) => `tools[${index2}]`).join(", "); + throw new Error(`Incompatible tools found at ${formattedIndexes}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`); + } + const streamFunctionCall = (_c = (_b = (_a7 = params === null || params === void 0 ? void 0 : params.config) === null || _a7 === void 0 ? void 0 : _a7.toolConfig) === null || _b === void 0 ? void 0 : _b.functionCallingConfig) === null || _c === void 0 ? void 0 : _c.streamFunctionCallArguments; + const disableAfc = (_e2 = (_d = params === null || params === void 0 ? void 0 : params.config) === null || _d === void 0 ? void 0 : _d.automaticFunctionCalling) === null || _e2 === void 0 ? void 0 : _e2.disable; + if (streamFunctionCall && !disableAfc) { + 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(params); + }; + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a7; + let positivePromptSafetyAttributes; + const generatedImages = []; + if (apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.generatedImages) { + for (const generatedImage of apiResponse.generatedImages) { + if (generatedImage && (generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) && ((_a7 = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes) === null || _a7 === void 0 ? void 0 : _a7.contentType) === "Positive Prompt") { + positivePromptSafetyAttributes = generatedImage === null || generatedImage === void 0 ? void 0 : generatedImage.safetyAttributes; + } else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages, + positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse + }; + } else { + response = { + generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a7; + const defaultConfig = { + queryBase: true + }; + const actualConfig = Object.assign(Object.assign({}, defaultConfig), params === null || params === void 0 ? void 0 : params.config); + const actualParams = { + config: actualConfig + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ((_a7 = actualParams.config) === null || _a7 === void 0 ? void 0 : _a7.filter) { + throw new Error("Filtering tuned models list for Vertex AI is not currently supported"); + } else { + actualParams.config.filter = "labels.tune-type:*"; + } + } + } + return new Pager(PagedItem.PAGED_ITEM_MODELS, (x2) => this.listInternal(x2), await this.listInternal(actualParams), actualParams); + }; + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => img.toReferenceImageAPI()); + } + } + return await this.editImageInternal(paramsInternal); + }; + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: "upscale" + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig + }; + return await this.upscaleImageInternal(apiParams); + }; + this.generateVideos = async (params) => { + var _a7, _b, _c, _d, _e2, _f; + if ((params.prompt || params.image || params.video) && params.source) { + throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source."); + } + if (!this.apiClient.isVertexAI()) { + if (((_a7 = params.video) === null || _a7 === void 0 ? void 0 : _a7.uri) && ((_b = params.video) === null || _b === void 0 ? void 0 : _b.videoBytes)) { + params.video = { + uri: params.video.uri, + mimeType: params.video.mimeType + }; + } else if (((_d = (_c = params.source) === null || _c === void 0 ? void 0 : _c.video) === null || _d === void 0 ? void 0 : _d.uri) && ((_f = (_e2 = params.source) === null || _e2 === void 0 ? void 0 : _e2.video) === null || _f === void 0 ? void 0 : _f.videoBytes)) { + params.source.video = { + uri: params.source.video.uri, + mimeType: params.source.video.mimeType + }; + } + } + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes("$schema")) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a7, _b, _c; + const tools = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all(tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + })); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { tools: transformedTools }) + }; + newParams.config.tools = transformedTools; + if (params.config && params.config.tools && hasMcpToolUsage(params.config.tools)) { + const headers = (_c = (_b = params.config.httpOptions) === null || _b === void 0 ? void 0 : _b.headers) !== null && _c !== void 0 ? _c : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign(Object.assign({}, params.config.httpOptions), { headers: newHeaders }); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a7, _b, _c; + const afcTools = /* @__PURE__ */ new Map(); + for (const tool of (_b = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.tools) !== null && _b !== void 0 ? _b : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = toolDeclaration.functionDeclarations) !== null && _c !== void 0 ? _c : []) { + if (!declaration.name) { + throw new Error("Function declaration name is required."); + } + if (afcTools.has(declaration.name)) { + throw new Error(`Duplicate tool declaration name: ${declaration.name}`); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a7, _b, _c; + const maxRemoteCalls = (_c = (_b = (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.automaticFunctionCalling) === null || _b === void 0 ? void 0 : _b.maximumRemoteCalls) !== null && _c !== void 0 ? _c : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function(models, afcTools, params2) { + return __asyncGenerator(this, arguments, function* () { + var _a8, e_1, _b2, _c2; + var _d, _e2; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await(models.processParamsMaybeAddMcpUsage(params2)); + const response = yield __await(models.generateContentStreamInternal(transformedParams)); + const functionResponses = []; + const responseContents = []; + try { + for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _a8 = response_1_1.done, !_a8; _f = true) { + _c2 = response_1_1.value; + _f = false; + const chunk = _c2; + yield yield __await(chunk); + if (chunk.candidates && ((_d = chunk.candidates[0]) === null || _d === void 0 ? void 0 : _d.content)) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_e2 = chunk.candidates[0].content.parts) !== null && _e2 !== void 0 ? _e2 : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error("Function call name was not returned by the model."); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`); + } else { + const responseParts = yield __await(afcTools.get(part.functionCall.name).callTool([part.functionCall])); + functionResponses.push(...responseParts); + } + } + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_a8 && (_b2 = response_1.return)) yield __await(_b2.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: "user", + parts: functionResponses + } + } + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: "user", + parts: functionResponses + }); + const updatedContents = tContents(params2.contents).concat(newContents); + params2.contents = updatedContents; + } else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }); + return response.then(function(apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a8, e_2, _b2, _c2; + try { + for (var _d2 = true, apiResponse_1 = __asyncValues(apiResponse), apiResponse_1_1; apiResponse_1_1 = yield __await(apiResponse_1.next()), _a8 = apiResponse_1_1.done, !_a8; _d2 = true) { + _c2 = apiResponse_1_1.value; + _d2 = false; + const chunk = _c2; + const resp = generateContentResponseFromVertex(yield __await(chunk.json()), params); + resp["sdkHttpResponse"] = { + headers: chunk.headers + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d2 && !_a8 && (_b2 = apiResponse_1.return)) yield __await(_b2.call(apiResponse_1)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }); + return response.then(function(apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a8, e_3, _b2, _c2; + try { + for (var _d2 = true, apiResponse_2 = __asyncValues(apiResponse), apiResponse_2_1; apiResponse_2_1 = yield __await(apiResponse_2.next()), _a8 = apiResponse_2_1.done, !_a8; _d2 = true) { + _c2 = apiResponse_2_1.value; + _d2 = false; + const chunk = _c2; + const resp = generateContentResponseFromMldev(yield __await(chunk.json()), params); + resp["sdkHttpResponse"] = { + headers: chunk.headers + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d2 && !_a8 && (_b2 = apiResponse_2.return)) yield __await(_b2.call(apiResponse_2)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContentInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersPrivateToVertex(this.apiClient, params, params); + const endpointUrl = tIsVertexEmbedContentModel(params.model) ? "{model}:embedContent" : "{model}:predict"; + path6 = formatMap(endpointUrl, body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse, params); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = embedContentParametersPrivateToMldev(this.apiClient, params); + path6 = formatMap("{model}:batchEmbedContents", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for generating images. + */ + async generateImagesInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Private method for editing an image. + */ + async editImageInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path6 = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Private method for upscaling an image. + */ + async upscaleImageInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex(this.apiClient, params); + path6 = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Recontextualizes an image. + * + * There are two types of recontextualization currently supported: + * 1) Imagen Product Recontext - Generate images of products in new scenes + * and contexts. + * 2) Virtual Try-On: Generate images of persons modeling fashion products. + * + * @param params - The parameters for recontextualizing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response1 = await ai.models.recontextImage({ + * model: 'imagen-product-recontext-preview-06-30', + * source: { + * prompt: 'In a modern kitchen setting.', + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response1?.generatedImages?.[0]?.image?.imageBytes); + * + * const response2 = await ai.models.recontextImage({ + * model: 'virtual-try-on-001', + * source: { + * personImage: personImage, + * productImages: [productImage], + * }, + * config: { + * numberOfImages: 1, + * }, + * }); + * console.log(response2?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async recontextImage(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = recontextImageParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = recontextImageResponseFromVertex(apiResponse); + const typedResp = new RecontextImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Segments an image, creating a mask of a specified area. + * + * @param params - The parameters for segmenting an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.segmentImage({ + * model: 'image-segmentation-001', + * source: { + * image: image, + * }, + * config: { + * mode: 'foreground', + * }, + * }); + * console.log(response?.generatedMasks?.[0]?.mask?.imageBytes); + * ``` + */ + async segmentImage(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = segmentImageParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = segmentImageResponseFromVertex(apiResponse); + const typedResp = new SegmentImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = getModelParametersToMldev(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path6 = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listModelsParametersToMldev(this.apiClient, params); + path6 = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateModelParametersToMldev(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromVertex(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = deleteModelResponseFromMldev(apiResponse); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = countTokensParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:computeTokens", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Private method for generating videos. + */ + async generateVideosInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path6 = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path6 = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + }; + Operations = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === void 0 || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName2 = operation.name.split("/operations/")[0]; + let httpOptions = void 0; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName2, + config: { httpOptions } + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: true + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: false + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === void 0 || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName2 = operation.name.split("/operations/")[0]; + let httpOptions = void 0; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName2, + config: { httpOptions } + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: true + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + _isVertexAI: false + }); + } + } + async getVideosOperationInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path6 = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + const body = getOperationParametersToMldev(params); + path6 = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path6 = formatMap("{resourceName}:fetchPredictOperation", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + }; + Tokens = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("The client.tokens.create method is only supported by the Gemini Developer API."); + } else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path6 = formatMap("auth_tokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(transformedBody), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + }; + Documents = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + this.list = async (params) => { + return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x2) => this.listInternal({ parent: params.parent, config: x2.config }), await this.listInternal(params), params); + }; + } + /** + * Gets a Document. + * + * @param params - The parameters for getting a document. + * @return Document. + */ + async get(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = getDocumentParametersToMldev(params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes a Document. + * + * @param params - The parameters for deleting a document. + */ + async delete(params) { + var _a7, _b; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = deleteDocumentParametersToMldev(params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }); + } + } + async listInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = listDocumentsParametersToMldev(params); + path6 = formatMap("{parent}/documents", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listDocumentsResponseFromMldev(apiResponse); + const typedResp = new ListDocumentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + }; + FileSearchStores = class extends BaseModule { + constructor(apiClient, documents = new Documents(apiClient)) { + super(); + this.apiClient = apiClient; + this.documents = documents; + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_FILE_SEARCH_STORES, (x2) => this.listInternal(x2), await this.listInternal(params), params); + }; + } + /** + * Uploads a file asynchronously to a given File Search Store. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadToFileSearchStoreParameters` interface. + * @see {@link types.UploadToFileSearchStoreParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a long running operation. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to a given file search store. + * + * ```ts + * const operation = await ai.fileSearchStores.upload({fileSearchStoreName: 'fileSearchStores/foo-bar', file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(operation.name); + * ``` + */ + async uploadToFileSearchStore(params) { + if (this.apiClient.isVertexAI()) { + throw new Error("Vertex AI does not support uploading files to a file search store."); + } + return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config); + } + /** + * Creates a File Search Store. + * + * @param params - The parameters for creating a File Search Store. + * @return FileSearchStore. + */ + async create(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = createFileSearchStoreParametersToMldev(params); + path6 = formatMap("fileSearchStores", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Gets a File Search Store. + * + * @param params - The parameters for getting a File Search Store. + * @return FileSearchStore. + */ + async get(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = getFileSearchStoreParametersToMldev(params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((resp) => { + return resp; + }); + } + } + /** + * Deletes a File Search Store. + * + * @param params - The parameters for deleting a File Search Store. + */ + async delete(params) { + var _a7, _b; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = deleteFileSearchStoreParametersToMldev(params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }); + } + } + async listInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = listFileSearchStoresParametersToMldev(params); + path6 = formatMap("fileSearchStores", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = listFileSearchStoresResponseFromMldev(apiResponse); + const typedResp = new ListFileSearchStoresResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async uploadToFileSearchStoreInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = uploadToFileSearchStoreParametersToMldev(params); + path6 = formatMap("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse); + const typedResp = new UploadToFileSearchStoreResumableResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Imports a File from File Service to a FileSearchStore. + * + * This is a long-running operation, see aip.dev/151 + * + * @param params - The parameters for importing a file to a file search store. + * @return ImportFileOperation. + */ + async importFile(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = importFileParametersToMldev(params); + path6 = formatMap("{file_search_store_name}:importFile", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = importFileOperationFromMldev(apiResponse); + const typedResp = new ImportFileOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + }; + uuid4Internal = function() { + const { crypto: crypto2 } = globalThis; + if (crypto2 === null || crypto2 === void 0 ? void 0 : crypto2.randomUUID) { + uuid4Internal = crypto2.randomUUID.bind(crypto2); + return crypto2.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto2 ? () => crypto2.getRandomValues(u8)[0] : () => Math.random() * 255 & 255; + return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c6) => (+c6 ^ randomByte() & 15 >> +c6 / 4).toString(16)); + }; + uuid43 = () => uuid4Internal(); + castToError3 = (err) => { + if (err instanceof Error) + return err; + if (typeof err === "object" && err !== null) { + try { + if (Object.prototype.toString.call(err) === "[object Error]") { + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } catch (_a7) { + } + try { + return new Error(JSON.stringify(err)); + } catch (_b) { + } + } + return new Error(err); + }; + GeminiNextGenAPIClientError = class extends Error { + }; + APIError3 = class _APIError extends GeminiNextGenAPIClientError { + constructor(status, error, message, headers) { + super(`${_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.error = error; + } + static makeMessage(status, error, message) { + const msg = (error === null || error === void 0 ? void 0 : error.message) ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return "(no status code or body)"; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError3({ message, cause: castToError3(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError3(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError3(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError3(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError3(status, error, message, headers); + } + if (status === 409) { + return new ConflictError3(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError3(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError3(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError3(status, error, message, headers); + } + return new _APIError(status, error, message, headers); + } + }; + APIUserAbortError3 = class extends APIError3 { + constructor({ message } = {}) { + super(void 0, void 0, message || "Request was aborted.", void 0); + } + }; + APIConnectionError3 = class extends APIError3 { + constructor({ message, cause }) { + super(void 0, void 0, message || "Connection error.", void 0); + if (cause) + this.cause = cause; + } + }; + APIConnectionTimeoutError3 = class extends APIConnectionError3 { + constructor({ message } = {}) { + super({ message: message !== null && message !== void 0 ? message : "Request timed out." }); + } + }; + BadRequestError3 = class extends APIError3 { + }; + AuthenticationError3 = class extends APIError3 { + }; + PermissionDeniedError3 = class extends APIError3 { + }; + NotFoundError3 = class extends APIError3 { + }; + ConflictError3 = class extends APIError3 { + }; + UnprocessableEntityError3 = class extends APIError3 { + }; + RateLimitError3 = class extends APIError3 { + }; + InternalServerError3 = class extends APIError3 { + }; + startsWithSchemeRegexp3 = /^[a-z][a-z0-9+.-]*:/i; + isAbsoluteURL3 = (url) => { + return startsWithSchemeRegexp3.test(url); + }; + isArrayInternal = (val2) => (isArrayInternal = Array.isArray, isArrayInternal(val2)); + isArray3 = isArrayInternal; + isReadonlyArrayInternal = isArray3; + isReadonlyArray3 = isReadonlyArrayInternal; + validatePositiveInteger3 = (name, n7) => { + if (typeof n7 !== "number" || !Number.isInteger(n7)) { + throw new GeminiNextGenAPIClientError(`${name} must be an integer`); + } + if (n7 < 0) { + throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`); + } + return n7; + }; + safeJSON3 = (text3) => { + try { + return JSON.parse(text3); + } catch (err) { + return void 0; + } + }; + sleep$1 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms)); + FallbackEncoder3 = ({ headers, body }) => { + return { + bodyHeaders: { + "content-type": "application/json" + }, + body: JSON.stringify(body) + }; + }; + VERSION3 = "0.0.1"; + checkFileSupport3 = () => { + var _a7; + if (typeof File === "undefined") { + const { process: process2 } = globalThis; + const isOldNode = typeof ((_a7 = process2 === null || process2 === void 0 ? void 0 : process2.versions) === null || _a7 === void 0 ? void 0 : _a7.node) === "string" && parseInt(process2.versions.node.split(".")) < 20; + throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : "")); + } + }; + isAsyncIterable3 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; + isBlobLike3 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; + isFileLike3 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike3(value); + isResponseLike3 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; + APIResource3 = class { + constructor(client) { + this._client = client; + } + }; + APIResource3._key = []; + EMPTY3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); + createPathTagFunction3 = (pathEncoder = encodeURIPath3) => (function path6(statics, ...params) { + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path7 = statics.reduce((previousValue, currentValue, index2) => { + var _a7, _b, _c; + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index2]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value); + if (index2 !== params.length && (value == null || typeof value === "object" && // handle values from other realms + value.toString === ((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a7 = value.hasOwnProperty) !== null && _a7 !== void 0 ? _a7 : EMPTY3)) !== null && _b !== void 0 ? _b : EMPTY3)) === null || _c === void 0 ? void 0 : _c.toString))) { + encoded = value + ""; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter` + }); + } + return previousValue + currentValue + (index2 === params.length ? "" : encoded); + }, ""); + const pathOnly = path7.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match2; + while ((match2 = invalidSegmentPattern.exec(pathOnly)) !== null) { + const hasLeadingSlash = match2[0].startsWith("/"); + const offset = hasLeadingSlash ? 1 : 0; + const cleanMatch = hasLeadingSlash ? match2[0].slice(1) : match2[0]; + invalidSegments.push({ + start: match2.index + offset, + length: cleanMatch.length, + error: `Value "${cleanMatch}" can't be safely passed as a path parameter` + }); + } + invalidSegments.sort((a3, b4) => a3.start - b4.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = " ".repeat(segment.start - lastEnd); + const arrows = "^".repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ""); + throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments: +${invalidSegments.map((e9) => e9.error).join("\n")} +${path7} +${underline}`); + } + return path7; + }); + path3 = /* @__PURE__ */ createPathTagFunction3(encodeURIPath3); + BaseInteractions = class extends APIResource3 { + create(params, options) { + var _a7; + const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]); + if ("model" in body && "agent_config" in body) { + throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`); + } + if ("agent" in body && "generation_config" in body) { + throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`); + } + return this._client.post(path3`/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a7 = params.stream) !== null && _a7 !== void 0 ? _a7 : false })); + } + /** + * Deletes the interaction by id. + * + * @example + * ```ts + * const interaction = await client.interactions.delete('id', { + * api_version: 'api_version', + * }); + * ``` + */ + delete(id, params = {}, options) { + const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {}; + return this._client.delete(path3`/${api_version}/interactions/${id}`, options); + } + /** + * Cancels an interaction by id. This only applies to background interactions that are still running. + * + * @example + * ```ts + * const interaction = await client.interactions.cancel('id', { + * api_version: 'api_version', + * }); + * ``` + */ + cancel(id, params = {}, options) { + const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {}; + return this._client.post(path3`/${api_version}/interactions/${id}/cancel`, options); + } + get(id, params = {}, options) { + var _a7; + const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]); + return this._client.get(path3`/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a7 = params === null || params === void 0 ? void 0 : params.stream) !== null && _a7 !== void 0 ? _a7 : false })); + } + }; + BaseInteractions._key = Object.freeze(["interactions"]); + Interactions = class extends BaseInteractions { + }; + LineDecoder3 = class { + constructor() { + this.buffer = new Uint8Array(); + this.carriageReturnIndex = null; + this.searchIndex = 0; + } + decode(chunk) { + var _a7; + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF83(chunk) : chunk; + this.buffer = concatBytes3([this.buffer, binaryChunk]); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex3(this.buffer, (_a7 = this.carriageReturnIndex) !== null && _a7 !== void 0 ? _a7 : this.searchIndex)) != null) { + if (patternIndex.carriage && this.carriageReturnIndex == null) { + this.carriageReturnIndex = patternIndex.index; + continue; + } + if (this.carriageReturnIndex != null && (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) { + lines.push(decodeUTF83(this.buffer.subarray(0, this.carriageReturnIndex - 1))); + this.buffer = this.buffer.subarray(this.carriageReturnIndex); + this.carriageReturnIndex = null; + this.searchIndex = 0; + continue; + } + const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF83(this.buffer.subarray(0, endIndex)); + lines.push(line); + this.buffer = this.buffer.subarray(patternIndex.index); + this.carriageReturnIndex = null; + this.searchIndex = 0; + } + this.searchIndex = Math.max(0, this.buffer.length - 1); + return lines; + } + flush() { + if (!this.buffer.length) { + return []; + } + return this.decode("\n"); + } + }; + LineDecoder3.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]); + LineDecoder3.NEWLINE_REGEXP = /\r\n|[\n\r]/g; + levelNumbers3 = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500 + }; + parseLogLevel3 = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return void 0; + } + if (hasOwn3(levelNumbers3, maybeLevel)) { + return maybeLevel; + } + loggerFor3(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers3))}`); + return void 0; + }; + noopLogger3 = { + error: noop3, + warn: noop3, + info: noop3, + debug: noop3 + }; + cachedLoggers3 = /* @__PURE__ */ new WeakMap(); + formatRequestDetails3 = (details) => { + if (details.options) { + details.options = Object.assign({}, details.options); + delete details.options["headers"]; + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + name.toLowerCase() === "x-goog-api-key" || name.toLowerCase() === "authorization" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value + ])); + } + if ("retryOfRequestLogID" in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; + }; + Stream3 = class _Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + this.controller = controller; + this.client = client; + } + static fromSSEResponse(response, controller, client) { + let consumed2 = false; + const logger2 = client ? loggerFor3(client) : console; + function iterator() { + return __asyncGenerator(this, arguments, function* iterator_1() { + var _a7, e_1, _b, _c; + if (consumed2) { + throw new GeminiNextGenAPIClientError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed2 = true; + let done = false; + try { + try { + for (var _d = true, _e2 = __asyncValues(_iterSSEMessages3(response, controller)), _f; _f = yield __await(_e2.next()), _a7 = _f.done, !_a7; _d = true) { + _c = _f.value; + _d = false; + const sse = _c; + if (done) + continue; + if (sse.data.startsWith("[DONE]")) { + done = true; + continue; + } else { + try { + yield yield __await(JSON.parse(sse.data)); + } catch (e9) { + logger2.error(`Could not parse message into JSON:`, sse.data); + logger2.error(`From chunk:`, sse.raw); + throw e9; + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a7 && (_b = _e2.return)) yield __await(_b.call(_e2)); + } finally { + if (e_1) throw e_1.error; + } + } + done = true; + } catch (e9) { + if (isAbortError3(e9)) + return yield __await(void 0); + throw e9; + } finally { + if (!done) + controller.abort(); + } + }); + } + return new _Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed2 = false; + function iterLines() { + return __asyncGenerator(this, arguments, function* iterLines_1() { + var _a7, e_2, _b, _c; + const lineDecoder = new LineDecoder3(); + const iter = ReadableStreamToAsyncIterable3(readableStream); + try { + for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a7 = iter_1_1.done, !_a7; _d = true) { + _c = iter_1_1.value; + _d = false; + const chunk = _c; + for (const line of lineDecoder.decode(chunk)) { + yield yield __await(line); + } + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a7 && (_b = iter_1.return)) yield __await(_b.call(iter_1)); + } finally { + if (e_2) throw e_2.error; + } + } + for (const line of lineDecoder.flush()) { + yield yield __await(line); + } + }); + } + function iterator() { + return __asyncGenerator(this, arguments, function* iterator_2() { + var _a7, e_3, _b, _c; + if (consumed2) { + throw new GeminiNextGenAPIClientError("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); + } + consumed2 = true; + let done = false; + try { + try { + for (var _d = true, _e2 = __asyncValues(iterLines()), _f; _f = yield __await(_e2.next()), _a7 = _f.done, !_a7; _d = true) { + _c = _f.value; + _d = false; + const line = _c; + if (done) + continue; + if (line) + yield yield __await(JSON.parse(line)); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a7 && (_b = _e2.return)) yield __await(_b.call(_e2)); + } finally { + if (e_3) throw e_3.error; + } + } + done = true; + } catch (e9) { + if (isAbortError3(e9)) + return yield __await(void 0); + throw e9; + } finally { + if (!done) + controller.abort(); + } + }); + } + return new _Stream(iterator, controller, client); + } + [Symbol.asyncIterator]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + } + }; + }; + return [ + new _Stream(() => teeIterator(left), this.controller, this.client), + new _Stream(() => teeIterator(right), this.controller, this.client) + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self2 = this; + let iter; + return makeReadableStream3({ + async start() { + iter = self2[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = encodeUTF83(JSON.stringify(value) + "\n"); + ctrl.enqueue(bytes); + } catch (err) { + ctrl.error(err); + } + }, + async cancel() { + var _a7; + await ((_a7 = iter.return) === null || _a7 === void 0 ? void 0 : _a7.call(iter)); + } + }); + } + }; + SSEDecoder3 = class { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith("\r")) { + line = line.substring(0, line.length - 1); + } + if (!line) { + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join("\n"), + raw: this.chunks + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(":")) { + return null; + } + let [fieldname, _3, value] = partition3(line, ":"); + if (value.startsWith(" ")) { + value = value.substring(1); + } + if (fieldname === "event") { + this.event = value; + } else if (fieldname === "data") { + this.data.push(value); + } + return null; + } + }; + APIPromise3 = class _APIPromise extends Promise { + constructor(client, responsePromise, parseResponse2 = defaultParseResponse3) { + super((resolve2) => { + resolve2(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse2; + this.client = client; + } + _thenUnwrap(transform) { + return new _APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p4) => p4.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } + }; + brand_privateNullableHeaders3 = /* @__PURE__ */ Symbol("brand.privateNullableHeaders"); + buildHeaders3 = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = /* @__PURE__ */ new Set(); + for (const headers of newHeaders) { + const seenHeaders = /* @__PURE__ */ new Set(); + for (const [name, value] of iterateHeaders3(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders3]: true, values: targetHeaders, nulls: nullHeaders }; + }; + readEnv3 = (env) => { + var _a7, _b, _c, _d, _e2, _f; + if (typeof globalThis.process !== "undefined") { + return (_c = (_b = (_a7 = globalThis.process.env) === null || _a7 === void 0 ? void 0 : _a7[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : void 0; + } + if (typeof globalThis.Deno !== "undefined") { + return (_f = (_e2 = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e2 === void 0 ? void 0 : _e2.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim(); + } + return void 0; + }; + BaseGeminiNextGenAPIClient = class _BaseGeminiNextGenAPIClient { + /** + * API Client for interfacing with the Gemini Next Gen API API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null] + * @param {string | undefined} [opts.apiVersion=v1beta] + * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + */ + constructor(_b) { + var _c, _d, _e2, _f, _g, _h, _j; + var { baseURL = readEnv3("GEMINI_NEXT_GEN_API_BASE_URL"), apiKey = (_c = readEnv3("GEMINI_API_KEY")) !== null && _c !== void 0 ? _c : null, apiVersion = "v1beta" } = _b, opts = __rest(_b, ["baseURL", "apiKey", "apiVersion"]); + const options = Object.assign(Object.assign({ + apiKey, + apiVersion + }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` }); + this.baseURL = options.baseURL; + this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : _BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT; + this.logger = (_e2 = options.logger) !== null && _e2 !== void 0 ? _e2 : console; + const defaultLogLevel = "warn"; + this.logLevel = defaultLogLevel; + this.logLevel = (_g = (_f = parseLogLevel3(options.logLevel, "ClientOptions.logLevel", this)) !== null && _f !== void 0 ? _f : parseLogLevel3(readEnv3("GEMINI_NEXT_GEN_API_LOG"), "process.env['GEMINI_NEXT_GEN_API_LOG']", this)) !== null && _g !== void 0 ? _g : defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2; + this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch3(); + this.encoder = FallbackEncoder3; + this._options = options; + this.apiKey = apiKey; + this.apiVersion = apiVersion; + this.clientAdapter = options.clientAdapter; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = 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 }), options)); + return client; + } + /** + * Check whether the base URL is set to its default. + */ + baseURLOverridden() { + return this.baseURL !== "https://generativelanguage.googleapis.com"; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values: values2, nulls }) { + if (values2.has("authorization") || values2.has("x-goog-api-key")) { + return; + } + if (this.apiKey && values2.get("x-goog-api-key")) { + return; + } + if (nulls.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(opts) { + const existingHeaders = buildHeaders3([opts.headers]); + if (existingHeaders.values.has("authorization") || existingHeaders.values.has("x-goog-api-key")) { + return void 0; + } + if (this.apiKey) { + return buildHeaders3([{ "x-goog-api-key": this.apiKey }]); + } + if (this.clientAdapter.isVertexAI()) { + return buildHeaders3([await this.clientAdapter.getAuthHeaders()]); + } + return void 0; + } + /** + * Basic re-implementation of `qs.stringify` for primitive types. + */ + stringifyQuery(query) { + return stringifyQuery2(query); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION3}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid43()}`; + } + makeStatusError(status, error, message, headers) { + return APIError3.generate(status, error, message, headers); + } + buildURL(path6, query, defaultBaseURL) { + const baseURL = !this.baseURLOverridden() && defaultBaseURL || this.baseURL; + const url = isAbsoluteURL3(path6) ? new URL(path6) : new URL(baseURL + (baseURL.endsWith("/") && path6.startsWith("/") ? path6.slice(1) : path6)); + const defaultQuery = this.defaultQuery(); + const pathQuery = Object.fromEntries(url.searchParams); + if (!isEmptyObj3(defaultQuery) || !isEmptyObj3(pathQuery)) { + query = Object.assign(Object.assign(Object.assign({}, pathQuery), defaultQuery), query); + } + if (typeof query === "object" && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + + */ + async prepareOptions(options) { + if (this.clientAdapter && this.clientAdapter.isVertexAI() && !options.path.startsWith(`/${this.apiVersion}/projects/`)) { + const oldPath = options.path.slice(this.apiVersion.length + 1); + options.path = `/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${oldPath}`; + } + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { + } + get(path6, opts) { + return this.methodRequest("get", path6, opts); + } + post(path6, opts) { + return this.methodRequest("post", path6, opts); + } + patch(path6, opts) { + return this.methodRequest("patch", path6, opts); + } + put(path6, opts) { + return this.methodRequest("put", path6, opts); + } + delete(path6, opts) { + return this.methodRequest("delete", path6, opts); + } + methodRequest(method, path6, opts) { + return this.request(Promise.resolve(opts).then((opts2) => { + return Object.assign({ method, path: path6 }, opts2); + })); + } + request(options, remainingRetries = null) { + return new APIPromise3(this, this.makeRequest(options, remainingRetries, void 0)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + var _b, _c, _d; + const options = await optionsInput; + const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining + }); + await this.prepareRequest(req, { url, options }); + const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0"); + const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor3(this).debug(`[${requestLogID}] sending request`, formatRequestDetails3({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers + })); + if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) { + throw new APIUserAbortError3(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError3); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) { + throw new APIUserAbortError3(); + } + const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : "")); + if (retriesRemaining) { + loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`); + loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID); + } + loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`); + loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, formatRequestDetails3({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message + })); + if (isTimeout) { + throw new APIConnectionTimeoutError3(); + } + throw new APIConnectionError3({ cause: response }); + } + const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; + await CancelReadableStream3(response.body); + loggerFor3(this).info(`${responseInfo} - ${retryMessage2}`); + loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor3(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err2) => castToError3(err2).message); + const errJSON = safeJSON3(errText); + const errMessage = errJSON ? void 0 : errText; + loggerFor3(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor3(this).info(responseInfo); + loggerFor3(this).debug(`[${requestLogID}] response start`, formatRequestDetails3({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + async fetchWithTimeout(url, init, ms, controller) { + const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]); + const abort = this._makeAbort(controller); + if (signal) + signal.addEventListener("abort", abort, { once: true }); + const timeout = setTimeout(abort, ms); + const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body; + const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, isReadableBody ? { duplex: "half" } : {}), { method: "GET" }), options); + if (method) { + fetchOptions.method = method.toUpperCase(); + } + try { + return await this.fetch.call(void 0, url, fetchOptions); + } finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + const shouldRetryHeader = response.headers.get("x-should-retry"); + if (shouldRetryHeader === "true") + return true; + if (shouldRetryHeader === "false") + return false; + if (response.status === 408) + return true; + if (response.status === 409) + return true; + if (response.status === 429) + return true; + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + var _b; + let timeoutMillis; + const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get("retry-after-ms"); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get("retry-after"); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1e3; + } else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + if (timeoutMillis === void 0) { + const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep$1(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8; + const numRetries = maxRetries - retriesRemaining; + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1e3; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + var _b, _c, _d; + const options = Object.assign({}, inputOptions); + const { method, path: path6, query, defaultBaseURL } = options; + const url = this.buildURL(path6, query, defaultBaseURL); + if ("timeout" in options) + validatePositiveInteger3("timeout", options.timeout); + options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, options.signal && { signal: options.signal }), globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" }), body && { body }), (_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {}), (_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {}); + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== "get") { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const authHeaders = await this.authHeaders(options); + let headers = buildHeaders3([ + idempotencyHeaders, + { Accept: "application/json", "User-Agent": this.getUserAgent() }, + this._options.defaultHeaders, + bodyHeaders, + options.headers, + authHeaders + ]); + this.validateHeaders(headers); + return headers.values; + } + _makeAbort(controller) { + return () => controller.abort(); + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: void 0, body: void 0 }; + } + const headers = buildHeaders3([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now + headers.values.has("content-type") || // `Blob` is superset of `File` + globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data` + body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`) + globalThis.ReadableStream && body instanceof globalThis.ReadableStream + ) { + return { bodyHeaders: void 0, body }; + } else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) { + return { bodyHeaders: void 0, body: ReadableStreamFrom3(body) }; + } else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") { + return { + bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, + body: this.stringifyQuery(body) + }; + } else { + return this.encoder({ body, headers }); + } + } + }; + BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 6e4; + GeminiNextGenAPIClient = class extends BaseGeminiNextGenAPIClient { + constructor() { + super(...arguments); + this.interactions = new Interactions(this); + } + }; + _a4 = GeminiNextGenAPIClient; + GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a4; + GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError; + GeminiNextGenAPIClient.APIError = APIError3; + GeminiNextGenAPIClient.APIConnectionError = APIConnectionError3; + GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError3; + GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError3; + GeminiNextGenAPIClient.NotFoundError = NotFoundError3; + GeminiNextGenAPIClient.ConflictError = ConflictError3; + GeminiNextGenAPIClient.RateLimitError = RateLimitError3; + GeminiNextGenAPIClient.BadRequestError = BadRequestError3; + GeminiNextGenAPIClient.AuthenticationError = AuthenticationError3; + GeminiNextGenAPIClient.InternalServerError = InternalServerError3; + GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError3; + GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError3; + GeminiNextGenAPIClient.toFile = toFile3; + GeminiNextGenAPIClient.Interactions = Interactions; + Tunings = class extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + this.list = async (params = {}) => { + return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x2) => this.listInternal(x2), await this.listInternal(params), params); + }; + this.get = async (params) => { + return await this.getInternal(params); + }; + this.tune = async (params) => { + var _a7; + if (this.apiClient.isVertexAI()) { + if (params.baseModel.startsWith("projects/")) { + const preTunedModel = { + tunedModelName: params.baseModel + }; + if ((_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.preTunedModelCheckpointId) { + preTunedModel.checkpointId = params.config.preTunedModelCheckpointId; + } + const paramsPrivate = Object.assign(Object.assign({}, params), { preTunedModel }); + paramsPrivate.baseModel = void 0; + return await this.tuneInternal(paramsPrivate); + } else { + const paramsPrivate = Object.assign({}, params); + return await this.tuneInternal(paramsPrivate); + } + } else { + const paramsPrivate = Object.assign({}, params); + const operation = await this.tuneMldevInternal(paramsPrivate); + let tunedModelName = ""; + if (operation["metadata"] !== void 0 && operation["metadata"]["tunedModel"] !== void 0) { + tunedModelName = operation["metadata"]["tunedModel"]; + } else if (operation["name"] !== void 0 && operation["name"].includes("/operations/")) { + tunedModelName = operation["name"].split("/operations/")[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getTuningJobParametersToMldev(params); + path6 = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path6 = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listTuningJobsParametersToMldev(params); + path6 = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Cancels a tuning job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.tunings.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a7, _b, _c, _d; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelTuningJobParametersToVertex(params); + path6 = formatMap("{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = cancelTuningJobResponseFromVertex(apiResponse); + const typedResp = new CancelTuningJobResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = cancelTuningJobParametersToMldev(params); + path6 = formatMap("{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions, + abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = cancelTuningJobResponseFromMldev(apiResponse); + const typedResp = new CancelTuningJobResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersPrivateToVertex(params, params); + path6 = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async tuneMldevInternal(params) { + var _a7, _b; + let response; + let path6 = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error("This method is only supported by the Gemini Developer API."); + } else { + const body = createTuningJobParametersPrivateToMldev(params); + path6 = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient.request({ + path: path6, + queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: (_a7 = params.config) === null || _a7 === void 0 ? void 0 : _a7.httpOptions, + abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal + }).then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response2 = jsonResponse; + response2.sdkHttpResponse = { + headers: httpResponse.headers + }; + return response2; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } + }; + BrowserDownloader = class { + async download(_params, _apiClient) { + throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an tag."); + } + }; + MAX_CHUNK_SIZE = 1024 * 1024 * 8; + MAX_RETRY_COUNT = 3; + INITIAL_RETRY_DELAY_MS = 1e3; + DELAY_MULTIPLIER = 2; + X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status"; + BrowserUploader = class { + async upload(file, uploadUrl, apiClient) { + if (typeof file === "string") { + throw new Error("File path is not supported in browser uploader."); + } + return await uploadBlob(file, uploadUrl, apiClient); + } + async uploadToFileSearchStore(file, uploadUrl, apiClient) { + if (typeof file === "string") { + throw new Error("File path is not supported in browser uploader."); + } + return await uploadBlobToFileSearchStore(file, uploadUrl, apiClient); + } + async stat(file) { + if (typeof file === "string") { + throw new Error("File path is not supported in browser uploader."); + } else { + return await getBlobStat(file); + } + } + }; + BrowserWebSocketFactory = class { + create(url, headers, callbacks) { + return new BrowserWebSocket(url, headers, callbacks); + } + }; + BrowserWebSocket = class { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new WebSocket(this.url); + 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(message) { + if (this.ws === void 0) { + throw new Error("WebSocket is not connected"); + } + this.ws.send(message); + } + close() { + if (this.ws === void 0) { + throw new Error("WebSocket is not connected"); + } + this.ws.close(); + } + }; + GOOGLE_API_KEY_HEADER = "x-goog-api-key"; + WebAuth = class { + constructor(apiKey) { + this.apiKey = apiKey; + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + async addAuthHeaders(headers, url) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith("auth_tokens/")) { + throw new Error("Ephemeral tokens are only supported by the live API."); + } + if (!this.apiKey) { + throw new Error("API key is missing. Please provide a valid API key."); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + }; + LANGUAGE_LABEL_PREFIX = "gl-node/"; + GoogleGenAI = class { + get interactions() { + var _a7; + if (this._interactions !== void 0) { + return this._interactions; + } + console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions."); + const httpOpts = this.httpOptions; + if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) { + console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored."); + } + const nextGenClient = new GeminiNextGenAPIClient({ + baseURL: this.apiClient.getBaseUrl(), + apiKey: this.apiKey, + apiVersion: this.apiClient.getApiVersion(), + clientAdapter: this.apiClient, + defaultHeaders: this.apiClient.getDefaultHeaders(), + timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout, + maxRetries: (_a7 = httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.retryOptions) === null || _a7 === void 0 ? void 0 : _a7.attempts + }); + this._interactions = nextGenClient.interactions; + return this._interactions; + } + constructor(options) { + var _a7; + if (options.apiKey == null) { + throw new Error("An API Key must be set when running in a browser"); + } + if (options.project || options.location) { + throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location."); + } + this.vertexai = (_a7 = options.vertexai) !== null && _a7 !== void 0 ? _a7 : false; + this.apiKey = options.apiKey; + const baseUrl = getBaseUrl( + options.httpOptions, + options.vertexai, + /*vertexBaseUrlFromEnv*/ + void 0, + /*geminiBaseUrlFromEnv*/ + void 0 + ); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } else { + options.httpOptions = { baseUrl }; + } + } + this.apiVersion = options.apiVersion; + this.httpOptions = options.httpOptions; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: this.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + "web", + uploader: new BrowserUploader(), + downloader: new BrowserDownloader() + }); + this.models = new Models4(this.apiClient); + this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory()); + this.batches = new Batches4(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files5(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + this.fileSearchStores = new FileSearchStores(this.apiClient); + } + }; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/url.js +var require_url = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/url.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.pathToFunc = pathToFunc; + var hasOwn5 = Object.prototype.hasOwnProperty; + function pathToFunc(pathPattern, options) { + const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g; + return function buildURLPath(params = {}) { + return pathPattern.replace(paramRE, function(_3, placeholder) { + if (!hasOwn5.call(params, placeholder)) { + throw new Error(`Parameter '${placeholder}' is required`); + } + const value = params[placeholder]; + if (typeof value !== "string" && typeof value !== "number") { + throw new Error(`Parameter '${placeholder}' must be a string or number`); + } + return options?.charEncoding === "percent" ? encodeURIComponent(`${value}`) : `${value}`; + }); + }; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/config.js +var require_config = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/config.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDK_METADATA = exports.ServerList = exports.ServerEu = void 0; + exports.serverURLFromOptions = serverURLFromOptions; + var url_js_1 = require_url(); + exports.ServerEu = "eu"; + exports.ServerList = { + [exports.ServerEu]: "https://api.mistral.ai" + }; + function serverURLFromOptions(options) { + let serverURL = options.serverURL; + const params = {}; + if (!serverURL) { + const server = options.server ?? exports.ServerEu; + serverURL = exports.ServerList[server] || ""; + } + const u5 = (0, url_js_1.pathToFunc)(serverURL)(params); + return new URL(u5); + } + exports.SDK_METADATA = { + language: "typescript", + openapiDocVersion: "1.0.0", + sdkVersion: "1.14.1", + genVersion: "2.797.1", + userAgent: "speakeasy-sdk/typescript 1.14.1 2.797.1 1.0.0 @mistralai/mistralai" + }; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/files.js +var require_files = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/files.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readableStreamToArrayBuffer = readableStreamToArrayBuffer; + exports.getContentTypeFromFileName = getContentTypeFromFileName; + async function readableStreamToArrayBuffer(readable) { + const reader = readable.getReader(); + const chunks = []; + let totalLength = 0; + let done = false; + while (!done) { + const { value, done: doneReading } = await reader.read(); + if (doneReading) { + done = true; + } else { + chunks.push(value); + totalLength += value.length; + } + } + const concatenatedChunks = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of chunks) { + concatenatedChunks.set(chunk, offset); + offset += chunk.length; + } + return concatenatedChunks.buffer; + } + function getContentTypeFromFileName(fileName) { + if (!fileName) + return null; + const ext2 = fileName.toLowerCase().split(".").pop(); + if (!ext2) + return null; + const mimeTypes = { + json: "application/json", + xml: "application/xml", + html: "text/html", + htm: "text/html", + txt: "text/plain", + csv: "text/csv", + pdf: "application/pdf", + png: "image/png", + jpg: "image/jpeg", + jpeg: "image/jpeg", + gif: "image/gif", + svg: "image/svg+xml", + js: "application/javascript", + css: "text/css", + zip: "application/zip", + tar: "application/x-tar", + gz: "application/gzip", + mp4: "video/mp4", + mp3: "audio/mpeg", + wav: "audio/wav", + webp: "image/webp", + ico: "image/x-icon", + woff: "font/woff", + woff2: "font/woff2", + ttf: "font/ttf", + otf: "font/otf" + }; + return mimeTypes[ext2] || null; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/http.js +var require_http = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/http.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTPClient = void 0; + exports.matchContentType = matchContentType; + exports.matchStatusCode = matchStatusCode; + exports.matchResponse = matchResponse; + exports.isConnectionError = isConnectionError; + exports.isTimeoutError = isTimeoutError; + exports.isAbortError = isAbortError4; + var DEFAULT_FETCHER = (input, init) => { + if (init == null) { + return fetch(input); + } else { + return fetch(input, init); + } + }; + var HTTPClient = class _HTTPClient { + constructor(options = {}) { + this.options = options; + this.requestHooks = []; + this.requestErrorHooks = []; + this.responseHooks = []; + this.fetcher = options.fetcher || DEFAULT_FETCHER; + } + async request(request) { + let req = request; + for (const hook of this.requestHooks) { + const nextRequest = await hook(req); + if (nextRequest) { + req = nextRequest; + } + } + try { + const res = await this.fetcher(req); + for (const hook of this.responseHooks) { + await hook(res, req); + } + return res; + } catch (err) { + for (const hook of this.requestErrorHooks) { + await hook(err, req); + } + throw err; + } + } + addHook(...args) { + if (args[0] === "beforeRequest") { + this.requestHooks.push(args[1]); + } else if (args[0] === "requestError") { + this.requestErrorHooks.push(args[1]); + } else if (args[0] === "response") { + this.responseHooks.push(args[1]); + } else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + return this; + } + removeHook(...args) { + let target; + if (args[0] === "beforeRequest") { + target = this.requestHooks; + } else if (args[0] === "requestError") { + target = this.requestErrorHooks; + } else if (args[0] === "response") { + target = this.responseHooks; + } else { + throw new Error(`Invalid hook type: ${args[0]}`); + } + const index2 = target.findIndex((v4) => v4 === args[1]); + if (index2 >= 0) { + target.splice(index2, 1); + } + return this; + } + clone() { + const child = new _HTTPClient(this.options); + child.requestHooks = this.requestHooks.slice(); + child.requestErrorHooks = this.requestErrorHooks.slice(); + child.responseHooks = this.responseHooks.slice(); + return child; + } + }; + exports.HTTPClient = HTTPClient; + var mediaParamSeparator = /\s*;\s*/g; + function matchContentType(response, pattern) { + if (pattern === "*") { + return true; + } + let contentType = response.headers.get("content-type")?.trim() || "application/octet-stream"; + contentType = contentType.toLowerCase(); + const wantParts = pattern.toLowerCase().trim().split(mediaParamSeparator); + const [wantType = "", ...wantParams] = wantParts; + if (wantType.split("/").length !== 2) { + return false; + } + const gotParts = contentType.split(mediaParamSeparator); + const [gotType = "", ...gotParams] = gotParts; + const [type = "", subtype = ""] = gotType.split("/"); + if (!type || !subtype) { + return false; + } + if (wantType !== "*/*" && gotType !== wantType && `${type}/*` !== wantType && `*/${subtype}` !== wantType) { + return false; + } + if (gotParams.length < wantParams.length) { + return false; + } + const params = new Set(gotParams); + for (const wantParam of wantParams) { + if (!params.has(wantParam)) { + return false; + } + } + return true; + } + var codeRangeRE = new RegExp("^[0-9]xx$", "i"); + function matchStatusCode(response, codes) { + const actual = `${response.status}`; + const expectedCodes = Array.isArray(codes) ? codes : [codes]; + if (!expectedCodes.length) { + return false; + } + return expectedCodes.some((ec) => { + const code = `${ec}`; + if (code === "default") { + return true; + } + if (!codeRangeRE.test(`${code}`)) { + return code === actual; + } + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); + } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); + } + return actualFamily === expectFamily; + }); + } + function matchResponse(response, code, contentTypePattern) { + return matchStatusCode(response, code) && matchContentType(response, contentTypePattern); + } + function isConnectionError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + const isBrowserErr = err instanceof TypeError && err.message.toLowerCase().startsWith("failed to fetch"); + const isNodeErr = err instanceof TypeError && err.message.toLowerCase().startsWith("fetch failed"); + const isBunErr = "name" in err && err.name === "ConnectionError"; + const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnreset"; + return isBrowserErr || isNodeErr || isGenericErr || isBunErr; + } + function isTimeoutError(err) { + if (typeof err !== "object" || err == null) { + return false; + } + const isNative = "name" in err && err.name === "TimeoutError"; + const isLegacyNative = "code" in err && err.code === 23; + const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted"; + return isNative || isLegacyNative || isGenericErr; + } + function isAbortError4(err) { + if (typeof err !== "object" || err == null) { + return false; + } + const isNative = "name" in err && err.name === "AbortError"; + const isLegacyNative = "code" in err && err.code === 20; + const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted"; + return isNative || isLegacyNative || isGenericErr; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/custom_user_agent.js +var require_custom_user_agent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/custom_user_agent.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CustomUserAgentHook = void 0; + var config_1 = require_config(); + var CustomUserAgentHook = class { + beforeRequest(_3, request) { + const version6 = config_1.SDK_METADATA.sdkVersion; + const ua = `mistral-client-typescript/${version6}`; + request.headers.set("user-agent", ua); + if (!request.headers.get("user-agent")) { + request.headers.set("x-mistral-user-agent", ua); + } + return request; + } + }; + exports.CustomUserAgentHook = CustomUserAgentHook; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/deprecation_warning.js +var require_deprecation_warning = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/deprecation_warning.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeprecationWarningHook = void 0; + var HEADER_MODEL_DEPRECATION_TIMESTAMP = "x-model-deprecation-timestamp"; + var DeprecationWarningHook = class { + afterSuccess(_3, response) { + if (response.headers.has(HEADER_MODEL_DEPRECATION_TIMESTAMP)) { + response.clone().json().then((body) => { + const model = body.model; + console.warn(`WARNING: The model ${model} is deprecated and will be removed on ${response.headers.get(HEADER_MODEL_DEPRECATION_TIMESTAMP)}. Please refer to https://docs.mistral.ai/getting-started/models/#api-versioning for more information.`); + }); + } + return response; + } + }; + exports.DeprecationWarningHook = DeprecationWarningHook; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/registration.js +var require_registration = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/registration.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.initHooks = initHooks; + var custom_user_agent_1 = require_custom_user_agent(); + var deprecation_warning_1 = require_deprecation_warning(); + function initHooks(hooks) { + const customUserAgentHook = new custom_user_agent_1.CustomUserAgentHook(); + hooks.registerBeforeRequestHook(customUserAgentHook); + const deprecationWarningHook = new deprecation_warning_1.DeprecationWarningHook(); + hooks.registerAfterSuccessHook(deprecationWarningHook); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/hooks/hooks.js +var require_hooks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/hooks/hooks.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDKHooks = void 0; + var registration_js_1 = require_registration(); + var SDKHooks = class { + constructor() { + this.sdkInitHooks = []; + this.beforeCreateRequestHooks = []; + this.beforeRequestHooks = []; + this.afterSuccessHooks = []; + this.afterErrorHooks = []; + const presetHooks = []; + for (const hook of presetHooks) { + if ("sdkInit" in hook) { + this.registerSDKInitHook(hook); + } + if ("beforeCreateRequest" in hook) { + this.registerBeforeCreateRequestHook(hook); + } + if ("beforeRequest" in hook) { + this.registerBeforeRequestHook(hook); + } + if ("afterSuccess" in hook) { + this.registerAfterSuccessHook(hook); + } + if ("afterError" in hook) { + this.registerAfterErrorHook(hook); + } + } + (0, registration_js_1.initHooks)(this); + } + registerSDKInitHook(hook) { + this.sdkInitHooks.push(hook); + } + registerBeforeCreateRequestHook(hook) { + this.beforeCreateRequestHooks.push(hook); + } + registerBeforeRequestHook(hook) { + this.beforeRequestHooks.push(hook); + } + registerAfterSuccessHook(hook) { + this.afterSuccessHooks.push(hook); + } + registerAfterErrorHook(hook) { + this.afterErrorHooks.push(hook); + } + sdkInit(opts) { + return this.sdkInitHooks.reduce((opts2, hook) => hook.sdkInit(opts2), opts); + } + beforeCreateRequest(hookCtx, input) { + let inp = input; + for (const hook of this.beforeCreateRequestHooks) { + inp = hook.beforeCreateRequest(hookCtx, inp); + } + return inp; + } + async beforeRequest(hookCtx, request) { + let req = request; + for (const hook of this.beforeRequestHooks) { + req = await hook.beforeRequest(hookCtx, req); + } + return req; + } + async afterSuccess(hookCtx, response) { + let res = response; + for (const hook of this.afterSuccessHooks) { + res = await hook.afterSuccess(hookCtx, res); + } + return res; + } + async afterError(hookCtx, response, error) { + let res = response; + let err = error; + for (const hook of this.afterErrorHooks) { + const result = await hook.afterError(hookCtx, res, err); + res = result.response; + err = result.error; + } + return { response: res, error: err }; + } + }; + exports.SDKHooks = SDKHooks; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpclienterrors.js +var require_httpclienterrors = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpclienterrors.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConnectionError = exports.RequestTimeoutError = exports.RequestAbortedError = exports.InvalidRequestError = exports.UnexpectedClientError = exports.HTTPClientError = void 0; + var HTTPClientError = class extends Error { + constructor(message, opts) { + let msg = message; + if (opts?.cause) { + msg += `: ${opts.cause}`; + } + super(msg, opts); + this.name = "HTTPClientError"; + if (typeof this.cause === "undefined") { + this.cause = opts?.cause; + } + } + }; + exports.HTTPClientError = HTTPClientError; + var UnexpectedClientError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "UnexpectedClientError"; + } + }; + exports.UnexpectedClientError = UnexpectedClientError; + var InvalidRequestError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "InvalidRequestError"; + } + }; + exports.InvalidRequestError = InvalidRequestError; + var RequestAbortedError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "RequestAbortedError"; + } + }; + exports.RequestAbortedError = RequestAbortedError; + var RequestTimeoutError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "RequestTimeoutError"; + } + }; + exports.RequestTimeoutError = RequestTimeoutError; + var ConnectionError = class extends HTTPClientError { + constructor() { + super(...arguments); + this.name = "ConnectionError"; + } + }; + exports.ConnectionError = ConnectionError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/fp.js +var require_fp = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/fp.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OK = OK3; + exports.ERR = ERR; + exports.unwrap = unwrap; + exports.unwrapAsync = unwrapAsync; + function OK3(value) { + return { ok: true, value }; + } + function ERR(error) { + return { ok: false, error }; + } + function unwrap(r8) { + if (!r8.ok) { + throw r8.error; + } + return r8.value; + } + async function unwrapAsync(pr) { + const r8 = await pr; + if (!r8.ok) { + throw r8.error; + } + return r8.value; + } + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/util.cjs +var require_util = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/util.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; + var util3; + (function(util4) { + util4.assertEqual = (_3) => { + }; + function assertIs(_arg) { + } + util4.assertIs = assertIs; + function assertNever3(_x2) { + throw new Error(); + } + util4.assertNever = assertNever3; + util4.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util4.getValidEnumValues = (obj) => { + const validKeys = util4.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); + const filtered = {}; + for (const k2 of validKeys) { + filtered[k2] = obj[k2]; + } + return util4.objectValues(filtered); + }; + util4.objectValues = (obj) => { + return util4.objectKeys(obj).map(function(e9) { + return obj[e9]; + }); + }; + util4.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys2 = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys2.push(key); + } + } + return keys2; + }; + util4.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util4.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2; + function joinValues(array, separator = " | ") { + return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); + } + util4.joinValues = joinValues; + util4.jsonStringifyReplacer = (_3, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util3 || (exports.util = util3 = {})); + var objectUtil3; + (function(objectUtil4) { + objectUtil4.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; + })(objectUtil3 || (exports.objectUtil = objectUtil3 = {})); + exports.ZodParsedType = util3.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); + var getParsedType3 = (data) => { + const t6 = typeof data; + switch (t6) { + case "undefined": + return exports.ZodParsedType.undefined; + case "string": + return exports.ZodParsedType.string; + case "number": + return Number.isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; + case "boolean": + return exports.ZodParsedType.boolean; + case "function": + return exports.ZodParsedType.function; + case "bigint": + return exports.ZodParsedType.bigint; + case "symbol": + return exports.ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return exports.ZodParsedType.array; + } + if (data === null) { + return exports.ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return exports.ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return exports.ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return exports.ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return exports.ZodParsedType.date; + } + return exports.ZodParsedType.object; + default: + return exports.ZodParsedType.unknown; + } + }; + exports.getParsedType = getParsedType3; + } +}); + +// ../pi-mono/node_modules/zod/v3/ZodError.cjs +var require_ZodError = __commonJS({ + "../pi-mono/node_modules/zod/v3/ZodError.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; + var util_js_1 = require_util(); + exports.ZodIssueCode = util_js_1.util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + var quotelessJson2 = (obj) => { + const json2 = JSON.stringify(obj, null, 2); + return json2.replace(/"([^"]+)":/g, "$1:"); + }; + exports.quotelessJson = quotelessJson2; + var ZodError3 = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub2) => { + this.issues = [...this.issues, sub2]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i7 = 0; + while (i7 < issue.path.length) { + const el = issue.path[i7]; + const terminal = i7 === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i7++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util_js_1.util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = /* @__PURE__ */ Object.create(null); + const formErrors = []; + for (const sub2 of this.issues) { + if (sub2.path.length > 0) { + const firstEl = sub2.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub2)); + } else { + formErrors.push(mapper(sub2)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + }; + exports.ZodError = ZodError3; + ZodError3.create = (issues) => { + const error = new ZodError3(issues); + return error; + }; + } +}); + +// ../pi-mono/node_modules/zod/v3/locales/en.cjs +var require_en = __commonJS({ + "../pi-mono/node_modules/zod/v3/locales/en.cjs"(exports, module) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var ZodError_js_1 = require_ZodError(); + var util_js_1 = require_util(); + var errorMap3 = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodError_js_1.ZodIssueCode.invalid_type: + if (issue.received === util_js_1.ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodError_js_1.ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_js_1.util.jsonStringifyReplacer)}`; + break; + case ZodError_js_1.ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util_js_1.util.joinValues(issue.keys, ", ")}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util_js_1.util.joinValues(issue.options)}`; + break; + case ZodError_js_1.ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util_js_1.util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodError_js_1.ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodError_js_1.ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodError_js_1.ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodError_js_1.ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util_js_1.util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodError_js_1.ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodError_js_1.ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodError_js_1.ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodError_js_1.ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodError_js_1.ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util_js_1.util.assertNever(issue); + } + return { message }; + }; + exports.default = errorMap3; + module.exports = exports.default; + } +}); + +// ../pi-mono/node_modules/zod/v3/errors.cjs +var require_errors = __commonJS({ + "../pi-mono/node_modules/zod/v3/errors.cjs"(exports) { + "use strict"; + init_process_shim(); + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.defaultErrorMap = void 0; + exports.setErrorMap = setErrorMap2; + exports.getErrorMap = getErrorMap3; + var en_js_1 = __importDefault(require_en()); + exports.defaultErrorMap = en_js_1.default; + var overrideErrorMap3 = en_js_1.default; + function setErrorMap2(map3) { + overrideErrorMap3 = map3; + } + function getErrorMap3() { + return overrideErrorMap3; + } + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/parseUtil.cjs +var require_parseUtil = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/parseUtil.cjs"(exports) { + "use strict"; + init_process_shim(); + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.EMPTY_PATH = exports.makeIssue = void 0; + exports.addIssueToContext = addIssueToContext3; + var errors_js_1 = require_errors(); + var en_js_1 = __importDefault(require_en()); + var makeIssue3 = (params) => { + const { data, path: path6, errorMaps, issueData } = params; + const fullPath = [...path6, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m4) => !!m4).slice().reverse(); + for (const map3 of maps) { + errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; + }; + exports.makeIssue = makeIssue3; + exports.EMPTY_PATH = []; + function addIssueToContext3(ctx, issueData) { + const overrideMap = (0, errors_js_1.getErrorMap)(); + const issue = (0, exports.makeIssue)({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_js_1.default ? void 0 : en_js_1.default + // then global default map + ].filter((x2) => !!x2) + }); + ctx.common.issues.push(issue); + } + var ParseStatus3 = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s6 of results) { + if (s6.status === "aborted") + return exports.INVALID; + if (s6.status === "dirty") + status.dirty(); + arrayValue.push(s6.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return exports.INVALID; + if (value.status === "aborted") + return exports.INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + }; + exports.ParseStatus = ParseStatus3; + exports.INVALID = Object.freeze({ + status: "aborted" + }); + var DIRTY3 = (value) => ({ status: "dirty", value }); + exports.DIRTY = DIRTY3; + var OK3 = (value) => ({ status: "valid", value }); + exports.OK = OK3; + var isAborted3 = (x2) => x2.status === "aborted"; + exports.isAborted = isAborted3; + var isDirty3 = (x2) => x2.status === "dirty"; + exports.isDirty = isDirty3; + var isValid3 = (x2) => x2.status === "valid"; + exports.isValid = isValid3; + var isAsync3 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; + exports.isAsync = isAsync3; + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/typeAliases.cjs +var require_typeAliases = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/typeAliases.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/errorUtil.cjs +var require_errorUtil = __commonJS({ + "../pi-mono/node_modules/zod/v3/helpers/errorUtil.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.errorUtil = void 0; + var errorUtil3; + (function(errorUtil4) { + errorUtil4.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil4.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil3 || (exports.errorUtil = errorUtil3 = {})); + } +}); + +// ../pi-mono/node_modules/zod/v3/types.cjs +var require_types = __commonJS({ + "../pi-mono/node_modules/zod/v3/types.cjs"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; + exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0; + exports.datetimeRegex = datetimeRegex3; + exports.custom = custom2; + var ZodError_js_1 = require_ZodError(); + var errors_js_1 = require_errors(); + var errorUtil_js_1 = require_errorUtil(); + var parseUtil_js_1 = require_parseUtil(); + var util_js_1 = require_util(); + var ParseInputLazyPath3 = class { + constructor(parent, value, path6, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path6; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + }; + var handleResult3 = (ctx, result) => { + if ((0, parseUtil_js_1.isValid)(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError_js_1.ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } + }; + function processCreateParams3(params) { + if (!params) + return {}; + const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; + if (errorMap3 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap3) + return { errorMap: errorMap3, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; + } + var ZodType3 = class { + get description() { + return this._def.description; + } + _getType(input) { + return (0, util_js_1.getParsedType)(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new parseUtil_js_1.ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: (0, util_js_1.getParsedType)(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if ((0, parseUtil_js_1.isAsync)(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult3(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return (0, parseUtil_js_1.isValid)(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => (0, parseUtil_js_1.isValid)(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: (0, util_js_1.getParsedType)(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await ((0, parseUtil_js_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult3(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val2) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val2); + } else { + return message; + } + }; + return this._refinement((val2, ctx) => { + const result = check(val2); + const setError = () => ctx.addIssue({ + code: ZodError_js_1.ZodIssueCode.custom, + ...getIssueProperties(val2) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val2, ctx) => { + if (!check(val2)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects3({ + schema: this, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional3.create(this, this._def); + } + nullable() { + return ZodNullable3.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray3.create(this); + } + promise() { + return ZodPromise3.create(this, this._def); + } + or(option) { + return ZodUnion3.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection3.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects3({ + ...processCreateParams3(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault3({ + ...processCreateParams3(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind3.ZodDefault + }); + } + brand() { + return new ZodBranded3({ + typeName: ZodFirstPartyTypeKind3.ZodBranded, + type: this, + ...processCreateParams3(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch3({ + ...processCreateParams3(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind3.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline3.create(this, target); + } + readonly() { + return ZodReadonly3.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } + }; + exports.ZodType = ZodType3; + exports.Schema = ZodType3; + exports.ZodSchema = ZodType3; + var cuidRegex3 = /^c[^\s-]{8,}$/i; + var cuid2Regex3 = /^[0-9a-z]+$/; + var ulidRegex3 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + var uuidRegex3 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + var nanoidRegex3 = /^[a-z0-9_-]{21}$/i; + var jwtRegex3 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + var durationRegex3 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + var emailRegex3 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + var _emojiRegex3 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + var emojiRegex5; + var ipv4Regex3 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + var ipv4CidrRegex3 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + var ipv6Regex3 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + var ipv6CidrRegex3 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + var base64Regex3 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + var base64urlRegex3 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + var dateRegexSource3 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; + var dateRegex3 = new RegExp(`^${dateRegexSource3}$`); + function timeRegexSource3(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; + } + function timeRegex3(args) { + return new RegExp(`^${timeRegexSource3(args)}$`); + } + function datetimeRegex3(args) { + let regex = `${dateRegexSource3}T${timeRegexSource3(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); + } + function isValidIP3(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4Regex3.test(ip)) { + return true; + } + if ((version6 === "v6" || !version6) && ipv6Regex3.test(ip)) { + return true; + } + return false; + } + function isValidJWT3(jwt, alg) { + if (!jwtRegex3.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } + } + function isValidCidr3(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4CidrRegex3.test(ip)) { + return true; + } + if ((version6 === "v6" || !version6) && ipv6CidrRegex3.test(ip)) { + return true; + } + return false; + } + var ZodString3 = class _ZodString extends ZodType3 { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.string, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + const status = new parseUtil_js_1.ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "email", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex5) { + emojiRegex5 = new RegExp(_emojiRegex3, "u"); + } + if (!emojiRegex5.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "emoji", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "uuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "nanoid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cuid2", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ulid", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "regex", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex3(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex3; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex3(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "duration", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP3(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "ip", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT3(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "jwt", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr3(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "cidr", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex3.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + validation: "base64url", + code: ZodError_js_1.ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodError_js_1.ZodIssueCode.invalid_string, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil_js_1.errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil_js_1.errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil_js_1.errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil_js_1.errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil_js_1.errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil_js_1.errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil_js_1.errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + exports.ZodString = ZodString3; + ZodString3.create = (params) => { + return new ZodString3({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams3(params) + }); + }; + function floatSafeRemainder3(val2, step) { + const valDecCount = (val2.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; + } + var ZodNumber3 = class _ZodNumber extends ZodType3 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.number, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + let ctx = void 0; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util_js_1.util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder3(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util_js_1.util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + }; + exports.ZodNumber = ZodNumber3; + ZodNumber3.create = (params) => { + return new ZodNumber3({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams3(params) + }); + }; + var ZodBigInt3 = class _ZodBigInt extends ZodType3 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new parseUtil_js_1.ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.bigint, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil_js_1.errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil_js_1.errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil_js_1.errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + exports.ZodBigInt = ZodBigInt3; + ZodBigInt3.create = (params) => { + return new ZodBigInt3({ + checks: [], + typeName: ZodFirstPartyTypeKind3.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams3(params) + }); + }; + var ZodBoolean3 = class extends ZodType3 { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.boolean, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodBoolean = ZodBoolean3; + ZodBoolean3.create = (params) => { + return new ZodBoolean3({ + typeName: ZodFirstPartyTypeKind3.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams3(params) + }); + }; + var ZodDate3 = class _ZodDate extends ZodType3 { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.date, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_date + }); + return parseUtil_js_1.INVALID; + } + const status = new parseUtil_js_1.ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util_js_1.util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil_js_1.errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + }; + exports.ZodDate = ZodDate3; + ZodDate3.create = (params) => { + return new ZodDate3({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind3.ZodDate, + ...processCreateParams3(params) + }); + }; + var ZodSymbol3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.symbol, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodSymbol = ZodSymbol3; + ZodSymbol3.create = (params) => { + return new ZodSymbol3({ + typeName: ZodFirstPartyTypeKind3.ZodSymbol, + ...processCreateParams3(params) + }); + }; + var ZodUndefined3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.undefined, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodUndefined = ZodUndefined3; + ZodUndefined3.create = (params) => { + return new ZodUndefined3({ + typeName: ZodFirstPartyTypeKind3.ZodUndefined, + ...processCreateParams3(params) + }); + }; + var ZodNull3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.null, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodNull = ZodNull3; + ZodNull3.create = (params) => { + return new ZodNull3({ + typeName: ZodFirstPartyTypeKind3.ZodNull, + ...processCreateParams3(params) + }); + }; + var ZodAny3 = class extends ZodType3 { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodAny = ZodAny3; + ZodAny3.create = (params) => { + return new ZodAny3({ + typeName: ZodFirstPartyTypeKind3.ZodAny, + ...processCreateParams3(params) + }); + }; + var ZodUnknown3 = class extends ZodType3 { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodUnknown = ZodUnknown3; + ZodUnknown3.create = (params) => { + return new ZodUnknown3({ + typeName: ZodFirstPartyTypeKind3.ZodUnknown, + ...processCreateParams3(params) + }); + }; + var ZodNever3 = class extends ZodType3 { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.never, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + }; + exports.ZodNever = ZodNever3; + ZodNever3.create = (params) => { + return new ZodNever3({ + typeName: ZodFirstPartyTypeKind3.ZodNever, + ...processCreateParams3(params) + }); + }; + var ZodVoid3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.void, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + }; + exports.ZodVoid = ZodVoid3; + ZodVoid3.create = (params) => { + return new ZodVoid3({ + typeName: ZodFirstPartyTypeKind3.ZodVoid, + ...processCreateParams3(params) + }); + }; + var ZodArray3 = class _ZodArray extends ZodType3 { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: tooBig ? ZodError_js_1.ZodIssueCode.too_big : ZodError_js_1.ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i7) => { + return def.type._parseAsync(new ParseInputLazyPath3(ctx, item, ctx.path, i7)); + })).then((result2) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i7) => { + return def.type._parseSync(new ParseInputLazyPath3(ctx, item, ctx.path, i7)); + }); + return parseUtil_js_1.ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } + }; + exports.ZodArray = ZodArray3; + ZodArray3.create = (schema, params) => { + return new ZodArray3({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind3.ZodArray, + ...processCreateParams3(params) + }); + }; + function deepPartialify3(schema) { + if (schema instanceof ZodObject3) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional3.create(deepPartialify3(fieldSchema)); + } + return new ZodObject3({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray3) { + return new ZodArray3({ + ...schema._def, + type: deepPartialify3(schema.element) + }); + } else if (schema instanceof ZodOptional3) { + return ZodOptional3.create(deepPartialify3(schema.unwrap())); + } else if (schema instanceof ZodNullable3) { + return ZodNullable3.create(deepPartialify3(schema.unwrap())); + } else if (schema instanceof ZodTuple3) { + return ZodTuple3.create(schema.items.map((item) => deepPartialify3(item))); + } else { + return schema; + } + } + var ZodObject3 = class _ZodObject extends ZodType3 { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys2 = util_js_1.util.objectKeys(shape); + this._cached = { shape, keys: keys2 }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx2, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx2.parsedType + }); + return parseUtil_js_1.INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever3 && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath3(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever3) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath3(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil_js_1.errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil_js_1.errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind3.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index2) { + return new _ZodObject({ + ...this._def, + catchall: index2 + }); + } + pick(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify3(this); + } + partial(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util_js_1.util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional3) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum3(util_js_1.util.objectKeys(this.shape)); + } + }; + exports.ZodObject = ZodObject3; + ZodObject3.create = (shape, params) => { + return new ZodObject3({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever3.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams3(params) + }); + }; + ZodObject3.strictCreate = (shape, params) => { + return new ZodObject3({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever3.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams3(params) + }); + }; + ZodObject3.lazycreate = (shape, params) => { + return new ZodObject3({ + shape, + unknownKeys: "strip", + catchall: ZodNever3.create(), + typeName: ZodFirstPartyTypeKind3.ZodObject, + ...processCreateParams3(params) + }); + }; + var ZodUnion3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError_js_1.ZodError(result.ctx.common.issues)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors + }); + return parseUtil_js_1.INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError_js_1.ZodError(issues2)); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union, + unionErrors + }); + return parseUtil_js_1.INVALID; + } + } + get options() { + return this._def.options; + } + }; + exports.ZodUnion = ZodUnion3; + ZodUnion3.create = (types2, params) => { + return new ZodUnion3({ + options: types2, + typeName: ZodFirstPartyTypeKind3.ZodUnion, + ...processCreateParams3(params) + }); + }; + var getDiscriminator3 = (type) => { + if (type instanceof ZodLazy3) { + return getDiscriminator3(type.schema); + } else if (type instanceof ZodEffects3) { + return getDiscriminator3(type.innerType()); + } else if (type instanceof ZodLiteral3) { + return [type.value]; + } else if (type instanceof ZodEnum3) { + return type.options; + } else if (type instanceof ZodNativeEnum3) { + return util_js_1.util.objectValues(type.enum); + } else if (type instanceof ZodDefault3) { + return getDiscriminator3(type._def.innerType); + } else if (type instanceof ZodUndefined3) { + return [void 0]; + } else if (type instanceof ZodNull3) { + return [null]; + } else if (type instanceof ZodOptional3) { + return [void 0, ...getDiscriminator3(type.unwrap())]; + } else if (type instanceof ZodNullable3) { + return [null, ...getDiscriminator3(type.unwrap())]; + } else if (type instanceof ZodBranded3) { + return getDiscriminator3(type.unwrap()); + } else if (type instanceof ZodReadonly3) { + return getDiscriminator3(type.unwrap()); + } else if (type instanceof ZodCatch3) { + return getDiscriminator3(type._def.innerType); + } else { + return []; + } + }; + var ZodDiscriminatedUnion3 = class _ZodDiscriminatedUnion extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return parseUtil_js_1.INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator3(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind3.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams3(params) + }); + } + }; + exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion3; + function mergeValues3(a3, b4) { + const aType = (0, util_js_1.getParsedType)(a3); + const bType = (0, util_js_1.getParsedType)(b4); + if (a3 === b4) { + return { valid: true, data: a3 }; + } else if (aType === util_js_1.ZodParsedType.object && bType === util_js_1.ZodParsedType.object) { + const bKeys = util_js_1.util.objectKeys(b4); + const sharedKeys = util_js_1.util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a3, ...b4 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues3(a3[key], b4[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === util_js_1.ZodParsedType.array && bType === util_js_1.ZodParsedType.array) { + if (a3.length !== b4.length) { + return { valid: false }; + } + const newArray = []; + for (let index2 = 0; index2 < a3.length; index2++) { + const itemA = a3[index2]; + const itemB = b4[index2]; + const sharedValue = mergeValues3(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === util_js_1.ZodParsedType.date && bType === util_js_1.ZodParsedType.date && +a3 === +b4) { + return { valid: true, data: a3 }; + } else { + return { valid: false }; + } + } + var ZodIntersection3 = class extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if ((0, parseUtil_js_1.isAborted)(parsedLeft) || (0, parseUtil_js_1.isAborted)(parsedRight)) { + return parseUtil_js_1.INVALID; + } + const merged = mergeValues3(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_intersection_types + }); + return parseUtil_js_1.INVALID; + } + if ((0, parseUtil_js_1.isDirty)(parsedLeft) || (0, parseUtil_js_1.isDirty)(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } + }; + exports.ZodIntersection = ZodIntersection3; + ZodIntersection3.create = (left, right, params) => { + return new ZodIntersection3({ + left, + right, + typeName: ZodFirstPartyTypeKind3.ZodIntersection, + ...processCreateParams3(params) + }); + }; + var ZodTuple3 = class _ZodTuple extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.array) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.array, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + if (ctx.data.length < this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return parseUtil_js_1.INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath3(ctx, item, ctx.path, itemIndex)); + }).filter((x2) => !!x2); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return parseUtil_js_1.ParseStatus.mergeArray(status, results); + }); + } else { + return parseUtil_js_1.ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } + }; + exports.ZodTuple = ZodTuple3; + ZodTuple3.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple3({ + items: schemas, + typeName: ZodFirstPartyTypeKind3.ZodTuple, + rest: null, + ...processCreateParams3(params) + }); + }; + var ZodRecord3 = class _ZodRecord extends ZodType3 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.object) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.object, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath3(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return parseUtil_js_1.ParseStatus.mergeObjectAsync(status, pairs); + } else { + return parseUtil_js_1.ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType3) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind3.ZodRecord, + ...processCreateParams3(third) + }); + } + return new _ZodRecord({ + keyType: ZodString3.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind3.ZodRecord, + ...processCreateParams3(second) + }); + } + }; + exports.ZodRecord = ZodRecord3; + var ZodMap3 = class extends ZodType3 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.map) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.map, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath3(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath3(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return parseUtil_js_1.INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + }; + exports.ZodMap = ZodMap3; + ZodMap3.create = (keyType, valueType, params) => { + return new ZodMap3({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind3.ZodMap, + ...processCreateParams3(params) + }); + }; + var ZodSet3 = class _ZodSet extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.set) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.set, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements3) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements3) { + if (element.status === "aborted") + return parseUtil_js_1.INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements2 = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath3(ctx, item, ctx.path, i7))); + if (ctx.common.async) { + return Promise.all(elements2).then((elements3) => finalizeSet(elements3)); + } else { + return finalizeSet(elements2); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil_js_1.errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + }; + exports.ZodSet = ZodSet3; + ZodSet3.create = (valueType, params) => { + return new ZodSet3({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind3.ZodSet, + ...processCreateParams3(params) + }); + }; + var ZodFunction3 = class _ZodFunction extends ZodType3 { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.function) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.function, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + function makeArgsIssue(args, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x2) => !!x2), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return (0, parseUtil_js_1.makeIssue)({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_js_1.getErrorMap)(), errors_js_1.defaultErrorMap].filter((x2) => !!x2), + issueData: { + code: ZodError_js_1.ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise3) { + const me = this; + return (0, parseUtil_js_1.OK)(async function(...args) { + const error = new ZodError_js_1.ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e9) => { + error.addIssue(makeArgsIssue(args, e9)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => { + error.addIssue(makeReturnsIssue(result, e9)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return (0, parseUtil_js_1.OK)(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError_js_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError_js_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple3.create(items).rest(ZodUnknown3.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple3.create([]).rest(ZodUnknown3.create()), + returns: returns || ZodUnknown3.create(), + typeName: ZodFirstPartyTypeKind3.ZodFunction, + ...processCreateParams3(params) + }); + } + }; + exports.ZodFunction = ZodFunction3; + var ZodLazy3 = class extends ZodType3 { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + exports.ZodLazy = ZodLazy3; + ZodLazy3.create = (getter, params) => { + return new ZodLazy3({ + getter, + typeName: ZodFirstPartyTypeKind3.ZodLazy, + ...processCreateParams3(params) + }); + }; + var ZodLiteral3 = class extends ZodType3 { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return parseUtil_js_1.INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + }; + exports.ZodLiteral = ZodLiteral3; + ZodLiteral3.create = (value, params) => { + return new ZodLiteral3({ + value, + typeName: ZodFirstPartyTypeKind3.ZodLiteral, + ...processCreateParams3(params) + }); + }; + function createZodEnum3(values2, params) { + return new ZodEnum3({ + values: values2, + typeName: ZodFirstPartyTypeKind3.ZodEnum, + ...processCreateParams3(params) + }); + } + var ZodEnum3 = class _ZodEnum extends ZodType3 { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + extract(values2, newDef = this._def) { + return _ZodEnum.create(values2, { + ...this._def, + ...newDef + }); + } + exclude(values2, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), { + ...this._def, + ...newDef + }); + } + }; + exports.ZodEnum = ZodEnum3; + ZodEnum3.create = createZodEnum3; + var ZodNativeEnum3 = class extends ZodType3 { + _parse(input) { + const nativeEnumValues = util_js_1.util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.string && ctx.parsedType !== util_js_1.ZodParsedType.number) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + expected: util_js_1.util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodError_js_1.ZodIssueCode.invalid_type + }); + return parseUtil_js_1.INVALID; + } + if (!this._cache) { + this._cache = new Set(util_js_1.util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util_js_1.util.objectValues(nativeEnumValues); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + received: ctx.data, + code: ZodError_js_1.ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return parseUtil_js_1.INVALID; + } + return (0, parseUtil_js_1.OK)(input.data); + } + get enum() { + return this._def.values; + } + }; + exports.ZodNativeEnum = ZodNativeEnum3; + ZodNativeEnum3.create = (values2, params) => { + return new ZodNativeEnum3({ + values: values2, + typeName: ZodFirstPartyTypeKind3.ZodNativeEnum, + ...processCreateParams3(params) + }); + }; + var ZodPromise3 = class extends ZodType3 { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== util_js_1.ZodParsedType.promise && ctx.common.async === false) { + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.promise, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + const promisified = ctx.parsedType === util_js_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return (0, parseUtil_js_1.OK)(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } + }; + exports.ZodPromise = ZodPromise3; + ZodPromise3.create = (schema, params) => { + return new ZodPromise3({ + type: schema, + typeName: ZodFirstPartyTypeKind3.ZodPromise, + ...processCreateParams3(params) + }); + }; + var ZodEffects3 = class extends ZodType3 { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind3.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + (0, parseUtil_js_1.addIssueToContext)(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return parseUtil_js_1.INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return parseUtil_js_1.INVALID; + if (result.status === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + if (status.value === "dirty") + return (0, parseUtil_js_1.DIRTY)(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner2 = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner2.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner2.status === "dirty") + status.dirty(); + executeRefinement(inner2.value); + return { status: status.value, value: inner2.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => { + if (inner2.status === "aborted") + return parseUtil_js_1.INVALID; + if (inner2.status === "dirty") + status.dirty(); + return executeRefinement(inner2.value).then(() => { + return { status: status.value, value: inner2.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!(0, parseUtil_js_1.isValid)(base)) + return parseUtil_js_1.INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util_js_1.util.assertNever(effect); + } + }; + exports.ZodEffects = ZodEffects3; + exports.ZodTransformer = ZodEffects3; + ZodEffects3.create = (schema, effect, params) => { + return new ZodEffects3({ + schema, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + effect, + ...processCreateParams3(params) + }); + }; + ZodEffects3.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects3({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind3.ZodEffects, + ...processCreateParams3(params) + }); + }; + var ZodOptional3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.undefined) { + return (0, parseUtil_js_1.OK)(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + exports.ZodOptional = ZodOptional3; + ZodOptional3.create = (type, params) => { + return new ZodOptional3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodOptional, + ...processCreateParams3(params) + }); + }; + var ZodNullable3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === util_js_1.ZodParsedType.null) { + return (0, parseUtil_js_1.OK)(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + exports.ZodNullable = ZodNullable3; + ZodNullable3.create = (type, params) => { + return new ZodNullable3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodNullable, + ...processCreateParams3(params) + }); + }; + var ZodDefault3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === util_js_1.ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } + }; + exports.ZodDefault = ZodDefault3; + ZodDefault3.create = (type, params) => { + return new ZodDefault3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams3(params) + }); + }; + var ZodCatch3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if ((0, parseUtil_js_1.isAsync)(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError_js_1.ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } + }; + exports.ZodCatch = ZodCatch3; + ZodCatch3.create = (type, params) => { + return new ZodCatch3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams3(params) + }); + }; + var ZodNaN3 = class extends ZodType3 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== util_js_1.ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + (0, parseUtil_js_1.addIssueToContext)(ctx, { + code: ZodError_js_1.ZodIssueCode.invalid_type, + expected: util_js_1.ZodParsedType.nan, + received: ctx.parsedType + }); + return parseUtil_js_1.INVALID; + } + return { status: "valid", value: input.data }; + } + }; + exports.ZodNaN = ZodNaN3; + ZodNaN3.create = (params) => { + return new ZodNaN3({ + typeName: ZodFirstPartyTypeKind3.ZodNaN, + ...processCreateParams3(params) + }); + }; + exports.BRAND = Symbol("zod_brand"); + var ZodBranded3 = class extends ZodType3 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } + }; + exports.ZodBranded = ZodBranded3; + var ZodPipeline3 = class _ZodPipeline extends ZodType3 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return (0, parseUtil_js_1.DIRTY)(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return parseUtil_js_1.INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a3, b4) { + return new _ZodPipeline({ + in: a3, + out: b4, + typeName: ZodFirstPartyTypeKind3.ZodPipeline + }); + } + }; + exports.ZodPipeline = ZodPipeline3; + var ZodReadonly3 = class extends ZodType3 { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze2 = (data) => { + if ((0, parseUtil_js_1.isValid)(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return (0, parseUtil_js_1.isAsync)(result) ? result.then((data) => freeze2(data)) : freeze2(result); + } + unwrap() { + return this._def.innerType; + } + }; + exports.ZodReadonly = ZodReadonly3; + ZodReadonly3.create = (type, params) => { + return new ZodReadonly3({ + innerType: type, + typeName: ZodFirstPartyTypeKind3.ZodReadonly, + ...processCreateParams3(params) + }); + }; + function cleanParams2(params, data) { + const p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p22 = typeof p4 === "string" ? { message: p4 } : p4; + return p22; + } + function custom2(check, _params = {}, fatal) { + if (check) + return ZodAny3.create().superRefine((data, ctx) => { + const r8 = check(data); + if (r8 instanceof Promise) { + return r8.then((r9) => { + if (!r9) { + const params = cleanParams2(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r8) { + const params = cleanParams2(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny3.create(); + } + exports.late = { + object: ZodObject3.lazycreate + }; + var ZodFirstPartyTypeKind3; + (function(ZodFirstPartyTypeKind4) { + ZodFirstPartyTypeKind4["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind4["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind4["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind4["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind4["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind4["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind4["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind4["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind4["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind4["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind4["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind4["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind4["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind4["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind4["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind4["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind4["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind4["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind4["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind4["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind4["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind4["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind4["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind4["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind4["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind4["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind4["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind4["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind4["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind4["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind4["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind4["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind4["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind4["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind4["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind4["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind3 || (exports.ZodFirstPartyTypeKind = ZodFirstPartyTypeKind3 = {})); + var instanceOfType2 = (cls, params = { + message: `Input not instance of ${cls.name}` + }) => custom2((data) => data instanceof cls, params); + exports.instanceof = instanceOfType2; + var stringType3 = ZodString3.create; + exports.string = stringType3; + var numberType3 = ZodNumber3.create; + exports.number = numberType3; + var nanType3 = ZodNaN3.create; + exports.nan = nanType3; + var bigIntType3 = ZodBigInt3.create; + exports.bigint = bigIntType3; + var booleanType3 = ZodBoolean3.create; + exports.boolean = booleanType3; + var dateType3 = ZodDate3.create; + exports.date = dateType3; + var symbolType3 = ZodSymbol3.create; + exports.symbol = symbolType3; + var undefinedType3 = ZodUndefined3.create; + exports.undefined = undefinedType3; + var nullType3 = ZodNull3.create; + exports.null = nullType3; + var anyType3 = ZodAny3.create; + exports.any = anyType3; + var unknownType3 = ZodUnknown3.create; + exports.unknown = unknownType3; + var neverType3 = ZodNever3.create; + exports.never = neverType3; + var voidType3 = ZodVoid3.create; + exports.void = voidType3; + var arrayType3 = ZodArray3.create; + exports.array = arrayType3; + var objectType3 = ZodObject3.create; + exports.object = objectType3; + var strictObjectType3 = ZodObject3.strictCreate; + exports.strictObject = strictObjectType3; + var unionType3 = ZodUnion3.create; + exports.union = unionType3; + var discriminatedUnionType3 = ZodDiscriminatedUnion3.create; + exports.discriminatedUnion = discriminatedUnionType3; + var intersectionType3 = ZodIntersection3.create; + exports.intersection = intersectionType3; + var tupleType3 = ZodTuple3.create; + exports.tuple = tupleType3; + var recordType3 = ZodRecord3.create; + exports.record = recordType3; + var mapType3 = ZodMap3.create; + exports.map = mapType3; + var setType3 = ZodSet3.create; + exports.set = setType3; + var functionType3 = ZodFunction3.create; + exports.function = functionType3; + var lazyType3 = ZodLazy3.create; + exports.lazy = lazyType3; + var literalType3 = ZodLiteral3.create; + exports.literal = literalType3; + var enumType3 = ZodEnum3.create; + exports.enum = enumType3; + var nativeEnumType3 = ZodNativeEnum3.create; + exports.nativeEnum = nativeEnumType3; + var promiseType3 = ZodPromise3.create; + exports.promise = promiseType3; + var effectsType3 = ZodEffects3.create; + exports.effect = effectsType3; + exports.transformer = effectsType3; + var optionalType3 = ZodOptional3.create; + exports.optional = optionalType3; + var nullableType3 = ZodNullable3.create; + exports.nullable = nullableType3; + var preprocessType3 = ZodEffects3.createWithPreprocess; + exports.preprocess = preprocessType3; + var pipelineType3 = ZodPipeline3.create; + exports.pipeline = pipelineType3; + var ostring2 = () => stringType3().optional(); + exports.ostring = ostring2; + var onumber2 = () => numberType3().optional(); + exports.onumber = onumber2; + var oboolean2 = () => booleanType3().optional(); + exports.oboolean = oboolean2; + exports.coerce = { + string: ((arg) => ZodString3.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber3.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean3.create({ + ...arg, + coerce: true + })), + bigint: ((arg) => ZodBigInt3.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate3.create({ ...arg, coerce: true })) + }; + exports.NEVER = parseUtil_js_1.INVALID; + } +}); + +// ../pi-mono/node_modules/zod/v3/external.cjs +var require_external = __commonJS({ + "../pi-mono/node_modules/zod/v3/external.cjs"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_errors(), exports); + __exportStar(require_parseUtil(), exports); + __exportStar(require_typeAliases(), exports); + __exportStar(require_util(), exports); + __exportStar(require_types(), exports); + __exportStar(require_ZodError(), exports); + } +}); + +// ../pi-mono/node_modules/zod/v3/index.cjs +var require_v3 = __commonJS({ + "../pi-mono/node_modules/zod/v3/index.cjs"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 in mod) if (k2 !== "default" && Object.prototype.hasOwnProperty.call(mod, k2)) __createBinding(result, mod, k2); + } + __setModuleDefault(result, mod); + return result; + }; + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.z = void 0; + var z3 = __importStar(require_external()); + exports.z = z3; + __exportStar(require_external(), exports); + exports.default = z3; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/base64.js +var require_base64 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/base64.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.zodInbound = exports.zodOutbound = void 0; + exports.bytesToBase64 = bytesToBase64; + exports.bytesFromBase64 = bytesFromBase64; + exports.stringToBytes = stringToBytes2; + exports.stringFromBytes = stringFromBytes; + exports.stringToBase64 = stringToBase64; + exports.stringFromBase64 = stringFromBase64; + var z3 = __importStar(require_v3()); + function bytesToBase64(u8arr) { + return btoa(String.fromCodePoint(...u8arr)); + } + function bytesFromBase64(encoded) { + return Uint8Array.from(atob(encoded), (c6) => c6.charCodeAt(0)); + } + function stringToBytes2(str2) { + return new TextEncoder().encode(str2); + } + function stringFromBytes(u8arr) { + return new TextDecoder().decode(u8arr); + } + function stringToBase64(str2) { + return bytesToBase64(stringToBytes2(str2)); + } + function stringFromBase64(b64str) { + return stringFromBytes(bytesFromBase64(b64str)); + } + exports.zodOutbound = z3.instanceof(Uint8Array).or(z3.string().transform(stringToBytes2)); + exports.zodInbound = z3.instanceof(Uint8Array).or(z3.string().transform(bytesFromBase64)); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/is-plain-object.js +var require_is_plain_object = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/is-plain-object.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isPlainObject = isPlainObject2; + function isPlainObject2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/encodings.js +var require_encodings = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/encodings.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.encodeDeepObjectQuery = exports.encodePipeDelimitedQuery = exports.encodeSpaceDelimitedQuery = exports.encodeFormQuery = exports.encodeJSONQuery = exports.encodeSimple = exports.encodePipeDelimited = exports.encodeSpaceDelimited = exports.encodeForm = exports.EncodingError = void 0; + exports.encodeMatrix = encodeMatrix; + exports.encodeLabel = encodeLabel; + exports.encodeBodyForm = encodeBodyForm; + exports.encodeDeepObject = encodeDeepObject; + exports.encodeDeepObjectObject = encodeDeepObjectObject; + exports.encodeJSON = encodeJSON; + exports.queryJoin = queryJoin; + exports.queryEncoder = queryEncoder; + exports.appendForm = appendForm; + var base64_js_1 = require_base64(); + var is_plain_object_js_1 = require_is_plain_object(); + var EncodingError = class extends Error { + constructor(message) { + super(message); + this.name = "EncodingError"; + } + }; + exports.EncodingError = EncodingError; + function encodeMatrix(key, value, options) { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue = null; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(","); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `,${encodeString(k2)},${encodeValue(v4)}`; + }); + encValue = mapped?.join("").slice(1); + } else { + encValue = `${encodeValue(pv)}`; + } + if (encValue == null) { + return; + } + const keyPrefix = encodeString(pk); + tmp = `${keyPrefix}=${encValue}`; + if (tmp === `${keyPrefix}=`) { + tmp = tmp.slice(0, -1); + } + if (!tmp) { + return; + } + out += `;${tmp}`; + }); + return out; + } + function encodeLabel(key, value, options) { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let encValue = ""; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join("."); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `.${encodeString(k2)}.${encodeValue(v4)}`; + }); + encValue = mapped?.join("").slice(1); + } else { + const k2 = options?.explode && (0, is_plain_object_js_1.isPlainObject)(value) ? `${encodeString(pk)}=` : ""; + encValue = `${k2}${encodeValue(pv)}`; + } + out += encValue == null ? "" : `.${encValue}`; + }); + return out; + } + function formEncoder(sep2) { + return (key, value, options) => { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + const encodedSep = encodeString(sep2); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue = null; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(encodedSep); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + encValue = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `${encodeString(k2)}${encodedSep}${encodeValue(v4)}`; + })?.join(encodedSep); + } else { + encValue = `${encodeValue(pv)}`; + } + if (encValue == null) { + return; + } + tmp = `${encodeString(pk)}=${encValue}`; + if (!tmp || tmp === "=") { + return; + } + out += `&${tmp}`; + }); + return out.slice(1); + }; + } + exports.encodeForm = formEncoder(","); + exports.encodeSpaceDelimited = formEncoder(" "); + exports.encodePipeDelimited = formEncoder("|"); + function encodeBodyForm(key, value, options) { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + let encValue = ""; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + encValue = JSON.stringify(pv, jsonReplacer); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + encValue = JSON.stringify(pv, jsonReplacer); + } else { + encValue = `${encodeValue(pv)}`; + } + tmp = `${encodeString(pk)}=${encValue}`; + if (!tmp || tmp === "=") { + return; + } + out += `&${tmp}`; + }); + return out.slice(1); + } + function encodeDeepObject(key, value, options) { + if (value == null) { + return; + } + if (!(0, is_plain_object_js_1.isPlainObject)(value)) { + throw new EncodingError(`Value of parameter '${key}' which uses deepObject encoding must be an object or null`); + } + return encodeDeepObjectObject(key, value, options); + } + function encodeDeepObjectObject(key, value, options) { + if (value == null) { + return; + } + let out = ""; + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + if (!(0, is_plain_object_js_1.isPlainObject)(value)) { + throw new EncodingError(`Expected parameter '${key}' to be an object.`); + } + Object.entries(value).forEach(([ck, cv]) => { + if (cv == null) { + return; + } + const pk = `${key}[${ck}]`; + if ((0, is_plain_object_js_1.isPlainObject)(cv)) { + const objOut = encodeDeepObjectObject(pk, cv, options); + out += objOut == null ? "" : `&${objOut}`; + return; + } + const pairs = Array.isArray(cv) ? cv : [cv]; + const encoded = mapDefined(pairs, (v4) => { + return `${encodeString(pk)}=${encodeString(serializeValue(v4))}`; + })?.join("&"); + out += encoded == null ? "" : `&${encoded}`; + }); + return out.slice(1); + } + function encodeJSON(key, value, options) { + if (typeof value === "undefined") { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encVal = encodeString(JSON.stringify(value, jsonReplacer)); + return options?.explode ? encVal : `${encodeString(key)}=${encVal}`; + } + var encodeSimple = (key, value, options) => { + let out = ""; + const pairs = options?.explode ? explode(key, value) : [[key, value]]; + if (pairs.every(([_3, v4]) => v4 == null)) { + return; + } + const encodeString = (v4) => { + return options?.charEncoding === "percent" ? encodeURIComponent(v4) : v4; + }; + const encodeValue = (v4) => encodeString(serializeValue(v4)); + pairs.forEach(([pk, pv]) => { + let tmp = ""; + if (pv == null) { + return; + } else if (Array.isArray(pv)) { + tmp = mapDefined(pv, (v4) => `${encodeValue(v4)}`)?.join(","); + } else if ((0, is_plain_object_js_1.isPlainObject)(pv)) { + const mapped = mapDefinedEntries(Object.entries(pv), ([k2, v4]) => { + return `,${encodeString(k2)},${encodeValue(v4)}`; + }); + tmp = mapped?.join("").slice(1); + } else { + const k2 = options?.explode && (0, is_plain_object_js_1.isPlainObject)(value) ? `${pk}=` : ""; + tmp = `${k2}${encodeValue(pv)}`; + } + out += tmp ? `,${tmp}` : ""; + }); + return out.slice(1); + }; + exports.encodeSimple = encodeSimple; + function explode(key, value) { + if (Array.isArray(value)) { + return value.map((v4) => [key, v4]); + } else if ((0, is_plain_object_js_1.isPlainObject)(value)) { + const o9 = value ?? {}; + return Object.entries(o9).map(([k2, v4]) => [k2, v4]); + } else { + return [[key, value]]; + } + } + function serializeValue(value) { + if (value == null) { + return ""; + } else if (value instanceof Date) { + return value.toISOString(); + } else if (value instanceof Uint8Array) { + return (0, base64_js_1.bytesToBase64)(value); + } else if (typeof value === "object") { + return JSON.stringify(value, jsonReplacer); + } + return `${value}`; + } + function jsonReplacer(_3, value) { + if (value instanceof Uint8Array) { + return (0, base64_js_1.bytesToBase64)(value); + } else { + return value; + } + } + function mapDefined(inp, mapper) { + const res = inp.reduce((acc, v4) => { + if (v4 == null) { + return acc; + } + const m4 = mapper(v4); + if (m4 == null) { + return acc; + } + acc.push(m4); + return acc; + }, []); + return res.length ? res : null; + } + function mapDefinedEntries(inp, mapper) { + const acc = []; + for (const [k2, v4] of inp) { + if (v4 == null) { + continue; + } + const m4 = mapper([k2, v4]); + if (m4 == null) { + continue; + } + acc.push(m4); + } + return acc.length ? acc : null; + } + function queryJoin(...args) { + return args.filter(Boolean).join("&"); + } + function queryEncoder(f4) { + const bulkEncode = function(values2, options) { + const opts = { + ...options, + explode: options?.explode ?? true, + charEncoding: options?.charEncoding ?? "percent" + }; + const allowEmptySet = new Set(options?.allowEmptyValue ?? []); + const encoded = Object.entries(values2).map(([key, value]) => { + if (allowEmptySet.has(key)) { + if (value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0) { + return `${encodeURIComponent(key)}=`; + } + } + return f4(key, value, opts); + }); + return queryJoin(...encoded); + }; + return bulkEncode; + } + exports.encodeJSONQuery = queryEncoder(encodeJSON); + exports.encodeFormQuery = queryEncoder(exports.encodeForm); + exports.encodeSpaceDelimitedQuery = queryEncoder(exports.encodeSpaceDelimited); + exports.encodePipeDelimitedQuery = queryEncoder(exports.encodePipeDelimited); + exports.encodeDeepObjectQuery = queryEncoder(encodeDeepObject); + function appendForm(fd, key, value, fileName) { + if (value == null) { + return; + } else if (value instanceof Blob && fileName) { + fd.append(key, value, fileName); + } else if (value instanceof Blob) { + fd.append(key, value); + } else { + fd.append(key, String(value)); + } + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/dlv.js +var require_dlv = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/dlv.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dlv = dlv; + function dlv(obj, key, def, p4, undef) { + key = Array.isArray(key) ? key : key.split("."); + for (p4 = 0; p4 < key.length; p4++) { + const k2 = key[p4]; + obj = k2 != null && obj ? obj[k2] : undef; + } + return obj === undef ? def : obj; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/env.js +var require_env = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/env.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.envSchema = void 0; + exports.env = env; + exports.resetEnv = resetEnv; + var z3 = __importStar(require_v3()); + var dlv_js_1 = require_dlv(); + exports.envSchema = z3.object({ + MISTRAL_API_KEY: z3.string().optional(), + MISTRAL_DEBUG: z3.coerce.boolean().optional() + }); + function isDeno() { + if ("Deno" in globalThis) { + return true; + } + return false; + } + var envMemo = void 0; + function env() { + if (envMemo) { + return envMemo; + } + let envObject = {}; + if (isDeno()) { + envObject = globalThis.Deno?.env?.toObject?.() ?? {}; + } else { + envObject = (0, dlv_js_1.dlv)(globalThis, "process.env") ?? {}; + } + envMemo = exports.envSchema.parse(envObject); + return envMemo; + } + function resetEnv() { + envMemo = void 0; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/retries.js +var require_retries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/retries.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TemporaryError = exports.PermanentError = void 0; + exports.retry = retry; + var http_js_1 = require_http(); + var defaultBackoff = { + initialInterval: 500, + maxInterval: 6e4, + exponent: 1.5, + maxElapsedTime: 36e5 + }; + var PermanentError = class _PermanentError extends Error { + constructor(message, options) { + let msg = message; + if (options?.cause) { + msg += `: ${options.cause}`; + } + super(msg, options); + this.name = "PermanentError"; + if (typeof this.cause === "undefined") { + this.cause = options?.cause; + } + Object.setPrototypeOf(this, _PermanentError.prototype); + } + }; + exports.PermanentError = PermanentError; + var TemporaryError = class _TemporaryError extends Error { + constructor(message, response) { + super(message); + this.response = response; + this.name = "TemporaryError"; + Object.setPrototypeOf(this, _TemporaryError.prototype); + } + }; + exports.TemporaryError = TemporaryError; + async function retry(fetchFn, options) { + switch (options.config.strategy) { + case "backoff": + return retryBackoff(wrapFetcher(fetchFn, { + statusCodes: options.statusCodes, + retryConnectionErrors: !!options.config.retryConnectionErrors + }), options.config.backoff ?? defaultBackoff); + default: + return await fetchFn(); + } + } + function wrapFetcher(fn, options) { + return async () => { + try { + const res = await fn(); + if (isRetryableResponse(res, options.statusCodes)) { + throw new TemporaryError("Response failed with retryable status code", res); + } + return res; + } catch (err) { + if (err instanceof TemporaryError) { + throw err; + } + if (options.retryConnectionErrors && ((0, http_js_1.isTimeoutError)(err) || (0, http_js_1.isConnectionError)(err))) { + throw err; + } + throw new PermanentError("Permanent error", { cause: err }); + } + }; + } + var codeRangeRE = new RegExp("^[0-9]xx$", "i"); + function isRetryableResponse(res, statusCodes) { + const actual = `${res.status}`; + return statusCodes.some((code) => { + if (!codeRangeRE.test(code)) { + return code === actual; + } + const expectFamily = code.charAt(0); + if (!expectFamily) { + throw new Error("Invalid status code range"); + } + const actualFamily = actual.charAt(0); + if (!actualFamily) { + throw new Error(`Invalid response status code: ${actual}`); + } + return actualFamily === expectFamily; + }); + } + async function retryBackoff(fn, strategy) { + const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy; + const start = Date.now(); + let x2 = 0; + while (true) { + try { + const res = await fn(); + return res; + } catch (err) { + if (err instanceof PermanentError) { + throw err.cause; + } + const elapsed = Date.now() - start; + if (elapsed > maxElapsedTime) { + if (err instanceof TemporaryError) { + return err.response; + } + throw err; + } + let retryInterval = 0; + if (err instanceof TemporaryError) { + retryInterval = retryIntervalFromResponse(err.response); + } + if (retryInterval <= 0) { + retryInterval = initialInterval * Math.pow(x2, exponent) + Math.random() * 1e3; + } + const d4 = Math.min(retryInterval, maxInterval); + await delay(d4); + x2++; + } + } + } + function retryIntervalFromResponse(res) { + const retryVal = res.headers.get("retry-after") || ""; + if (!retryVal) { + return 0; + } + const parsedNumber = Number(retryVal); + if (Number.isInteger(parsedNumber)) { + return parsedNumber * 1e3; + } + const parsedDate = Date.parse(retryVal); + if (Number.isInteger(parsedDate)) { + const deltaMS = parsedDate - Date.now(); + return deltaMS > 0 ? Math.ceil(deltaMS) : 0; + } + return 0; + } + async function delay(delay2) { + return new Promise((resolve2) => setTimeout(resolve2, delay2)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/sdks.js +var require_sdks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/sdks.js"(exports) { + "use strict"; + init_process_shim(); + var __classPrivateFieldSet3 = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f4) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; + }; + var __classPrivateFieldGet3 = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f4) { + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); + }; + var _ClientSDK_httpClient; + var _ClientSDK_hooks; + var _ClientSDK_logger; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClientSDK = void 0; + var hooks_js_1 = require_hooks(); + var httpclienterrors_js_1 = require_httpclienterrors(); + var fp_js_1 = require_fp(); + var base64_js_1 = require_base64(); + var config_js_1 = require_config(); + var encodings_js_1 = require_encodings(); + var env_js_1 = require_env(); + var http_js_1 = require_http(); + var retries_js_1 = require_retries(); + var gt = typeof globalThis === "undefined" ? null : globalThis; + var webWorkerLike = typeof gt === "object" && gt != null && "importScripts" in gt && typeof gt["importScripts"] === "function"; + var isBrowserLike = webWorkerLike || typeof navigator !== "undefined" && "serviceWorker" in navigator || typeof window === "object" && typeof window.document !== "undefined"; + var ClientSDK = class { + constructor(options = {}) { + _ClientSDK_httpClient.set(this, void 0); + _ClientSDK_hooks.set(this, void 0); + _ClientSDK_logger.set(this, void 0); + const opt = options; + if (typeof opt === "object" && opt != null && "hooks" in opt && opt.hooks instanceof hooks_js_1.SDKHooks) { + __classPrivateFieldSet3(this, _ClientSDK_hooks, opt.hooks, "f"); + } else { + __classPrivateFieldSet3(this, _ClientSDK_hooks, new hooks_js_1.SDKHooks(), "f"); + } + const url = (0, config_js_1.serverURLFromOptions)(options); + if (url) { + url.pathname = url.pathname.replace(/\/+$/, "") + "/"; + } + const { baseURL, client } = __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").sdkInit({ + baseURL: url, + client: options.httpClient || new http_js_1.HTTPClient() + }); + this._baseURL = baseURL; + __classPrivateFieldSet3(this, _ClientSDK_httpClient, client, "f"); + this._options = { ...options, hooks: __classPrivateFieldGet3(this, _ClientSDK_hooks, "f") }; + __classPrivateFieldSet3(this, _ClientSDK_logger, this._options.debugLogger, "f"); + if (!__classPrivateFieldGet3(this, _ClientSDK_logger, "f") && (0, env_js_1.env)().MISTRAL_DEBUG) { + __classPrivateFieldSet3(this, _ClientSDK_logger, console, "f"); + } + } + _createRequest(context, conf, options) { + const { method, path: path6, query, headers: opHeaders, security } = conf; + const base = conf.baseURL ?? this._baseURL; + if (!base) { + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.InvalidRequestError("No base URL provided for operation")); + } + const reqURL = new URL(base); + const inputURL = new URL(path6, reqURL); + if (path6) { + reqURL.pathname += reqURL.pathname.endsWith("/") ? "" : "/"; + reqURL.pathname += inputURL.pathname.replace(/^\/+/, ""); + } + let finalQuery = query || ""; + const secQuery = []; + for (const [k2, v4] of Object.entries(security?.queryParams || {})) { + const q2 = (0, encodings_js_1.encodeForm)(k2, v4, { charEncoding: "percent" }); + if (typeof q2 !== "undefined") { + secQuery.push(q2); + } + } + if (secQuery.length) { + finalQuery += `&${secQuery.join("&")}`; + } + if (finalQuery) { + const q2 = finalQuery.startsWith("&") ? finalQuery.slice(1) : finalQuery; + reqURL.search = `?${q2}`; + } + const headers = new Headers(opHeaders); + const username = security?.basic.username; + const password = security?.basic.password; + if (username != null || password != null) { + const encoded = (0, base64_js_1.stringToBase64)([username || "", password || ""].join(":")); + headers.set("Authorization", `Basic ${encoded}`); + } + const securityHeaders = new Headers(security?.headers || {}); + for (const [k2, v4] of securityHeaders) { + headers.set(k2, v4); + } + let cookie = headers.get("cookie") || ""; + for (const [k2, v4] of Object.entries(security?.cookies || {})) { + cookie += `; ${k2}=${v4}`; + } + cookie = cookie.startsWith("; ") ? cookie.slice(2) : cookie; + headers.set("cookie", cookie); + const userHeaders = new Headers(options?.headers ?? options?.fetchOptions?.headers); + for (const [k2, v4] of userHeaders) { + headers.set(k2, v4); + } + if (!isBrowserLike) { + headers.set(conf.uaHeader ?? "user-agent", conf.userAgent ?? config_js_1.SDK_METADATA.userAgent); + } + const fetchOptions = { + ...options?.fetchOptions, + ...options + }; + if (!fetchOptions?.signal && conf.timeoutMs && conf.timeoutMs > 0) { + const timeoutSignal = AbortSignal.timeout(conf.timeoutMs); + fetchOptions.signal = timeoutSignal; + } + if (conf.body instanceof ReadableStream) { + Object.assign(fetchOptions, { duplex: "half" }); + } + let input; + try { + input = __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").beforeCreateRequest(context, { + url: reqURL, + options: { + ...fetchOptions, + body: conf.body ?? null, + headers, + method + } + }); + } catch (err) { + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.UnexpectedClientError("Create request hook failed to execute", { + cause: err + })); + } + return (0, fp_js_1.OK)(new Request(input.url, input.options)); + } + async _do(request, options) { + const { context, errorCodes } = options; + return (0, retries_js_1.retry)(async () => { + const req = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").beforeRequest(context, request.clone()); + await logRequest(__classPrivateFieldGet3(this, _ClientSDK_logger, "f"), req).catch((e9) => __classPrivateFieldGet3(this, _ClientSDK_logger, "f")?.log("Failed to log request:", e9)); + let response = await __classPrivateFieldGet3(this, _ClientSDK_httpClient, "f").request(req); + try { + if ((0, http_js_1.matchStatusCode)(response, errorCodes)) { + const result = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").afterError(context, response, null); + if (result.error) { + throw result.error; + } + response = result.response || response; + } else { + response = await __classPrivateFieldGet3(this, _ClientSDK_hooks, "f").afterSuccess(context, response); + } + } finally { + await logResponse(__classPrivateFieldGet3(this, _ClientSDK_logger, "f"), response, req).catch((e9) => __classPrivateFieldGet3(this, _ClientSDK_logger, "f")?.log("Failed to log response:", e9)); + } + return response; + }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r8) => (0, fp_js_1.OK)(r8), (err) => { + switch (true) { + case (0, http_js_1.isAbortError)(err): + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.RequestAbortedError("Request aborted by client", { + cause: err + })); + case (0, http_js_1.isTimeoutError)(err): + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.RequestTimeoutError("Request timed out", { cause: err })); + case (0, http_js_1.isConnectionError)(err): + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.ConnectionError("Unable to make request", { cause: err })); + default: + return (0, fp_js_1.ERR)(new httpclienterrors_js_1.UnexpectedClientError("Unexpected HTTP client error", { + cause: err + })); + } + }); + } + }; + exports.ClientSDK = ClientSDK; + _ClientSDK_httpClient = /* @__PURE__ */ new WeakMap(), _ClientSDK_hooks = /* @__PURE__ */ new WeakMap(), _ClientSDK_logger = /* @__PURE__ */ new WeakMap(); + var jsonLikeContentTypeRE = /^(application|text)\/([^+]+\+)*json.*/; + var jsonlLikeContentTypeRE = /^(application|text)\/([^+]+\+)*(jsonl|x-ndjson)\b.*/; + async function logRequest(logger2, req) { + if (!logger2) { + return; + } + const contentType = req.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + logger2.group(`> Request: ${req.method} ${req.url}`); + logger2.group("Headers:"); + for (const [k2, v4] of req.headers.entries()) { + logger2.log(`${k2}: ${v4}`); + } + logger2.groupEnd(); + logger2.group("Body:"); + switch (true) { + case jsonLikeContentTypeRE.test(ct): + logger2.log(await req.clone().json()); + break; + case ct.startsWith("text/"): + logger2.log(await req.clone().text()); + break; + case ct === "multipart/form-data": { + const body = await req.clone().formData(); + for (const [k2, v4] of body) { + const vlabel = v4 instanceof Blob ? "" : v4; + logger2.log(`${k2}: ${vlabel}`); + } + break; + } + default: + logger2.log(`<${contentType}>`); + break; + } + logger2.groupEnd(); + logger2.groupEnd(); + } + async function logResponse(logger2, res, req) { + if (!logger2) { + return; + } + const contentType = res.headers.get("content-type"); + const ct = contentType?.split(";")[0] || ""; + logger2.group(`< Response: ${req.method} ${req.url}`); + logger2.log("Status Code:", res.status, res.statusText); + logger2.group("Headers:"); + for (const [k2, v4] of res.headers.entries()) { + logger2.log(`${k2}: ${v4}`); + } + logger2.groupEnd(); + logger2.group("Body:"); + switch (true) { + case ((0, http_js_1.matchContentType)(res, "application/json") || jsonLikeContentTypeRE.test(ct) && !jsonlLikeContentTypeRE.test(ct)): + logger2.log(await res.clone().json()); + break; + case ((0, http_js_1.matchContentType)(res, "application/jsonl") || jsonlLikeContentTypeRE.test(ct)): + logger2.log(await res.clone().text()); + break; + case (0, http_js_1.matchContentType)(res, "text/event-stream"): + logger2.log(`<${contentType}>`); + break; + case (0, http_js_1.matchContentType)(res, "text/*"): + logger2.log(await res.clone().text()); + break; + case (0, http_js_1.matchContentType)(res, "multipart/form-data"): { + const body = await res.clone().formData(); + for (const [k2, v4] of body) { + const vlabel = v4 instanceof Blob ? "" : v4; + logger2.log(`${k2}: ${vlabel}`); + } + break; + } + default: + logger2.log(`<${contentType}>`); + break; + } + logger2.groupEnd(); + logger2.groupEnd(); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/mistralerror.js +var require_mistralerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/mistralerror.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralError = void 0; + var MistralError = class extends Error { + constructor(message, httpMeta) { + super(message); + this.statusCode = httpMeta.response.status; + this.body = httpMeta.body; + this.headers = httpMeta.response.headers; + this.contentType = httpMeta.response.headers.get("content-type") || ""; + this.rawResponse = httpMeta.response; + this.name = "MistralError"; + } + }; + exports.MistralError = MistralError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkvalidationerror.js +var require_sdkvalidationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkvalidationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDKValidationError = void 0; + exports.formatZodError = formatZodError; + var z3 = __importStar(require_v3()); + var SDKValidationError = class extends Error { + // Allows for backwards compatibility for `instanceof` checks of `ResponseValidationError` + static [Symbol.hasInstance](instance) { + if (!(instance instanceof Error)) + return false; + if (!("rawValue" in instance)) + return false; + if (!("rawMessage" in instance)) + return false; + if (!("pretty" in instance)) + return false; + if (typeof instance.pretty !== "function") + return false; + return true; + } + constructor(message, cause, rawValue) { + super(`${message}: ${cause}`); + this.name = "SDKValidationError"; + this.cause = cause; + this.rawValue = rawValue; + this.rawMessage = message; + } + /** + * Return a pretty-formatted error message if the underlying validation error + * is a ZodError or some other recognized error type, otherwise return the + * default error message. + */ + pretty() { + if (this.cause instanceof z3.ZodError) { + return `${this.rawMessage} +${formatZodError(this.cause)}`; + } else { + return this.toString(); + } + } + }; + exports.SDKValidationError = SDKValidationError; + function formatZodError(err, level = 0) { + let pre = " ".repeat(level); + pre = level > 0 ? `\u2502${pre}` : pre; + pre += " ".repeat(level); + let message = ""; + const append = (str2) => message += ` +${pre}${str2}`; + const len = err.issues.length; + const headline = len === 1 ? `${len} issue found` : `${len} issues found`; + if (len) { + append(`\u250C ${headline}:`); + } + for (const issue of err.issues) { + let path6 = issue.path.join("."); + path6 = path6 ? `.${path6}` : ""; + append(`\u2502 \u2022 [${path6}]: ${issue.message} (${issue.code})`); + switch (issue.code) { + case "invalid_literal": + case "invalid_type": { + append(`\u2502 Want: ${issue.expected}`); + append(`\u2502 Got: ${issue.received}`); + break; + } + case "unrecognized_keys": { + append(`\u2502 Keys: ${issue.keys.join(", ")}`); + break; + } + case "invalid_enum_value": { + append(`\u2502 Allowed: ${issue.options.join(", ")}`); + append(`\u2502 Got: ${issue.received}`); + break; + } + case "invalid_union_discriminator": { + append(`\u2502 Allowed: ${issue.options.join(", ")}`); + break; + } + case "invalid_union": { + const len2 = issue.unionErrors.length; + append(`\u2502 \u2716\uFE0E Attemped to deserialize into one of ${len2} union members:`); + issue.unionErrors.forEach((err2, i7) => { + append(`\u2502 \u2716\uFE0E Member ${i7 + 1} of ${len2}`); + append(`${formatZodError(err2, level + 1)}`); + }); + } + } + } + if (err.issues.length) { + append(`\u2514\u2500*`); + } + return message.slice(1); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/responsevalidationerror.js +var require_responsevalidationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/responsevalidationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseValidationError = void 0; + var z3 = __importStar(require_v3()); + var mistralerror_js_1 = require_mistralerror(); + var sdkvalidationerror_js_1 = require_sdkvalidationerror(); + var ResponseValidationError = class extends mistralerror_js_1.MistralError { + constructor(message, extra) { + super(message, extra); + this.name = "ResponseValidationError"; + this.cause = extra.cause; + this.rawValue = extra.rawValue; + this.rawMessage = extra.rawMessage; + } + /** + * Return a pretty-formatted error message if the underlying validation error + * is a ZodError or some other recognized error type, otherwise return the + * default error message. + */ + pretty() { + if (this.cause instanceof z3.ZodError) { + return `${this.rawMessage} +${(0, sdkvalidationerror_js_1.formatZodError)(this.cause)}`; + } else { + return this.toString(); + } + } + }; + exports.ResponseValidationError = ResponseValidationError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkerror.js +var require_sdkerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/sdkerror.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SDKError = void 0; + var mistralerror_js_1 = require_mistralerror(); + var SDKError = class extends mistralerror_js_1.MistralError { + constructor(message, httpMeta) { + if (message) { + message += `: `; + } + message += `Status ${httpMeta.response.status}`; + const contentType = httpMeta.response.headers.get("content-type") || `""`; + if (contentType !== "application/json") { + message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`; + } + const body = httpMeta.body || `""`; + message += body.length > 100 ? "\n" : ". "; + let bodyDisplay = body; + if (body.length > 1e4) { + const truncated = body.substring(0, 1e4); + const remaining = body.length - 1e4; + bodyDisplay = `${truncated}...and ${remaining} more chars`; + } + message += `Body: ${bodyDisplay}`; + message = message.trim(); + super(message, httpMeta); + this.name = "SDKError"; + } + }; + exports.SDKError = SDKError; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/matchers.js +var require_matchers = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/matchers.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.jsonErr = jsonErr; + exports.json = json2; + exports.jsonl = jsonl; + exports.jsonlErr = jsonlErr; + exports.textErr = textErr; + exports.text = text3; + exports.bytesErr = bytesErr; + exports.bytes = bytes; + exports.streamErr = streamErr; + exports.stream = stream2; + exports.sseErr = sseErr; + exports.sse = sse; + exports.nilErr = nilErr; + exports.nil = nil; + exports.fail = fail; + exports.match = match2; + exports.unpackHeaders = unpackHeaders; + var responsevalidationerror_js_1 = require_responsevalidationerror(); + var sdkerror_js_1 = require_sdkerror(); + var fp_js_1 = require_fp(); + var http_js_1 = require_http(); + var is_plain_object_js_1 = require_is_plain_object(); + var DEFAULT_CONTENT_TYPES = { + jsonl: "application/jsonl", + json: "application/json", + text: "text/plain", + bytes: "application/octet-stream", + stream: "application/octet-stream", + sse: "text/event-stream", + nil: "*", + fail: "*" + }; + function jsonErr(codes, schema, options) { + return { ...options, err: true, enc: "json", codes, schema }; + } + function json2(codes, schema, options) { + return { ...options, enc: "json", codes, schema }; + } + function jsonl(codes, schema, options) { + return { ...options, enc: "jsonl", codes, schema }; + } + function jsonlErr(codes, schema, options) { + return { ...options, err: true, enc: "jsonl", codes, schema }; + } + function textErr(codes, schema, options) { + return { ...options, err: true, enc: "text", codes, schema }; + } + function text3(codes, schema, options) { + return { ...options, enc: "text", codes, schema }; + } + function bytesErr(codes, schema, options) { + return { ...options, err: true, enc: "bytes", codes, schema }; + } + function bytes(codes, schema, options) { + return { ...options, enc: "bytes", codes, schema }; + } + function streamErr(codes, schema, options) { + return { ...options, err: true, enc: "stream", codes, schema }; + } + function stream2(codes, schema, options) { + return { ...options, enc: "stream", codes, schema }; + } + function sseErr(codes, schema, options) { + return { ...options, err: true, enc: "sse", codes, schema }; + } + function sse(codes, schema, options) { + return { ...options, enc: "sse", codes, schema }; + } + function nilErr(codes, schema, options) { + return { ...options, err: true, enc: "nil", codes, schema }; + } + function nil(codes, schema, options) { + return { ...options, enc: "nil", codes, schema }; + } + function fail(codes) { + return { enc: "fail", codes }; + } + function match2(...matchers) { + return async function matchFunc(response, request, options) { + let raw; + let matcher; + for (const match3 of matchers) { + const { codes } = match3; + const ctpattern = "ctype" in match3 ? match3.ctype : DEFAULT_CONTENT_TYPES[match3.enc]; + if (ctpattern && (0, http_js_1.matchResponse)(response, codes, ctpattern)) { + matcher = match3; + break; + } else if (!ctpattern && (0, http_js_1.matchStatusCode)(response, codes)) { + matcher = match3; + break; + } + } + if (!matcher) { + return [{ + ok: false, + error: new sdkerror_js_1.SDKError("Unexpected Status or Content-Type", { + response, + request, + body: await response.text().catch(() => "") + }) + }, raw]; + } + const encoding = matcher.enc; + let body = ""; + switch (encoding) { + case "json": + body = await response.text(); + raw = JSON.parse(body); + break; + case "jsonl": + raw = response.body; + break; + case "bytes": + raw = new Uint8Array(await response.arrayBuffer()); + break; + case "stream": + raw = response.body; + break; + case "text": + body = await response.text(); + raw = body; + break; + case "sse": + raw = response.body; + break; + case "nil": + body = await response.text(); + raw = void 0; + break; + case "fail": + body = await response.text(); + raw = body; + break; + default: + encoding; + throw new Error(`Unsupported response type: ${encoding}`); + } + if (matcher.enc === "fail") { + return [{ + ok: false, + error: new sdkerror_js_1.SDKError("API error occurred", { request, response, body }) + }, raw]; + } + const resultKey = matcher.key || options?.resultKey; + let data; + if ("err" in matcher) { + data = { + ...options?.extraFields, + ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, + ...(0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null, + request$: request, + response$: response, + body$: body + }; + } else if (resultKey) { + data = { + ...options?.extraFields, + ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, + [resultKey]: raw + }; + } else if (matcher.hdrs) { + data = { + ...options?.extraFields, + ...matcher.hdrs ? { Headers: unpackHeaders(response.headers) } : null, + ...(0, is_plain_object_js_1.isPlainObject)(raw) ? raw : null + }; + } else { + data = raw; + } + if ("err" in matcher) { + const result = safeParseResponse(data, (v4) => matcher.schema.parse(v4), "Response validation failed", { request, response, body }); + return [result.ok ? { ok: false, error: result.value } : result, raw]; + } else { + return [ + safeParseResponse(data, (v4) => matcher.schema.parse(v4), "Response validation failed", { request, response, body }), + raw + ]; + } + }; + } + var headerValRE = /, */; + function unpackHeaders(headers) { + const out = {}; + for (const [k2, v4] of headers.entries()) { + out[k2] = v4.split(headerValRE); + } + return out; + } + function safeParseResponse(rawValue, fn, errorMessage, httpMeta) { + try { + return (0, fp_js_1.OK)(fn(rawValue)); + } catch (err) { + return (0, fp_js_1.ERR)(new responsevalidationerror_js_1.ResponseValidationError(errorMessage, { + cause: err, + rawValue, + rawMessage: errorMessage, + ...httpMeta + })); + } + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/primitives.js +var require_primitives = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/primitives.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.invariant = invariant; + exports.remap = remap; + exports.combineSignals = combineSignals; + exports.abortSignalAny = abortSignalAny; + exports.compactMap = compactMap; + exports.allRequired = allRequired; + var InvariantError = class extends Error { + constructor(message) { + super(message); + this.name = "InvariantError"; + } + }; + function invariant(condition, message) { + if (!condition) { + throw new InvariantError(message); + } + } + function remap(inp, mappings) { + let out = {}; + if (!Object.keys(mappings).length) { + out = inp; + return out; + } + for (const [k2, v4] of Object.entries(inp)) { + const j3 = mappings[k2]; + if (j3 === null) { + continue; + } + out[j3 ?? k2] = v4; + } + return out; + } + function combineSignals(...signals) { + const filtered = []; + for (const signal of signals) { + if (signal) { + filtered.push(signal); + } + } + switch (filtered.length) { + case 0: + case 1: + return filtered[0] || null; + default: + if ("any" in AbortSignal && typeof AbortSignal.any === "function") { + return AbortSignal.any(filtered); + } + return abortSignalAny(filtered); + } + } + function abortSignalAny(signals) { + const controller = new AbortController(); + const result = controller.signal; + if (!signals.length) { + return controller.signal; + } + if (signals.length === 1) { + return signals[0] || controller.signal; + } + for (const signal of signals) { + if (signal.aborted) { + return signal; + } + } + function abort() { + controller.abort(this.reason); + clean(); + } + const signalRefs = []; + function clean() { + for (const signalRef of signalRefs) { + const signal = signalRef.deref(); + if (signal) { + signal.removeEventListener("abort", abort); + } + } + } + for (const signal of signals) { + signalRefs.push(new WeakRef(signal)); + signal.addEventListener("abort", abort); + } + return result; + } + function compactMap(values2) { + const out = {}; + for (const [k2, v4] of Object.entries(values2)) { + if (typeof v4 !== "undefined") { + out[k2] = v4; + } + } + return out; + } + function allRequired(v4) { + if (Object.values(v4).every((x2) => x2 == null)) { + return void 0; + } + return v4; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/schemas.js +var require_schemas = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/schemas.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parse = parse3; + exports.safeParse = safeParse; + exports.collectExtraKeys = collectExtraKeys; + var v3_1 = require_v3(); + var sdkvalidationerror_js_1 = require_sdkvalidationerror(); + var fp_js_1 = require_fp(); + function parse3(rawValue, fn, errorMessage) { + try { + return fn(rawValue); + } catch (err) { + if (err instanceof v3_1.ZodError) { + throw new sdkvalidationerror_js_1.SDKValidationError(errorMessage, err, rawValue); + } + throw err; + } + } + function safeParse(rawValue, fn, errorMessage) { + try { + return (0, fp_js_1.OK)(fn(rawValue)); + } catch (err) { + return (0, fp_js_1.ERR)(new sdkvalidationerror_js_1.SDKValidationError(errorMessage, err, rawValue)); + } + } + function collectExtraKeys(obj, extrasKey, optional) { + return obj.transform((val2) => { + const extras = {}; + const { shape } = obj; + for (const [key] of Object.entries(val2)) { + if (key in shape) { + continue; + } + const v4 = val2[key]; + if (typeof v4 === "undefined") { + continue; + } + extras[key] = v4; + delete val2[key]; + } + if (optional && Object.keys(extras).length === 0) { + return val2; + } + return { ...val2, [extrasKey]: extras }; + }); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/security.js +var require_security = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/security.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SecurityError = exports.SecurityErrorCode = void 0; + exports.resolveSecurity = resolveSecurity; + exports.resolveGlobalSecurity = resolveGlobalSecurity; + exports.extractSecurity = extractSecurity; + var env_js_1 = require_env(); + var SecurityErrorCode; + (function(SecurityErrorCode2) { + SecurityErrorCode2["Incomplete"] = "incomplete"; + SecurityErrorCode2["UnrecognisedSecurityType"] = "unrecognized_security_type"; + })(SecurityErrorCode || (exports.SecurityErrorCode = SecurityErrorCode = {})); + var SecurityError = class _SecurityError extends Error { + constructor(code, message) { + super(message); + this.code = code; + this.name = "SecurityError"; + } + static incomplete() { + return new _SecurityError(SecurityErrorCode.Incomplete, "Security requirements not met in order to perform the operation"); + } + static unrecognizedType(type) { + return new _SecurityError(SecurityErrorCode.UnrecognisedSecurityType, `Unrecognised security type: ${type}`); + } + }; + exports.SecurityError = SecurityError; + function resolveSecurity(...options) { + const state = { + basic: {}, + headers: {}, + queryParams: {}, + cookies: {}, + oauth2: { type: "none" } + }; + const option = options.find((opts) => { + return opts.every((o9) => { + if (o9.value == null) { + return false; + } else if (o9.type === "http:basic") { + return o9.value.username != null || o9.value.password != null; + } else if (o9.type === "http:custom") { + return null; + } else if (o9.type === "oauth2:password") { + return typeof o9.value === "string" && !!o9.value; + } else if (o9.type === "oauth2:client_credentials") { + if (typeof o9.value == "string") { + return !!o9.value; + } + return o9.value.clientID != null || o9.value.clientSecret != null; + } else if (typeof o9.value === "string") { + return !!o9.value; + } else { + throw new Error(`Unrecognized security type: ${o9.type} (value type: ${typeof o9.value})`); + } + }); + }); + if (option == null) { + return null; + } + option.forEach((spec) => { + if (spec.value == null) { + return; + } + const { type } = spec; + switch (type) { + case "apiKey:header": + state.headers[spec.fieldName] = spec.value; + break; + case "apiKey:query": + state.queryParams[spec.fieldName] = spec.value; + break; + case "apiKey:cookie": + state.cookies[spec.fieldName] = spec.value; + break; + case "http:basic": + applyBasic(state, spec); + break; + case "http:custom": + break; + case "http:bearer": + applyBearer(state, spec); + break; + case "oauth2": + applyBearer(state, spec); + break; + case "oauth2:password": + applyBearer(state, spec); + break; + case "oauth2:client_credentials": + break; + case "openIdConnect": + applyBearer(state, spec); + break; + default: + spec; + throw SecurityError.unrecognizedType(type); + } + }); + return state; + } + function applyBasic(state, spec) { + if (spec.value == null) { + return; + } + state.basic = spec.value; + } + function applyBearer(state, spec) { + if (typeof spec.value !== "string" || !spec.value) { + return; + } + let value = spec.value; + if (value.slice(0, 7).toLowerCase() !== "bearer ") { + value = `Bearer ${value}`; + } + if (spec.fieldName !== void 0) { + state.headers[spec.fieldName] = value; + } + } + function resolveGlobalSecurity(security) { + return resolveSecurity([ + { + fieldName: "Authorization", + type: "http:bearer", + value: security?.apiKey ?? (0, env_js_1.env)().MISTRAL_API_KEY + } + ]); + } + async function extractSecurity(sec) { + if (sec == null) { + return; + } + return typeof sec === "function" ? sec() : sec; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolconfiguration.js +var require_toolconfiguration = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolconfiguration.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolConfiguration$outboundSchema = exports.ToolConfiguration$inboundSchema = void 0; + exports.toolConfigurationToJSON = toolConfigurationToJSON; + exports.toolConfigurationFromJSON = toolConfigurationFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ToolConfiguration$inboundSchema = z3.object({ + exclude: z3.nullable(z3.array(z3.string())).optional(), + include: z3.nullable(z3.array(z3.string())).optional(), + requires_confirmation: z3.nullable(z3.array(z3.string())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "requires_confirmation": "requiresConfirmation" + }); + }); + exports.ToolConfiguration$outboundSchema = z3.object({ + exclude: z3.nullable(z3.array(z3.string())).optional(), + include: z3.nullable(z3.array(z3.string())).optional(), + requiresConfirmation: z3.nullable(z3.array(z3.string())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + requiresConfirmation: "requires_confirmation" + }); + }); + function toolConfigurationToJSON(toolConfiguration) { + return JSON.stringify(exports.ToolConfiguration$outboundSchema.parse(toolConfiguration)); + } + function toolConfigurationFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolConfiguration$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolConfiguration' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/codeinterpretertool.js +var require_codeinterpretertool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/codeinterpretertool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeInterpreterTool$outboundSchema = exports.CodeInterpreterTool$inboundSchema = exports.CodeInterpreterToolType$outboundSchema = exports.CodeInterpreterToolType$inboundSchema = exports.CodeInterpreterToolType = void 0; + exports.codeInterpreterToolToJSON = codeInterpreterToolToJSON; + exports.codeInterpreterToolFromJSON = codeInterpreterToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.CodeInterpreterToolType = { + CodeInterpreter: "code_interpreter" + }; + exports.CodeInterpreterToolType$inboundSchema = z3.nativeEnum(exports.CodeInterpreterToolType); + exports.CodeInterpreterToolType$outboundSchema = exports.CodeInterpreterToolType$inboundSchema; + exports.CodeInterpreterTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.CodeInterpreterToolType$inboundSchema.default("code_interpreter") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.CodeInterpreterTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.CodeInterpreterToolType$outboundSchema.default("code_interpreter") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function codeInterpreterToolToJSON(codeInterpreterTool) { + return JSON.stringify(exports.CodeInterpreterTool$outboundSchema.parse(codeInterpreterTool)); + } + function codeInterpreterToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CodeInterpreterTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CodeInterpreterTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargsstop.js +var require_completionargsstop = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargsstop.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionArgsStop$outboundSchema = exports.CompletionArgsStop$inboundSchema = void 0; + exports.completionArgsStopToJSON = completionArgsStopToJSON; + exports.completionArgsStopFromJSON = completionArgsStopFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.CompletionArgsStop$inboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + exports.CompletionArgsStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function completionArgsStopToJSON(completionArgsStop) { + return JSON.stringify(exports.CompletionArgsStop$outboundSchema.parse(completionArgsStop)); + } + function completionArgsStopFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionArgsStop$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionArgsStop' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/prediction.js +var require_prediction = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/prediction.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Prediction$outboundSchema = exports.Prediction$inboundSchema = void 0; + exports.predictionToJSON = predictionToJSON; + exports.predictionFromJSON = predictionFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Prediction$inboundSchema = z3.object({ + type: z3.literal("content").default("content"), + content: z3.string().default("") + }); + exports.Prediction$outboundSchema = z3.object({ + type: z3.literal("content").default("content"), + content: z3.string().default("") + }); + function predictionToJSON(prediction) { + return JSON.stringify(exports.Prediction$outboundSchema.parse(prediction)); + } + function predictionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Prediction$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Prediction' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jsonschema.js +var require_jsonschema = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jsonschema.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonSchema$outboundSchema = exports.JsonSchema$inboundSchema = void 0; + exports.jsonSchemaToJSON = jsonSchemaToJSON; + exports.jsonSchemaFromJSON = jsonSchemaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.JsonSchema$inboundSchema = z3.object({ + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + schema: z3.record(z3.any()), + strict: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "schema": "schemaDefinition" + }); + }); + exports.JsonSchema$outboundSchema = z3.object({ + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + schemaDefinition: z3.record(z3.any()), + strict: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + schemaDefinition: "schema" + }); + }); + function jsonSchemaToJSON(jsonSchema) { + return JSON.stringify(exports.JsonSchema$outboundSchema.parse(jsonSchema)); + } + function jsonSchemaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JsonSchema$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JsonSchema' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformats.js +var require_responseformats = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformats.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema = exports.ResponseFormats = void 0; + var z3 = __importStar(require_v3()); + exports.ResponseFormats = { + Text: "text", + JsonObject: "json_object", + JsonSchema: "json_schema" + }; + exports.ResponseFormats$inboundSchema = z3.nativeEnum(exports.ResponseFormats); + exports.ResponseFormats$outboundSchema = exports.ResponseFormats$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformat.js +var require_responseformat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseformat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseFormat$outboundSchema = exports.ResponseFormat$inboundSchema = void 0; + exports.responseFormatToJSON = responseFormatToJSON; + exports.responseFormatFromJSON = responseFormatFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var jsonschema_js_1 = require_jsonschema(); + var responseformats_js_1 = require_responseformats(); + exports.ResponseFormat$inboundSchema = z3.object({ + type: responseformats_js_1.ResponseFormats$inboundSchema.optional(), + json_schema: z3.nullable(jsonschema_js_1.JsonSchema$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "json_schema": "jsonSchema" + }); + }); + exports.ResponseFormat$outboundSchema = z3.object({ + type: responseformats_js_1.ResponseFormats$outboundSchema.optional(), + jsonSchema: z3.nullable(jsonschema_js_1.JsonSchema$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jsonSchema: "json_schema" + }); + }); + function responseFormatToJSON(responseFormat) { + return JSON.stringify(exports.ResponseFormat$outboundSchema.parse(responseFormat)); + } + function responseFormatFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseFormat$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseFormat' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoiceenum.js +var require_toolchoiceenum = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoiceenum.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema = exports.ToolChoiceEnum = void 0; + var z3 = __importStar(require_v3()); + exports.ToolChoiceEnum = { + Auto: "auto", + None: "none", + Any: "any", + Required: "required" + }; + exports.ToolChoiceEnum$inboundSchema = z3.nativeEnum(exports.ToolChoiceEnum); + exports.ToolChoiceEnum$outboundSchema = exports.ToolChoiceEnum$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargs.js +var require_completionargs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionargs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionArgs$outboundSchema = exports.CompletionArgs$inboundSchema = void 0; + exports.completionArgsToJSON = completionArgsToJSON; + exports.completionArgsFromJSON = completionArgsFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var completionargsstop_js_1 = require_completionargsstop(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + exports.CompletionArgs$inboundSchema = z3.object({ + stop: z3.nullable(completionargsstop_js_1.CompletionArgsStop$inboundSchema).optional(), + presence_penalty: z3.nullable(z3.number()).optional(), + frequency_penalty: z3.nullable(z3.number()).optional(), + temperature: z3.nullable(z3.number()).optional(), + top_p: z3.nullable(z3.number()).optional(), + max_tokens: z3.nullable(z3.number().int()).optional(), + random_seed: z3.nullable(z3.number().int()).optional(), + prediction: z3.nullable(prediction_js_1.Prediction$inboundSchema).optional(), + response_format: z3.nullable(responseformat_js_1.ResponseFormat$inboundSchema).optional(), + tool_choice: toolchoiceenum_js_1.ToolChoiceEnum$inboundSchema.optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "presence_penalty": "presencePenalty", + "frequency_penalty": "frequencyPenalty", + "top_p": "topP", + "max_tokens": "maxTokens", + "random_seed": "randomSeed", + "response_format": "responseFormat", + "tool_choice": "toolChoice" + }); + }); + exports.CompletionArgs$outboundSchema = z3.object({ + stop: z3.nullable(completionargsstop_js_1.CompletionArgsStop$outboundSchema).optional(), + presencePenalty: z3.nullable(z3.number()).optional(), + frequencyPenalty: z3.nullable(z3.number()).optional(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.nullable(z3.number()).optional(), + maxTokens: z3.nullable(z3.number().int()).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + prediction: z3.nullable(prediction_js_1.Prediction$outboundSchema).optional(), + responseFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(), + toolChoice: toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema.optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice" + }); + }); + function completionArgsToJSON(completionArgs) { + return JSON.stringify(exports.CompletionArgs$outboundSchema.parse(completionArgs)); + } + function completionArgsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionArgs$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionArgs' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentlibrarytool.js +var require_documentlibrarytool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentlibrarytool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentLibraryTool$outboundSchema = exports.DocumentLibraryTool$inboundSchema = exports.DocumentLibraryToolType$outboundSchema = exports.DocumentLibraryToolType$inboundSchema = exports.DocumentLibraryToolType = void 0; + exports.documentLibraryToolToJSON = documentLibraryToolToJSON; + exports.documentLibraryToolFromJSON = documentLibraryToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.DocumentLibraryToolType = { + DocumentLibrary: "document_library" + }; + exports.DocumentLibraryToolType$inboundSchema = z3.nativeEnum(exports.DocumentLibraryToolType); + exports.DocumentLibraryToolType$outboundSchema = exports.DocumentLibraryToolType$inboundSchema; + exports.DocumentLibraryTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.DocumentLibraryToolType$inboundSchema.default("document_library"), + library_ids: z3.array(z3.string()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration", + "library_ids": "libraryIds" + }); + }); + exports.DocumentLibraryTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.DocumentLibraryToolType$outboundSchema.default("document_library"), + libraryIds: z3.array(z3.string()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration", + libraryIds: "library_ids" + }); + }); + function documentLibraryToolToJSON(documentLibraryTool) { + return JSON.stringify(exports.DocumentLibraryTool$outboundSchema.parse(documentLibraryTool)); + } + function documentLibraryToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentLibraryTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentLibraryTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/function.js +var require_function = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/function.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionT$outboundSchema = exports.FunctionT$inboundSchema = void 0; + exports.functionToJSON = functionToJSON; + exports.functionFromJSON = functionFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.FunctionT$inboundSchema = z3.object({ + name: z3.string(), + description: z3.string().optional(), + strict: z3.boolean().optional(), + parameters: z3.record(z3.any()) + }); + exports.FunctionT$outboundSchema = z3.object({ + name: z3.string(), + description: z3.string().optional(), + strict: z3.boolean().optional(), + parameters: z3.record(z3.any()) + }); + function functionToJSON(functionT) { + return JSON.stringify(exports.FunctionT$outboundSchema.parse(functionT)); + } + function functionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionT$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionT' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functiontool.js +var require_functiontool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functiontool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionTool$outboundSchema = exports.FunctionTool$inboundSchema = exports.Type$outboundSchema = exports.Type$inboundSchema = exports.Type = void 0; + exports.functionToolToJSON = functionToolToJSON; + exports.functionToolFromJSON = functionToolFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var function_js_1 = require_function(); + exports.Type = { + Function: "function" + }; + exports.Type$inboundSchema = z3.nativeEnum(exports.Type); + exports.Type$outboundSchema = exports.Type$inboundSchema; + exports.FunctionTool$inboundSchema = z3.object({ + type: exports.Type$inboundSchema.default("function"), + function: function_js_1.FunctionT$inboundSchema + }); + exports.FunctionTool$outboundSchema = z3.object({ + type: exports.Type$outboundSchema.default("function"), + function: function_js_1.FunctionT$outboundSchema + }); + function functionToolToJSON(functionTool) { + return JSON.stringify(exports.FunctionTool$outboundSchema.parse(functionTool)); + } + function functionToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imagegenerationtool.js +var require_imagegenerationtool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imagegenerationtool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageGenerationTool$outboundSchema = exports.ImageGenerationTool$inboundSchema = exports.ImageGenerationToolType$outboundSchema = exports.ImageGenerationToolType$inboundSchema = exports.ImageGenerationToolType = void 0; + exports.imageGenerationToolToJSON = imageGenerationToolToJSON; + exports.imageGenerationToolFromJSON = imageGenerationToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.ImageGenerationToolType = { + ImageGeneration: "image_generation" + }; + exports.ImageGenerationToolType$inboundSchema = z3.nativeEnum(exports.ImageGenerationToolType); + exports.ImageGenerationToolType$outboundSchema = exports.ImageGenerationToolType$inboundSchema; + exports.ImageGenerationTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.ImageGenerationToolType$inboundSchema.default("image_generation") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.ImageGenerationTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.ImageGenerationToolType$outboundSchema.default("image_generation") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function imageGenerationToolToJSON(imageGenerationTool) { + return JSON.stringify(exports.ImageGenerationTool$outboundSchema.parse(imageGenerationTool)); + } + function imageGenerationToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageGenerationTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageGenerationTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchpremiumtool.js +var require_websearchpremiumtool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchpremiumtool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSearchPremiumTool$outboundSchema = exports.WebSearchPremiumTool$inboundSchema = exports.WebSearchPremiumToolType$outboundSchema = exports.WebSearchPremiumToolType$inboundSchema = exports.WebSearchPremiumToolType = void 0; + exports.webSearchPremiumToolToJSON = webSearchPremiumToolToJSON; + exports.webSearchPremiumToolFromJSON = webSearchPremiumToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.WebSearchPremiumToolType = { + WebSearchPremium: "web_search_premium" + }; + exports.WebSearchPremiumToolType$inboundSchema = z3.nativeEnum(exports.WebSearchPremiumToolType); + exports.WebSearchPremiumToolType$outboundSchema = exports.WebSearchPremiumToolType$inboundSchema; + exports.WebSearchPremiumTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.WebSearchPremiumToolType$inboundSchema.default("web_search_premium") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.WebSearchPremiumTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.WebSearchPremiumToolType$outboundSchema.default("web_search_premium") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function webSearchPremiumToolToJSON(webSearchPremiumTool) { + return JSON.stringify(exports.WebSearchPremiumTool$outboundSchema.parse(webSearchPremiumTool)); + } + function webSearchPremiumToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WebSearchPremiumTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WebSearchPremiumTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchtool.js +var require_websearchtool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/websearchtool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSearchTool$outboundSchema = exports.WebSearchTool$inboundSchema = exports.WebSearchToolType$outboundSchema = exports.WebSearchToolType$inboundSchema = exports.WebSearchToolType = void 0; + exports.webSearchToolToJSON = webSearchToolToJSON; + exports.webSearchToolFromJSON = webSearchToolFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var toolconfiguration_js_1 = require_toolconfiguration(); + exports.WebSearchToolType = { + WebSearch: "web_search" + }; + exports.WebSearchToolType$inboundSchema = z3.nativeEnum(exports.WebSearchToolType); + exports.WebSearchToolType$outboundSchema = exports.WebSearchToolType$inboundSchema; + exports.WebSearchTool$inboundSchema = z3.object({ + tool_configuration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$inboundSchema).optional(), + type: exports.WebSearchToolType$inboundSchema.default("web_search") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_configuration": "toolConfiguration" + }); + }); + exports.WebSearchTool$outboundSchema = z3.object({ + toolConfiguration: z3.nullable(toolconfiguration_js_1.ToolConfiguration$outboundSchema).optional(), + type: exports.WebSearchToolType$outboundSchema.default("web_search") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolConfiguration: "tool_configuration" + }); + }); + function webSearchToolToJSON(webSearchTool) { + return JSON.stringify(exports.WebSearchTool$outboundSchema.parse(webSearchTool)); + } + function webSearchToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WebSearchTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WebSearchTool' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agent.js +var require_agent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Agent$inboundSchema = exports.AgentTools$inboundSchema = void 0; + exports.agentToolsFromJSON = agentToolsFromJSON; + exports.agentFromJSON = agentFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.AgentTools$inboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function agentToolsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentTools$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentTools' from JSON`); + } + exports.Agent$inboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completion_args: completionargs_js_1.CompletionArgs$inboundSchema.optional(), + model: z3.string(), + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + handoffs: z3.nullable(z3.array(z3.string())).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + object: z3.literal("agent").default("agent"), + id: z3.string(), + version: z3.number().int(), + versions: z3.array(z3.number().int()), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + deployment_chat: z3.boolean(), + source: z3.string(), + version_message: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_args": "completionArgs", + "created_at": "createdAt", + "updated_at": "updatedAt", + "deployment_chat": "deploymentChat", + "version_message": "versionMessage" + }); + }); + function agentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Agent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Agent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentaliasresponse.js +var require_agentaliasresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentaliasresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentAliasResponse$inboundSchema = void 0; + exports.agentAliasResponseFromJSON = agentAliasResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentAliasResponse$inboundSchema = z3.object({ + alias: z3.string(), + version: z3.number().int(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "updated_at": "updatedAt" + }); + }); + function agentAliasResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentAliasResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentAliasResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentconversation.js +var require_agentconversation = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentconversation.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentConversation$inboundSchema = exports.AgentConversationAgentVersion$inboundSchema = void 0; + exports.agentConversationAgentVersionFromJSON = agentConversationAgentVersionFromJSON; + exports.agentConversationFromJSON = agentConversationFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentConversationAgentVersion$inboundSchema = z3.union([z3.string(), z3.number().int()]); + function agentConversationAgentVersionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentConversationAgentVersion$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentConversationAgentVersion' from JSON`); + } + exports.AgentConversation$inboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + object: z3.literal("conversation").default("conversation"), + id: z3.string(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + agent_id: z3.string(), + agent_version: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "updated_at": "updatedAt", + "agent_id": "agentId", + "agent_version": "agentVersion" + }); + }); + function agentConversationFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentConversation$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentConversation' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentcreationrequest.js +var require_agentcreationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentcreationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentCreationRequest$outboundSchema = exports.AgentCreationRequestTools$outboundSchema = void 0; + exports.agentCreationRequestToolsToJSON = agentCreationRequestToolsToJSON; + exports.agentCreationRequestToJSON = agentCreationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.AgentCreationRequestTools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function agentCreationRequestToolsToJSON(agentCreationRequestTools) { + return JSON.stringify(exports.AgentCreationRequestTools$outboundSchema.parse(agentCreationRequestTools)); + } + exports.AgentCreationRequest$outboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + model: z3.string(), + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + handoffs: z3.nullable(z3.array(z3.string())).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + versionMessage: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + completionArgs: "completion_args", + versionMessage: "version_message" + }); + }); + function agentCreationRequestToJSON(agentCreationRequest) { + return JSON.stringify(exports.AgentCreationRequest$outboundSchema.parse(agentCreationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffdoneevent.js +var require_agenthandoffdoneevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffdoneevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentHandoffDoneEvent$inboundSchema = void 0; + exports.agentHandoffDoneEventFromJSON = agentHandoffDoneEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentHandoffDoneEvent$inboundSchema = z3.object({ + type: z3.literal("agent.handoff.done").default("agent.handoff.done"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + next_agent_id: z3.string(), + next_agent_name: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "next_agent_id": "nextAgentId", + "next_agent_name": "nextAgentName" + }); + }); + function agentHandoffDoneEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffDoneEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffentry.js +var require_agenthandoffentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentHandoffEntry$outboundSchema = exports.AgentHandoffEntry$inboundSchema = void 0; + exports.agentHandoffEntryToJSON = agentHandoffEntryToJSON; + exports.agentHandoffEntryFromJSON = agentHandoffEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentHandoffEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("agent.handoff").default("agent.handoff"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + previous_agent_id: z3.string(), + previous_agent_name: z3.string(), + next_agent_id: z3.string(), + next_agent_name: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "previous_agent_id": "previousAgentId", + "previous_agent_name": "previousAgentName", + "next_agent_id": "nextAgentId", + "next_agent_name": "nextAgentName" + }); + }); + exports.AgentHandoffEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("agent.handoff").default("agent.handoff"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + previousAgentId: z3.string(), + previousAgentName: z3.string(), + nextAgentId: z3.string(), + nextAgentName: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + previousAgentId: "previous_agent_id", + previousAgentName: "previous_agent_name", + nextAgentId: "next_agent_id", + nextAgentName: "next_agent_name" + }); + }); + function agentHandoffEntryToJSON(agentHandoffEntry) { + return JSON.stringify(exports.AgentHandoffEntry$outboundSchema.parse(agentHandoffEntry)); + } + function agentHandoffEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffstartedevent.js +var require_agenthandoffstartedevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agenthandoffstartedevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentHandoffStartedEvent$inboundSchema = void 0; + exports.agentHandoffStartedEventFromJSON = agentHandoffStartedEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AgentHandoffStartedEvent$inboundSchema = z3.object({ + type: z3.literal("agent.handoff.started").default("agent.handoff.started"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + previous_agent_id: z3.string(), + previous_agent_name: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "previous_agent_id": "previousAgentId", + "previous_agent_name": "previousAgentName" + }); + }); + function agentHandoffStartedEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentHandoffStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentHandoffStartedEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiochunk.js +var require_audiochunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiochunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioChunk$outboundSchema = exports.AudioChunk$inboundSchema = void 0; + exports.audioChunkToJSON = audioChunkToJSON; + exports.audioChunkFromJSON = audioChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.AudioChunk$inboundSchema = z3.object({ + type: z3.literal("input_audio").default("input_audio"), + input_audio: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "input_audio": "inputAudio" + }); + }); + exports.AudioChunk$outboundSchema = z3.object({ + type: z3.literal("input_audio").default("input_audio"), + inputAudio: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputAudio: "input_audio" + }); + }); + function audioChunkToJSON(audioChunk) { + return JSON.stringify(exports.AudioChunk$outboundSchema.parse(audioChunk)); + } + function audioChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AudioChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AudioChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documenturlchunk.js +var require_documenturlchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documenturlchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentURLChunk$outboundSchema = exports.DocumentURLChunk$inboundSchema = void 0; + exports.documentURLChunkToJSON = documentURLChunkToJSON; + exports.documentURLChunkFromJSON = documentURLChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.DocumentURLChunk$inboundSchema = z3.object({ + type: z3.literal("document_url").default("document_url"), + document_url: z3.string(), + document_name: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "document_url": "documentUrl", + "document_name": "documentName" + }); + }); + exports.DocumentURLChunk$outboundSchema = z3.object({ + type: z3.literal("document_url").default("document_url"), + documentUrl: z3.string(), + documentName: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + documentUrl: "document_url", + documentName: "document_name" + }); + }); + function documentURLChunkToJSON(documentURLChunk) { + return JSON.stringify(exports.DocumentURLChunk$outboundSchema.parse(documentURLChunk)); + } + function documentURLChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentURLChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentURLChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filechunk.js +var require_filechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/filechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileChunk$outboundSchema = exports.FileChunk$inboundSchema = void 0; + exports.fileChunkToJSON = fileChunkToJSON; + exports.fileChunkFromJSON = fileChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FileChunk$inboundSchema = z3.object({ + type: z3.literal("file").default("file"), + file_id: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "file_id": "fileId" + }); + }); + exports.FileChunk$outboundSchema = z3.object({ + type: z3.literal("file").default("file"), + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function fileChunkToJSON(fileChunk) { + return JSON.stringify(exports.FileChunk$outboundSchema.parse(fileChunk)); + } + function fileChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imagedetail.js +var require_imagedetail = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imagedetail.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageDetail$outboundSchema = exports.ImageDetail$inboundSchema = exports.ImageDetail = void 0; + var z3 = __importStar(require_v3()); + exports.ImageDetail = { + Low: "low", + Auto: "auto", + High: "high" + }; + exports.ImageDetail$inboundSchema = z3.nativeEnum(exports.ImageDetail); + exports.ImageDetail$outboundSchema = exports.ImageDetail$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurl.js +var require_imageurl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageURL$outboundSchema = exports.ImageURL$inboundSchema = void 0; + exports.imageURLToJSON = imageURLToJSON; + exports.imageURLFromJSON = imageURLFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var imagedetail_js_1 = require_imagedetail(); + exports.ImageURL$inboundSchema = z3.object({ + url: z3.string(), + detail: z3.nullable(imagedetail_js_1.ImageDetail$inboundSchema).optional() + }); + exports.ImageURL$outboundSchema = z3.object({ + url: z3.string(), + detail: z3.nullable(imagedetail_js_1.ImageDetail$outboundSchema).optional() + }); + function imageURLToJSON(imageURL) { + return JSON.stringify(exports.ImageURL$outboundSchema.parse(imageURL)); + } + function imageURLFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURL' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurlchunk.js +var require_imageurlchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/imageurlchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ImageURLChunk$outboundSchema = exports.ImageURLChunk$inboundSchema = exports.ImageURLChunkImageURL$outboundSchema = exports.ImageURLChunkImageURL$inboundSchema = void 0; + exports.imageURLChunkImageURLToJSON = imageURLChunkImageURLToJSON; + exports.imageURLChunkImageURLFromJSON = imageURLChunkImageURLFromJSON; + exports.imageURLChunkToJSON = imageURLChunkToJSON; + exports.imageURLChunkFromJSON = imageURLChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var imageurl_js_1 = require_imageurl(); + exports.ImageURLChunkImageURL$inboundSchema = z3.union([imageurl_js_1.ImageURL$inboundSchema, z3.string()]); + exports.ImageURLChunkImageURL$outboundSchema = z3.union([imageurl_js_1.ImageURL$outboundSchema, z3.string()]); + function imageURLChunkImageURLToJSON(imageURLChunkImageURL) { + return JSON.stringify(exports.ImageURLChunkImageURL$outboundSchema.parse(imageURLChunkImageURL)); + } + function imageURLChunkImageURLFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURLChunkImageURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURLChunkImageURL' from JSON`); + } + exports.ImageURLChunk$inboundSchema = z3.object({ + type: z3.literal("image_url").default("image_url"), + image_url: z3.union([imageurl_js_1.ImageURL$inboundSchema, z3.string()]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "image_url": "imageUrl" + }); + }); + exports.ImageURLChunk$outboundSchema = z3.object({ + type: z3.literal("image_url").default("image_url"), + imageUrl: z3.union([imageurl_js_1.ImageURL$outboundSchema, z3.string()]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + imageUrl: "image_url" + }); + }); + function imageURLChunkToJSON(imageURLChunk) { + return JSON.stringify(exports.ImageURLChunk$outboundSchema.parse(imageURLChunk)); + } + function imageURLChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ImageURLChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ImageURLChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/referencechunk.js +var require_referencechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/referencechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ReferenceChunk$outboundSchema = exports.ReferenceChunk$inboundSchema = void 0; + exports.referenceChunkToJSON = referenceChunkToJSON; + exports.referenceChunkFromJSON = referenceChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ReferenceChunk$inboundSchema = z3.object({ + type: z3.literal("reference").default("reference"), + reference_ids: z3.array(z3.number().int()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "reference_ids": "referenceIds" + }); + }); + exports.ReferenceChunk$outboundSchema = z3.object({ + type: z3.literal("reference").default("reference"), + referenceIds: z3.array(z3.number().int()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + referenceIds: "reference_ids" + }); + }); + function referenceChunkToJSON(referenceChunk) { + return JSON.stringify(exports.ReferenceChunk$outboundSchema.parse(referenceChunk)); + } + function referenceChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ReferenceChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ReferenceChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/textchunk.js +var require_textchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/textchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TextChunk$outboundSchema = exports.TextChunk$inboundSchema = void 0; + exports.textChunkToJSON = textChunkToJSON; + exports.textChunkFromJSON = textChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.TextChunk$inboundSchema = z3.object({ + type: z3.literal("text").default("text"), + text: z3.string() + }); + exports.TextChunk$outboundSchema = z3.object({ + type: z3.literal("text").default("text"), + text: z3.string() + }); + function textChunkToJSON(textChunk) { + return JSON.stringify(exports.TextChunk$outboundSchema.parse(textChunk)); + } + function textChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TextChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TextChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/builtinconnectors.js +var require_builtinconnectors = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/builtinconnectors.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BuiltInConnectors$outboundSchema = exports.BuiltInConnectors$inboundSchema = exports.BuiltInConnectors = void 0; + var z3 = __importStar(require_v3()); + exports.BuiltInConnectors = { + WebSearch: "web_search", + WebSearchPremium: "web_search_premium", + CodeInterpreter: "code_interpreter", + ImageGeneration: "image_generation", + DocumentLibrary: "document_library" + }; + exports.BuiltInConnectors$inboundSchema = z3.nativeEnum(exports.BuiltInConnectors); + exports.BuiltInConnectors$outboundSchema = exports.BuiltInConnectors$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolreferencechunk.js +var require_toolreferencechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolreferencechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolReferenceChunk$outboundSchema = exports.ToolReferenceChunk$inboundSchema = exports.ToolReferenceChunkTool$outboundSchema = exports.ToolReferenceChunkTool$inboundSchema = void 0; + exports.toolReferenceChunkToolToJSON = toolReferenceChunkToolToJSON; + exports.toolReferenceChunkToolFromJSON = toolReferenceChunkToolFromJSON; + exports.toolReferenceChunkToJSON = toolReferenceChunkToJSON; + exports.toolReferenceChunkFromJSON = toolReferenceChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolReferenceChunkTool$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + exports.ToolReferenceChunkTool$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]); + function toolReferenceChunkToolToJSON(toolReferenceChunkTool) { + return JSON.stringify(exports.ToolReferenceChunkTool$outboundSchema.parse(toolReferenceChunkTool)); + } + function toolReferenceChunkToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolReferenceChunkTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolReferenceChunkTool' from JSON`); + } + exports.ToolReferenceChunk$inboundSchema = z3.object({ + type: z3.literal("tool_reference").default("tool_reference"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + title: z3.string(), + url: z3.nullable(z3.string()).optional(), + favicon: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + exports.ToolReferenceChunk$outboundSchema = z3.object({ + type: z3.literal("tool_reference").default("tool_reference"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]), + title: z3.string(), + url: z3.nullable(z3.string()).optional(), + favicon: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + function toolReferenceChunkToJSON(toolReferenceChunk) { + return JSON.stringify(exports.ToolReferenceChunk$outboundSchema.parse(toolReferenceChunk)); + } + function toolReferenceChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolReferenceChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolReferenceChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/thinkchunk.js +var require_thinkchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/thinkchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ThinkChunk$outboundSchema = exports.ThinkChunk$inboundSchema = exports.Thinking$outboundSchema = exports.Thinking$inboundSchema = void 0; + exports.thinkingToJSON = thinkingToJSON; + exports.thinkingFromJSON = thinkingFromJSON; + exports.thinkChunkToJSON = thinkChunkToJSON; + exports.thinkChunkFromJSON = thinkChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var textchunk_js_1 = require_textchunk(); + var toolreferencechunk_js_1 = require_toolreferencechunk(); + exports.Thinking$inboundSchema = z3.union([toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, textchunk_js_1.TextChunk$inboundSchema]); + exports.Thinking$outboundSchema = z3.union([toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, textchunk_js_1.TextChunk$outboundSchema]); + function thinkingToJSON(thinking) { + return JSON.stringify(exports.Thinking$outboundSchema.parse(thinking)); + } + function thinkingFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Thinking$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Thinking' from JSON`); + } + exports.ThinkChunk$inboundSchema = z3.object({ + type: z3.literal("thinking").default("thinking"), + thinking: z3.array(z3.union([toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, textchunk_js_1.TextChunk$inboundSchema])), + closed: z3.boolean().default(true) + }); + exports.ThinkChunk$outboundSchema = z3.object({ + type: z3.literal("thinking").default("thinking"), + thinking: z3.array(z3.union([toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, textchunk_js_1.TextChunk$outboundSchema])), + closed: z3.boolean().default(true) + }); + function thinkChunkToJSON(thinkChunk) { + return JSON.stringify(exports.ThinkChunk$outboundSchema.parse(thinkChunk)); + } + function thinkChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ThinkChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ThinkChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/contentchunk.js +var require_contentchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/contentchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ContentChunk$outboundSchema = exports.ContentChunk$inboundSchema = void 0; + exports.contentChunkToJSON = contentChunkToJSON; + exports.contentChunkFromJSON = contentChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var audiochunk_js_1 = require_audiochunk(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var filechunk_js_1 = require_filechunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var referencechunk_js_1 = require_referencechunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + exports.ContentChunk$inboundSchema = z3.union([ + imageurlchunk_js_1.ImageURLChunk$inboundSchema.and(z3.object({ type: z3.literal("image_url") })), + documenturlchunk_js_1.DocumentURLChunk$inboundSchema.and(z3.object({ type: z3.literal("document_url") })), + textchunk_js_1.TextChunk$inboundSchema.and(z3.object({ type: z3.literal("text") })), + referencechunk_js_1.ReferenceChunk$inboundSchema.and(z3.object({ type: z3.literal("reference") })), + filechunk_js_1.FileChunk$inboundSchema.and(z3.object({ type: z3.literal("file") })), + thinkchunk_js_1.ThinkChunk$inboundSchema.and(z3.object({ type: z3.literal("thinking") })), + audiochunk_js_1.AudioChunk$inboundSchema.and(z3.object({ type: z3.literal("input_audio") })) + ]); + exports.ContentChunk$outboundSchema = z3.union([ + imageurlchunk_js_1.ImageURLChunk$outboundSchema.and(z3.object({ type: z3.literal("image_url") })), + documenturlchunk_js_1.DocumentURLChunk$outboundSchema.and(z3.object({ type: z3.literal("document_url") })), + textchunk_js_1.TextChunk$outboundSchema.and(z3.object({ type: z3.literal("text") })), + referencechunk_js_1.ReferenceChunk$outboundSchema.and(z3.object({ type: z3.literal("reference") })), + filechunk_js_1.FileChunk$outboundSchema.and(z3.object({ type: z3.literal("file") })), + thinkchunk_js_1.ThinkChunk$outboundSchema.and(z3.object({ type: z3.literal("thinking") })), + audiochunk_js_1.AudioChunk$outboundSchema.and(z3.object({ type: z3.literal("input_audio") })) + ]); + function contentChunkToJSON(contentChunk) { + return JSON.stringify(exports.ContentChunk$outboundSchema.parse(contentChunk)); + } + function contentChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ContentChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ContentChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncall.js +var require_functioncall = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncall.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCall$outboundSchema = exports.FunctionCall$inboundSchema = exports.Arguments$outboundSchema = exports.Arguments$inboundSchema = void 0; + exports.argumentsToJSON = argumentsToJSON; + exports.argumentsFromJSON = argumentsFromJSON; + exports.functionCallToJSON = functionCallToJSON; + exports.functionCallFromJSON = functionCallFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Arguments$inboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + exports.Arguments$outboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + function argumentsToJSON(value) { + return JSON.stringify(exports.Arguments$outboundSchema.parse(value)); + } + function argumentsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Arguments$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Arguments' from JSON`); + } + exports.FunctionCall$inboundSchema = z3.object({ + name: z3.string(), + arguments: z3.union([z3.record(z3.any()), z3.string()]) + }); + exports.FunctionCall$outboundSchema = z3.object({ + name: z3.string(), + arguments: z3.union([z3.record(z3.any()), z3.string()]) + }); + function functionCallToJSON(functionCall) { + return JSON.stringify(exports.FunctionCall$outboundSchema.parse(functionCall)); + } + function functionCallFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCall$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCall' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/unrecognized.js +var require_unrecognized = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/unrecognized.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.startCountingUnrecognized = startCountingUnrecognized; + exports.unrecognized = unrecognized; + function unrecognized(value) { + globalCount++; + return value; + } + var globalCount = 0; + var refCount = 0; + function startCountingUnrecognized() { + refCount++; + const start = globalCount; + return { + /** + * Ends counting and returns the delta. + * @param delta - If provided, only this amount is added to the parent counter + * (used for nested unions where we only want to record the winning option's count). + * If not provided, records all counts since start(). + */ + end: (delta) => { + const count = globalCount - start; + globalCount = start + (delta ?? count); + if (--refCount === 0) + globalCount = 0; + return count; + } + }; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/enums.js +var require_enums = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/enums.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.inboundSchema = inboundSchema; + exports.inboundSchemaInt = inboundSchemaInt; + exports.outboundSchema = outboundSchema; + exports.outboundSchemaInt = outboundSchemaInt; + var z3 = __importStar(require_v3()); + var unrecognized_js_1 = require_unrecognized(); + function inboundSchema(enumObj) { + const options = Object.values(enumObj); + return z3.union([ + ...options.map((x2) => z3.literal(x2)), + z3.string().transform((x2) => (0, unrecognized_js_1.unrecognized)(x2)) + ]); + } + function inboundSchemaInt(enumObj) { + const options = Object.values(enumObj).filter((v4) => typeof v4 === "number"); + return z3.union([ + ...options.map((x2) => z3.literal(x2)), + z3.number().int().transform((x2) => (0, unrecognized_js_1.unrecognized)(x2)) + ]); + } + function outboundSchema(_3) { + return z3.string(); + } + function outboundSchemaInt(_3) { + return z3.number().int(); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/tooltypes.js +var require_tooltypes = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/tooltypes.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolTypes$outboundSchema = exports.ToolTypes$inboundSchema = exports.ToolTypes = void 0; + var openEnums = __importStar(require_enums()); + exports.ToolTypes = { + Function: "function" + }; + exports.ToolTypes$inboundSchema = openEnums.inboundSchema(exports.ToolTypes); + exports.ToolTypes$outboundSchema = openEnums.outboundSchema(exports.ToolTypes); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcall.js +var require_toolcall = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcall.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolCall$outboundSchema = exports.ToolCall$inboundSchema = void 0; + exports.toolCallToJSON = toolCallToJSON; + exports.toolCallFromJSON = toolCallFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var functioncall_js_1 = require_functioncall(); + var tooltypes_js_1 = require_tooltypes(); + exports.ToolCall$inboundSchema = z3.object({ + id: z3.string().default("null"), + type: tooltypes_js_1.ToolTypes$inboundSchema.optional(), + function: functioncall_js_1.FunctionCall$inboundSchema, + index: z3.number().int().default(0) + }); + exports.ToolCall$outboundSchema = z3.object({ + id: z3.string().default("null"), + type: tooltypes_js_1.ToolTypes$outboundSchema.optional(), + function: functioncall_js_1.FunctionCall$outboundSchema, + index: z3.number().int().default(0) + }); + function toolCallToJSON(toolCall) { + return JSON.stringify(exports.ToolCall$outboundSchema.parse(toolCall)); + } + function toolCallFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolCall$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolCall' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/assistantmessage.js +var require_assistantmessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/assistantmessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AssistantMessage$outboundSchema = exports.AssistantMessage$inboundSchema = exports.AssistantMessageContent$outboundSchema = exports.AssistantMessageContent$inboundSchema = void 0; + exports.assistantMessageContentToJSON = assistantMessageContentToJSON; + exports.assistantMessageContentFromJSON = assistantMessageContentFromJSON; + exports.assistantMessageToJSON = assistantMessageToJSON; + exports.assistantMessageFromJSON = assistantMessageFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var contentchunk_js_1 = require_contentchunk(); + var toolcall_js_1 = require_toolcall(); + exports.AssistantMessageContent$inboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)]); + exports.AssistantMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]); + function assistantMessageContentToJSON(assistantMessageContent) { + return JSON.stringify(exports.AssistantMessageContent$outboundSchema.parse(assistantMessageContent)); + } + function assistantMessageContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AssistantMessageContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AssistantMessageContent' from JSON`); + } + exports.AssistantMessage$inboundSchema = z3.object({ + role: z3.literal("assistant").default("assistant"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)])).optional(), + tool_calls: z3.nullable(z3.array(toolcall_js_1.ToolCall$inboundSchema)).optional(), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_calls": "toolCalls" + }); + }); + exports.AssistantMessage$outboundSchema = z3.object({ + role: z3.literal("assistant").default("assistant"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])).optional(), + toolCalls: z3.nullable(z3.array(toolcall_js_1.ToolCall$outboundSchema)).optional(), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolCalls: "tool_calls" + }); + }); + function assistantMessageToJSON(assistantMessage) { + return JSON.stringify(exports.AssistantMessage$outboundSchema.parse(assistantMessage)); + } + function assistantMessageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AssistantMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AssistantMessage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/mistralpromptmode.js +var require_mistralpromptmode = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/mistralpromptmode.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralPromptMode$outboundSchema = exports.MistralPromptMode = void 0; + var openEnums = __importStar(require_enums()); + exports.MistralPromptMode = { + Reasoning: "reasoning" + }; + exports.MistralPromptMode$outboundSchema = openEnums.outboundSchema(exports.MistralPromptMode); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessagecontentchunks.js +var require_systemmessagecontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessagecontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SystemMessageContentChunks$outboundSchema = void 0; + exports.systemMessageContentChunksToJSON = systemMessageContentChunksToJSON; + var z3 = __importStar(require_v3()); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + exports.SystemMessageContentChunks$outboundSchema = z3.union([ + textchunk_js_1.TextChunk$outboundSchema.and(z3.object({ type: z3.literal("text") })), + thinkchunk_js_1.ThinkChunk$outboundSchema.and(z3.object({ type: z3.literal("thinking") })) + ]); + function systemMessageContentChunksToJSON(systemMessageContentChunks) { + return JSON.stringify(exports.SystemMessageContentChunks$outboundSchema.parse(systemMessageContentChunks)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessage.js +var require_systemmessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/systemmessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SystemMessage$outboundSchema = exports.SystemMessageContent$outboundSchema = void 0; + exports.systemMessageContentToJSON = systemMessageContentToJSON; + exports.systemMessageToJSON = systemMessageToJSON; + var z3 = __importStar(require_v3()); + var systemmessagecontentchunks_js_1 = require_systemmessagecontentchunks(); + exports.SystemMessageContent$outboundSchema = z3.union([z3.string(), z3.array(systemmessagecontentchunks_js_1.SystemMessageContentChunks$outboundSchema)]); + function systemMessageContentToJSON(systemMessageContent) { + return JSON.stringify(exports.SystemMessageContent$outboundSchema.parse(systemMessageContent)); + } + exports.SystemMessage$outboundSchema = z3.object({ + role: z3.literal("system").default("system"), + content: z3.union([ + z3.string(), + z3.array(systemmessagecontentchunks_js_1.SystemMessageContentChunks$outboundSchema) + ]) + }); + function systemMessageToJSON(systemMessage) { + return JSON.stringify(exports.SystemMessage$outboundSchema.parse(systemMessage)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/tool.js +var require_tool = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/tool.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Tool$outboundSchema = void 0; + exports.toolToJSON = toolToJSON; + var z3 = __importStar(require_v3()); + var function_js_1 = require_function(); + var tooltypes_js_1 = require_tooltypes(); + exports.Tool$outboundSchema = z3.object({ + type: tooltypes_js_1.ToolTypes$outboundSchema.optional(), + function: function_js_1.FunctionT$outboundSchema + }); + function toolToJSON(tool) { + return JSON.stringify(exports.Tool$outboundSchema.parse(tool)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functionname.js +var require_functionname = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functionname.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionName$outboundSchema = void 0; + exports.functionNameToJSON = functionNameToJSON; + var z3 = __importStar(require_v3()); + exports.FunctionName$outboundSchema = z3.object({ + name: z3.string() + }); + function functionNameToJSON(functionName) { + return JSON.stringify(exports.FunctionName$outboundSchema.parse(functionName)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoice.js +var require_toolchoice = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolchoice.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolChoice$outboundSchema = void 0; + exports.toolChoiceToJSON = toolChoiceToJSON; + var z3 = __importStar(require_v3()); + var functionname_js_1 = require_functionname(); + var tooltypes_js_1 = require_tooltypes(); + exports.ToolChoice$outboundSchema = z3.object({ + type: tooltypes_js_1.ToolTypes$outboundSchema.optional(), + function: functionname_js_1.FunctionName$outboundSchema + }); + function toolChoiceToJSON(toolChoice) { + return JSON.stringify(exports.ToolChoice$outboundSchema.parse(toolChoice)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolmessage.js +var require_toolmessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolmessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolMessage$outboundSchema = exports.ToolMessageContent$outboundSchema = void 0; + exports.toolMessageContentToJSON = toolMessageContentToJSON; + exports.toolMessageToJSON = toolMessageToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var contentchunk_js_1 = require_contentchunk(); + exports.ToolMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]); + function toolMessageContentToJSON(toolMessageContent) { + return JSON.stringify(exports.ToolMessageContent$outboundSchema.parse(toolMessageContent)); + } + exports.ToolMessage$outboundSchema = z3.object({ + role: z3.literal("tool").default("tool"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])), + toolCallId: z3.nullable(z3.string()).optional(), + name: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolCallId: "tool_call_id" + }); + }); + function toolMessageToJSON(toolMessage) { + return JSON.stringify(exports.ToolMessage$outboundSchema.parse(toolMessage)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/usermessage.js +var require_usermessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/usermessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UserMessage$outboundSchema = exports.UserMessageContent$outboundSchema = void 0; + exports.userMessageContentToJSON = userMessageContentToJSON; + exports.userMessageToJSON = userMessageToJSON; + var z3 = __importStar(require_v3()); + var contentchunk_js_1 = require_contentchunk(); + exports.UserMessageContent$outboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)]); + function userMessageContentToJSON(userMessageContent) { + return JSON.stringify(exports.UserMessageContent$outboundSchema.parse(userMessageContent)); + } + exports.UserMessage$outboundSchema = z3.object({ + role: z3.literal("user").default("user"), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$outboundSchema)])) + }); + function userMessageToJSON(userMessage) { + return JSON.stringify(exports.UserMessage$outboundSchema.parse(userMessage)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionrequest.js +var require_agentscompletionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsCompletionRequest$outboundSchema = exports.AgentsCompletionRequestToolChoice$outboundSchema = exports.AgentsCompletionRequestMessages$outboundSchema = exports.AgentsCompletionRequestStop$outboundSchema = void 0; + exports.agentsCompletionRequestStopToJSON = agentsCompletionRequestStopToJSON; + exports.agentsCompletionRequestMessagesToJSON = agentsCompletionRequestMessagesToJSON; + exports.agentsCompletionRequestToolChoiceToJSON = agentsCompletionRequestToolChoiceToJSON; + exports.agentsCompletionRequestToJSON = agentsCompletionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.AgentsCompletionRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function agentsCompletionRequestStopToJSON(agentsCompletionRequestStop) { + return JSON.stringify(exports.AgentsCompletionRequestStop$outboundSchema.parse(agentsCompletionRequestStop)); + } + exports.AgentsCompletionRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function agentsCompletionRequestMessagesToJSON(agentsCompletionRequestMessages) { + return JSON.stringify(exports.AgentsCompletionRequestMessages$outboundSchema.parse(agentsCompletionRequestMessages)); + } + exports.AgentsCompletionRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function agentsCompletionRequestToolChoiceToJSON(agentsCompletionRequestToolChoice) { + return JSON.stringify(exports.AgentsCompletionRequestToolChoice$outboundSchema.parse(agentsCompletionRequestToolChoice)); + } + exports.AgentsCompletionRequest$outboundSchema = z3.object({ + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(false), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + agentId: "agent_id" + }); + }); + function agentsCompletionRequestToJSON(agentsCompletionRequest) { + return JSON.stringify(exports.AgentsCompletionRequest$outboundSchema.parse(agentsCompletionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionstreamrequest.js +var require_agentscompletionstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentscompletionstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsCompletionStreamRequest$outboundSchema = exports.AgentsCompletionStreamRequestToolChoice$outboundSchema = exports.AgentsCompletionStreamRequestMessages$outboundSchema = exports.AgentsCompletionStreamRequestStop$outboundSchema = void 0; + exports.agentsCompletionStreamRequestStopToJSON = agentsCompletionStreamRequestStopToJSON; + exports.agentsCompletionStreamRequestMessagesToJSON = agentsCompletionStreamRequestMessagesToJSON; + exports.agentsCompletionStreamRequestToolChoiceToJSON = agentsCompletionStreamRequestToolChoiceToJSON; + exports.agentsCompletionStreamRequestToJSON = agentsCompletionStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.AgentsCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function agentsCompletionStreamRequestStopToJSON(agentsCompletionStreamRequestStop) { + return JSON.stringify(exports.AgentsCompletionStreamRequestStop$outboundSchema.parse(agentsCompletionStreamRequestStop)); + } + exports.AgentsCompletionStreamRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function agentsCompletionStreamRequestMessagesToJSON(agentsCompletionStreamRequestMessages) { + return JSON.stringify(exports.AgentsCompletionStreamRequestMessages$outboundSchema.parse(agentsCompletionStreamRequestMessages)); + } + exports.AgentsCompletionStreamRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function agentsCompletionStreamRequestToolChoiceToJSON(agentsCompletionStreamRequestToolChoice) { + return JSON.stringify(exports.AgentsCompletionStreamRequestToolChoice$outboundSchema.parse(agentsCompletionStreamRequestToolChoice)); + } + exports.AgentsCompletionStreamRequest$outboundSchema = z3.object({ + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(true), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + agentId: "agent_id" + }); + }); + function agentsCompletionStreamRequestToJSON(agentsCompletionStreamRequest) { + return JSON.stringify(exports.AgentsCompletionStreamRequest$outboundSchema.parse(agentsCompletionStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/agentupdaterequest.js +var require_agentupdaterequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/agentupdaterequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentUpdateRequest$outboundSchema = exports.AgentUpdateRequestTools$outboundSchema = void 0; + exports.agentUpdateRequestToolsToJSON = agentUpdateRequestToolsToJSON; + exports.agentUpdateRequestToJSON = agentUpdateRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.AgentUpdateRequestTools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function agentUpdateRequestToolsToJSON(agentUpdateRequestTools) { + return JSON.stringify(exports.AgentUpdateRequestTools$outboundSchema.parse(agentUpdateRequestTools)); + } + exports.AgentUpdateRequest$outboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + model: z3.nullable(z3.string()).optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + handoffs: z3.nullable(z3.array(z3.string())).optional(), + deploymentChat: z3.nullable(z3.boolean()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + versionMessage: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + completionArgs: "completion_args", + deploymentChat: "deployment_chat", + versionMessage: "version_message" + }); + }); + function agentUpdateRequestToJSON(agentUpdateRequest) { + return JSON.stringify(exports.AgentUpdateRequest$outboundSchema.parse(agentUpdateRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/apiendpoint.js +var require_apiendpoint = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/apiendpoint.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ApiEndpoint$outboundSchema = exports.ApiEndpoint = void 0; + var openEnums = __importStar(require_enums()); + exports.ApiEndpoint = { + RootV1ChatCompletions: "/v1/chat/completions", + RootV1Embeddings: "/v1/embeddings", + RootV1FimCompletions: "/v1/fim/completions", + RootV1Moderations: "/v1/moderations", + RootV1ChatModerations: "/v1/chat/moderations", + RootV1Ocr: "/v1/ocr", + RootV1Classifications: "/v1/classifications", + RootV1ChatClassifications: "/v1/chat/classifications", + RootV1Conversations: "/v1/conversations", + RootV1AudioTranscriptions: "/v1/audio/transcriptions" + }; + exports.ApiEndpoint$outboundSchema = openEnums.outboundSchema(exports.ApiEndpoint); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/archiveftmodelout.js +var require_archiveftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/archiveftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ArchiveFTModelOut$inboundSchema = void 0; + exports.archiveFTModelOutFromJSON = archiveFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.ArchiveFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + archived: z3.boolean().default(true) + }); + function archiveFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ArchiveFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ArchiveFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audioencoding.js +var require_audioencoding = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audioencoding.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioEncoding$outboundSchema = exports.AudioEncoding$inboundSchema = exports.AudioEncoding = void 0; + var openEnums = __importStar(require_enums()); + exports.AudioEncoding = { + PcmS16le: "pcm_s16le", + PcmS32le: "pcm_s32le", + PcmF16le: "pcm_f16le", + PcmF32le: "pcm_f32le", + PcmMulaw: "pcm_mulaw", + PcmAlaw: "pcm_alaw" + }; + exports.AudioEncoding$inboundSchema = openEnums.inboundSchema(exports.AudioEncoding); + exports.AudioEncoding$outboundSchema = openEnums.outboundSchema(exports.AudioEncoding); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audioformat.js +var require_audioformat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audioformat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioFormat$outboundSchema = exports.AudioFormat$inboundSchema = void 0; + exports.audioFormatToJSON = audioFormatToJSON; + exports.audioFormatFromJSON = audioFormatFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var audioencoding_js_1 = require_audioencoding(); + exports.AudioFormat$inboundSchema = z3.object({ + encoding: audioencoding_js_1.AudioEncoding$inboundSchema, + sample_rate: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "sample_rate": "sampleRate" + }); + }); + exports.AudioFormat$outboundSchema = z3.object({ + encoding: audioencoding_js_1.AudioEncoding$outboundSchema, + sampleRate: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + sampleRate: "sample_rate" + }); + }); + function audioFormatToJSON(audioFormat) { + return JSON.stringify(exports.AudioFormat$outboundSchema.parse(audioFormat)); + } + function audioFormatFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AudioFormat$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AudioFormat' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/blobs.js +var require_blobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/blobs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.blobLikeSchema = void 0; + exports.isBlobLike = isBlobLike4; + var z3 = __importStar(require_v3()); + exports.blobLikeSchema = z3.custom(isBlobLike4, { + message: "expected a Blob, File or Blob-like object", + fatal: true + }); + function isBlobLike4(val2) { + if (val2 instanceof Blob) { + return true; + } + if (typeof val2 !== "object" || val2 == null || !(Symbol.toStringTag in val2)) { + return false; + } + const name = val2[Symbol.toStringTag]; + if (typeof name !== "string") { + return false; + } + if (name !== "Blob" && name !== "File") { + return false; + } + return "stream" in val2 && typeof val2.stream === "function"; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/file.js +var require_file = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/file.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileT$outboundSchema = void 0; + exports.fileToJSON = fileToJSON; + var z3 = __importStar(require_v3()); + exports.FileT$outboundSchema = z3.object({ + fileName: z3.string(), + content: z3.union([ + z3.instanceof(ReadableStream), + z3.instanceof(Blob), + z3.instanceof(ArrayBuffer), + z3.instanceof(Uint8Array) + ]) + }); + function fileToJSON(fileT) { + return JSON.stringify(exports.FileT$outboundSchema.parse(fileT)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/timestampgranularity.js +var require_timestampgranularity = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/timestampgranularity.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TimestampGranularity$outboundSchema = exports.TimestampGranularity = void 0; + var z3 = __importStar(require_v3()); + exports.TimestampGranularity = { + Segment: "segment", + Word: "word" + }; + exports.TimestampGranularity$outboundSchema = z3.nativeEnum(exports.TimestampGranularity); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequest.js +var require_audiotranscriptionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioTranscriptionRequest$outboundSchema = void 0; + exports.audioTranscriptionRequestToJSON = audioTranscriptionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var blobs_js_1 = require_blobs(); + var file_js_1 = require_file(); + var timestampgranularity_js_1 = require_timestampgranularity(); + exports.AudioTranscriptionRequest$outboundSchema = z3.object({ + model: z3.string(), + file: file_js_1.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema).optional(), + fileUrl: z3.nullable(z3.string()).optional(), + fileId: z3.nullable(z3.string()).optional(), + language: z3.nullable(z3.string()).optional(), + temperature: z3.nullable(z3.number()).optional(), + stream: z3.literal(false).default(false), + diarize: z3.boolean().default(false), + contextBias: z3.array(z3.string()).optional(), + timestampGranularities: z3.array(timestampgranularity_js_1.TimestampGranularity$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileUrl: "file_url", + fileId: "file_id", + contextBias: "context_bias", + timestampGranularities: "timestamp_granularities" + }); + }); + function audioTranscriptionRequestToJSON(audioTranscriptionRequest) { + return JSON.stringify(exports.AudioTranscriptionRequest$outboundSchema.parse(audioTranscriptionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequeststream.js +var require_audiotranscriptionrequeststream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/audiotranscriptionrequeststream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AudioTranscriptionRequestStream$outboundSchema = void 0; + exports.audioTranscriptionRequestStreamToJSON = audioTranscriptionRequestStreamToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var blobs_js_1 = require_blobs(); + var file_js_1 = require_file(); + var timestampgranularity_js_1 = require_timestampgranularity(); + exports.AudioTranscriptionRequestStream$outboundSchema = z3.object({ + model: z3.string(), + file: file_js_1.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema).optional(), + fileUrl: z3.nullable(z3.string()).optional(), + fileId: z3.nullable(z3.string()).optional(), + language: z3.nullable(z3.string()).optional(), + temperature: z3.nullable(z3.number()).optional(), + stream: z3.literal(true).default(true), + diarize: z3.boolean().default(false), + contextBias: z3.array(z3.string()).optional(), + timestampGranularities: z3.array(timestampgranularity_js_1.TimestampGranularity$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileUrl: "file_url", + fileId: "file_id", + contextBias: "context_bias", + timestampGranularities: "timestamp_granularities" + }); + }); + function audioTranscriptionRequestStreamToJSON(audioTranscriptionRequestStream) { + return JSON.stringify(exports.AudioTranscriptionRequestStream$outboundSchema.parse(audioTranscriptionRequestStream)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modelcapabilities.js +var require_modelcapabilities = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/modelcapabilities.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModelCapabilities$inboundSchema = void 0; + exports.modelCapabilitiesFromJSON = modelCapabilitiesFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ModelCapabilities$inboundSchema = z3.object({ + completion_chat: z3.boolean().default(false), + function_calling: z3.boolean().default(false), + completion_fim: z3.boolean().default(false), + fine_tuning: z3.boolean().default(false), + vision: z3.boolean().default(false), + ocr: z3.boolean().default(false), + classification: z3.boolean().default(false), + moderation: z3.boolean().default(false), + audio: z3.boolean().default(false), + audio_transcription: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_chat": "completionChat", + "function_calling": "functionCalling", + "completion_fim": "completionFim", + "fine_tuning": "fineTuning", + "audio_transcription": "audioTranscription" + }); + }); + function modelCapabilitiesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelCapabilities$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelCapabilities' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/basemodelcard.js +var require_basemodelcard = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/basemodelcard.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaseModelCard$inboundSchema = void 0; + exports.baseModelCardFromJSON = baseModelCardFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var modelcapabilities_js_1 = require_modelcapabilities(); + exports.BaseModelCard$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().default("model"), + created: z3.number().int().optional(), + owned_by: z3.string().default("mistralai"), + capabilities: modelcapabilities_js_1.ModelCapabilities$inboundSchema, + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + deprecation: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + deprecation_replacement_model: z3.nullable(z3.string()).optional(), + default_model_temperature: z3.nullable(z3.number()).optional(), + type: z3.literal("base").default("base") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "max_context_length": "maxContextLength", + "deprecation_replacement_model": "deprecationReplacementModel", + "default_model_temperature": "defaultModelTemperature" + }); + }); + function baseModelCardFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BaseModelCard$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BaseModelCard' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batcherror.js +var require_batcherror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batcherror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchError$inboundSchema = void 0; + exports.batchErrorFromJSON = batchErrorFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.BatchError$inboundSchema = z3.object({ + message: z3.string(), + count: z3.number().int().default(1) + }); + function batchErrorFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchError' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchrequest.js +var require_batchrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchRequest$outboundSchema = void 0; + exports.batchRequestToJSON = batchRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.BatchRequest$outboundSchema = z3.object({ + customId: z3.nullable(z3.string()).optional(), + body: z3.record(z3.any()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + customId: "custom_id" + }); + }); + function batchRequestToJSON(batchRequest) { + return JSON.stringify(exports.BatchRequest$outboundSchema.parse(batchRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobin.js +var require_batchjobin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobIn$outboundSchema = void 0; + exports.batchJobInToJSON = batchJobInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var apiendpoint_js_1 = require_apiendpoint(); + var batchrequest_js_1 = require_batchrequest(); + exports.BatchJobIn$outboundSchema = z3.object({ + inputFiles: z3.nullable(z3.array(z3.string())).optional(), + requests: z3.nullable(z3.array(batchrequest_js_1.BatchRequest$outboundSchema)).optional(), + endpoint: apiendpoint_js_1.ApiEndpoint$outboundSchema, + model: z3.nullable(z3.string()).optional(), + agentId: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.string())).optional(), + timeoutHours: z3.number().int().default(24) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputFiles: "input_files", + agentId: "agent_id", + timeoutHours: "timeout_hours" + }); + }); + function batchJobInToJSON(batchJobIn) { + return JSON.stringify(exports.BatchJobIn$outboundSchema.parse(batchJobIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobstatus.js +var require_batchjobstatus = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobstatus.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema = exports.BatchJobStatus = void 0; + var z3 = __importStar(require_v3()); + exports.BatchJobStatus = { + Queued: "QUEUED", + Running: "RUNNING", + Success: "SUCCESS", + Failed: "FAILED", + TimeoutExceeded: "TIMEOUT_EXCEEDED", + CancellationRequested: "CANCELLATION_REQUESTED", + Cancelled: "CANCELLED" + }; + exports.BatchJobStatus$inboundSchema = z3.nativeEnum(exports.BatchJobStatus); + exports.BatchJobStatus$outboundSchema = exports.BatchJobStatus$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobout.js +var require_batchjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobOut$inboundSchema = void 0; + exports.batchJobOutFromJSON = batchJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var batcherror_js_1 = require_batcherror(); + var batchjobstatus_js_1 = require_batchjobstatus(); + exports.BatchJobOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("batch").default("batch"), + input_files: z3.array(z3.string()), + metadata: z3.nullable(z3.record(z3.any())).optional(), + endpoint: z3.string(), + model: z3.nullable(z3.string()).optional(), + agent_id: z3.nullable(z3.string()).optional(), + output_file: z3.nullable(z3.string()).optional(), + error_file: z3.nullable(z3.string()).optional(), + errors: z3.array(batcherror_js_1.BatchError$inboundSchema), + outputs: z3.nullable(z3.array(z3.record(z3.any()))).optional(), + status: batchjobstatus_js_1.BatchJobStatus$inboundSchema, + created_at: z3.number().int(), + total_requests: z3.number().int(), + completed_requests: z3.number().int(), + succeeded_requests: z3.number().int(), + failed_requests: z3.number().int(), + started_at: z3.nullable(z3.number().int()).optional(), + completed_at: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "input_files": "inputFiles", + "agent_id": "agentId", + "output_file": "outputFile", + "error_file": "errorFile", + "created_at": "createdAt", + "total_requests": "totalRequests", + "completed_requests": "completedRequests", + "succeeded_requests": "succeededRequests", + "failed_requests": "failedRequests", + "started_at": "startedAt", + "completed_at": "completedAt" + }); + }); + function batchJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobsout.js +var require_batchjobsout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/batchjobsout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BatchJobsOut$inboundSchema = void 0; + exports.batchJobsOutFromJSON = batchJobsOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var batchjobout_js_1 = require_batchjobout(); + exports.BatchJobsOut$inboundSchema = z3.object({ + data: z3.array(batchjobout_js_1.BatchJobOut$inboundSchema).optional(), + object: z3.literal("list").default("list"), + total: z3.number().int() + }); + function batchJobsOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.BatchJobsOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'BatchJobsOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/instructrequest.js +var require_instructrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/instructrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InstructRequest$outboundSchema = exports.InstructRequestMessages$outboundSchema = void 0; + exports.instructRequestMessagesToJSON = instructRequestMessagesToJSON; + exports.instructRequestToJSON = instructRequestToJSON; + var z3 = __importStar(require_v3()); + var assistantmessage_js_1 = require_assistantmessage(); + var systemmessage_js_1 = require_systemmessage(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.InstructRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function instructRequestMessagesToJSON(instructRequestMessages) { + return JSON.stringify(exports.InstructRequestMessages$outboundSchema.parse(instructRequestMessages)); + } + exports.InstructRequest$outboundSchema = z3.object({ + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])) + }); + function instructRequestToJSON(instructRequest) { + return JSON.stringify(exports.InstructRequest$outboundSchema.parse(instructRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/inputs.js +var require_inputs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/inputs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Inputs$outboundSchema = void 0; + exports.inputsToJSON = inputsToJSON; + var z3 = __importStar(require_v3()); + var instructrequest_js_1 = require_instructrequest(); + exports.Inputs$outboundSchema = z3.union([ + instructrequest_js_1.InstructRequest$outboundSchema, + z3.array(instructrequest_js_1.InstructRequest$outboundSchema) + ]); + function inputsToJSON(inputs) { + return JSON.stringify(exports.Inputs$outboundSchema.parse(inputs)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatclassificationrequest.js +var require_chatclassificationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatclassificationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatClassificationRequest$outboundSchema = void 0; + exports.chatClassificationRequestToJSON = chatClassificationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var inputs_js_1 = require_inputs(); + exports.ChatClassificationRequest$outboundSchema = z3.object({ + model: z3.string(), + inputs: inputs_js_1.Inputs$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input" + }); + }); + function chatClassificationRequestToJSON(chatClassificationRequest) { + return JSON.stringify(exports.ChatClassificationRequest$outboundSchema.parse(chatClassificationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionchoice.js +var require_chatcompletionchoice = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionchoice.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionChoice$inboundSchema = exports.FinishReason$inboundSchema = exports.FinishReason = void 0; + exports.chatCompletionChoiceFromJSON = chatCompletionChoiceFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var openEnums = __importStar(require_enums()); + var assistantmessage_js_1 = require_assistantmessage(); + exports.FinishReason = { + Stop: "stop", + Length: "length", + ModelLength: "model_length", + Error: "error", + ToolCalls: "tool_calls" + }; + exports.FinishReason$inboundSchema = openEnums.inboundSchema(exports.FinishReason); + exports.ChatCompletionChoice$inboundSchema = z3.object({ + index: z3.number().int(), + message: assistantmessage_js_1.AssistantMessage$inboundSchema, + finish_reason: exports.FinishReason$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "finish_reason": "finishReason" + }); + }); + function chatCompletionChoiceFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ChatCompletionChoice$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ChatCompletionChoice' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionrequest.js +var require_chatcompletionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionRequest$outboundSchema = exports.ChatCompletionRequestToolChoice$outboundSchema = exports.Messages$outboundSchema = exports.Stop$outboundSchema = void 0; + exports.stopToJSON = stopToJSON; + exports.messagesToJSON = messagesToJSON; + exports.chatCompletionRequestToolChoiceToJSON = chatCompletionRequestToolChoiceToJSON; + exports.chatCompletionRequestToJSON = chatCompletionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.Stop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function stopToJSON(stop) { + return JSON.stringify(exports.Stop$outboundSchema.parse(stop)); + } + exports.Messages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function messagesToJSON(messages) { + return JSON.stringify(exports.Messages$outboundSchema.parse(messages)); + } + exports.ChatCompletionRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function chatCompletionRequestToolChoiceToJSON(chatCompletionRequestToolChoice) { + return JSON.stringify(exports.ChatCompletionRequestToolChoice$outboundSchema.parse(chatCompletionRequestToolChoice)); + } + exports.ChatCompletionRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().optional(), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(false), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + safePrompt: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + safePrompt: "safe_prompt" + }); + }); + function chatCompletionRequestToJSON(chatCompletionRequest) { + return JSON.stringify(exports.ChatCompletionRequest$outboundSchema.parse(chatCompletionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/usageinfo.js +var require_usageinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/usageinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UsageInfo$outboundSchema = exports.UsageInfo$inboundSchema = void 0; + exports.usageInfoToJSON = usageInfoToJSON; + exports.usageInfoFromJSON = usageInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.UsageInfo$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + prompt_tokens: z3.number().int().default(0), + completion_tokens: z3.number().int().default(0), + total_tokens: z3.number().int().default(0), + prompt_audio_seconds: z3.nullable(z3.number().int()).optional() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "prompt_tokens": "promptTokens", + "completion_tokens": "completionTokens", + "total_tokens": "totalTokens", + "prompt_audio_seconds": "promptAudioSeconds" + }); + }); + exports.UsageInfo$outboundSchema = z3.object({ + promptTokens: z3.number().int().default(0), + completionTokens: z3.number().int().default(0), + totalTokens: z3.number().int().default(0), + promptAudioSeconds: z3.nullable(z3.number().int()).optional(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + promptTokens: "prompt_tokens", + completionTokens: "completion_tokens", + totalTokens: "total_tokens", + promptAudioSeconds: "prompt_audio_seconds", + additionalProperties: null + }) + }; + }); + function usageInfoToJSON(usageInfo) { + return JSON.stringify(exports.UsageInfo$outboundSchema.parse(usageInfo)); + } + function usageInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UsageInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionresponse.js +var require_chatcompletionresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionResponse$inboundSchema = void 0; + exports.chatCompletionResponseFromJSON = chatCompletionResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var chatcompletionchoice_js_1 = require_chatcompletionchoice(); + var usageinfo_js_1 = require_usageinfo(); + exports.ChatCompletionResponse$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + created: z3.number().int(), + choices: z3.array(chatcompletionchoice_js_1.ChatCompletionChoice$inboundSchema) + }); + function chatCompletionResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ChatCompletionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ChatCompletionResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionstreamrequest.js +var require_chatcompletionstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatcompletionstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatCompletionStreamRequest$outboundSchema = exports.ChatCompletionStreamRequestToolChoice$outboundSchema = exports.ChatCompletionStreamRequestMessages$outboundSchema = exports.ChatCompletionStreamRequestStop$outboundSchema = void 0; + exports.chatCompletionStreamRequestStopToJSON = chatCompletionStreamRequestStopToJSON; + exports.chatCompletionStreamRequestMessagesToJSON = chatCompletionStreamRequestMessagesToJSON; + exports.chatCompletionStreamRequestToolChoiceToJSON = chatCompletionStreamRequestToolChoiceToJSON; + exports.chatCompletionStreamRequestToJSON = chatCompletionStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var mistralpromptmode_js_1 = require_mistralpromptmode(); + var prediction_js_1 = require_prediction(); + var responseformat_js_1 = require_responseformat(); + var systemmessage_js_1 = require_systemmessage(); + var tool_js_1 = require_tool(); + var toolchoice_js_1 = require_toolchoice(); + var toolchoiceenum_js_1 = require_toolchoiceenum(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.ChatCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function chatCompletionStreamRequestStopToJSON(chatCompletionStreamRequestStop) { + return JSON.stringify(exports.ChatCompletionStreamRequestStop$outboundSchema.parse(chatCompletionStreamRequestStop)); + } + exports.ChatCompletionStreamRequestMessages$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function chatCompletionStreamRequestMessagesToJSON(chatCompletionStreamRequestMessages) { + return JSON.stringify(exports.ChatCompletionStreamRequestMessages$outboundSchema.parse(chatCompletionStreamRequestMessages)); + } + exports.ChatCompletionStreamRequestToolChoice$outboundSchema = z3.union([toolchoice_js_1.ToolChoice$outboundSchema, toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema]); + function chatCompletionStreamRequestToolChoiceToJSON(chatCompletionStreamRequestToolChoice) { + return JSON.stringify(exports.ChatCompletionStreamRequestToolChoice$outboundSchema.parse(chatCompletionStreamRequestToolChoice)); + } + exports.ChatCompletionStreamRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().optional(), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(true), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + messages: z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + responseFormat: responseformat_js_1.ResponseFormat$outboundSchema.optional(), + tools: z3.nullable(z3.array(tool_js_1.Tool$outboundSchema)).optional(), + toolChoice: z3.union([ + toolchoice_js_1.ToolChoice$outboundSchema, + toolchoiceenum_js_1.ToolChoiceEnum$outboundSchema + ]).optional(), + presencePenalty: z3.number().optional(), + frequencyPenalty: z3.number().optional(), + n: z3.nullable(z3.number().int()).optional(), + prediction: prediction_js_1.Prediction$outboundSchema.optional(), + parallelToolCalls: z3.boolean().optional(), + promptMode: z3.nullable(mistralpromptmode_js_1.MistralPromptMode$outboundSchema).optional(), + safePrompt: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + responseFormat: "response_format", + toolChoice: "tool_choice", + presencePenalty: "presence_penalty", + frequencyPenalty: "frequency_penalty", + parallelToolCalls: "parallel_tool_calls", + promptMode: "prompt_mode", + safePrompt: "safe_prompt" + }); + }); + function chatCompletionStreamRequestToJSON(chatCompletionStreamRequest) { + return JSON.stringify(exports.ChatCompletionStreamRequest$outboundSchema.parse(chatCompletionStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/chatmoderationrequest.js +var require_chatmoderationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/chatmoderationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ChatModerationRequest$outboundSchema = exports.ChatModerationRequestInputs$outboundSchema = exports.One$outboundSchema = exports.Two$outboundSchema = void 0; + exports.twoToJSON = twoToJSON; + exports.oneToJSON = oneToJSON; + exports.chatModerationRequestInputsToJSON = chatModerationRequestInputsToJSON; + exports.chatModerationRequestToJSON = chatModerationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var assistantmessage_js_1 = require_assistantmessage(); + var systemmessage_js_1 = require_systemmessage(); + var toolmessage_js_1 = require_toolmessage(); + var usermessage_js_1 = require_usermessage(); + exports.Two$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function twoToJSON(two) { + return JSON.stringify(exports.Two$outboundSchema.parse(two)); + } + exports.One$outboundSchema = z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]); + function oneToJSON(one) { + return JSON.stringify(exports.One$outboundSchema.parse(one)); + } + exports.ChatModerationRequestInputs$outboundSchema = z3.union([ + z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + z3.array(z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]))) + ]); + function chatModerationRequestInputsToJSON(chatModerationRequestInputs) { + return JSON.stringify(exports.ChatModerationRequestInputs$outboundSchema.parse(chatModerationRequestInputs)); + } + exports.ChatModerationRequest$outboundSchema = z3.object({ + inputs: z3.union([ + z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ])), + z3.array(z3.array(z3.union([ + assistantmessage_js_1.AssistantMessage$outboundSchema.and(z3.object({ role: z3.literal("assistant") })), + systemmessage_js_1.SystemMessage$outboundSchema.and(z3.object({ role: z3.literal("system") })), + toolmessage_js_1.ToolMessage$outboundSchema.and(z3.object({ role: z3.literal("tool") })), + usermessage_js_1.UserMessage$outboundSchema.and(z3.object({ role: z3.literal("user") })) + ]))) + ]), + model: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input" + }); + }); + function chatModerationRequestToJSON(chatModerationRequest) { + return JSON.stringify(exports.ChatModerationRequest$outboundSchema.parse(chatModerationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/metricout.js +var require_metricout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/metricout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MetricOut$inboundSchema = void 0; + exports.metricOutFromJSON = metricOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.MetricOut$inboundSchema = z3.object({ + train_loss: z3.nullable(z3.number()).optional(), + valid_loss: z3.nullable(z3.number()).optional(), + valid_mean_token_accuracy: z3.nullable(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "train_loss": "trainLoss", + "valid_loss": "validLoss", + "valid_mean_token_accuracy": "validMeanTokenAccuracy" + }); + }); + function metricOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MetricOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MetricOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/checkpointout.js +var require_checkpointout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/checkpointout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CheckpointOut$inboundSchema = void 0; + exports.checkpointOutFromJSON = checkpointOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var metricout_js_1 = require_metricout(); + exports.CheckpointOut$inboundSchema = z3.object({ + metrics: metricout_js_1.MetricOut$inboundSchema, + step_number: z3.number().int(), + created_at: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "step_number": "stepNumber", + "created_at": "createdAt" + }); + }); + function checkpointOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CheckpointOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CheckpointOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationrequest.js +var require_classificationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassificationRequest$outboundSchema = exports.ClassificationRequestInputs$outboundSchema = void 0; + exports.classificationRequestInputsToJSON = classificationRequestInputsToJSON; + exports.classificationRequestToJSON = classificationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.ClassificationRequestInputs$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function classificationRequestInputsToJSON(classificationRequestInputs) { + return JSON.stringify(exports.ClassificationRequestInputs$outboundSchema.parse(classificationRequestInputs)); + } + exports.ClassificationRequest$outboundSchema = z3.object({ + model: z3.string(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + inputs: z3.union([z3.string(), z3.array(z3.string())]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input" + }); + }); + function classificationRequestToJSON(classificationRequest) { + return JSON.stringify(exports.ClassificationRequest$outboundSchema.parse(classificationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationtargetresult.js +var require_classificationtargetresult = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationtargetresult.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassificationTargetResult$inboundSchema = void 0; + exports.classificationTargetResultFromJSON = classificationTargetResultFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.ClassificationTargetResult$inboundSchema = z3.object({ + scores: z3.record(z3.number()) + }); + function classificationTargetResultFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassificationTargetResult$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassificationTargetResult' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationresponse.js +var require_classificationresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classificationresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassificationResponse$inboundSchema = void 0; + exports.classificationResponseFromJSON = classificationResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var classificationtargetresult_js_1 = require_classificationtargetresult(); + exports.ClassificationResponse$inboundSchema = z3.object({ + id: z3.string(), + model: z3.string(), + results: z3.array(z3.record(classificationtargetresult_js_1.ClassificationTargetResult$inboundSchema)) + }); + function classificationResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassificationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassificationResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftclassifierlossfunction.js +var require_ftclassifierlossfunction = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftclassifierlossfunction.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FTClassifierLossFunction$outboundSchema = exports.FTClassifierLossFunction$inboundSchema = exports.FTClassifierLossFunction = void 0; + var z3 = __importStar(require_v3()); + exports.FTClassifierLossFunction = { + SingleClass: "single_class", + MultiClass: "multi_class" + }; + exports.FTClassifierLossFunction$inboundSchema = z3.nativeEnum(exports.FTClassifierLossFunction); + exports.FTClassifierLossFunction$outboundSchema = exports.FTClassifierLossFunction$inboundSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetout.js +var require_classifiertargetout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTargetOut$inboundSchema = void 0; + exports.classifierTargetOutFromJSON = classifierTargetOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var ftclassifierlossfunction_js_1 = require_ftclassifierlossfunction(); + exports.ClassifierTargetOut$inboundSchema = z3.object({ + name: z3.string(), + labels: z3.array(z3.string()), + weight: z3.number(), + loss_function: ftclassifierlossfunction_js_1.FTClassifierLossFunction$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "loss_function": "lossFunction" + }); + }); + function classifierTargetOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierTargetOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierTargetOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparameters.js +var require_classifiertrainingparameters = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparameters.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTrainingParameters$inboundSchema = void 0; + exports.classifierTrainingParametersFromJSON = classifierTrainingParametersFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ClassifierTrainingParameters$inboundSchema = z3.object({ + training_steps: z3.nullable(z3.number().int()).optional(), + learning_rate: z3.number().default(1e-4), + weight_decay: z3.nullable(z3.number()).optional(), + warmup_fraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seq_len: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "training_steps": "trainingSteps", + "learning_rate": "learningRate", + "weight_decay": "weightDecay", + "warmup_fraction": "warmupFraction", + "seq_len": "seqLen" + }); + }); + function classifierTrainingParametersFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierTrainingParameters$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierTrainingParameters' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/eventout.js +var require_eventout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/eventout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EventOut$inboundSchema = void 0; + exports.eventOutFromJSON = eventOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.EventOut$inboundSchema = z3.object({ + name: z3.string(), + data: z3.nullable(z3.record(z3.any())).optional(), + created_at: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt" + }); + }); + function eventOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EventOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EventOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobmetadataout.js +var require_jobmetadataout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobmetadataout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobMetadataOut$inboundSchema = void 0; + exports.jobMetadataOutFromJSON = jobMetadataOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.JobMetadataOut$inboundSchema = z3.object({ + expected_duration_seconds: z3.nullable(z3.number().int()).optional(), + cost: z3.nullable(z3.number()).optional(), + cost_currency: z3.nullable(z3.string()).optional(), + train_tokens_per_step: z3.nullable(z3.number().int()).optional(), + train_tokens: z3.nullable(z3.number().int()).optional(), + data_tokens: z3.nullable(z3.number().int()).optional(), + estimated_start_time: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "expected_duration_seconds": "expectedDurationSeconds", + "cost_currency": "costCurrency", + "train_tokens_per_step": "trainTokensPerStep", + "train_tokens": "trainTokens", + "data_tokens": "dataTokens", + "estimated_start_time": "estimatedStartTime" + }); + }); + function jobMetadataOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobMetadataOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobMetadataOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegrationout.js +var require_wandbintegrationout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegrationout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WandbIntegrationOut$inboundSchema = void 0; + exports.wandbIntegrationOutFromJSON = wandbIntegrationOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.WandbIntegrationOut$inboundSchema = z3.object({ + type: z3.literal("wandb").default("wandb"), + project: z3.string(), + name: z3.nullable(z3.string()).optional(), + run_name: z3.nullable(z3.string()).optional(), + url: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "run_name": "runName" + }); + }); + function wandbIntegrationOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.WandbIntegrationOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'WandbIntegrationOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierdetailedjobout.js +var require_classifierdetailedjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierdetailedjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierDetailedJobOut$inboundSchema = exports.ClassifierDetailedJobOutIntegrations$inboundSchema = exports.ClassifierDetailedJobOutStatus$inboundSchema = exports.ClassifierDetailedJobOutStatus = void 0; + exports.classifierDetailedJobOutIntegrationsFromJSON = classifierDetailedJobOutIntegrationsFromJSON; + exports.classifierDetailedJobOutFromJSON = classifierDetailedJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var checkpointout_js_1 = require_checkpointout(); + var classifiertargetout_js_1 = require_classifiertargetout(); + var classifiertrainingparameters_js_1 = require_classifiertrainingparameters(); + var eventout_js_1 = require_eventout(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.ClassifierDetailedJobOutStatus = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.ClassifierDetailedJobOutStatus$inboundSchema = z3.nativeEnum(exports.ClassifierDetailedJobOutStatus); + exports.ClassifierDetailedJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function classifierDetailedJobOutIntegrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierDetailedJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierDetailedJobOutIntegrations' from JSON`); + } + exports.ClassifierDetailedJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.ClassifierDetailedJobOutStatus$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("classifier").default("classifier"), + hyperparameters: classifiertrainingparameters_js_1.ClassifierTrainingParameters$inboundSchema, + events: z3.array(eventout_js_1.EventOut$inboundSchema).optional(), + checkpoints: z3.array(checkpointout_js_1.CheckpointOut$inboundSchema).optional(), + classifier_targets: z3.array(classifiertargetout_js_1.ClassifierTargetOut$inboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType", + "classifier_targets": "classifierTargets" + }); + }); + function classifierDetailedJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierDetailedJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierDetailedJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcapabilitiesout.js +var require_ftmodelcapabilitiesout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcapabilitiesout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FTModelCapabilitiesOut$inboundSchema = void 0; + exports.ftModelCapabilitiesOutFromJSON = ftModelCapabilitiesOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FTModelCapabilitiesOut$inboundSchema = z3.object({ + completion_chat: z3.boolean().default(true), + completion_fim: z3.boolean().default(false), + function_calling: z3.boolean().default(false), + fine_tuning: z3.boolean().default(false), + classification: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_chat": "completionChat", + "completion_fim": "completionFim", + "function_calling": "functionCalling", + "fine_tuning": "fineTuning" + }); + }); + function ftModelCapabilitiesOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FTModelCapabilitiesOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FTModelCapabilitiesOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierftmodelout.js +var require_classifierftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierFTModelOut$inboundSchema = void 0; + exports.classifierFTModelOutFromJSON = classifierFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var classifiertargetout_js_1 = require_classifiertargetout(); + var ftmodelcapabilitiesout_js_1 = require_ftmodelcapabilitiesout(); + exports.ClassifierFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + created: z3.number().int(), + owned_by: z3.string(), + workspace_id: z3.string(), + root: z3.string(), + root_version: z3.string(), + archived: z3.boolean(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + capabilities: ftmodelcapabilitiesout_js_1.FTModelCapabilitiesOut$inboundSchema, + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + job: z3.string(), + classifier_targets: z3.array(classifiertargetout_js_1.ClassifierTargetOut$inboundSchema), + model_type: z3.literal("classifier").default("classifier") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "workspace_id": "workspaceId", + "root_version": "rootVersion", + "max_context_length": "maxContextLength", + "classifier_targets": "classifierTargets", + "model_type": "modelType" + }); + }); + function classifierFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierjobout.js +var require_classifierjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifierjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierJobOut$inboundSchema = exports.ClassifierJobOutIntegrations$inboundSchema = exports.ClassifierJobOutStatus$inboundSchema = exports.ClassifierJobOutStatus = void 0; + exports.classifierJobOutIntegrationsFromJSON = classifierJobOutIntegrationsFromJSON; + exports.classifierJobOutFromJSON = classifierJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var classifiertrainingparameters_js_1 = require_classifiertrainingparameters(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.ClassifierJobOutStatus = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.ClassifierJobOutStatus$inboundSchema = z3.nativeEnum(exports.ClassifierJobOutStatus); + exports.ClassifierJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function classifierJobOutIntegrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierJobOutIntegrations' from JSON`); + } + exports.ClassifierJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.ClassifierJobOutStatus$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("classifier").default("classifier"), + hyperparameters: classifiertrainingparameters_js_1.ClassifierTrainingParameters$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType" + }); + }); + function classifierJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ClassifierJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ClassifierJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetin.js +var require_classifiertargetin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertargetin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTargetIn$outboundSchema = void 0; + exports.classifierTargetInToJSON = classifierTargetInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var ftclassifierlossfunction_js_1 = require_ftclassifierlossfunction(); + exports.ClassifierTargetIn$outboundSchema = z3.object({ + name: z3.string(), + labels: z3.array(z3.string()), + weight: z3.number().default(1), + lossFunction: z3.nullable(ftclassifierlossfunction_js_1.FTClassifierLossFunction$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + lossFunction: "loss_function" + }); + }); + function classifierTargetInToJSON(classifierTargetIn) { + return JSON.stringify(exports.ClassifierTargetIn$outboundSchema.parse(classifierTargetIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparametersin.js +var require_classifiertrainingparametersin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/classifiertrainingparametersin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ClassifierTrainingParametersIn$outboundSchema = void 0; + exports.classifierTrainingParametersInToJSON = classifierTrainingParametersInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.ClassifierTrainingParametersIn$outboundSchema = z3.object({ + trainingSteps: z3.nullable(z3.number().int()).optional(), + learningRate: z3.number().default(1e-4), + weightDecay: z3.nullable(z3.number()).optional(), + warmupFraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seqLen: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + trainingSteps: "training_steps", + learningRate: "learning_rate", + weightDecay: "weight_decay", + warmupFraction: "warmup_fraction", + seqLen: "seq_len" + }); + }); + function classifierTrainingParametersInToJSON(classifierTrainingParametersIn) { + return JSON.stringify(exports.ClassifierTrainingParametersIn$outboundSchema.parse(classifierTrainingParametersIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deltamessage.js +var require_deltamessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/deltamessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeltaMessage$inboundSchema = exports.Content$inboundSchema = void 0; + exports.contentFromJSON = contentFromJSON; + exports.deltaMessageFromJSON = deltaMessageFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var contentchunk_js_1 = require_contentchunk(); + var toolcall_js_1 = require_toolcall(); + exports.Content$inboundSchema = z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)]); + function contentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Content$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Content' from JSON`); + } + exports.DeltaMessage$inboundSchema = z3.object({ + role: z3.nullable(z3.string()).optional(), + content: z3.nullable(z3.union([z3.string(), z3.array(contentchunk_js_1.ContentChunk$inboundSchema)])).optional(), + tool_calls: z3.nullable(z3.array(toolcall_js_1.ToolCall$inboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "tool_calls": "toolCalls" + }); + }); + function deltaMessageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeltaMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeltaMessage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionresponsestreamchoice.js +var require_completionresponsestreamchoice = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionresponsestreamchoice.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionResponseStreamChoice$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = exports.CompletionResponseStreamChoiceFinishReason = void 0; + exports.completionResponseStreamChoiceFromJSON = completionResponseStreamChoiceFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var openEnums = __importStar(require_enums()); + var deltamessage_js_1 = require_deltamessage(); + exports.CompletionResponseStreamChoiceFinishReason = { + Stop: "stop", + Length: "length", + Error: "error", + ToolCalls: "tool_calls" + }; + exports.CompletionResponseStreamChoiceFinishReason$inboundSchema = openEnums.inboundSchema(exports.CompletionResponseStreamChoiceFinishReason); + exports.CompletionResponseStreamChoice$inboundSchema = z3.object({ + index: z3.number().int(), + delta: deltamessage_js_1.DeltaMessage$inboundSchema, + finish_reason: z3.nullable(exports.CompletionResponseStreamChoiceFinishReason$inboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "finish_reason": "finishReason" + }); + }); + function completionResponseStreamChoiceFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionResponseStreamChoice$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionResponseStreamChoice' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionchunk.js +var require_completionchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionChunk$inboundSchema = void 0; + exports.completionChunkFromJSON = completionChunkFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var completionresponsestreamchoice_js_1 = require_completionresponsestreamchoice(); + var usageinfo_js_1 = require_usageinfo(); + exports.CompletionChunk$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().optional(), + created: z3.number().int().optional(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema.optional(), + choices: z3.array(completionresponsestreamchoice_js_1.CompletionResponseStreamChoice$inboundSchema) + }); + function completionChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparameters.js +var require_completiontrainingparameters = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparameters.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionTrainingParameters$inboundSchema = void 0; + exports.completionTrainingParametersFromJSON = completionTrainingParametersFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.CompletionTrainingParameters$inboundSchema = z3.object({ + training_steps: z3.nullable(z3.number().int()).optional(), + learning_rate: z3.number().default(1e-4), + weight_decay: z3.nullable(z3.number()).optional(), + warmup_fraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seq_len: z3.nullable(z3.number().int()).optional(), + fim_ratio: z3.nullable(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "training_steps": "trainingSteps", + "learning_rate": "learningRate", + "weight_decay": "weightDecay", + "warmup_fraction": "warmupFraction", + "seq_len": "seqLen", + "fim_ratio": "fimRatio" + }); + }); + function completionTrainingParametersFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionTrainingParameters$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionTrainingParameters' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryout.js +var require_githubrepositoryout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GithubRepositoryOut$inboundSchema = void 0; + exports.githubRepositoryOutFromJSON = githubRepositoryOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.GithubRepositoryOut$inboundSchema = z3.object({ + type: z3.literal("github").default("github"), + name: z3.string(), + owner: z3.string(), + ref: z3.nullable(z3.string()).optional(), + weight: z3.number().default(1), + commit_id: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "commit_id": "commitId" + }); + }); + function githubRepositoryOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.GithubRepositoryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'GithubRepositoryOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiondetailedjobout.js +var require_completiondetailedjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiondetailedjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionDetailedJobOut$inboundSchema = exports.CompletionDetailedJobOutRepositories$inboundSchema = exports.CompletionDetailedJobOutIntegrations$inboundSchema = exports.CompletionDetailedJobOutStatus$inboundSchema = exports.CompletionDetailedJobOutStatus = void 0; + exports.completionDetailedJobOutIntegrationsFromJSON = completionDetailedJobOutIntegrationsFromJSON; + exports.completionDetailedJobOutRepositoriesFromJSON = completionDetailedJobOutRepositoriesFromJSON; + exports.completionDetailedJobOutFromJSON = completionDetailedJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var checkpointout_js_1 = require_checkpointout(); + var completiontrainingparameters_js_1 = require_completiontrainingparameters(); + var eventout_js_1 = require_eventout(); + var githubrepositoryout_js_1 = require_githubrepositoryout(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.CompletionDetailedJobOutStatus = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.CompletionDetailedJobOutStatus$inboundSchema = z3.nativeEnum(exports.CompletionDetailedJobOutStatus); + exports.CompletionDetailedJobOutIntegrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function completionDetailedJobOutIntegrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOutIntegrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOutIntegrations' from JSON`); + } + exports.CompletionDetailedJobOutRepositories$inboundSchema = githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema; + function completionDetailedJobOutRepositoriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOutRepositories$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOutRepositories' from JSON`); + } + exports.CompletionDetailedJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.CompletionDetailedJobOutStatus$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("completion").default("completion"), + hyperparameters: completiontrainingparameters_js_1.CompletionTrainingParameters$inboundSchema, + repositories: z3.array(githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema).optional(), + events: z3.array(eventout_js_1.EventOut$inboundSchema).optional(), + checkpoints: z3.array(checkpointout_js_1.CheckpointOut$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType" + }); + }); + function completionDetailedJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionDetailedJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionDetailedJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionevent.js +var require_completionevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionEvent$inboundSchema = void 0; + exports.completionEventFromJSON = completionEventFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var completionchunk_js_1 = require_completionchunk(); + exports.CompletionEvent$inboundSchema = z3.object({ + data: z3.string().transform((v4, ctx) => { + try { + return JSON.parse(v4); + } catch (err) { + ctx.addIssue({ code: "custom", message: `malformed json: ${err}` }); + return z3.NEVER; + } + }).pipe(completionchunk_js_1.CompletionChunk$inboundSchema) + }); + function completionEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionftmodelout.js +var require_completionftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionFTModelOut$inboundSchema = void 0; + exports.completionFTModelOutFromJSON = completionFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var ftmodelcapabilitiesout_js_1 = require_ftmodelcapabilitiesout(); + exports.CompletionFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + created: z3.number().int(), + owned_by: z3.string(), + workspace_id: z3.string(), + root: z3.string(), + root_version: z3.string(), + archived: z3.boolean(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + capabilities: ftmodelcapabilitiesout_js_1.FTModelCapabilitiesOut$inboundSchema, + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + job: z3.string(), + model_type: z3.literal("completion").default("completion") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "workspace_id": "workspaceId", + "root_version": "rootVersion", + "max_context_length": "maxContextLength", + "model_type": "modelType" + }); + }); + function completionFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completionjobout.js +var require_completionjobout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completionjobout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionJobOut$inboundSchema = exports.Repositories$inboundSchema = exports.Integrations$inboundSchema = exports.Status$inboundSchema = exports.Status = void 0; + exports.integrationsFromJSON = integrationsFromJSON; + exports.repositoriesFromJSON = repositoriesFromJSON; + exports.completionJobOutFromJSON = completionJobOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var completiontrainingparameters_js_1 = require_completiontrainingparameters(); + var githubrepositoryout_js_1 = require_githubrepositoryout(); + var jobmetadataout_js_1 = require_jobmetadataout(); + var wandbintegrationout_js_1 = require_wandbintegrationout(); + exports.Status = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.Status$inboundSchema = z3.nativeEnum(exports.Status); + exports.Integrations$inboundSchema = wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema; + function integrationsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Integrations$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Integrations' from JSON`); + } + exports.Repositories$inboundSchema = githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema; + function repositoriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Repositories$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Repositories' from JSON`); + } + exports.CompletionJobOut$inboundSchema = z3.object({ + id: z3.string(), + auto_start: z3.boolean(), + model: z3.string(), + status: exports.Status$inboundSchema, + created_at: z3.number().int(), + modified_at: z3.number().int(), + training_files: z3.array(z3.string()), + validation_files: z3.nullable(z3.array(z3.string())).optional(), + object: z3.literal("job").default("job"), + fine_tuned_model: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegrationout_js_1.WandbIntegrationOut$inboundSchema)).optional(), + trained_tokens: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(jobmetadataout_js_1.JobMetadataOut$inboundSchema).optional(), + job_type: z3.literal("completion").default("completion"), + hyperparameters: completiontrainingparameters_js_1.CompletionTrainingParameters$inboundSchema, + repositories: z3.array(githubrepositoryout_js_1.GithubRepositoryOut$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "auto_start": "autoStart", + "created_at": "createdAt", + "modified_at": "modifiedAt", + "training_files": "trainingFiles", + "validation_files": "validationFiles", + "fine_tuned_model": "fineTunedModel", + "trained_tokens": "trainedTokens", + "job_type": "jobType" + }); + }); + function completionJobOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.CompletionJobOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'CompletionJobOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparametersin.js +var require_completiontrainingparametersin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/completiontrainingparametersin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CompletionTrainingParametersIn$outboundSchema = void 0; + exports.completionTrainingParametersInToJSON = completionTrainingParametersInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.CompletionTrainingParametersIn$outboundSchema = z3.object({ + trainingSteps: z3.nullable(z3.number().int()).optional(), + learningRate: z3.number().default(1e-4), + weightDecay: z3.nullable(z3.number()).optional(), + warmupFraction: z3.nullable(z3.number()).optional(), + epochs: z3.nullable(z3.number()).optional(), + seqLen: z3.nullable(z3.number().int()).optional(), + fimRatio: z3.nullable(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + trainingSteps: "training_steps", + learningRate: "learning_rate", + weightDecay: "weight_decay", + warmupFraction: "warmup_fraction", + seqLen: "seq_len", + fimRatio: "fim_ratio" + }); + }); + function completionTrainingParametersInToJSON(completionTrainingParametersIn) { + return JSON.stringify(exports.CompletionTrainingParametersIn$outboundSchema.parse(completionTrainingParametersIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentryarguments.js +var require_functioncallentryarguments = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentryarguments.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCallEntryArguments$outboundSchema = exports.FunctionCallEntryArguments$inboundSchema = void 0; + exports.functionCallEntryArgumentsToJSON = functionCallEntryArgumentsToJSON; + exports.functionCallEntryArgumentsFromJSON = functionCallEntryArgumentsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.FunctionCallEntryArguments$inboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + exports.FunctionCallEntryArguments$outboundSchema = z3.union([z3.record(z3.any()), z3.string()]); + function functionCallEntryArgumentsToJSON(functionCallEntryArguments) { + return JSON.stringify(exports.FunctionCallEntryArguments$outboundSchema.parse(functionCallEntryArguments)); + } + function functionCallEntryArgumentsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEntryArguments$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEntryArguments' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentry.js +var require_functioncallentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCallEntry$outboundSchema = exports.FunctionCallEntry$inboundSchema = exports.ConfirmationStatus$outboundSchema = exports.ConfirmationStatus$inboundSchema = exports.ConfirmationStatus = void 0; + exports.functionCallEntryToJSON = functionCallEntryToJSON; + exports.functionCallEntryFromJSON = functionCallEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var functioncallentryarguments_js_1 = require_functioncallentryarguments(); + exports.ConfirmationStatus = { + Pending: "pending", + Allowed: "allowed", + Denied: "denied" + }; + exports.ConfirmationStatus$inboundSchema = z3.nativeEnum(exports.ConfirmationStatus); + exports.ConfirmationStatus$outboundSchema = exports.ConfirmationStatus$inboundSchema; + exports.FunctionCallEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.call").default("function.call"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + tool_call_id: z3.string(), + name: z3.string(), + arguments: functioncallentryarguments_js_1.FunctionCallEntryArguments$inboundSchema, + confirmation_status: z3.nullable(exports.ConfirmationStatus$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "tool_call_id": "toolCallId", + "confirmation_status": "confirmationStatus" + }); + }); + exports.FunctionCallEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.call").default("function.call"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + toolCallId: z3.string(), + name: z3.string(), + arguments: functioncallentryarguments_js_1.FunctionCallEntryArguments$outboundSchema, + confirmationStatus: z3.nullable(exports.ConfirmationStatus$outboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + toolCallId: "tool_call_id", + confirmationStatus: "confirmation_status" + }); + }); + function functionCallEntryToJSON(functionCallEntry) { + return JSON.stringify(exports.FunctionCallEntry$outboundSchema.parse(functionCallEntry)); + } + function functionCallEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functionresultentry.js +var require_functionresultentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functionresultentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionResultEntry$outboundSchema = exports.FunctionResultEntry$inboundSchema = void 0; + exports.functionResultEntryToJSON = functionResultEntryToJSON; + exports.functionResultEntryFromJSON = functionResultEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FunctionResultEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.result").default("function.result"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + tool_call_id: z3.string(), + result: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "tool_call_id": "toolCallId" + }); + }); + exports.FunctionResultEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("function.result").default("function.result"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + toolCallId: z3.string(), + result: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + toolCallId: "tool_call_id" + }); + }); + function functionResultEntryToJSON(functionResultEntry) { + return JSON.stringify(exports.FunctionResultEntry$outboundSchema.parse(functionResultEntry)); + } + function functionResultEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionResultEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionResultEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolfilechunk.js +var require_toolfilechunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolfilechunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolFileChunk$outboundSchema = exports.ToolFileChunk$inboundSchema = exports.ToolFileChunkTool$outboundSchema = exports.ToolFileChunkTool$inboundSchema = void 0; + exports.toolFileChunkToolToJSON = toolFileChunkToolToJSON; + exports.toolFileChunkToolFromJSON = toolFileChunkToolFromJSON; + exports.toolFileChunkToJSON = toolFileChunkToJSON; + exports.toolFileChunkFromJSON = toolFileChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolFileChunkTool$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + exports.ToolFileChunkTool$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]); + function toolFileChunkToolToJSON(toolFileChunkTool) { + return JSON.stringify(exports.ToolFileChunkTool$outboundSchema.parse(toolFileChunkTool)); + } + function toolFileChunkToolFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolFileChunkTool$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolFileChunkTool' from JSON`); + } + exports.ToolFileChunk$inboundSchema = z3.object({ + type: z3.literal("tool_file").default("tool_file"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + file_id: z3.string(), + file_name: z3.nullable(z3.string()).optional(), + file_type: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "file_id": "fileId", + "file_name": "fileName", + "file_type": "fileType" + }); + }); + exports.ToolFileChunk$outboundSchema = z3.object({ + type: z3.literal("tool_file").default("tool_file"), + tool: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]), + fileId: z3.string(), + fileName: z3.nullable(z3.string()).optional(), + fileType: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id", + fileName: "file_name", + fileType: "file_type" + }); + }); + function toolFileChunkToJSON(toolFileChunk) { + return JSON.stringify(exports.ToolFileChunk$outboundSchema.parse(toolFileChunk)); + } + function toolFileChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolFileChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolFileChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputcontentchunks.js +var require_messageinputcontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputcontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageInputContentChunks$outboundSchema = exports.MessageInputContentChunks$inboundSchema = void 0; + exports.messageInputContentChunksToJSON = messageInputContentChunksToJSON; + exports.messageInputContentChunksFromJSON = messageInputContentChunksFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + var toolfilechunk_js_1 = require_toolfilechunk(); + exports.MessageInputContentChunks$inboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$inboundSchema, + textchunk_js_1.TextChunk$inboundSchema, + imageurlchunk_js_1.ImageURLChunk$inboundSchema, + documenturlchunk_js_1.DocumentURLChunk$inboundSchema, + thinkchunk_js_1.ThinkChunk$inboundSchema + ]); + exports.MessageInputContentChunks$outboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$outboundSchema, + textchunk_js_1.TextChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + thinkchunk_js_1.ThinkChunk$outboundSchema + ]); + function messageInputContentChunksToJSON(messageInputContentChunks) { + return JSON.stringify(exports.MessageInputContentChunks$outboundSchema.parse(messageInputContentChunks)); + } + function messageInputContentChunksFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputContentChunks' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputentry.js +var require_messageinputentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageinputentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageInputEntry$outboundSchema = exports.MessageInputEntry$inboundSchema = exports.MessageInputEntryContent$outboundSchema = exports.MessageInputEntryContent$inboundSchema = exports.Role$outboundSchema = exports.Role$inboundSchema = exports.Role = void 0; + exports.messageInputEntryContentToJSON = messageInputEntryContentToJSON; + exports.messageInputEntryContentFromJSON = messageInputEntryContentFromJSON; + exports.messageInputEntryToJSON = messageInputEntryToJSON; + exports.messageInputEntryFromJSON = messageInputEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var messageinputcontentchunks_js_1 = require_messageinputcontentchunks(); + exports.Role = { + Assistant: "assistant", + User: "user" + }; + exports.Role$inboundSchema = z3.nativeEnum(exports.Role); + exports.Role$outboundSchema = exports.Role$inboundSchema; + exports.MessageInputEntryContent$inboundSchema = z3.union([z3.string(), z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$inboundSchema)]); + exports.MessageInputEntryContent$outboundSchema = z3.union([z3.string(), z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$outboundSchema)]); + function messageInputEntryContentToJSON(messageInputEntryContent) { + return JSON.stringify(exports.MessageInputEntryContent$outboundSchema.parse(messageInputEntryContent)); + } + function messageInputEntryContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputEntryContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputEntryContent' from JSON`); + } + exports.MessageInputEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.input").default("message.input"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + role: exports.Role$inboundSchema, + content: z3.union([ + z3.string(), + z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$inboundSchema) + ]), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt" + }); + }); + exports.MessageInputEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.input").default("message.input"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + role: exports.Role$outboundSchema, + content: z3.union([ + z3.string(), + z3.array(messageinputcontentchunks_js_1.MessageInputContentChunks$outboundSchema) + ]), + prefix: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at" + }); + }); + function messageInputEntryToJSON(messageInputEntry) { + return JSON.stringify(exports.MessageInputEntry$outboundSchema.parse(messageInputEntry)); + } + function messageInputEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageInputEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageInputEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputcontentchunks.js +var require_messageoutputcontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputcontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageOutputContentChunks$outboundSchema = exports.MessageOutputContentChunks$inboundSchema = void 0; + exports.messageOutputContentChunksToJSON = messageOutputContentChunksToJSON; + exports.messageOutputContentChunksFromJSON = messageOutputContentChunksFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + var toolfilechunk_js_1 = require_toolfilechunk(); + var toolreferencechunk_js_1 = require_toolreferencechunk(); + exports.MessageOutputContentChunks$inboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$inboundSchema, + toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, + textchunk_js_1.TextChunk$inboundSchema, + imageurlchunk_js_1.ImageURLChunk$inboundSchema, + documenturlchunk_js_1.DocumentURLChunk$inboundSchema, + thinkchunk_js_1.ThinkChunk$inboundSchema + ]); + exports.MessageOutputContentChunks$outboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$outboundSchema, + toolreferencechunk_js_1.ToolReferenceChunk$outboundSchema, + textchunk_js_1.TextChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + thinkchunk_js_1.ThinkChunk$outboundSchema + ]); + function messageOutputContentChunksToJSON(messageOutputContentChunks) { + return JSON.stringify(exports.MessageOutputContentChunks$outboundSchema.parse(messageOutputContentChunks)); + } + function messageOutputContentChunksFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputContentChunks' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputentry.js +var require_messageoutputentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageOutputEntry$outboundSchema = exports.MessageOutputEntry$inboundSchema = exports.MessageOutputEntryContent$outboundSchema = exports.MessageOutputEntryContent$inboundSchema = void 0; + exports.messageOutputEntryContentToJSON = messageOutputEntryContentToJSON; + exports.messageOutputEntryContentFromJSON = messageOutputEntryContentFromJSON; + exports.messageOutputEntryToJSON = messageOutputEntryToJSON; + exports.messageOutputEntryFromJSON = messageOutputEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var messageoutputcontentchunks_js_1 = require_messageoutputcontentchunks(); + exports.MessageOutputEntryContent$inboundSchema = z3.union([z3.string(), z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$inboundSchema)]); + exports.MessageOutputEntryContent$outboundSchema = z3.union([z3.string(), z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$outboundSchema)]); + function messageOutputEntryContentToJSON(messageOutputEntryContent) { + return JSON.stringify(exports.MessageOutputEntryContent$outboundSchema.parse(messageOutputEntryContent)); + } + function messageOutputEntryContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEntryContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEntryContent' from JSON`); + } + exports.MessageOutputEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.output").default("message.output"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + agent_id: z3.nullable(z3.string()).optional(), + model: z3.nullable(z3.string()).optional(), + role: z3.literal("assistant").default("assistant"), + content: z3.union([ + z3.string(), + z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$inboundSchema) + ]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt", + "agent_id": "agentId" + }); + }); + exports.MessageOutputEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("message.output").default("message.output"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + agentId: z3.nullable(z3.string()).optional(), + model: z3.nullable(z3.string()).optional(), + role: z3.literal("assistant").default("assistant"), + content: z3.union([ + z3.string(), + z3.array(messageoutputcontentchunks_js_1.MessageOutputContentChunks$outboundSchema) + ]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at", + agentId: "agent_id" + }); + }); + function messageOutputEntryToJSON(messageOutputEntry) { + return JSON.stringify(exports.MessageOutputEntry$outboundSchema.parse(messageOutputEntry)); + } + function messageOutputEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionentry.js +var require_toolexecutionentry = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionentry.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionEntry$outboundSchema = exports.ToolExecutionEntry$inboundSchema = exports.Name$outboundSchema = exports.Name$inboundSchema = void 0; + exports.nameToJSON = nameToJSON; + exports.nameFromJSON = nameFromJSON; + exports.toolExecutionEntryToJSON = toolExecutionEntryToJSON; + exports.toolExecutionEntryFromJSON = toolExecutionEntryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.Name$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + exports.Name$outboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]); + function nameToJSON(name) { + return JSON.stringify(exports.Name$outboundSchema.parse(name)); + } + function nameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Name$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Name' from JSON`); + } + exports.ToolExecutionEntry$inboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("tool.execution").default("tool.execution"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + completed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + id: z3.string().optional(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + arguments: z3.string(), + info: z3.record(z3.any()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "completed_at": "completedAt" + }); + }); + exports.ToolExecutionEntry$outboundSchema = z3.object({ + object: z3.literal("entry").default("entry"), + type: z3.literal("tool.execution").default("tool.execution"), + createdAt: z3.date().transform((v4) => v4.toISOString()).optional(), + completedAt: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + id: z3.string().optional(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$outboundSchema, z3.string()]), + arguments: z3.string(), + info: z3.record(z3.any()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + createdAt: "created_at", + completedAt: "completed_at" + }); + }); + function toolExecutionEntryToJSON(toolExecutionEntry) { + return JSON.stringify(exports.ToolExecutionEntry$outboundSchema.parse(toolExecutionEntry)); + } + function toolExecutionEntryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionEntry$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionEntry' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/inputentries.js +var require_inputentries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/inputentries.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.InputEntries$outboundSchema = void 0; + exports.inputEntriesToJSON = inputEntriesToJSON; + var z3 = __importStar(require_v3()); + var agenthandoffentry_js_1 = require_agenthandoffentry(); + var functioncallentry_js_1 = require_functioncallentry(); + var functionresultentry_js_1 = require_functionresultentry(); + var messageinputentry_js_1 = require_messageinputentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + var toolexecutionentry_js_1 = require_toolexecutionentry(); + exports.InputEntries$outboundSchema = z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$outboundSchema, + functioncallentry_js_1.FunctionCallEntry$outboundSchema, + messageinputentry_js_1.MessageInputEntry$outboundSchema, + functionresultentry_js_1.FunctionResultEntry$outboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$outboundSchema, + messageoutputentry_js_1.MessageOutputEntry$outboundSchema + ]); + function inputEntriesToJSON(inputEntries) { + return JSON.stringify(exports.InputEntries$outboundSchema.parse(inputEntries)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationinputs.js +var require_conversationinputs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationinputs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationInputs$outboundSchema = void 0; + exports.conversationInputsToJSON = conversationInputsToJSON; + var z3 = __importStar(require_v3()); + var inputentries_js_1 = require_inputentries(); + exports.ConversationInputs$outboundSchema = z3.union([z3.string(), z3.array(inputentries_js_1.InputEntries$outboundSchema)]); + function conversationInputsToJSON(conversationInputs) { + return JSON.stringify(exports.ConversationInputs$outboundSchema.parse(conversationInputs)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcallconfirmation.js +var require_toolcallconfirmation = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolcallconfirmation.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolCallConfirmation$outboundSchema = exports.Confirmation$outboundSchema = exports.Confirmation = void 0; + exports.toolCallConfirmationToJSON = toolCallConfirmationToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.Confirmation = { + Allow: "allow", + Deny: "deny" + }; + exports.Confirmation$outboundSchema = z3.nativeEnum(exports.Confirmation); + exports.ToolCallConfirmation$outboundSchema = z3.object({ + toolCallId: z3.string(), + confirmation: exports.Confirmation$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + toolCallId: "tool_call_id" + }); + }); + function toolCallConfirmationToJSON(toolCallConfirmation) { + return JSON.stringify(exports.ToolCallConfirmation$outboundSchema.parse(toolCallConfirmation)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendrequest.js +var require_conversationappendrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationAppendRequest$outboundSchema = exports.ConversationAppendRequestHandoffExecution$outboundSchema = exports.ConversationAppendRequestHandoffExecution = void 0; + exports.conversationAppendRequestToJSON = conversationAppendRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var toolcallconfirmation_js_1 = require_toolcallconfirmation(); + exports.ConversationAppendRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationAppendRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationAppendRequestHandoffExecution); + exports.ConversationAppendRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(false), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationAppendRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + toolConfirmations: z3.nullable(z3.array(toolcallconfirmation_js_1.ToolCallConfirmation$outboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + toolConfirmations: "tool_confirmations" + }); + }); + function conversationAppendRequestToJSON(conversationAppendRequest) { + return JSON.stringify(exports.ConversationAppendRequest$outboundSchema.parse(conversationAppendRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendstreamrequest.js +var require_conversationappendstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationappendstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationAppendStreamRequest$outboundSchema = exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema = exports.ConversationAppendStreamRequestHandoffExecution = void 0; + exports.conversationAppendStreamRequestToJSON = conversationAppendStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var toolcallconfirmation_js_1 = require_toolcallconfirmation(); + exports.ConversationAppendStreamRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationAppendStreamRequestHandoffExecution); + exports.ConversationAppendStreamRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(true), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationAppendStreamRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + toolConfirmations: z3.nullable(z3.array(toolcallconfirmation_js_1.ToolCallConfirmation$outboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + toolConfirmations: "tool_confirmations" + }); + }); + function conversationAppendStreamRequestToJSON(conversationAppendStreamRequest) { + return JSON.stringify(exports.ConversationAppendStreamRequest$outboundSchema.parse(conversationAppendStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallevent.js +var require_functioncallevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/functioncallevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FunctionCallEvent$inboundSchema = exports.FunctionCallEventConfirmationStatus$inboundSchema = exports.FunctionCallEventConfirmationStatus = void 0; + exports.functionCallEventFromJSON = functionCallEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.FunctionCallEventConfirmationStatus = { + Pending: "pending", + Allowed: "allowed", + Denied: "denied" + }; + exports.FunctionCallEventConfirmationStatus$inboundSchema = z3.nativeEnum(exports.FunctionCallEventConfirmationStatus); + exports.FunctionCallEvent$inboundSchema = z3.object({ + type: z3.literal("function.call.delta").default("function.call.delta"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.string(), + tool_call_id: z3.string(), + arguments: z3.string(), + confirmation_status: z3.nullable(exports.FunctionCallEventConfirmationStatus$inboundSchema).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "tool_call_id": "toolCallId", + "confirmation_status": "confirmationStatus" + }); + }); + function functionCallEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FunctionCallEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FunctionCallEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/outputcontentchunks.js +var require_outputcontentchunks = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/outputcontentchunks.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OutputContentChunks$inboundSchema = void 0; + exports.outputContentChunksFromJSON = outputContentChunksFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var textchunk_js_1 = require_textchunk(); + var thinkchunk_js_1 = require_thinkchunk(); + var toolfilechunk_js_1 = require_toolfilechunk(); + var toolreferencechunk_js_1 = require_toolreferencechunk(); + exports.OutputContentChunks$inboundSchema = z3.union([ + toolfilechunk_js_1.ToolFileChunk$inboundSchema, + toolreferencechunk_js_1.ToolReferenceChunk$inboundSchema, + textchunk_js_1.TextChunk$inboundSchema, + imageurlchunk_js_1.ImageURLChunk$inboundSchema, + documenturlchunk_js_1.DocumentURLChunk$inboundSchema, + thinkchunk_js_1.ThinkChunk$inboundSchema + ]); + function outputContentChunksFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OutputContentChunks$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OutputContentChunks' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputevent.js +var require_messageoutputevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageoutputevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageOutputEvent$inboundSchema = exports.MessageOutputEventContent$inboundSchema = void 0; + exports.messageOutputEventContentFromJSON = messageOutputEventContentFromJSON; + exports.messageOutputEventFromJSON = messageOutputEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var outputcontentchunks_js_1 = require_outputcontentchunks(); + exports.MessageOutputEventContent$inboundSchema = z3.union([z3.string(), outputcontentchunks_js_1.OutputContentChunks$inboundSchema]); + function messageOutputEventContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEventContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEventContent' from JSON`); + } + exports.MessageOutputEvent$inboundSchema = z3.object({ + type: z3.literal("message.output.delta").default("message.output.delta"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + content_index: z3.number().int().default(0), + model: z3.nullable(z3.string()).optional(), + agent_id: z3.nullable(z3.string()).optional(), + role: z3.literal("assistant").default("assistant"), + content: z3.union([z3.string(), outputcontentchunks_js_1.OutputContentChunks$inboundSchema]) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex", + "content_index": "contentIndex", + "agent_id": "agentId" + }); + }); + function messageOutputEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageOutputEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageOutputEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationusageinfo.js +var require_conversationusageinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationusageinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationUsageInfo$inboundSchema = void 0; + exports.conversationUsageInfoFromJSON = conversationUsageInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ConversationUsageInfo$inboundSchema = z3.object({ + prompt_tokens: z3.number().int().default(0), + completion_tokens: z3.number().int().default(0), + total_tokens: z3.number().int().default(0), + connector_tokens: z3.nullable(z3.number().int()).optional(), + connectors: z3.nullable(z3.record(z3.number().int())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "prompt_tokens": "promptTokens", + "completion_tokens": "completionTokens", + "total_tokens": "totalTokens", + "connector_tokens": "connectorTokens" + }); + }); + function conversationUsageInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationUsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationUsageInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responsedoneevent.js +var require_responsedoneevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responsedoneevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseDoneEvent$inboundSchema = void 0; + exports.responseDoneEventFromJSON = responseDoneEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var conversationusageinfo_js_1 = require_conversationusageinfo(); + exports.ResponseDoneEvent$inboundSchema = z3.object({ + type: z3.literal("conversation.response.done").default("conversation.response.done"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + usage: conversationusageinfo_js_1.ConversationUsageInfo$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt" + }); + }); + function responseDoneEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseDoneEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responseerrorevent.js +var require_responseerrorevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responseerrorevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseErrorEvent$inboundSchema = void 0; + exports.responseErrorEventFromJSON = responseErrorEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ResponseErrorEvent$inboundSchema = z3.object({ + type: z3.literal("conversation.response.error").default("conversation.response.error"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + message: z3.string(), + code: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt" + }); + }); + function responseErrorEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseErrorEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseErrorEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/responsestartedevent.js +var require_responsestartedevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/responsestartedevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseStartedEvent$inboundSchema = void 0; + exports.responseStartedEventFromJSON = responseStartedEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ResponseStartedEvent$inboundSchema = z3.object({ + type: z3.literal("conversation.response.started").default("conversation.response.started"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + conversation_id: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "conversation_id": "conversationId" + }); + }); + function responseStartedEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseStartedEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ssetypes.js +var require_ssetypes = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ssetypes.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SSETypes$inboundSchema = exports.SSETypes = void 0; + var z3 = __importStar(require_v3()); + exports.SSETypes = { + ConversationResponseStarted: "conversation.response.started", + ConversationResponseDone: "conversation.response.done", + ConversationResponseError: "conversation.response.error", + MessageOutputDelta: "message.output.delta", + ToolExecutionStarted: "tool.execution.started", + ToolExecutionDelta: "tool.execution.delta", + ToolExecutionDone: "tool.execution.done", + AgentHandoffStarted: "agent.handoff.started", + AgentHandoffDone: "agent.handoff.done", + FunctionCallDelta: "function.call.delta" + }; + exports.SSETypes$inboundSchema = z3.nativeEnum(exports.SSETypes); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondeltaevent.js +var require_toolexecutiondeltaevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondeltaevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionDeltaEvent$inboundSchema = exports.ToolExecutionDeltaEventName$inboundSchema = void 0; + exports.toolExecutionDeltaEventNameFromJSON = toolExecutionDeltaEventNameFromJSON; + exports.toolExecutionDeltaEventFromJSON = toolExecutionDeltaEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolExecutionDeltaEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + function toolExecutionDeltaEventNameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDeltaEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDeltaEventName' from JSON`); + } + exports.ToolExecutionDeltaEvent$inboundSchema = z3.object({ + type: z3.literal("tool.execution.delta").default("tool.execution.delta"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + arguments: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex" + }); + }); + function toolExecutionDeltaEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDeltaEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDeltaEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondoneevent.js +var require_toolexecutiondoneevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutiondoneevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionDoneEvent$inboundSchema = exports.ToolExecutionDoneEventName$inboundSchema = void 0; + exports.toolExecutionDoneEventNameFromJSON = toolExecutionDoneEventNameFromJSON; + exports.toolExecutionDoneEventFromJSON = toolExecutionDoneEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolExecutionDoneEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + function toolExecutionDoneEventNameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDoneEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDoneEventName' from JSON`); + } + exports.ToolExecutionDoneEvent$inboundSchema = z3.object({ + type: z3.literal("tool.execution.done").default("tool.execution.done"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + info: z3.record(z3.any()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex" + }); + }); + function toolExecutionDoneEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionDoneEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionDoneEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionstartedevent.js +var require_toolexecutionstartedevent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/toolexecutionstartedevent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ToolExecutionStartedEvent$inboundSchema = exports.ToolExecutionStartedEventName$inboundSchema = void 0; + exports.toolExecutionStartedEventNameFromJSON = toolExecutionStartedEventNameFromJSON; + exports.toolExecutionStartedEventFromJSON = toolExecutionStartedEventFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var builtinconnectors_js_1 = require_builtinconnectors(); + exports.ToolExecutionStartedEventName$inboundSchema = z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]); + function toolExecutionStartedEventNameFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionStartedEventName$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionStartedEventName' from JSON`); + } + exports.ToolExecutionStartedEvent$inboundSchema = z3.object({ + type: z3.literal("tool.execution.started").default("tool.execution.started"), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)).optional(), + output_index: z3.number().int().default(0), + id: z3.string(), + name: z3.union([builtinconnectors_js_1.BuiltInConnectors$inboundSchema, z3.string()]), + arguments: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "output_index": "outputIndex" + }); + }); + function toolExecutionStartedEventFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ToolExecutionStartedEvent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ToolExecutionStartedEvent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationevents.js +var require_conversationevents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationevents.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationEvents$inboundSchema = exports.ConversationEventsData$inboundSchema = void 0; + exports.conversationEventsDataFromJSON = conversationEventsDataFromJSON; + exports.conversationEventsFromJSON = conversationEventsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var agenthandoffdoneevent_js_1 = require_agenthandoffdoneevent(); + var agenthandoffstartedevent_js_1 = require_agenthandoffstartedevent(); + var functioncallevent_js_1 = require_functioncallevent(); + var messageoutputevent_js_1 = require_messageoutputevent(); + var responsedoneevent_js_1 = require_responsedoneevent(); + var responseerrorevent_js_1 = require_responseerrorevent(); + var responsestartedevent_js_1 = require_responsestartedevent(); + var ssetypes_js_1 = require_ssetypes(); + var toolexecutiondeltaevent_js_1 = require_toolexecutiondeltaevent(); + var toolexecutiondoneevent_js_1 = require_toolexecutiondoneevent(); + var toolexecutionstartedevent_js_1 = require_toolexecutionstartedevent(); + exports.ConversationEventsData$inboundSchema = z3.union([ + agenthandoffdoneevent_js_1.AgentHandoffDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.done") })), + agenthandoffstartedevent_js_1.AgentHandoffStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.started") })), + responsedoneevent_js_1.ResponseDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.done") })), + responseerrorevent_js_1.ResponseErrorEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.error") })), + responsestartedevent_js_1.ResponseStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.started") })), + functioncallevent_js_1.FunctionCallEvent$inboundSchema.and(z3.object({ type: z3.literal("function.call.delta") })), + messageoutputevent_js_1.MessageOutputEvent$inboundSchema.and(z3.object({ type: z3.literal("message.output.delta") })), + toolexecutiondeltaevent_js_1.ToolExecutionDeltaEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.delta") })), + toolexecutiondoneevent_js_1.ToolExecutionDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.done") })), + toolexecutionstartedevent_js_1.ToolExecutionStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.started") })) + ]); + function conversationEventsDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationEventsData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationEventsData' from JSON`); + } + exports.ConversationEvents$inboundSchema = z3.object({ + event: ssetypes_js_1.SSETypes$inboundSchema, + data: z3.string().transform((v4, ctx) => { + try { + return JSON.parse(v4); + } catch (err) { + ctx.addIssue({ code: "custom", message: `malformed json: ${err}` }); + return z3.NEVER; + } + }).pipe(z3.union([ + agenthandoffdoneevent_js_1.AgentHandoffDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.done") })), + agenthandoffstartedevent_js_1.AgentHandoffStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("agent.handoff.started") })), + responsedoneevent_js_1.ResponseDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.done") })), + responseerrorevent_js_1.ResponseErrorEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.error") })), + responsestartedevent_js_1.ResponseStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("conversation.response.started") })), + functioncallevent_js_1.FunctionCallEvent$inboundSchema.and(z3.object({ type: z3.literal("function.call.delta") })), + messageoutputevent_js_1.MessageOutputEvent$inboundSchema.and(z3.object({ type: z3.literal("message.output.delta") })), + toolexecutiondeltaevent_js_1.ToolExecutionDeltaEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.delta") })), + toolexecutiondoneevent_js_1.ToolExecutionDoneEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.done") })), + toolexecutionstartedevent_js_1.ToolExecutionStartedEvent$inboundSchema.and(z3.object({ type: z3.literal("tool.execution.started") })) + ])) + }); + function conversationEventsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationEvents$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationEvents' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationhistory.js +var require_conversationhistory = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationhistory.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationHistory$inboundSchema = exports.Entries$inboundSchema = void 0; + exports.entriesFromJSON = entriesFromJSON; + exports.conversationHistoryFromJSON = conversationHistoryFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var agenthandoffentry_js_1 = require_agenthandoffentry(); + var functioncallentry_js_1 = require_functioncallentry(); + var functionresultentry_js_1 = require_functionresultentry(); + var messageinputentry_js_1 = require_messageinputentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + var toolexecutionentry_js_1 = require_toolexecutionentry(); + exports.Entries$inboundSchema = z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + messageinputentry_js_1.MessageInputEntry$inboundSchema, + functionresultentry_js_1.FunctionResultEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ]); + function entriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Entries$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Entries' from JSON`); + } + exports.ConversationHistory$inboundSchema = z3.object({ + object: z3.literal("conversation.history").default("conversation.history"), + conversation_id: z3.string(), + entries: z3.array(z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + messageinputentry_js_1.MessageInputEntry$inboundSchema, + functionresultentry_js_1.FunctionResultEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ])) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "conversation_id": "conversationId" + }); + }); + function conversationHistoryFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationHistory$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationHistory' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/messageentries.js +var require_messageentries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/messageentries.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MessageEntries$inboundSchema = void 0; + exports.messageEntriesFromJSON = messageEntriesFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var messageinputentry_js_1 = require_messageinputentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + exports.MessageEntries$inboundSchema = z3.union([ + messageinputentry_js_1.MessageInputEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ]); + function messageEntriesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.MessageEntries$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'MessageEntries' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationmessages.js +var require_conversationmessages = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationmessages.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationMessages$inboundSchema = void 0; + exports.conversationMessagesFromJSON = conversationMessagesFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var messageentries_js_1 = require_messageentries(); + exports.ConversationMessages$inboundSchema = z3.object({ + object: z3.literal("conversation.messages").default("conversation.messages"), + conversation_id: z3.string(), + messages: z3.array(messageentries_js_1.MessageEntries$inboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "conversation_id": "conversationId" + }); + }); + function conversationMessagesFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationMessages$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationMessages' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrequest.js +var require_conversationrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationRequest$outboundSchema = exports.AgentVersion$outboundSchema = exports.Tools$outboundSchema = exports.HandoffExecution$outboundSchema = exports.HandoffExecution = void 0; + exports.toolsToJSON = toolsToJSON; + exports.agentVersionToJSON = agentVersionToJSON; + exports.conversationRequestToJSON = conversationRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.HandoffExecution = { + Client: "client", + Server: "server" + }; + exports.HandoffExecution$outboundSchema = z3.nativeEnum(exports.HandoffExecution); + exports.Tools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function toolsToJSON(tools) { + return JSON.stringify(exports.Tools$outboundSchema.parse(tools)); + } + exports.AgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function agentVersionToJSON(agentVersion) { + return JSON.stringify(exports.AgentVersion$outboundSchema.parse(agentVersion)); + } + exports.ConversationRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema, + stream: z3.boolean().default(false), + store: z3.nullable(z3.boolean()).optional(), + handoffExecution: z3.nullable(exports.HandoffExecution$outboundSchema).optional(), + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: z3.nullable(completionargs_js_1.CompletionArgs$outboundSchema).optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + agentId: z3.nullable(z3.string()).optional(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional(), + model: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + agentId: "agent_id", + agentVersion: "agent_version" + }); + }); + function conversationRequestToJSON(conversationRequest) { + return JSON.stringify(exports.ConversationRequest$outboundSchema.parse(conversationRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationresponse.js +var require_conversationresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationResponse$inboundSchema = exports.Outputs$inboundSchema = void 0; + exports.outputsFromJSON = outputsFromJSON; + exports.conversationResponseFromJSON = conversationResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var agenthandoffentry_js_1 = require_agenthandoffentry(); + var conversationusageinfo_js_1 = require_conversationusageinfo(); + var functioncallentry_js_1 = require_functioncallentry(); + var messageoutputentry_js_1 = require_messageoutputentry(); + var toolexecutionentry_js_1 = require_toolexecutionentry(); + exports.Outputs$inboundSchema = z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ]); + function outputsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Outputs$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Outputs' from JSON`); + } + exports.ConversationResponse$inboundSchema = z3.object({ + object: z3.literal("conversation.response").default("conversation.response"), + conversation_id: z3.string(), + outputs: z3.array(z3.union([ + agenthandoffentry_js_1.AgentHandoffEntry$inboundSchema, + functioncallentry_js_1.FunctionCallEntry$inboundSchema, + toolexecutionentry_js_1.ToolExecutionEntry$inboundSchema, + messageoutputentry_js_1.MessageOutputEntry$inboundSchema + ])), + usage: conversationusageinfo_js_1.ConversationUsageInfo$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "conversation_id": "conversationId" + }); + }); + function conversationResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ConversationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ConversationResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartrequest.js +var require_conversationrestartrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationRestartRequest$outboundSchema = exports.ConversationRestartRequestAgentVersion$outboundSchema = exports.ConversationRestartRequestHandoffExecution$outboundSchema = exports.ConversationRestartRequestHandoffExecution = void 0; + exports.conversationRestartRequestAgentVersionToJSON = conversationRestartRequestAgentVersionToJSON; + exports.conversationRestartRequestToJSON = conversationRestartRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + exports.ConversationRestartRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationRestartRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationRestartRequestHandoffExecution); + exports.ConversationRestartRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function conversationRestartRequestAgentVersionToJSON(conversationRestartRequestAgentVersion) { + return JSON.stringify(exports.ConversationRestartRequestAgentVersion$outboundSchema.parse(conversationRestartRequestAgentVersion)); + } + exports.ConversationRestartRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(false), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationRestartRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + fromEntryId: z3.string(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + fromEntryId: "from_entry_id", + agentVersion: "agent_version" + }); + }); + function conversationRestartRequestToJSON(conversationRestartRequest) { + return JSON.stringify(exports.ConversationRestartRequest$outboundSchema.parse(conversationRestartRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartstreamrequest.js +var require_conversationrestartstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationrestartstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationRestartStreamRequest$outboundSchema = exports.ConversationRestartStreamRequestAgentVersion$outboundSchema = exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema = exports.ConversationRestartStreamRequestHandoffExecution = void 0; + exports.conversationRestartStreamRequestAgentVersionToJSON = conversationRestartStreamRequestAgentVersionToJSON; + exports.conversationRestartStreamRequestToJSON = conversationRestartStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + exports.ConversationRestartStreamRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationRestartStreamRequestHandoffExecution); + exports.ConversationRestartStreamRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function conversationRestartStreamRequestAgentVersionToJSON(conversationRestartStreamRequestAgentVersion) { + return JSON.stringify(exports.ConversationRestartStreamRequestAgentVersion$outboundSchema.parse(conversationRestartStreamRequestAgentVersion)); + } + exports.ConversationRestartStreamRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema.optional(), + stream: z3.boolean().default(true), + store: z3.boolean().default(true), + handoffExecution: exports.ConversationRestartStreamRequestHandoffExecution$outboundSchema.default("server"), + completionArgs: completionargs_js_1.CompletionArgs$outboundSchema.optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + fromEntryId: z3.string(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + fromEntryId: "from_entry_id", + agentVersion: "agent_version" + }); + }); + function conversationRestartStreamRequestToJSON(conversationRestartStreamRequest) { + return JSON.stringify(exports.ConversationRestartStreamRequest$outboundSchema.parse(conversationRestartStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationstreamrequest.js +var require_conversationstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/conversationstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ConversationStreamRequest$outboundSchema = exports.ConversationStreamRequestAgentVersion$outboundSchema = exports.ConversationStreamRequestTools$outboundSchema = exports.ConversationStreamRequestHandoffExecution$outboundSchema = exports.ConversationStreamRequestHandoffExecution = void 0; + exports.conversationStreamRequestToolsToJSON = conversationStreamRequestToolsToJSON; + exports.conversationStreamRequestAgentVersionToJSON = conversationStreamRequestAgentVersionToJSON; + exports.conversationStreamRequestToJSON = conversationStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var conversationinputs_js_1 = require_conversationinputs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.ConversationStreamRequestHandoffExecution = { + Client: "client", + Server: "server" + }; + exports.ConversationStreamRequestHandoffExecution$outboundSchema = z3.nativeEnum(exports.ConversationStreamRequestHandoffExecution); + exports.ConversationStreamRequestTools$outboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function conversationStreamRequestToolsToJSON(conversationStreamRequestTools) { + return JSON.stringify(exports.ConversationStreamRequestTools$outboundSchema.parse(conversationStreamRequestTools)); + } + exports.ConversationStreamRequestAgentVersion$outboundSchema = z3.union([z3.string(), z3.number().int()]); + function conversationStreamRequestAgentVersionToJSON(conversationStreamRequestAgentVersion) { + return JSON.stringify(exports.ConversationStreamRequestAgentVersion$outboundSchema.parse(conversationStreamRequestAgentVersion)); + } + exports.ConversationStreamRequest$outboundSchema = z3.object({ + inputs: conversationinputs_js_1.ConversationInputs$outboundSchema, + stream: z3.boolean().default(true), + store: z3.nullable(z3.boolean()).optional(), + handoffExecution: z3.nullable(exports.ConversationStreamRequestHandoffExecution$outboundSchema).optional(), + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$outboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$outboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$outboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$outboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$outboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$outboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completionArgs: z3.nullable(completionargs_js_1.CompletionArgs$outboundSchema).optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + agentId: z3.nullable(z3.string()).optional(), + agentVersion: z3.nullable(z3.union([z3.string(), z3.number().int()])).optional(), + model: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + handoffExecution: "handoff_execution", + completionArgs: "completion_args", + agentId: "agent_id", + agentVersion: "agent_version" + }); + }); + function conversationStreamRequestToJSON(conversationStreamRequest) { + return JSON.stringify(exports.ConversationStreamRequest$outboundSchema.parse(conversationStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deletefileout.js +var require_deletefileout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/deletefileout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteFileOut$inboundSchema = void 0; + exports.deleteFileOutFromJSON = deleteFileOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.DeleteFileOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + deleted: z3.boolean() + }); + function deleteFileOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeleteFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeleteFileOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/deletemodelout.js +var require_deletemodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/deletemodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteModelOut$inboundSchema = void 0; + exports.deleteModelOutFromJSON = deleteModelOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.DeleteModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().default("model"), + deleted: z3.boolean().default(true) + }); + function deleteModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DeleteModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DeleteModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentout.js +var require_documentout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentOut$inboundSchema = void 0; + exports.documentOutFromJSON = documentOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.DocumentOut$inboundSchema = z3.object({ + id: z3.string(), + library_id: z3.string(), + hash: z3.nullable(z3.string()), + mime_type: z3.nullable(z3.string()), + extension: z3.nullable(z3.string()), + size: z3.nullable(z3.number().int()), + name: z3.string(), + summary: z3.nullable(z3.string()).optional(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + last_processed_at: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + number_of_pages: z3.nullable(z3.number().int()).optional(), + uploaded_by_id: z3.nullable(z3.string()), + uploaded_by_type: z3.string(), + tokens_processing_main_content: z3.nullable(z3.number().int()).optional(), + tokens_processing_summary: z3.nullable(z3.number().int()).optional(), + url: z3.nullable(z3.string()).optional(), + attributes: z3.nullable(z3.record(z3.any())).optional(), + processing_status: z3.string(), + tokens_processing_total: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "library_id": "libraryId", + "mime_type": "mimeType", + "created_at": "createdAt", + "last_processed_at": "lastProcessedAt", + "number_of_pages": "numberOfPages", + "uploaded_by_id": "uploadedById", + "uploaded_by_type": "uploadedByType", + "tokens_processing_main_content": "tokensProcessingMainContent", + "tokens_processing_summary": "tokensProcessingSummary", + "processing_status": "processingStatus", + "tokens_processing_total": "tokensProcessingTotal" + }); + }); + function documentOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documenttextcontent.js +var require_documenttextcontent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documenttextcontent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentTextContent$inboundSchema = void 0; + exports.documentTextContentFromJSON = documentTextContentFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.DocumentTextContent$inboundSchema = z3.object({ + text: z3.string() + }); + function documentTextContentFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.DocumentTextContent$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'DocumentTextContent' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/documentupdatein.js +var require_documentupdatein = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/documentupdatein.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DocumentUpdateIn$outboundSchema = exports.Attributes$outboundSchema = void 0; + exports.attributesToJSON = attributesToJSON; + exports.documentUpdateInToJSON = documentUpdateInToJSON; + var z3 = __importStar(require_v3()); + exports.Attributes$outboundSchema = z3.union([ + z3.boolean(), + z3.string(), + z3.number().int(), + z3.number(), + z3.date().transform((v4) => v4.toISOString()), + z3.array(z3.string()), + z3.array(z3.number().int()), + z3.array(z3.number()), + z3.array(z3.boolean()) + ]); + function attributesToJSON(attributes) { + return JSON.stringify(exports.Attributes$outboundSchema.parse(attributes)); + } + exports.DocumentUpdateIn$outboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + attributes: z3.nullable(z3.record(z3.union([ + z3.boolean(), + z3.string(), + z3.number().int(), + z3.number(), + z3.date().transform((v4) => v4.toISOString()), + z3.array(z3.string()), + z3.array(z3.number().int()), + z3.array(z3.number()), + z3.array(z3.boolean()) + ]))).optional() + }); + function documentUpdateInToJSON(documentUpdateIn) { + return JSON.stringify(exports.DocumentUpdateIn$outboundSchema.parse(documentUpdateIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingdtype.js +var require_embeddingdtype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingdtype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingDtype$outboundSchema = exports.EmbeddingDtype = void 0; + var z3 = __importStar(require_v3()); + exports.EmbeddingDtype = { + Float: "float", + Int8: "int8", + Uint8: "uint8", + Binary: "binary", + Ubinary: "ubinary" + }; + exports.EmbeddingDtype$outboundSchema = z3.nativeEnum(exports.EmbeddingDtype); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/encodingformat.js +var require_encodingformat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/encodingformat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EncodingFormat$outboundSchema = exports.EncodingFormat = void 0; + var z3 = __importStar(require_v3()); + exports.EncodingFormat = { + Float: "float", + Base64: "base64" + }; + exports.EncodingFormat$outboundSchema = z3.nativeEnum(exports.EncodingFormat); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingrequest.js +var require_embeddingrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingRequest$outboundSchema = exports.EmbeddingRequestInputs$outboundSchema = void 0; + exports.embeddingRequestInputsToJSON = embeddingRequestInputsToJSON; + exports.embeddingRequestToJSON = embeddingRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var embeddingdtype_js_1 = require_embeddingdtype(); + var encodingformat_js_1 = require_encodingformat(); + exports.EmbeddingRequestInputs$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function embeddingRequestInputsToJSON(embeddingRequestInputs) { + return JSON.stringify(exports.EmbeddingRequestInputs$outboundSchema.parse(embeddingRequestInputs)); + } + exports.EmbeddingRequest$outboundSchema = z3.object({ + model: z3.string(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + inputs: z3.union([z3.string(), z3.array(z3.string())]), + outputDimension: z3.nullable(z3.number().int()).optional(), + outputDtype: embeddingdtype_js_1.EmbeddingDtype$outboundSchema.optional(), + encodingFormat: encodingformat_js_1.EncodingFormat$outboundSchema.optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + inputs: "input", + outputDimension: "output_dimension", + outputDtype: "output_dtype", + encodingFormat: "encoding_format" + }); + }); + function embeddingRequestToJSON(embeddingRequest) { + return JSON.stringify(exports.EmbeddingRequest$outboundSchema.parse(embeddingRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponsedata.js +var require_embeddingresponsedata = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponsedata.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingResponseData$inboundSchema = void 0; + exports.embeddingResponseDataFromJSON = embeddingResponseDataFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.EmbeddingResponseData$inboundSchema = z3.object({ + object: z3.string().optional(), + embedding: z3.array(z3.number()).optional(), + index: z3.number().int().optional() + }); + function embeddingResponseDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EmbeddingResponseData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EmbeddingResponseData' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponse.js +var require_embeddingresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/embeddingresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EmbeddingResponse$inboundSchema = void 0; + exports.embeddingResponseFromJSON = embeddingResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var embeddingresponsedata_js_1 = require_embeddingresponsedata(); + var usageinfo_js_1 = require_usageinfo(); + exports.EmbeddingResponse$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + data: z3.array(embeddingresponsedata_js_1.EmbeddingResponseData$inboundSchema) + }); + function embeddingResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.EmbeddingResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'EmbeddingResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/entitytype.js +var require_entitytype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/entitytype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EntityType$outboundSchema = exports.EntityType = void 0; + var openEnums = __importStar(require_enums()); + exports.EntityType = { + User: "User", + Workspace: "Workspace", + Org: "Org" + }; + exports.EntityType$outboundSchema = openEnums.outboundSchema(exports.EntityType); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filepurpose.js +var require_filepurpose = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/filepurpose.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilePurpose$outboundSchema = exports.FilePurpose$inboundSchema = exports.FilePurpose = void 0; + var openEnums = __importStar(require_enums()); + exports.FilePurpose = { + FineTune: "fine-tune", + Batch: "batch", + Ocr: "ocr" + }; + exports.FilePurpose$inboundSchema = openEnums.inboundSchema(exports.FilePurpose); + exports.FilePurpose$outboundSchema = openEnums.outboundSchema(exports.FilePurpose); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sampletype.js +var require_sampletype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sampletype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SampleType$outboundSchema = exports.SampleType$inboundSchema = exports.SampleType = void 0; + var openEnums = __importStar(require_enums()); + exports.SampleType = { + Pretrain: "pretrain", + Instruct: "instruct", + BatchRequest: "batch_request", + BatchResult: "batch_result", + BatchError: "batch_error" + }; + exports.SampleType$inboundSchema = openEnums.inboundSchema(exports.SampleType); + exports.SampleType$outboundSchema = openEnums.outboundSchema(exports.SampleType); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/source.js +var require_source = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/source.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Source$outboundSchema = exports.Source$inboundSchema = exports.Source = void 0; + var openEnums = __importStar(require_enums()); + exports.Source = { + Upload: "upload", + Repository: "repository", + Mistral: "mistral" + }; + exports.Source$inboundSchema = openEnums.inboundSchema(exports.Source); + exports.Source$outboundSchema = openEnums.outboundSchema(exports.Source); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fileschema.js +var require_fileschema = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fileschema.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileSchema$inboundSchema = void 0; + exports.fileSchemaFromJSON = fileSchemaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var filepurpose_js_1 = require_filepurpose(); + var sampletype_js_1 = require_sampletype(); + var source_js_1 = require_source(); + exports.FileSchema$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + bytes: z3.number().int(), + created_at: z3.number().int(), + filename: z3.string(), + purpose: filepurpose_js_1.FilePurpose$inboundSchema, + sample_type: sampletype_js_1.SampleType$inboundSchema, + num_lines: z3.nullable(z3.number().int()).optional(), + mimetype: z3.nullable(z3.string()).optional(), + source: source_js_1.Source$inboundSchema, + signature: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "bytes": "sizeBytes", + "created_at": "createdAt", + "sample_type": "sampleType", + "num_lines": "numLines" + }); + }); + function fileSchemaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileSchema$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileSchema' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/filesignedurl.js +var require_filesignedurl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/filesignedurl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileSignedURL$inboundSchema = void 0; + exports.fileSignedURLFromJSON = fileSignedURLFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.FileSignedURL$inboundSchema = z3.object({ + url: z3.string() + }); + function fileSignedURLFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FileSignedURL$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FileSignedURL' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionrequest.js +var require_fimcompletionrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FIMCompletionRequest$outboundSchema = exports.FIMCompletionRequestStop$outboundSchema = void 0; + exports.fimCompletionRequestStopToJSON = fimCompletionRequestStopToJSON; + exports.fimCompletionRequestToJSON = fimCompletionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FIMCompletionRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function fimCompletionRequestStopToJSON(fimCompletionRequestStop) { + return JSON.stringify(exports.FIMCompletionRequestStop$outboundSchema.parse(fimCompletionRequestStop)); + } + exports.FIMCompletionRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().default(1), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(false), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + prompt: z3.string(), + suffix: z3.nullable(z3.string()).optional(), + minTokens: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + minTokens: "min_tokens" + }); + }); + function fimCompletionRequestToJSON(fimCompletionRequest) { + return JSON.stringify(exports.FIMCompletionRequest$outboundSchema.parse(fimCompletionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionresponse.js +var require_fimcompletionresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FIMCompletionResponse$inboundSchema = void 0; + exports.fimCompletionResponseFromJSON = fimCompletionResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var chatcompletionchoice_js_1 = require_chatcompletionchoice(); + var usageinfo_js_1 = require_usageinfo(); + exports.FIMCompletionResponse$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + model: z3.string(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + created: z3.number().int(), + choices: z3.array(chatcompletionchoice_js_1.ChatCompletionChoice$inboundSchema) + }); + function fimCompletionResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FIMCompletionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FIMCompletionResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionstreamrequest.js +var require_fimcompletionstreamrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/fimcompletionstreamrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FIMCompletionStreamRequest$outboundSchema = exports.FIMCompletionStreamRequestStop$outboundSchema = void 0; + exports.fimCompletionStreamRequestStopToJSON = fimCompletionStreamRequestStopToJSON; + exports.fimCompletionStreamRequestToJSON = fimCompletionStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FIMCompletionStreamRequestStop$outboundSchema = z3.union([z3.string(), z3.array(z3.string())]); + function fimCompletionStreamRequestStopToJSON(fimCompletionStreamRequestStop) { + return JSON.stringify(exports.FIMCompletionStreamRequestStop$outboundSchema.parse(fimCompletionStreamRequestStop)); + } + exports.FIMCompletionStreamRequest$outboundSchema = z3.object({ + model: z3.string(), + temperature: z3.nullable(z3.number()).optional(), + topP: z3.number().default(1), + maxTokens: z3.nullable(z3.number().int()).optional(), + stream: z3.boolean().default(true), + stop: z3.union([z3.string(), z3.array(z3.string())]).optional(), + randomSeed: z3.nullable(z3.number().int()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + prompt: z3.string(), + suffix: z3.nullable(z3.string()).optional(), + minTokens: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + topP: "top_p", + maxTokens: "max_tokens", + randomSeed: "random_seed", + minTokens: "min_tokens" + }); + }); + function fimCompletionStreamRequestToJSON(fimCompletionStreamRequest) { + return JSON.stringify(exports.FIMCompletionStreamRequest$outboundSchema.parse(fimCompletionStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/finetuneablemodeltype.js +var require_finetuneablemodeltype = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/finetuneablemodeltype.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FineTuneableModelType$outboundSchema = exports.FineTuneableModelType = void 0; + var z3 = __importStar(require_v3()); + exports.FineTuneableModelType = { + Completion: "completion", + Classifier: "classifier" + }; + exports.FineTuneableModelType$outboundSchema = z3.nativeEnum(exports.FineTuneableModelType); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcard.js +var require_ftmodelcard = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ftmodelcard.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FTModelCard$inboundSchema = void 0; + exports.ftModelCardFromJSON = ftModelCardFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var modelcapabilities_js_1 = require_modelcapabilities(); + exports.FTModelCard$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string().default("model"), + created: z3.number().int().optional(), + owned_by: z3.string().default("mistralai"), + capabilities: modelcapabilities_js_1.ModelCapabilities$inboundSchema, + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + max_context_length: z3.number().int().default(32768), + aliases: z3.array(z3.string()).optional(), + deprecation: z3.nullable(z3.string().datetime({ offset: true }).transform((v4) => new Date(v4))).optional(), + deprecation_replacement_model: z3.nullable(z3.string()).optional(), + default_model_temperature: z3.nullable(z3.number()).optional(), + type: z3.literal("fine-tuned").default("fine-tuned"), + job: z3.string(), + root: z3.string(), + archived: z3.boolean().default(false) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "owned_by": "ownedBy", + "max_context_length": "maxContextLength", + "deprecation_replacement_model": "deprecationReplacementModel", + "default_model_temperature": "defaultModelTemperature" + }); + }); + function ftModelCardFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.FTModelCard$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'FTModelCard' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryin.js +var require_githubrepositoryin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/githubrepositoryin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GithubRepositoryIn$outboundSchema = void 0; + exports.githubRepositoryInToJSON = githubRepositoryInToJSON; + var z3 = __importStar(require_v3()); + exports.GithubRepositoryIn$outboundSchema = z3.object({ + type: z3.literal("github").default("github"), + name: z3.string(), + owner: z3.string(), + ref: z3.nullable(z3.string()).optional(), + weight: z3.number().default(1), + token: z3.string() + }); + function githubRepositoryInToJSON(githubRepositoryIn) { + return JSON.stringify(exports.GithubRepositoryIn$outboundSchema.parse(githubRepositoryIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/trainingfile.js +var require_trainingfile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/trainingfile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TrainingFile$outboundSchema = void 0; + exports.trainingFileToJSON = trainingFileToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.TrainingFile$outboundSchema = z3.object({ + fileId: z3.string(), + weight: z3.number().default(1) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function trainingFileToJSON(trainingFile) { + return JSON.stringify(exports.TrainingFile$outboundSchema.parse(trainingFile)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegration.js +var require_wandbintegration = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/wandbintegration.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WandbIntegration$outboundSchema = void 0; + exports.wandbIntegrationToJSON = wandbIntegrationToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.WandbIntegration$outboundSchema = z3.object({ + type: z3.literal("wandb").default("wandb"), + project: z3.string(), + name: z3.nullable(z3.string()).optional(), + apiKey: z3.string(), + runName: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + apiKey: "api_key", + runName: "run_name" + }); + }); + function wandbIntegrationToJSON(wandbIntegration) { + return JSON.stringify(exports.WandbIntegration$outboundSchema.parse(wandbIntegration)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobin.js +var require_jobin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobIn$outboundSchema = exports.JobInRepositories$outboundSchema = exports.Hyperparameters$outboundSchema = exports.JobInIntegrations$outboundSchema = void 0; + exports.jobInIntegrationsToJSON = jobInIntegrationsToJSON; + exports.hyperparametersToJSON = hyperparametersToJSON; + exports.jobInRepositoriesToJSON = jobInRepositoriesToJSON; + exports.jobInToJSON = jobInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var classifiertargetin_js_1 = require_classifiertargetin(); + var classifiertrainingparametersin_js_1 = require_classifiertrainingparametersin(); + var completiontrainingparametersin_js_1 = require_completiontrainingparametersin(); + var finetuneablemodeltype_js_1 = require_finetuneablemodeltype(); + var githubrepositoryin_js_1 = require_githubrepositoryin(); + var trainingfile_js_1 = require_trainingfile(); + var wandbintegration_js_1 = require_wandbintegration(); + exports.JobInIntegrations$outboundSchema = wandbintegration_js_1.WandbIntegration$outboundSchema; + function jobInIntegrationsToJSON(jobInIntegrations) { + return JSON.stringify(exports.JobInIntegrations$outboundSchema.parse(jobInIntegrations)); + } + exports.Hyperparameters$outboundSchema = z3.union([ + completiontrainingparametersin_js_1.CompletionTrainingParametersIn$outboundSchema, + classifiertrainingparametersin_js_1.ClassifierTrainingParametersIn$outboundSchema + ]); + function hyperparametersToJSON(hyperparameters) { + return JSON.stringify(exports.Hyperparameters$outboundSchema.parse(hyperparameters)); + } + exports.JobInRepositories$outboundSchema = githubrepositoryin_js_1.GithubRepositoryIn$outboundSchema; + function jobInRepositoriesToJSON(jobInRepositories) { + return JSON.stringify(exports.JobInRepositories$outboundSchema.parse(jobInRepositories)); + } + exports.JobIn$outboundSchema = z3.object({ + model: z3.string(), + trainingFiles: z3.array(trainingfile_js_1.TrainingFile$outboundSchema).optional(), + validationFiles: z3.nullable(z3.array(z3.string())).optional(), + suffix: z3.nullable(z3.string()).optional(), + integrations: z3.nullable(z3.array(wandbintegration_js_1.WandbIntegration$outboundSchema)).optional(), + autoStart: z3.boolean().optional(), + invalidSampleSkipPercentage: z3.number().default(0), + jobType: z3.nullable(finetuneablemodeltype_js_1.FineTuneableModelType$outboundSchema).optional(), + hyperparameters: z3.union([ + completiontrainingparametersin_js_1.CompletionTrainingParametersIn$outboundSchema, + classifiertrainingparametersin_js_1.ClassifierTrainingParametersIn$outboundSchema + ]), + repositories: z3.nullable(z3.array(githubrepositoryin_js_1.GithubRepositoryIn$outboundSchema)).optional(), + classifierTargets: z3.nullable(z3.array(classifiertargetin_js_1.ClassifierTargetIn$outboundSchema)).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + trainingFiles: "training_files", + validationFiles: "validation_files", + autoStart: "auto_start", + invalidSampleSkipPercentage: "invalid_sample_skip_percentage", + jobType: "job_type", + classifierTargets: "classifier_targets" + }); + }); + function jobInToJSON(jobIn) { + return JSON.stringify(exports.JobIn$outboundSchema.parse(jobIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/jobsout.js +var require_jobsout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/jobsout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsOut$inboundSchema = exports.JobsOutData$inboundSchema = void 0; + exports.jobsOutDataFromJSON = jobsOutDataFromJSON; + exports.jobsOutFromJSON = jobsOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var classifierjobout_js_1 = require_classifierjobout(); + var completionjobout_js_1 = require_completionjobout(); + exports.JobsOutData$inboundSchema = z3.union([ + classifierjobout_js_1.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + completionjobout_js_1.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsOutDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsOutData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsOutData' from JSON`); + } + exports.JobsOut$inboundSchema = z3.object({ + data: z3.array(z3.union([ + classifierjobout_js_1.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + completionjobout_js_1.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ])).optional(), + object: z3.literal("list").default("list"), + total: z3.number().int() + }); + function jobsOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/legacyjobmetadataout.js +var require_legacyjobmetadataout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/legacyjobmetadataout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LegacyJobMetadataOut$inboundSchema = void 0; + exports.legacyJobMetadataOutFromJSON = legacyJobMetadataOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.LegacyJobMetadataOut$inboundSchema = z3.object({ + expected_duration_seconds: z3.nullable(z3.number().int()).optional(), + cost: z3.nullable(z3.number()).optional(), + cost_currency: z3.nullable(z3.string()).optional(), + train_tokens_per_step: z3.nullable(z3.number().int()).optional(), + train_tokens: z3.nullable(z3.number().int()).optional(), + data_tokens: z3.nullable(z3.number().int()).optional(), + estimated_start_time: z3.nullable(z3.number().int()).optional(), + deprecated: z3.boolean().default(true), + details: z3.string(), + epochs: z3.nullable(z3.number()).optional(), + training_steps: z3.nullable(z3.number().int()).optional(), + object: z3.literal("job.metadata").default("job.metadata") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "expected_duration_seconds": "expectedDurationSeconds", + "cost_currency": "costCurrency", + "train_tokens_per_step": "trainTokensPerStep", + "train_tokens": "trainTokens", + "data_tokens": "dataTokens", + "estimated_start_time": "estimatedStartTime", + "training_steps": "trainingSteps" + }); + }); + function legacyJobMetadataOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.LegacyJobMetadataOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'LegacyJobMetadataOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryin.js +var require_libraryin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibraryIn$outboundSchema = void 0; + exports.libraryInToJSON = libraryInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibraryIn$outboundSchema = z3.object({ + name: z3.string(), + description: z3.nullable(z3.string()).optional(), + chunkSize: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + chunkSize: "chunk_size" + }); + }); + function libraryInToJSON(libraryIn) { + return JSON.stringify(exports.LibraryIn$outboundSchema.parse(libraryIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryinupdate.js +var require_libraryinupdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryinupdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibraryInUpdate$outboundSchema = void 0; + exports.libraryInUpdateToJSON = libraryInUpdateToJSON; + var z3 = __importStar(require_v3()); + exports.LibraryInUpdate$outboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + function libraryInUpdateToJSON(libraryInUpdate) { + return JSON.stringify(exports.LibraryInUpdate$outboundSchema.parse(libraryInUpdate)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryout.js +var require_libraryout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/libraryout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibraryOut$inboundSchema = void 0; + exports.libraryOutFromJSON = libraryOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.LibraryOut$inboundSchema = z3.object({ + id: z3.string(), + name: z3.string(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + owner_id: z3.nullable(z3.string()), + owner_type: z3.string(), + total_size: z3.number().int(), + nb_documents: z3.number().int(), + chunk_size: z3.nullable(z3.number().int()), + emoji: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + generated_description: z3.nullable(z3.string()).optional(), + explicit_user_members_count: z3.nullable(z3.number().int()).optional(), + explicit_workspace_members_count: z3.nullable(z3.number().int()).optional(), + org_sharing_role: z3.nullable(z3.string()).optional(), + generated_name: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "created_at": "createdAt", + "updated_at": "updatedAt", + "owner_id": "ownerId", + "owner_type": "ownerType", + "total_size": "totalSize", + "nb_documents": "nbDocuments", + "chunk_size": "chunkSize", + "generated_description": "generatedDescription", + "explicit_user_members_count": "explicitUserMembersCount", + "explicit_workspace_members_count": "explicitWorkspaceMembersCount", + "org_sharing_role": "orgSharingRole", + "generated_name": "generatedName" + }); + }); + function libraryOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.LibraryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'LibraryOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/paginationinfo.js +var require_paginationinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/paginationinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.PaginationInfo$inboundSchema = void 0; + exports.paginationInfoFromJSON = paginationInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.PaginationInfo$inboundSchema = z3.object({ + total_items: z3.number().int(), + total_pages: z3.number().int(), + current_page: z3.number().int(), + page_size: z3.number().int(), + has_more: z3.boolean() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "total_items": "totalItems", + "total_pages": "totalPages", + "current_page": "currentPage", + "page_size": "pageSize", + "has_more": "hasMore" + }); + }); + function paginationInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.PaginationInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'PaginationInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listdocumentout.js +var require_listdocumentout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listdocumentout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListDocumentOut$inboundSchema = void 0; + exports.listDocumentOutFromJSON = listDocumentOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var documentout_js_1 = require_documentout(); + var paginationinfo_js_1 = require_paginationinfo(); + exports.ListDocumentOut$inboundSchema = z3.object({ + pagination: paginationinfo_js_1.PaginationInfo$inboundSchema, + data: z3.array(documentout_js_1.DocumentOut$inboundSchema) + }); + function listDocumentOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListDocumentOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListDocumentOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listfilesout.js +var require_listfilesout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listfilesout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListFilesOut$inboundSchema = void 0; + exports.listFilesOutFromJSON = listFilesOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var fileschema_js_1 = require_fileschema(); + exports.ListFilesOut$inboundSchema = z3.object({ + data: z3.array(fileschema_js_1.FileSchema$inboundSchema), + object: z3.string(), + total: z3.nullable(z3.number().int()).optional() + }); + function listFilesOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListFilesOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListFilesOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listlibraryout.js +var require_listlibraryout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listlibraryout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListLibraryOut$inboundSchema = void 0; + exports.listLibraryOutFromJSON = listLibraryOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var libraryout_js_1 = require_libraryout(); + exports.ListLibraryOut$inboundSchema = z3.object({ + data: z3.array(libraryout_js_1.LibraryOut$inboundSchema) + }); + function listLibraryOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListLibraryOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListLibraryOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingout.js +var require_sharingout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SharingOut$inboundSchema = void 0; + exports.sharingOutFromJSON = sharingOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.SharingOut$inboundSchema = z3.object({ + library_id: z3.string(), + user_id: z3.nullable(z3.string()).optional(), + org_id: z3.string(), + role: z3.string(), + share_with_type: z3.string(), + share_with_uuid: z3.nullable(z3.string()) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "library_id": "libraryId", + "user_id": "userId", + "org_id": "orgId", + "share_with_type": "shareWithType", + "share_with_uuid": "shareWithUuid" + }); + }); + function sharingOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.SharingOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'SharingOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/listsharingout.js +var require_listsharingout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/listsharingout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ListSharingOut$inboundSchema = void 0; + exports.listSharingOutFromJSON = listSharingOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var sharingout_js_1 = require_sharingout(); + exports.ListSharingOut$inboundSchema = z3.object({ + data: z3.array(sharingout_js_1.SharingOut$inboundSchema) + }); + function listSharingOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ListSharingOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ListSharingOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modelconversation.js +var require_modelconversation = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/modelconversation.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModelConversation$inboundSchema = exports.ModelConversationTools$inboundSchema = void 0; + exports.modelConversationToolsFromJSON = modelConversationToolsFromJSON; + exports.modelConversationFromJSON = modelConversationFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var codeinterpretertool_js_1 = require_codeinterpretertool(); + var completionargs_js_1 = require_completionargs(); + var documentlibrarytool_js_1 = require_documentlibrarytool(); + var functiontool_js_1 = require_functiontool(); + var imagegenerationtool_js_1 = require_imagegenerationtool(); + var websearchpremiumtool_js_1 = require_websearchpremiumtool(); + var websearchtool_js_1 = require_websearchtool(); + exports.ModelConversationTools$inboundSchema = z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ]); + function modelConversationToolsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelConversationTools$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelConversationTools' from JSON`); + } + exports.ModelConversation$inboundSchema = z3.object({ + instructions: z3.nullable(z3.string()).optional(), + tools: z3.array(z3.union([ + codeinterpretertool_js_1.CodeInterpreterTool$inboundSchema.and(z3.object({ type: z3.literal("code_interpreter") })), + documentlibrarytool_js_1.DocumentLibraryTool$inboundSchema.and(z3.object({ type: z3.literal("document_library") })), + functiontool_js_1.FunctionTool$inboundSchema.and(z3.object({ type: z3.literal("function") })), + imagegenerationtool_js_1.ImageGenerationTool$inboundSchema.and(z3.object({ type: z3.literal("image_generation") })), + websearchtool_js_1.WebSearchTool$inboundSchema.and(z3.object({ type: z3.literal("web_search") })), + websearchpremiumtool_js_1.WebSearchPremiumTool$inboundSchema.and(z3.object({ type: z3.literal("web_search_premium") })) + ])).optional(), + completion_args: completionargs_js_1.CompletionArgs$inboundSchema.optional(), + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + object: z3.literal("conversation").default("conversation"), + id: z3.string(), + created_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + updated_at: z3.string().datetime({ offset: true }).transform((v4) => new Date(v4)), + model: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "completion_args": "completionArgs", + "created_at": "createdAt", + "updated_at": "updatedAt" + }); + }); + function modelConversationFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelConversation$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelConversation' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/modellist.js +var require_modellist = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/modellist.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModelList$inboundSchema = exports.Data$inboundSchema = void 0; + exports.dataFromJSON = dataFromJSON; + exports.modelListFromJSON = modelListFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var basemodelcard_js_1 = require_basemodelcard(); + var ftmodelcard_js_1 = require_ftmodelcard(); + exports.Data$inboundSchema = z3.union([ + basemodelcard_js_1.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })), + ftmodelcard_js_1.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") })) + ]); + function dataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Data$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Data' from JSON`); + } + exports.ModelList$inboundSchema = z3.object({ + object: z3.string().default("list"), + data: z3.array(z3.union([ + basemodelcard_js_1.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })), + ftmodelcard_js_1.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") })) + ])).optional() + }); + function modelListFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModelList$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModelList' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationobject.js +var require_moderationobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModerationObject$inboundSchema = void 0; + exports.moderationObjectFromJSON = moderationObjectFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ModerationObject$inboundSchema = z3.object({ + categories: z3.record(z3.boolean()).optional(), + category_scores: z3.record(z3.number()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "category_scores": "categoryScores" + }); + }); + function moderationObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModerationObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModerationObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationresponse.js +var require_moderationresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/moderationresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ModerationResponse$inboundSchema = void 0; + exports.moderationResponseFromJSON = moderationResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var moderationobject_js_1 = require_moderationobject(); + exports.ModerationResponse$inboundSchema = z3.object({ + id: z3.string(), + model: z3.string(), + results: z3.array(moderationobject_js_1.ModerationObject$inboundSchema) + }); + function moderationResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ModerationResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ModerationResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrimageobject.js +var require_ocrimageobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrimageobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRImageObject$inboundSchema = void 0; + exports.ocrImageObjectFromJSON = ocrImageObjectFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.OCRImageObject$inboundSchema = z3.object({ + id: z3.string(), + top_left_x: z3.nullable(z3.number().int()), + top_left_y: z3.nullable(z3.number().int()), + bottom_right_x: z3.nullable(z3.number().int()), + bottom_right_y: z3.nullable(z3.number().int()), + image_base64: z3.nullable(z3.string()).optional(), + image_annotation: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "top_left_x": "topLeftX", + "top_left_y": "topLeftY", + "bottom_right_x": "bottomRightX", + "bottom_right_y": "bottomRightY", + "image_base64": "imageBase64", + "image_annotation": "imageAnnotation" + }); + }); + function ocrImageObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRImageObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRImageObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpagedimensions.js +var require_ocrpagedimensions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpagedimensions.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRPageDimensions$inboundSchema = void 0; + exports.ocrPageDimensionsFromJSON = ocrPageDimensionsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.OCRPageDimensions$inboundSchema = z3.object({ + dpi: z3.number().int(), + height: z3.number().int(), + width: z3.number().int() + }); + function ocrPageDimensionsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRPageDimensions$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRPageDimensions' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrtableobject.js +var require_ocrtableobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrtableobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRTableObject$inboundSchema = exports.Format$inboundSchema = exports.Format = void 0; + exports.ocrTableObjectFromJSON = ocrTableObjectFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Format = { + Markdown: "markdown", + Html: "html" + }; + exports.Format$inboundSchema = z3.nativeEnum(exports.Format); + exports.OCRTableObject$inboundSchema = z3.object({ + id: z3.string(), + content: z3.string(), + format: exports.Format$inboundSchema + }); + function ocrTableObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRTableObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRTableObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpageobject.js +var require_ocrpageobject = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrpageobject.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRPageObject$inboundSchema = void 0; + exports.ocrPageObjectFromJSON = ocrPageObjectFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var ocrimageobject_js_1 = require_ocrimageobject(); + var ocrpagedimensions_js_1 = require_ocrpagedimensions(); + var ocrtableobject_js_1 = require_ocrtableobject(); + exports.OCRPageObject$inboundSchema = z3.object({ + index: z3.number().int(), + markdown: z3.string(), + images: z3.array(ocrimageobject_js_1.OCRImageObject$inboundSchema), + tables: z3.array(ocrtableobject_js_1.OCRTableObject$inboundSchema).optional(), + hyperlinks: z3.array(z3.string()).optional(), + header: z3.nullable(z3.string()).optional(), + footer: z3.nullable(z3.string()).optional(), + dimensions: z3.nullable(ocrpagedimensions_js_1.OCRPageDimensions$inboundSchema) + }); + function ocrPageObjectFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRPageObject$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRPageObject' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrrequest.js +var require_ocrrequest = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrrequest.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRRequest$outboundSchema = exports.TableFormat$outboundSchema = exports.Document$outboundSchema = exports.TableFormat = void 0; + exports.documentToJSON = documentToJSON; + exports.ocrRequestToJSON = ocrRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var documenturlchunk_js_1 = require_documenturlchunk(); + var filechunk_js_1 = require_filechunk(); + var imageurlchunk_js_1 = require_imageurlchunk(); + var responseformat_js_1 = require_responseformat(); + exports.TableFormat = { + Markdown: "markdown", + Html: "html" + }; + exports.Document$outboundSchema = z3.union([ + filechunk_js_1.FileChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema + ]); + function documentToJSON(document2) { + return JSON.stringify(exports.Document$outboundSchema.parse(document2)); + } + exports.TableFormat$outboundSchema = z3.nativeEnum(exports.TableFormat); + exports.OCRRequest$outboundSchema = z3.object({ + model: z3.nullable(z3.string()), + id: z3.string().optional(), + document: z3.union([ + filechunk_js_1.FileChunk$outboundSchema, + documenturlchunk_js_1.DocumentURLChunk$outboundSchema, + imageurlchunk_js_1.ImageURLChunk$outboundSchema + ]), + pages: z3.nullable(z3.array(z3.number().int())).optional(), + includeImageBase64: z3.nullable(z3.boolean()).optional(), + imageLimit: z3.nullable(z3.number().int()).optional(), + imageMinSize: z3.nullable(z3.number().int()).optional(), + bboxAnnotationFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(), + documentAnnotationFormat: z3.nullable(responseformat_js_1.ResponseFormat$outboundSchema).optional(), + documentAnnotationPrompt: z3.nullable(z3.string()).optional(), + tableFormat: z3.nullable(exports.TableFormat$outboundSchema).optional(), + extractHeader: z3.boolean().optional(), + extractFooter: z3.boolean().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + includeImageBase64: "include_image_base64", + imageLimit: "image_limit", + imageMinSize: "image_min_size", + bboxAnnotationFormat: "bbox_annotation_format", + documentAnnotationFormat: "document_annotation_format", + documentAnnotationPrompt: "document_annotation_prompt", + tableFormat: "table_format", + extractHeader: "extract_header", + extractFooter: "extract_footer" + }); + }); + function ocrRequestToJSON(ocrRequest) { + return JSON.stringify(exports.OCRRequest$outboundSchema.parse(ocrRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrusageinfo.js +var require_ocrusageinfo = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrusageinfo.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRUsageInfo$inboundSchema = void 0; + exports.ocrUsageInfoFromJSON = ocrUsageInfoFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.OCRUsageInfo$inboundSchema = z3.object({ + pages_processed: z3.number().int(), + doc_size_bytes: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "pages_processed": "pagesProcessed", + "doc_size_bytes": "docSizeBytes" + }); + }); + function ocrUsageInfoFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRUsageInfo$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRUsageInfo' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrresponse.js +var require_ocrresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/ocrresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OCRResponse$inboundSchema = void 0; + exports.ocrResponseFromJSON = ocrResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var ocrpageobject_js_1 = require_ocrpageobject(); + var ocrusageinfo_js_1 = require_ocrusageinfo(); + exports.OCRResponse$inboundSchema = z3.object({ + pages: z3.array(ocrpageobject_js_1.OCRPageObject$inboundSchema), + model: z3.string(), + document_annotation: z3.nullable(z3.string()).optional(), + usage_info: ocrusageinfo_js_1.OCRUsageInfo$inboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "document_annotation": "documentAnnotation", + "usage_info": "usageInfo" + }); + }); + function ocrResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.OCRResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'OCRResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/processingstatusout.js +var require_processingstatusout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/processingstatusout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ProcessingStatusOut$inboundSchema = void 0; + exports.processingStatusOutFromJSON = processingStatusOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.ProcessingStatusOut$inboundSchema = z3.object({ + document_id: z3.string(), + processing_status: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "document_id": "documentId", + "processing_status": "processingStatus" + }); + }); + function processingStatusOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ProcessingStatusOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ProcessingStatusOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerrordetail.js +var require_realtimetranscriptionerrordetail = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerrordetail.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionErrorDetail$outboundSchema = exports.RealtimeTranscriptionErrorDetail$inboundSchema = exports.Message$outboundSchema = exports.Message$inboundSchema = void 0; + exports.messageToJSON = messageToJSON; + exports.messageFromJSON = messageFromJSON; + exports.realtimeTranscriptionErrorDetailToJSON = realtimeTranscriptionErrorDetailToJSON; + exports.realtimeTranscriptionErrorDetailFromJSON = realtimeTranscriptionErrorDetailFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Message$inboundSchema = z3.union([z3.string(), z3.record(z3.any())]); + exports.Message$outboundSchema = z3.union([z3.string(), z3.record(z3.any())]); + function messageToJSON(message) { + return JSON.stringify(exports.Message$outboundSchema.parse(message)); + } + function messageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Message$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Message' from JSON`); + } + exports.RealtimeTranscriptionErrorDetail$inboundSchema = z3.object({ + message: z3.union([z3.string(), z3.record(z3.any())]), + code: z3.number().int() + }); + exports.RealtimeTranscriptionErrorDetail$outboundSchema = z3.object({ + message: z3.union([z3.string(), z3.record(z3.any())]), + code: z3.number().int() + }); + function realtimeTranscriptionErrorDetailToJSON(realtimeTranscriptionErrorDetail) { + return JSON.stringify(exports.RealtimeTranscriptionErrorDetail$outboundSchema.parse(realtimeTranscriptionErrorDetail)); + } + function realtimeTranscriptionErrorDetailFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionErrorDetail$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionErrorDetail' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerror.js +var require_realtimetranscriptionerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionError$outboundSchema = exports.RealtimeTranscriptionError$inboundSchema = void 0; + exports.realtimeTranscriptionErrorToJSON = realtimeTranscriptionErrorToJSON; + exports.realtimeTranscriptionErrorFromJSON = realtimeTranscriptionErrorFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionerrordetail_js_1 = require_realtimetranscriptionerrordetail(); + exports.RealtimeTranscriptionError$inboundSchema = z3.object({ + type: z3.literal("error").default("error"), + error: realtimetranscriptionerrordetail_js_1.RealtimeTranscriptionErrorDetail$inboundSchema + }); + exports.RealtimeTranscriptionError$outboundSchema = z3.object({ + type: z3.literal("error").default("error"), + error: realtimetranscriptionerrordetail_js_1.RealtimeTranscriptionErrorDetail$outboundSchema + }); + function realtimeTranscriptionErrorToJSON(realtimeTranscriptionError) { + return JSON.stringify(exports.RealtimeTranscriptionError$outboundSchema.parse(realtimeTranscriptionError)); + } + function realtimeTranscriptionErrorFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionError' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioappend.js +var require_realtimetranscriptioninputaudioappend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioappend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionInputAudioAppend$outboundSchema = exports.RealtimeTranscriptionInputAudioAppend$inboundSchema = void 0; + exports.realtimeTranscriptionInputAudioAppendToJSON = realtimeTranscriptionInputAudioAppendToJSON; + exports.realtimeTranscriptionInputAudioAppendFromJSON = realtimeTranscriptionInputAudioAppendFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.RealtimeTranscriptionInputAudioAppend$inboundSchema = z3.object({ + type: z3.literal("input_audio.append").default("input_audio.append"), + audio: z3.string() + }); + exports.RealtimeTranscriptionInputAudioAppend$outboundSchema = z3.object({ + type: z3.literal("input_audio.append").default("input_audio.append"), + audio: z3.string() + }); + function realtimeTranscriptionInputAudioAppendToJSON(realtimeTranscriptionInputAudioAppend) { + return JSON.stringify(exports.RealtimeTranscriptionInputAudioAppend$outboundSchema.parse(realtimeTranscriptionInputAudioAppend)); + } + function realtimeTranscriptionInputAudioAppendFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioAppend$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioAppend' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioend.js +var require_realtimetranscriptioninputaudioend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionInputAudioEnd$outboundSchema = exports.RealtimeTranscriptionInputAudioEnd$inboundSchema = void 0; + exports.realtimeTranscriptionInputAudioEndToJSON = realtimeTranscriptionInputAudioEndToJSON; + exports.realtimeTranscriptionInputAudioEndFromJSON = realtimeTranscriptionInputAudioEndFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.RealtimeTranscriptionInputAudioEnd$inboundSchema = z3.object({ + type: z3.literal("input_audio.end").default("input_audio.end") + }); + exports.RealtimeTranscriptionInputAudioEnd$outboundSchema = z3.object({ + type: z3.literal("input_audio.end").default("input_audio.end") + }); + function realtimeTranscriptionInputAudioEndToJSON(realtimeTranscriptionInputAudioEnd) { + return JSON.stringify(exports.RealtimeTranscriptionInputAudioEnd$outboundSchema.parse(realtimeTranscriptionInputAudioEnd)); + } + function realtimeTranscriptionInputAudioEndFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioEnd$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioEnd' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioflush.js +var require_realtimetranscriptioninputaudioflush = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptioninputaudioflush.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionInputAudioFlush$outboundSchema = exports.RealtimeTranscriptionInputAudioFlush$inboundSchema = void 0; + exports.realtimeTranscriptionInputAudioFlushToJSON = realtimeTranscriptionInputAudioFlushToJSON; + exports.realtimeTranscriptionInputAudioFlushFromJSON = realtimeTranscriptionInputAudioFlushFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.RealtimeTranscriptionInputAudioFlush$inboundSchema = z3.object({ + type: z3.literal("input_audio.flush").default("input_audio.flush") + }); + exports.RealtimeTranscriptionInputAudioFlush$outboundSchema = z3.object({ + type: z3.literal("input_audio.flush").default("input_audio.flush") + }); + function realtimeTranscriptionInputAudioFlushToJSON(realtimeTranscriptionInputAudioFlush) { + return JSON.stringify(exports.RealtimeTranscriptionInputAudioFlush$outboundSchema.parse(realtimeTranscriptionInputAudioFlush)); + } + function realtimeTranscriptionInputAudioFlushFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionInputAudioFlush$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionInputAudioFlush' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsession.js +var require_realtimetranscriptionsession = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsession.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSession$outboundSchema = exports.RealtimeTranscriptionSession$inboundSchema = void 0; + exports.realtimeTranscriptionSessionToJSON = realtimeTranscriptionSessionToJSON; + exports.realtimeTranscriptionSessionFromJSON = realtimeTranscriptionSessionFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var audioformat_js_1 = require_audioformat(); + exports.RealtimeTranscriptionSession$inboundSchema = z3.object({ + request_id: z3.string(), + model: z3.string(), + audio_format: audioformat_js_1.AudioFormat$inboundSchema, + target_streaming_delay_ms: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "request_id": "requestId", + "audio_format": "audioFormat", + "target_streaming_delay_ms": "targetStreamingDelayMs" + }); + }); + exports.RealtimeTranscriptionSession$outboundSchema = z3.object({ + requestId: z3.string(), + model: z3.string(), + audioFormat: audioformat_js_1.AudioFormat$outboundSchema, + targetStreamingDelayMs: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + requestId: "request_id", + audioFormat: "audio_format", + targetStreamingDelayMs: "target_streaming_delay_ms" + }); + }); + function realtimeTranscriptionSessionToJSON(realtimeTranscriptionSession) { + return JSON.stringify(exports.RealtimeTranscriptionSession$outboundSchema.parse(realtimeTranscriptionSession)); + } + function realtimeTranscriptionSessionFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSession$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSession' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessioncreated.js +var require_realtimetranscriptionsessioncreated = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessioncreated.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionCreated$outboundSchema = exports.RealtimeTranscriptionSessionCreated$inboundSchema = void 0; + exports.realtimeTranscriptionSessionCreatedToJSON = realtimeTranscriptionSessionCreatedToJSON; + exports.realtimeTranscriptionSessionCreatedFromJSON = realtimeTranscriptionSessionCreatedFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionsession_js_1 = require_realtimetranscriptionsession(); + exports.RealtimeTranscriptionSessionCreated$inboundSchema = z3.object({ + type: z3.literal("session.created").default("session.created"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$inboundSchema + }); + exports.RealtimeTranscriptionSessionCreated$outboundSchema = z3.object({ + type: z3.literal("session.created").default("session.created"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$outboundSchema + }); + function realtimeTranscriptionSessionCreatedToJSON(realtimeTranscriptionSessionCreated) { + return JSON.stringify(exports.RealtimeTranscriptionSessionCreated$outboundSchema.parse(realtimeTranscriptionSessionCreated)); + } + function realtimeTranscriptionSessionCreatedFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionCreated$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionCreated' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdated.js +var require_realtimetranscriptionsessionupdated = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdated.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionUpdated$outboundSchema = exports.RealtimeTranscriptionSessionUpdated$inboundSchema = void 0; + exports.realtimeTranscriptionSessionUpdatedToJSON = realtimeTranscriptionSessionUpdatedToJSON; + exports.realtimeTranscriptionSessionUpdatedFromJSON = realtimeTranscriptionSessionUpdatedFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionsession_js_1 = require_realtimetranscriptionsession(); + exports.RealtimeTranscriptionSessionUpdated$inboundSchema = z3.object({ + type: z3.literal("session.updated").default("session.updated"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$inboundSchema + }); + exports.RealtimeTranscriptionSessionUpdated$outboundSchema = z3.object({ + type: z3.literal("session.updated").default("session.updated"), + session: realtimetranscriptionsession_js_1.RealtimeTranscriptionSession$outboundSchema + }); + function realtimeTranscriptionSessionUpdatedToJSON(realtimeTranscriptionSessionUpdated) { + return JSON.stringify(exports.RealtimeTranscriptionSessionUpdated$outboundSchema.parse(realtimeTranscriptionSessionUpdated)); + } + function realtimeTranscriptionSessionUpdatedFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdated$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdated' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatepayload.js +var require_realtimetranscriptionsessionupdatepayload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatepayload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema = exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema = void 0; + exports.realtimeTranscriptionSessionUpdatePayloadToJSON = realtimeTranscriptionSessionUpdatePayloadToJSON; + exports.realtimeTranscriptionSessionUpdatePayloadFromJSON = realtimeTranscriptionSessionUpdatePayloadFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var audioformat_js_1 = require_audioformat(); + exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema = z3.object({ + audio_format: z3.nullable(audioformat_js_1.AudioFormat$inboundSchema).optional(), + target_streaming_delay_ms: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "audio_format": "audioFormat", + "target_streaming_delay_ms": "targetStreamingDelayMs" + }); + }); + exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema = z3.object({ + audioFormat: z3.nullable(audioformat_js_1.AudioFormat$outboundSchema).optional(), + targetStreamingDelayMs: z3.nullable(z3.number().int()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + audioFormat: "audio_format", + targetStreamingDelayMs: "target_streaming_delay_ms" + }); + }); + function realtimeTranscriptionSessionUpdatePayloadToJSON(realtimeTranscriptionSessionUpdatePayload) { + return JSON.stringify(exports.RealtimeTranscriptionSessionUpdatePayload$outboundSchema.parse(realtimeTranscriptionSessionUpdatePayload)); + } + function realtimeTranscriptionSessionUpdatePayloadFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdatePayload$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdatePayload' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatemessage.js +var require_realtimetranscriptionsessionupdatemessage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/realtimetranscriptionsessionupdatemessage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema = exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema = void 0; + exports.realtimeTranscriptionSessionUpdateMessageToJSON = realtimeTranscriptionSessionUpdateMessageToJSON; + exports.realtimeTranscriptionSessionUpdateMessageFromJSON = realtimeTranscriptionSessionUpdateMessageFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var realtimetranscriptionsessionupdatepayload_js_1 = require_realtimetranscriptionsessionupdatepayload(); + exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema = z3.object({ + type: z3.literal("session.update").default("session.update"), + session: realtimetranscriptionsessionupdatepayload_js_1.RealtimeTranscriptionSessionUpdatePayload$inboundSchema + }); + exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema = z3.object({ + type: z3.literal("session.update").default("session.update"), + session: realtimetranscriptionsessionupdatepayload_js_1.RealtimeTranscriptionSessionUpdatePayload$outboundSchema + }); + function realtimeTranscriptionSessionUpdateMessageToJSON(realtimeTranscriptionSessionUpdateMessage) { + return JSON.stringify(exports.RealtimeTranscriptionSessionUpdateMessage$outboundSchema.parse(realtimeTranscriptionSessionUpdateMessage)); + } + function realtimeTranscriptionSessionUpdateMessageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RealtimeTranscriptionSessionUpdateMessage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RealtimeTranscriptionSessionUpdateMessage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/requestsource.js +var require_requestsource = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/requestsource.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RequestSource$outboundSchema = exports.RequestSource = void 0; + var z3 = __importStar(require_v3()); + exports.RequestSource = { + Api: "api", + Playground: "playground", + AgentBuilderV1: "agent_builder_v1" + }; + exports.RequestSource$outboundSchema = z3.nativeEnum(exports.RequestSource); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/retrievefileout.js +var require_retrievefileout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/retrievefileout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RetrieveFileOut$inboundSchema = void 0; + exports.retrieveFileOutFromJSON = retrieveFileOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var filepurpose_js_1 = require_filepurpose(); + var sampletype_js_1 = require_sampletype(); + var source_js_1 = require_source(); + exports.RetrieveFileOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + bytes: z3.number().int(), + created_at: z3.number().int(), + filename: z3.string(), + purpose: filepurpose_js_1.FilePurpose$inboundSchema, + sample_type: sampletype_js_1.SampleType$inboundSchema, + num_lines: z3.nullable(z3.number().int()).optional(), + mimetype: z3.nullable(z3.string()).optional(), + source: source_js_1.Source$inboundSchema, + signature: z3.nullable(z3.string()).optional(), + deleted: z3.boolean() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "bytes": "sizeBytes", + "created_at": "createdAt", + "sample_type": "sampleType", + "num_lines": "numLines" + }); + }); + function retrieveFileOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RetrieveFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RetrieveFileOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/security.js +var require_security2 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/security.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Security$outboundSchema = void 0; + exports.securityToJSON = securityToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.Security$outboundSchema = z3.object({ + apiKey: z3.string().optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + apiKey: "ApiKey" + }); + }); + function securityToJSON(security) { + return JSON.stringify(exports.Security$outboundSchema.parse(security)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/shareenum.js +var require_shareenum = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/shareenum.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ShareEnum$outboundSchema = exports.ShareEnum = void 0; + var openEnums = __importStar(require_enums()); + exports.ShareEnum = { + Viewer: "Viewer", + Editor: "Editor" + }; + exports.ShareEnum$outboundSchema = openEnums.outboundSchema(exports.ShareEnum); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingdelete.js +var require_sharingdelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingdelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SharingDelete$outboundSchema = void 0; + exports.sharingDeleteToJSON = sharingDeleteToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var entitytype_js_1 = require_entitytype(); + exports.SharingDelete$outboundSchema = z3.object({ + orgId: z3.nullable(z3.string()).optional(), + shareWithUuid: z3.string(), + shareWithType: entitytype_js_1.EntityType$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + orgId: "org_id", + shareWithUuid: "share_with_uuid", + shareWithType: "share_with_type" + }); + }); + function sharingDeleteToJSON(sharingDelete) { + return JSON.stringify(exports.SharingDelete$outboundSchema.parse(sharingDelete)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingin.js +var require_sharingin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/sharingin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SharingIn$outboundSchema = void 0; + exports.sharingInToJSON = sharingInToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var entitytype_js_1 = require_entitytype(); + var shareenum_js_1 = require_shareenum(); + exports.SharingIn$outboundSchema = z3.object({ + orgId: z3.nullable(z3.string()).optional(), + level: shareenum_js_1.ShareEnum$outboundSchema, + shareWithUuid: z3.string(), + shareWithType: entitytype_js_1.EntityType$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + orgId: "org_id", + shareWithUuid: "share_with_uuid", + shareWithType: "share_with_type" + }); + }); + function sharingInToJSON(sharingIn) { + return JSON.stringify(exports.SharingIn$outboundSchema.parse(sharingIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionsegmentchunk.js +var require_transcriptionsegmentchunk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionsegmentchunk.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionSegmentChunk$outboundSchema = exports.TranscriptionSegmentChunk$inboundSchema = void 0; + exports.transcriptionSegmentChunkToJSON = transcriptionSegmentChunkToJSON; + exports.transcriptionSegmentChunkFromJSON = transcriptionSegmentChunkFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionSegmentChunk$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription_segment").default("transcription_segment"), + text: z3.string(), + start: z3.number(), + end: z3.number(), + score: z3.nullable(z3.number()).optional(), + speaker_id: z3.nullable(z3.string()).optional() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "speaker_id": "speakerId" + }); + }); + exports.TranscriptionSegmentChunk$outboundSchema = z3.object({ + type: z3.literal("transcription_segment").default("transcription_segment"), + text: z3.string(), + start: z3.number(), + end: z3.number(), + score: z3.nullable(z3.number()).optional(), + speakerId: z3.nullable(z3.string()).optional(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + speakerId: "speaker_id", + additionalProperties: null + }) + }; + }); + function transcriptionSegmentChunkToJSON(transcriptionSegmentChunk) { + return JSON.stringify(exports.TranscriptionSegmentChunk$outboundSchema.parse(transcriptionSegmentChunk)); + } + function transcriptionSegmentChunkFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionSegmentChunk$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionSegmentChunk' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionresponse.js +var require_transcriptionresponse = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionresponse.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionResponse$inboundSchema = void 0; + exports.transcriptionResponseFromJSON = transcriptionResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var transcriptionsegmentchunk_js_1 = require_transcriptionsegmentchunk(); + var usageinfo_js_1 = require_usageinfo(); + exports.TranscriptionResponse$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + model: z3.string(), + text: z3.string(), + segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$inboundSchema).optional(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + language: z3.nullable(z3.string()) + }).catchall(z3.any()), "additionalProperties", true); + function transcriptionResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamdone.js +var require_transcriptionstreamdone = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamdone.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamDone$outboundSchema = exports.TranscriptionStreamDone$inboundSchema = void 0; + exports.transcriptionStreamDoneToJSON = transcriptionStreamDoneToJSON; + exports.transcriptionStreamDoneFromJSON = transcriptionStreamDoneFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var transcriptionsegmentchunk_js_1 = require_transcriptionsegmentchunk(); + var usageinfo_js_1 = require_usageinfo(); + exports.TranscriptionStreamDone$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + model: z3.string(), + text: z3.string(), + segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$inboundSchema).optional(), + usage: usageinfo_js_1.UsageInfo$inboundSchema, + type: z3.literal("transcription.done").default("transcription.done"), + language: z3.nullable(z3.string()) + }).catchall(z3.any()), "additionalProperties", true); + exports.TranscriptionStreamDone$outboundSchema = z3.object({ + model: z3.string(), + text: z3.string(), + segments: z3.array(transcriptionsegmentchunk_js_1.TranscriptionSegmentChunk$outboundSchema).optional(), + usage: usageinfo_js_1.UsageInfo$outboundSchema, + type: z3.literal("transcription.done").default("transcription.done"), + language: z3.nullable(z3.string()), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + additionalProperties: null + }) + }; + }); + function transcriptionStreamDoneToJSON(transcriptionStreamDone) { + return JSON.stringify(exports.TranscriptionStreamDone$outboundSchema.parse(transcriptionStreamDone)); + } + function transcriptionStreamDoneFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamDone$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamDone' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreameventtypes.js +var require_transcriptionstreameventtypes = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreameventtypes.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamEventTypes$inboundSchema = exports.TranscriptionStreamEventTypes = void 0; + var z3 = __importStar(require_v3()); + exports.TranscriptionStreamEventTypes = { + TranscriptionLanguage: "transcription.language", + TranscriptionSegment: "transcription.segment", + TranscriptionTextDelta: "transcription.text.delta", + TranscriptionDone: "transcription.done" + }; + exports.TranscriptionStreamEventTypes$inboundSchema = z3.nativeEnum(exports.TranscriptionStreamEventTypes); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamlanguage.js +var require_transcriptionstreamlanguage = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamlanguage.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamLanguage$outboundSchema = exports.TranscriptionStreamLanguage$inboundSchema = void 0; + exports.transcriptionStreamLanguageToJSON = transcriptionStreamLanguageToJSON; + exports.transcriptionStreamLanguageFromJSON = transcriptionStreamLanguageFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionStreamLanguage$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription.language").default("transcription.language"), + audio_language: z3.string() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "audio_language": "audioLanguage" + }); + }); + exports.TranscriptionStreamLanguage$outboundSchema = z3.object({ + type: z3.literal("transcription.language").default("transcription.language"), + audioLanguage: z3.string(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + audioLanguage: "audio_language", + additionalProperties: null + }) + }; + }); + function transcriptionStreamLanguageToJSON(transcriptionStreamLanguage) { + return JSON.stringify(exports.TranscriptionStreamLanguage$outboundSchema.parse(transcriptionStreamLanguage)); + } + function transcriptionStreamLanguageFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamLanguage$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamLanguage' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamsegmentdelta.js +var require_transcriptionstreamsegmentdelta = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamsegmentdelta.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamSegmentDelta$inboundSchema = void 0; + exports.transcriptionStreamSegmentDeltaFromJSON = transcriptionStreamSegmentDeltaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionStreamSegmentDelta$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription.segment").default("transcription.segment"), + text: z3.string(), + start: z3.number(), + end: z3.number(), + speaker_id: z3.nullable(z3.string()).optional() + }).catchall(z3.any()), "additionalProperties", true).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "speaker_id": "speakerId" + }); + }); + function transcriptionStreamSegmentDeltaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamSegmentDelta$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamSegmentDelta' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamtextdelta.js +var require_transcriptionstreamtextdelta = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamtextdelta.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamTextDelta$outboundSchema = exports.TranscriptionStreamTextDelta$inboundSchema = void 0; + exports.transcriptionStreamTextDeltaToJSON = transcriptionStreamTextDeltaToJSON; + exports.transcriptionStreamTextDeltaFromJSON = transcriptionStreamTextDeltaFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + exports.TranscriptionStreamTextDelta$inboundSchema = (0, schemas_js_1.collectExtraKeys)(z3.object({ + type: z3.literal("transcription.text.delta").default("transcription.text.delta"), + text: z3.string() + }).catchall(z3.any()), "additionalProperties", true); + exports.TranscriptionStreamTextDelta$outboundSchema = z3.object({ + type: z3.literal("transcription.text.delta").default("transcription.text.delta"), + text: z3.string(), + additionalProperties: z3.record(z3.any()).optional() + }).transform((v4) => { + return { + ...v4.additionalProperties, + ...(0, primitives_js_1.remap)(v4, { + additionalProperties: null + }) + }; + }); + function transcriptionStreamTextDeltaToJSON(transcriptionStreamTextDelta) { + return JSON.stringify(exports.TranscriptionStreamTextDelta$outboundSchema.parse(transcriptionStreamTextDelta)); + } + function transcriptionStreamTextDeltaFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamTextDelta$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamTextDelta' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamevents.js +var require_transcriptionstreamevents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/transcriptionstreamevents.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TranscriptionStreamEvents$inboundSchema = exports.TranscriptionStreamEventsData$inboundSchema = void 0; + exports.transcriptionStreamEventsDataFromJSON = transcriptionStreamEventsDataFromJSON; + exports.transcriptionStreamEventsFromJSON = transcriptionStreamEventsFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var transcriptionstreamdone_js_1 = require_transcriptionstreamdone(); + var transcriptionstreameventtypes_js_1 = require_transcriptionstreameventtypes(); + var transcriptionstreamlanguage_js_1 = require_transcriptionstreamlanguage(); + var transcriptionstreamsegmentdelta_js_1 = require_transcriptionstreamsegmentdelta(); + var transcriptionstreamtextdelta_js_1 = require_transcriptionstreamtextdelta(); + exports.TranscriptionStreamEventsData$inboundSchema = z3.union([ + transcriptionstreamdone_js_1.TranscriptionStreamDone$inboundSchema.and(z3.object({ type: z3.literal("transcription.done") })), + transcriptionstreamlanguage_js_1.TranscriptionStreamLanguage$inboundSchema.and(z3.object({ type: z3.literal("transcription.language") })), + transcriptionstreamsegmentdelta_js_1.TranscriptionStreamSegmentDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.segment") })), + transcriptionstreamtextdelta_js_1.TranscriptionStreamTextDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.text.delta") })) + ]); + function transcriptionStreamEventsDataFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamEventsData$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamEventsData' from JSON`); + } + exports.TranscriptionStreamEvents$inboundSchema = z3.object({ + event: transcriptionstreameventtypes_js_1.TranscriptionStreamEventTypes$inboundSchema, + data: z3.string().transform((v4, ctx) => { + try { + return JSON.parse(v4); + } catch (err) { + ctx.addIssue({ code: "custom", message: `malformed json: ${err}` }); + return z3.NEVER; + } + }).pipe(z3.union([ + transcriptionstreamdone_js_1.TranscriptionStreamDone$inboundSchema.and(z3.object({ type: z3.literal("transcription.done") })), + transcriptionstreamlanguage_js_1.TranscriptionStreamLanguage$inboundSchema.and(z3.object({ type: z3.literal("transcription.language") })), + transcriptionstreamsegmentdelta_js_1.TranscriptionStreamSegmentDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.segment") })), + transcriptionstreamtextdelta_js_1.TranscriptionStreamTextDelta$inboundSchema.and(z3.object({ type: z3.literal("transcription.text.delta") })) + ])) + }); + function transcriptionStreamEventsFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.TranscriptionStreamEvents$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'TranscriptionStreamEvents' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/unarchiveftmodelout.js +var require_unarchiveftmodelout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/unarchiveftmodelout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UnarchiveFTModelOut$inboundSchema = void 0; + exports.unarchiveFTModelOutFromJSON = unarchiveFTModelOutFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.UnarchiveFTModelOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.literal("model").default("model"), + archived: z3.boolean().default(false) + }); + function unarchiveFTModelOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UnarchiveFTModelOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UnarchiveFTModelOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/updateftmodelin.js +var require_updateftmodelin = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/updateftmodelin.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UpdateFTModelIn$outboundSchema = void 0; + exports.updateFTModelInToJSON = updateFTModelInToJSON; + var z3 = __importStar(require_v3()); + exports.UpdateFTModelIn$outboundSchema = z3.object({ + name: z3.nullable(z3.string()).optional(), + description: z3.nullable(z3.string()).optional() + }); + function updateFTModelInToJSON(updateFTModelIn) { + return JSON.stringify(exports.UpdateFTModelIn$outboundSchema.parse(updateFTModelIn)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/uploadfileout.js +var require_uploadfileout = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/uploadfileout.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UploadFileOut$inboundSchema = void 0; + exports.uploadFileOutFromJSON = uploadFileOutFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var filepurpose_js_1 = require_filepurpose(); + var sampletype_js_1 = require_sampletype(); + var source_js_1 = require_source(); + exports.UploadFileOut$inboundSchema = z3.object({ + id: z3.string(), + object: z3.string(), + bytes: z3.number().int(), + created_at: z3.number().int(), + filename: z3.string(), + purpose: filepurpose_js_1.FilePurpose$inboundSchema, + sample_type: sampletype_js_1.SampleType$inboundSchema, + num_lines: z3.nullable(z3.number().int()).optional(), + mimetype: z3.nullable(z3.string()).optional(), + source: source_js_1.Source$inboundSchema, + signature: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + "bytes": "sizeBytes", + "created_at": "createdAt", + "sample_type": "sampleType", + "num_lines": "numLines" + }); + }); + function uploadFileOutFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.UploadFileOut$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'UploadFileOut' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/validationerror.js +var require_validationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/validationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValidationError$inboundSchema = exports.Loc$inboundSchema = void 0; + exports.locFromJSON = locFromJSON; + exports.validationErrorFromJSON = validationErrorFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + exports.Loc$inboundSchema = z3.union([z3.string(), z3.number().int()]); + function locFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.Loc$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'Loc' from JSON`); + } + exports.ValidationError$inboundSchema = z3.object({ + loc: z3.array(z3.union([z3.string(), z3.number().int()])), + msg: z3.string(), + type: z3.string() + }); + function validationErrorFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ValidationError$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ValidationError' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/components/index.js +var require_components = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/components/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_agent(), exports); + __exportStar(require_agentaliasresponse(), exports); + __exportStar(require_agentconversation(), exports); + __exportStar(require_agentcreationrequest(), exports); + __exportStar(require_agenthandoffdoneevent(), exports); + __exportStar(require_agenthandoffentry(), exports); + __exportStar(require_agenthandoffstartedevent(), exports); + __exportStar(require_agentscompletionrequest(), exports); + __exportStar(require_agentscompletionstreamrequest(), exports); + __exportStar(require_agentupdaterequest(), exports); + __exportStar(require_apiendpoint(), exports); + __exportStar(require_archiveftmodelout(), exports); + __exportStar(require_assistantmessage(), exports); + __exportStar(require_audiochunk(), exports); + __exportStar(require_audioencoding(), exports); + __exportStar(require_audioformat(), exports); + __exportStar(require_audiotranscriptionrequest(), exports); + __exportStar(require_audiotranscriptionrequeststream(), exports); + __exportStar(require_basemodelcard(), exports); + __exportStar(require_batcherror(), exports); + __exportStar(require_batchjobin(), exports); + __exportStar(require_batchjobout(), exports); + __exportStar(require_batchjobsout(), exports); + __exportStar(require_batchjobstatus(), exports); + __exportStar(require_batchrequest(), exports); + __exportStar(require_builtinconnectors(), exports); + __exportStar(require_chatclassificationrequest(), exports); + __exportStar(require_chatcompletionchoice(), exports); + __exportStar(require_chatcompletionrequest(), exports); + __exportStar(require_chatcompletionresponse(), exports); + __exportStar(require_chatcompletionstreamrequest(), exports); + __exportStar(require_chatmoderationrequest(), exports); + __exportStar(require_checkpointout(), exports); + __exportStar(require_classificationrequest(), exports); + __exportStar(require_classificationresponse(), exports); + __exportStar(require_classificationtargetresult(), exports); + __exportStar(require_classifierdetailedjobout(), exports); + __exportStar(require_classifierftmodelout(), exports); + __exportStar(require_classifierjobout(), exports); + __exportStar(require_classifiertargetin(), exports); + __exportStar(require_classifiertargetout(), exports); + __exportStar(require_classifiertrainingparameters(), exports); + __exportStar(require_classifiertrainingparametersin(), exports); + __exportStar(require_codeinterpretertool(), exports); + __exportStar(require_completionargs(), exports); + __exportStar(require_completionargsstop(), exports); + __exportStar(require_completionchunk(), exports); + __exportStar(require_completiondetailedjobout(), exports); + __exportStar(require_completionevent(), exports); + __exportStar(require_completionftmodelout(), exports); + __exportStar(require_completionjobout(), exports); + __exportStar(require_completionresponsestreamchoice(), exports); + __exportStar(require_completiontrainingparameters(), exports); + __exportStar(require_completiontrainingparametersin(), exports); + __exportStar(require_contentchunk(), exports); + __exportStar(require_conversationappendrequest(), exports); + __exportStar(require_conversationappendstreamrequest(), exports); + __exportStar(require_conversationevents(), exports); + __exportStar(require_conversationhistory(), exports); + __exportStar(require_conversationinputs(), exports); + __exportStar(require_conversationmessages(), exports); + __exportStar(require_conversationrequest(), exports); + __exportStar(require_conversationresponse(), exports); + __exportStar(require_conversationrestartrequest(), exports); + __exportStar(require_conversationrestartstreamrequest(), exports); + __exportStar(require_conversationstreamrequest(), exports); + __exportStar(require_conversationusageinfo(), exports); + __exportStar(require_deletefileout(), exports); + __exportStar(require_deletemodelout(), exports); + __exportStar(require_deltamessage(), exports); + __exportStar(require_documentlibrarytool(), exports); + __exportStar(require_documentout(), exports); + __exportStar(require_documenttextcontent(), exports); + __exportStar(require_documentupdatein(), exports); + __exportStar(require_documenturlchunk(), exports); + __exportStar(require_embeddingdtype(), exports); + __exportStar(require_embeddingrequest(), exports); + __exportStar(require_embeddingresponse(), exports); + __exportStar(require_embeddingresponsedata(), exports); + __exportStar(require_encodingformat(), exports); + __exportStar(require_entitytype(), exports); + __exportStar(require_eventout(), exports); + __exportStar(require_file(), exports); + __exportStar(require_filechunk(), exports); + __exportStar(require_filepurpose(), exports); + __exportStar(require_fileschema(), exports); + __exportStar(require_filesignedurl(), exports); + __exportStar(require_fimcompletionrequest(), exports); + __exportStar(require_fimcompletionresponse(), exports); + __exportStar(require_fimcompletionstreamrequest(), exports); + __exportStar(require_finetuneablemodeltype(), exports); + __exportStar(require_ftclassifierlossfunction(), exports); + __exportStar(require_ftmodelcapabilitiesout(), exports); + __exportStar(require_ftmodelcard(), exports); + __exportStar(require_function(), exports); + __exportStar(require_functioncall(), exports); + __exportStar(require_functioncallentry(), exports); + __exportStar(require_functioncallentryarguments(), exports); + __exportStar(require_functioncallevent(), exports); + __exportStar(require_functionname(), exports); + __exportStar(require_functionresultentry(), exports); + __exportStar(require_functiontool(), exports); + __exportStar(require_githubrepositoryin(), exports); + __exportStar(require_githubrepositoryout(), exports); + __exportStar(require_imagedetail(), exports); + __exportStar(require_imagegenerationtool(), exports); + __exportStar(require_imageurl(), exports); + __exportStar(require_imageurlchunk(), exports); + __exportStar(require_inputentries(), exports); + __exportStar(require_inputs(), exports); + __exportStar(require_instructrequest(), exports); + __exportStar(require_jobin(), exports); + __exportStar(require_jobmetadataout(), exports); + __exportStar(require_jobsout(), exports); + __exportStar(require_jsonschema(), exports); + __exportStar(require_legacyjobmetadataout(), exports); + __exportStar(require_libraryin(), exports); + __exportStar(require_libraryinupdate(), exports); + __exportStar(require_libraryout(), exports); + __exportStar(require_listdocumentout(), exports); + __exportStar(require_listfilesout(), exports); + __exportStar(require_listlibraryout(), exports); + __exportStar(require_listsharingout(), exports); + __exportStar(require_messageentries(), exports); + __exportStar(require_messageinputcontentchunks(), exports); + __exportStar(require_messageinputentry(), exports); + __exportStar(require_messageoutputcontentchunks(), exports); + __exportStar(require_messageoutputentry(), exports); + __exportStar(require_messageoutputevent(), exports); + __exportStar(require_metricout(), exports); + __exportStar(require_mistralpromptmode(), exports); + __exportStar(require_modelcapabilities(), exports); + __exportStar(require_modelconversation(), exports); + __exportStar(require_modellist(), exports); + __exportStar(require_moderationobject(), exports); + __exportStar(require_moderationresponse(), exports); + __exportStar(require_ocrimageobject(), exports); + __exportStar(require_ocrpagedimensions(), exports); + __exportStar(require_ocrpageobject(), exports); + __exportStar(require_ocrrequest(), exports); + __exportStar(require_ocrresponse(), exports); + __exportStar(require_ocrtableobject(), exports); + __exportStar(require_ocrusageinfo(), exports); + __exportStar(require_outputcontentchunks(), exports); + __exportStar(require_paginationinfo(), exports); + __exportStar(require_prediction(), exports); + __exportStar(require_processingstatusout(), exports); + __exportStar(require_realtimetranscriptionerror(), exports); + __exportStar(require_realtimetranscriptionerrordetail(), exports); + __exportStar(require_realtimetranscriptioninputaudioappend(), exports); + __exportStar(require_realtimetranscriptioninputaudioend(), exports); + __exportStar(require_realtimetranscriptioninputaudioflush(), exports); + __exportStar(require_realtimetranscriptionsession(), exports); + __exportStar(require_realtimetranscriptionsessioncreated(), exports); + __exportStar(require_realtimetranscriptionsessionupdated(), exports); + __exportStar(require_realtimetranscriptionsessionupdatemessage(), exports); + __exportStar(require_realtimetranscriptionsessionupdatepayload(), exports); + __exportStar(require_referencechunk(), exports); + __exportStar(require_requestsource(), exports); + __exportStar(require_responsedoneevent(), exports); + __exportStar(require_responseerrorevent(), exports); + __exportStar(require_responseformat(), exports); + __exportStar(require_responseformats(), exports); + __exportStar(require_responsestartedevent(), exports); + __exportStar(require_retrievefileout(), exports); + __exportStar(require_sampletype(), exports); + __exportStar(require_security2(), exports); + __exportStar(require_shareenum(), exports); + __exportStar(require_sharingdelete(), exports); + __exportStar(require_sharingin(), exports); + __exportStar(require_sharingout(), exports); + __exportStar(require_source(), exports); + __exportStar(require_ssetypes(), exports); + __exportStar(require_systemmessage(), exports); + __exportStar(require_systemmessagecontentchunks(), exports); + __exportStar(require_textchunk(), exports); + __exportStar(require_thinkchunk(), exports); + __exportStar(require_timestampgranularity(), exports); + __exportStar(require_tool(), exports); + __exportStar(require_toolcall(), exports); + __exportStar(require_toolcallconfirmation(), exports); + __exportStar(require_toolchoice(), exports); + __exportStar(require_toolchoiceenum(), exports); + __exportStar(require_toolconfiguration(), exports); + __exportStar(require_toolexecutiondeltaevent(), exports); + __exportStar(require_toolexecutiondoneevent(), exports); + __exportStar(require_toolexecutionentry(), exports); + __exportStar(require_toolexecutionstartedevent(), exports); + __exportStar(require_toolfilechunk(), exports); + __exportStar(require_toolmessage(), exports); + __exportStar(require_toolreferencechunk(), exports); + __exportStar(require_tooltypes(), exports); + __exportStar(require_trainingfile(), exports); + __exportStar(require_transcriptionresponse(), exports); + __exportStar(require_transcriptionsegmentchunk(), exports); + __exportStar(require_transcriptionstreamdone(), exports); + __exportStar(require_transcriptionstreamevents(), exports); + __exportStar(require_transcriptionstreameventtypes(), exports); + __exportStar(require_transcriptionstreamlanguage(), exports); + __exportStar(require_transcriptionstreamsegmentdelta(), exports); + __exportStar(require_transcriptionstreamtextdelta(), exports); + __exportStar(require_unarchiveftmodelout(), exports); + __exportStar(require_updateftmodelin(), exports); + __exportStar(require_uploadfileout(), exports); + __exportStar(require_usageinfo(), exports); + __exportStar(require_usermessage(), exports); + __exportStar(require_validationerror(), exports); + __exportStar(require_wandbintegration(), exports); + __exportStar(require_wandbintegrationout(), exports); + __exportStar(require_websearchpremiumtool(), exports); + __exportStar(require_websearchtool(), exports); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpvalidationerror.js +var require_httpvalidationerror = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/httpvalidationerror.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTPValidationError$inboundSchema = exports.HTTPValidationError = void 0; + var z3 = __importStar(require_v3()); + var components = __importStar(require_components()); + var mistralerror_js_1 = require_mistralerror(); + var HTTPValidationError = class extends mistralerror_js_1.MistralError { + constructor(err, httpMeta) { + const message = "message" in err && typeof err.message === "string" ? err.message : `API error occurred: ${JSON.stringify(err)}`; + super(message, httpMeta); + this.data$ = err; + if (err.detail != null) + this.detail = err.detail; + this.name = "HTTPValidationError"; + } + }; + exports.HTTPValidationError = HTTPValidationError; + exports.HTTPValidationError$inboundSchema = z3.object({ + detail: z3.array(components.ValidationError$inboundSchema).optional(), + request$: z3.instanceof(Request), + response$: z3.instanceof(Response), + body$: z3.string() + }).transform((v4) => { + return new HTTPValidationError(v4, { + request: v4.request$, + response: v4.response$, + body: v4.body$ + }); + }); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/errors/index.js +var require_errors2 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/errors/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_httpclienterrors(), exports); + __exportStar(require_httpvalidationerror(), exports); + __exportStar(require_mistralerror(), exports); + __exportStar(require_responsevalidationerror(), exports); + __exportStar(require_sdkerror(), exports); + __exportStar(require_sdkvalidationerror(), exports); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/async.js +var require_async = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/async.js"(exports) { + "use strict"; + init_process_shim(); + var __classPrivateFieldSet3 = exports && exports.__classPrivateFieldSet || function(receiver, state, value, kind, f4) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f4.call(receiver, value) : f4 ? f4.value = value : state.set(receiver, value), value; + }; + var __classPrivateFieldGet3 = exports && exports.__classPrivateFieldGet || function(receiver, state, kind, f4) { + if (kind === "a" && !f4) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f4 : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f4 : kind === "a" ? f4.call(receiver) : f4 ? f4.value : state.get(receiver); + }; + var _APIPromise_promise; + var _APIPromise_unwrapped; + var _a7; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.APIPromise = void 0; + var APIPromise4 = class { + constructor(p4) { + _APIPromise_promise.set(this, void 0); + _APIPromise_unwrapped.set(this, void 0); + this[_a7] = "APIPromise"; + __classPrivateFieldSet3(this, _APIPromise_promise, p4 instanceof Promise ? p4 : Promise.resolve(p4), "f"); + __classPrivateFieldSet3(this, _APIPromise_unwrapped, p4 instanceof Promise ? __classPrivateFieldGet3(this, _APIPromise_promise, "f").then(([value]) => value) : Promise.resolve(p4[0]), "f"); + } + then(onfulfilled, onrejected) { + return __classPrivateFieldGet3(this, _APIPromise_promise, "f").then(onfulfilled ? ([value]) => onfulfilled(value) : void 0, onrejected); + } + catch(onrejected) { + return __classPrivateFieldGet3(this, _APIPromise_unwrapped, "f").catch(onrejected); + } + finally(onfinally) { + return __classPrivateFieldGet3(this, _APIPromise_unwrapped, "f").finally(onfinally); + } + $inspect() { + return __classPrivateFieldGet3(this, _APIPromise_promise, "f"); + } + }; + exports.APIPromise = APIPromise4; + _APIPromise_promise = /* @__PURE__ */ new WeakMap(), _APIPromise_unwrapped = /* @__PURE__ */ new WeakMap(), _a7 = Symbol.toStringTag; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsComplete.js +var require_agentsComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.agentsComplete = agentsComplete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function agentsComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentsCompletionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/completions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_completion_v1_agents_completions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ChatCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/lib/event-streams.js +var require_event_streams = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/lib/event-streams.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EventStream = void 0; + var EventStream4 = class extends ReadableStream { + constructor(responseBody, parse3) { + const upstream = responseBody.getReader(); + let buffer = new Uint8Array(); + super({ + async pull(downstream) { + try { + while (true) { + const match2 = findBoundary(buffer); + if (!match2) { + const chunk = await upstream.read(); + if (chunk.done) + return downstream.close(); + buffer = concatBuffer(buffer, chunk.value); + continue; + } + const message = buffer.slice(0, match2.index); + buffer = buffer.slice(match2.index + match2.length); + const item = parseMessage2(message, parse3); + if (item && !item.done) + return downstream.enqueue(item.value); + if (item?.done) { + await upstream.cancel("done"); + return downstream.close(); + } + } + } catch (e9) { + downstream.error(e9); + await upstream.cancel(e9); + } + }, + cancel: (reason) => upstream.cancel(reason) + }); + } + // Polyfill for older browsers + [Symbol.asyncIterator]() { + const fn = ReadableStream.prototype[Symbol.asyncIterator]; + if (typeof fn === "function") + return fn.call(this); + const reader = this.getReader(); + return { + next: async () => { + const r8 = await reader.read(); + if (r8.done) { + reader.releaseLock(); + return { done: true, value: void 0 }; + } + return { done: false, value: r8.value }; + }, + throw: async (e9) => { + await reader.cancel(e9); + reader.releaseLock(); + return { done: true, value: void 0 }; + }, + return: async () => { + await reader.cancel("done"); + reader.releaseLock(); + return { done: true, value: void 0 }; + }, + [Symbol.asyncIterator]() { + return this; + } + }; + } + }; + exports.EventStream = EventStream4; + function concatBuffer(a3, b4) { + const c6 = new Uint8Array(a3.length + b4.length); + c6.set(a3, 0); + c6.set(b4, a3.length); + return c6; + } + function findBoundary(buf) { + const len = buf.length; + for (let i7 = 0; i7 < len; i7++) { + if (i7 <= len - 4 && buf[i7] === 13 && buf[i7 + 1] === 10 && buf[i7 + 2] === 13 && buf[i7 + 3] === 10) { + return { index: i7, length: 4 }; + } + if (i7 <= len - 2 && buf[i7] === 13 && buf[i7 + 1] === 13) { + return { index: i7, length: 2 }; + } + if (i7 <= len - 2 && buf[i7] === 10 && buf[i7 + 1] === 10) { + return { index: i7, length: 2 }; + } + } + return null; + } + function parseMessage2(chunk, parse3) { + const text3 = new TextDecoder().decode(chunk); + const lines = text3.split(/\r\n|\r|\n/); + const dataLines = []; + const ret = {}; + let ignore = true; + for (const line of lines) { + if (!line || line.startsWith(":")) + continue; + ignore = false; + const i7 = line.indexOf(":"); + const field = line.slice(0, i7); + const value = line[i7 + 1] === " " ? line.slice(i7 + 2) : line.slice(i7 + 1); + if (field === "data") + dataLines.push(value); + else if (field === "event") + ret.event = value; + else if (field === "id") + ret.id = value; + else if (field === "retry") { + const n7 = Number(value); + if (!isNaN(n7)) + ret.retry = n7; + } + } + if (ignore) + return; + if (dataLines.length) + ret.data = dataLines.join("\n"); + return parse3(ret); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsStream.js +var require_agentsStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/agentsStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.agentsStream = agentsStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function agentsStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentsCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/completions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "stream_agents", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + if (rawEvent.data === "[DONE]") + return { done: true }; + return { + value: components.CompletionEvent$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/agents.js +var require_agents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/agents.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Agents = void 0; + var agentsComplete_js_1 = require_agentsComplete(); + var agentsStream_js_1 = require_agentsStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Agents = class extends sdks_js_1.ClientSDK { + /** + * Agents Completion + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, agentsComplete_js_1.agentsComplete)(this, request, options)); + } + /** + * Stream Agents completion + * + * @remarks + * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON. + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, agentsStream_js_1.agentsStream)(this, request, options)); + } + }; + exports.Agents = Agents; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/types/streams.js +var require_streams = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/types/streams.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isReadableStream = isReadableStream; + function isReadableStream(val2) { + if (typeof val2 !== "object" || val2 === null) { + return false; + } + const stream2 = val2; + return typeof stream2.getReader === "function" && typeof stream2.cancel === "function" && typeof stream2.tee === "function"; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsComplete.js +var require_audioTranscriptionsComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.audioTranscriptionsComplete = audioTranscriptionsComplete; + var encodings_js_1 = require_encodings(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function audioTranscriptionsComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AudioTranscriptionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + (0, encodings_js_1.appendForm)(body, "model", payload.model); + if (payload.context_bias !== void 0) { + (0, encodings_js_1.appendForm)(body, "context_bias", payload.context_bias); + } + if (payload.diarize !== void 0) { + (0, encodings_js_1.appendForm)(body, "diarize", payload.diarize); + } + if (payload.file !== void 0) { + if ((0, blobs_js_1.isBlobLike)(payload.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.file); + } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName); + } + } + if (payload.file_id !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_id", payload.file_id); + } + if (payload.file_url !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_url", payload.file_url); + } + if (payload.language !== void 0) { + (0, encodings_js_1.appendForm)(body, "language", payload.language); + } + if (payload.stream !== void 0) { + (0, encodings_js_1.appendForm)(body, "stream", payload.stream); + } + if (payload.temperature !== void 0) { + (0, encodings_js_1.appendForm)(body, "temperature", payload.temperature); + } + if (payload.timestamp_granularities !== void 0) { + (0, encodings_js_1.appendForm)(body, "timestamp_granularities", payload.timestamp_granularities); + } + const path6 = (0, url_js_1.pathToFunc)("/v1/audio/transcriptions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "audio_api_v1_transcriptions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.TranscriptionResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsStream.js +var require_audioTranscriptionsStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/audioTranscriptionsStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.audioTranscriptionsStream = audioTranscriptionsStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function audioTranscriptionsStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AudioTranscriptionRequestStream$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + (0, encodings_js_1.appendForm)(body, "model", payload.model); + if (payload.context_bias !== void 0) { + (0, encodings_js_1.appendForm)(body, "context_bias", payload.context_bias); + } + if (payload.diarize !== void 0) { + (0, encodings_js_1.appendForm)(body, "diarize", payload.diarize); + } + if (payload.file !== void 0) { + if ((0, blobs_js_1.isBlobLike)(payload.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.file); + } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName); + } + } + if (payload.file_id !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_id", payload.file_id); + } + if (payload.file_url !== void 0) { + (0, encodings_js_1.appendForm)(body, "file_url", payload.file_url); + } + if (payload.language !== void 0) { + (0, encodings_js_1.appendForm)(body, "language", payload.language); + } + if (payload.stream !== void 0) { + (0, encodings_js_1.appendForm)(body, "stream", payload.stream); + } + if (payload.temperature !== void 0) { + (0, encodings_js_1.appendForm)(body, "temperature", payload.temperature); + } + if (payload.timestamp_granularities !== void 0) { + (0, encodings_js_1.appendForm)(body, "timestamp_granularities", payload.timestamp_granularities); + } + const path6 = (0, url_js_1.pathToFunc)("/v1/audio/transcriptions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "audio_api_v1_transcriptions_post_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.TranscriptionStreamEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/transcriptions.js +var require_transcriptions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/transcriptions.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Transcriptions = void 0; + var audioTranscriptionsComplete_js_1 = require_audioTranscriptionsComplete(); + var audioTranscriptionsStream_js_1 = require_audioTranscriptionsStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Transcriptions2 = class extends sdks_js_1.ClientSDK { + /** + * Create Transcription + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, audioTranscriptionsComplete_js_1.audioTranscriptionsComplete)(this, request, options)); + } + /** + * Create Streaming Transcription (SSE) + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, audioTranscriptionsStream_js_1.audioTranscriptionsStream)(this, request, options)); + } + }; + exports.Transcriptions = Transcriptions2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/audio.js +var require_audio = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/audio.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Audio = void 0; + var sdks_js_1 = require_sdks(); + var transcriptions_js_1 = require_transcriptions(); + var Audio3 = class extends sdks_js_1.ClientSDK { + get transcriptions() { + return this._transcriptions ?? (this._transcriptions = new transcriptions_js_1.Transcriptions(this._options)); + } + }; + exports.Audio = Audio3; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentscreateorupdatealias.js +var require_agentsapiv1agentscreateorupdatealias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentscreateorupdatealias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON = agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema = z3.object({ + agentId: z3.string(), + alias: z3.string(), + version: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsCreateOrUpdateAliasRequestToJSON(agentsApiV1AgentsCreateOrUpdateAliasRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema.parse(agentsApiV1AgentsCreateOrUpdateAliasRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdelete.js +var require_agentsapiv1agentsdelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsDeleteRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsDeleteRequestToJSON = agentsApiV1AgentsDeleteRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsDeleteRequest$outboundSchema = z3.object({ + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsDeleteRequestToJSON(agentsApiV1AgentsDeleteRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsDeleteRequest$outboundSchema.parse(agentsApiV1AgentsDeleteRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdeletealias.js +var require_agentsapiv1agentsdeletealias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsdeletealias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsDeleteAliasRequestToJSON = agentsApiV1AgentsDeleteAliasRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema = z3.object({ + agentId: z3.string(), + alias: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsDeleteAliasRequestToJSON(agentsApiV1AgentsDeleteAliasRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema.parse(agentsApiV1AgentsDeleteAliasRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsget.js +var require_agentsapiv1agentsget = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsget.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsGetRequest$outboundSchema = exports.AgentVersion$outboundSchema = void 0; + exports.agentVersionToJSON = agentVersionToJSON; + exports.agentsApiV1AgentsGetRequestToJSON = agentsApiV1AgentsGetRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentVersion$outboundSchema = z3.union([z3.number().int(), z3.string()]); + function agentVersionToJSON(agentVersion) { + return JSON.stringify(exports.AgentVersion$outboundSchema.parse(agentVersion)); + } + exports.AgentsApiV1AgentsGetRequest$outboundSchema = z3.object({ + agentId: z3.string(), + agentVersion: z3.nullable(z3.union([z3.number().int(), z3.string()])).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id", + agentVersion: "agent_version" + }); + }); + function agentsApiV1AgentsGetRequestToJSON(agentsApiV1AgentsGetRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsGetRequest$outboundSchema.parse(agentsApiV1AgentsGetRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsgetversion.js +var require_agentsapiv1agentsgetversion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsgetversion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsGetVersionRequestToJSON = agentsApiV1AgentsGetVersionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema = z3.object({ + agentId: z3.string(), + version: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsGetVersionRequestToJSON(agentsApiV1AgentsGetVersionRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsGetVersionRequest$outboundSchema.parse(agentsApiV1AgentsGetVersionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslist.js +var require_agentsapiv1agentslist = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslist.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsListRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsListRequestToJSON = agentsApiV1AgentsListRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1AgentsListRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(20), + deploymentChat: z3.nullable(z3.boolean()).optional(), + sources: z3.nullable(z3.array(components.RequestSource$outboundSchema)).optional(), + name: z3.nullable(z3.string()).optional(), + search: z3.nullable(z3.string()).optional(), + id: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + deploymentChat: "deployment_chat" + }); + }); + function agentsApiV1AgentsListRequestToJSON(agentsApiV1AgentsListRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsListRequest$outboundSchema.parse(agentsApiV1AgentsListRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversionaliases.js +var require_agentsapiv1agentslistversionaliases = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversionaliases.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsListVersionAliasesRequestToJSON = agentsApiV1AgentsListVersionAliasesRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema = z3.object({ + agentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsListVersionAliasesRequestToJSON(agentsApiV1AgentsListVersionAliasesRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema.parse(agentsApiV1AgentsListVersionAliasesRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversions.js +var require_agentsapiv1agentslistversions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentslistversions.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsListVersionsRequestToJSON = agentsApiV1AgentsListVersionsRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema = z3.object({ + agentId: z3.string(), + page: z3.number().int().default(0), + pageSize: z3.number().int().default(20) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id", + pageSize: "page_size" + }); + }); + function agentsApiV1AgentsListVersionsRequestToJSON(agentsApiV1AgentsListVersionsRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsListVersionsRequest$outboundSchema.parse(agentsApiV1AgentsListVersionsRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdate.js +var require_agentsapiv1agentsupdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsUpdateRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsUpdateRequestToJSON = agentsApiV1AgentsUpdateRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1AgentsUpdateRequest$outboundSchema = z3.object({ + agentId: z3.string(), + agentUpdateRequest: components.AgentUpdateRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id", + agentUpdateRequest: "AgentUpdateRequest" + }); + }); + function agentsApiV1AgentsUpdateRequestToJSON(agentsApiV1AgentsUpdateRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsUpdateRequest$outboundSchema.parse(agentsApiV1AgentsUpdateRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdateversion.js +var require_agentsapiv1agentsupdateversion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1agentsupdateversion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema = void 0; + exports.agentsApiV1AgentsUpdateVersionRequestToJSON = agentsApiV1AgentsUpdateVersionRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema = z3.object({ + agentId: z3.string(), + version: z3.number().int() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + agentId: "agent_id" + }); + }); + function agentsApiV1AgentsUpdateVersionRequestToJSON(agentsApiV1AgentsUpdateVersionRequest) { + return JSON.stringify(exports.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema.parse(agentsApiV1AgentsUpdateVersionRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappend.js +var require_agentsapiv1conversationsappend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsAppendRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsAppendRequestToJSON = agentsApiV1ConversationsAppendRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsAppendRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationAppendRequest: components.ConversationAppendRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationAppendRequest: "ConversationAppendRequest" + }); + }); + function agentsApiV1ConversationsAppendRequestToJSON(agentsApiV1ConversationsAppendRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsAppendRequest$outboundSchema.parse(agentsApiV1ConversationsAppendRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappendstream.js +var require_agentsapiv1conversationsappendstream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsappendstream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsAppendStreamRequestToJSON = agentsApiV1ConversationsAppendStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationAppendStreamRequest: components.ConversationAppendStreamRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationAppendStreamRequest: "ConversationAppendStreamRequest" + }); + }); + function agentsApiV1ConversationsAppendStreamRequestToJSON(agentsApiV1ConversationsAppendStreamRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema.parse(agentsApiV1ConversationsAppendStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsdelete.js +var require_agentsapiv1conversationsdelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsdelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsDeleteRequestToJSON = agentsApiV1ConversationsDeleteRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsDeleteRequestToJSON(agentsApiV1ConversationsDeleteRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsDeleteRequest$outboundSchema.parse(agentsApiV1ConversationsDeleteRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsget.js +var require_agentsapiv1conversationsget = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsget.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema = exports.AgentsApiV1ConversationsGetRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsGetRequestToJSON = agentsApiV1ConversationsGetRequestToJSON; + exports.agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON = agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsGetRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsGetRequestToJSON(agentsApiV1ConversationsGetRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsGetRequest$outboundSchema.parse(agentsApiV1ConversationsGetRequest)); + } + exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema = z3.union([ + components.ModelConversation$inboundSchema, + components.AgentConversation$inboundSchema + ]); + function agentsApiV1ConversationsGetResponseV1ConversationsGetFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'AgentsApiV1ConversationsGetResponseV1ConversationsGet' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationshistory.js +var require_agentsapiv1conversationshistory = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationshistory.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsHistoryRequestToJSON = agentsApiV1ConversationsHistoryRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsHistoryRequestToJSON(agentsApiV1ConversationsHistoryRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsHistoryRequest$outboundSchema.parse(agentsApiV1ConversationsHistoryRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationslist.js +var require_agentsapiv1conversationslist = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationslist.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ResponseBody$inboundSchema = exports.AgentsApiV1ConversationsListRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsListRequestToJSON = agentsApiV1ConversationsListRequestToJSON; + exports.responseBodyFromJSON = responseBodyFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsListRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + metadata: z3.nullable(z3.record(z3.any())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size" + }); + }); + function agentsApiV1ConversationsListRequestToJSON(agentsApiV1ConversationsListRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsListRequest$outboundSchema.parse(agentsApiV1ConversationsListRequest)); + } + exports.ResponseBody$inboundSchema = z3.union([ + components.ModelConversation$inboundSchema, + components.AgentConversation$inboundSchema + ]); + function responseBodyFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.ResponseBody$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'ResponseBody' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsmessages.js +var require_agentsapiv1conversationsmessages = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsmessages.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsMessagesRequestToJSON = agentsApiV1ConversationsMessagesRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema = z3.object({ + conversationId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id" + }); + }); + function agentsApiV1ConversationsMessagesRequestToJSON(agentsApiV1ConversationsMessagesRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsMessagesRequest$outboundSchema.parse(agentsApiV1ConversationsMessagesRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestart.js +var require_agentsapiv1conversationsrestart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsRestartRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsRestartRequestToJSON = agentsApiV1ConversationsRestartRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsRestartRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationRestartRequest: components.ConversationRestartRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationRestartRequest: "ConversationRestartRequest" + }); + }); + function agentsApiV1ConversationsRestartRequestToJSON(agentsApiV1ConversationsRestartRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsRestartRequest$outboundSchema.parse(agentsApiV1ConversationsRestartRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestartstream.js +var require_agentsapiv1conversationsrestartstream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/agentsapiv1conversationsrestartstream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema = void 0; + exports.agentsApiV1ConversationsRestartStreamRequestToJSON = agentsApiV1ConversationsRestartStreamRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema = z3.object({ + conversationId: z3.string(), + conversationRestartStreamRequest: components.ConversationRestartStreamRequest$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + conversationId: "conversation_id", + conversationRestartStreamRequest: "ConversationRestartStreamRequest" + }); + }); + function agentsApiV1ConversationsRestartStreamRequestToJSON(agentsApiV1ConversationsRestartStreamRequest) { + return JSON.stringify(exports.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema.parse(agentsApiV1ConversationsRestartStreamRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/deletemodelv1modelsmodeliddelete.js +var require_deletemodelv1modelsmodeliddelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/deletemodelv1modelsmodeliddelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = void 0; + exports.deleteModelV1ModelsModelIdDeleteRequestToJSON = deleteModelV1ModelsModelIdDeleteRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function deleteModelV1ModelsModelIdDeleteRequestToJSON(deleteModelV1ModelsModelIdDeleteRequest) { + return JSON.stringify(exports.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema.parse(deleteModelV1ModelsModelIdDeleteRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdeletefile.js +var require_filesapiroutesdeletefile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdeletefile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesDeleteFileRequest$outboundSchema = void 0; + exports.filesApiRoutesDeleteFileRequestToJSON = filesApiRoutesDeleteFileRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesDeleteFileRequest$outboundSchema = z3.object({ + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesDeleteFileRequestToJSON(filesApiRoutesDeleteFileRequest) { + return JSON.stringify(exports.FilesApiRoutesDeleteFileRequest$outboundSchema.parse(filesApiRoutesDeleteFileRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdownloadfile.js +var require_filesapiroutesdownloadfile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesdownloadfile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesDownloadFileRequest$outboundSchema = void 0; + exports.filesApiRoutesDownloadFileRequestToJSON = filesApiRoutesDownloadFileRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesDownloadFileRequest$outboundSchema = z3.object({ + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesDownloadFileRequestToJSON(filesApiRoutesDownloadFileRequest) { + return JSON.stringify(exports.FilesApiRoutesDownloadFileRequest$outboundSchema.parse(filesApiRoutesDownloadFileRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesgetsignedurl.js +var require_filesapiroutesgetsignedurl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesgetsignedurl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = void 0; + exports.filesApiRoutesGetSignedUrlRequestToJSON = filesApiRoutesGetSignedUrlRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema = z3.object({ + fileId: z3.string(), + expiry: z3.number().int().default(24) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesGetSignedUrlRequestToJSON(filesApiRoutesGetSignedUrlRequest) { + return JSON.stringify(exports.FilesApiRoutesGetSignedUrlRequest$outboundSchema.parse(filesApiRoutesGetSignedUrlRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapirouteslistfiles.js +var require_filesapirouteslistfiles = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapirouteslistfiles.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesListFilesRequest$outboundSchema = void 0; + exports.filesApiRoutesListFilesRequestToJSON = filesApiRoutesListFilesRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.FilesApiRoutesListFilesRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + includeTotal: z3.boolean().default(true), + sampleType: z3.nullable(z3.array(components.SampleType$outboundSchema)).optional(), + source: z3.nullable(z3.array(components.Source$outboundSchema)).optional(), + search: z3.nullable(z3.string()).optional(), + purpose: z3.nullable(components.FilePurpose$outboundSchema).optional(), + mimetypes: z3.nullable(z3.array(z3.string())).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + includeTotal: "include_total", + sampleType: "sample_type" + }); + }); + function filesApiRoutesListFilesRequestToJSON(filesApiRoutesListFilesRequest) { + return JSON.stringify(exports.FilesApiRoutesListFilesRequest$outboundSchema.parse(filesApiRoutesListFilesRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesretrievefile.js +var require_filesapiroutesretrievefile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesretrievefile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = void 0; + exports.filesApiRoutesRetrieveFileRequestToJSON = filesApiRoutesRetrieveFileRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.FilesApiRoutesRetrieveFileRequest$outboundSchema = z3.object({ + fileId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + fileId: "file_id" + }); + }); + function filesApiRoutesRetrieveFileRequestToJSON(filesApiRoutesRetrieveFileRequest) { + return JSON.stringify(exports.FilesApiRoutesRetrieveFileRequest$outboundSchema.parse(filesApiRoutesRetrieveFileRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesuploadfile.js +var require_filesapiroutesuploadfile = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/filesapiroutesuploadfile.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema = void 0; + exports.filesApiRoutesUploadFileMultiPartBodyParamsToJSON = filesApiRoutesUploadFileMultiPartBodyParamsToJSON; + var z3 = __importStar(require_v3()); + var blobs_js_1 = require_blobs(); + var components = __importStar(require_components()); + exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema = z3.object({ + purpose: components.FilePurpose$outboundSchema.optional(), + file: components.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema) + }); + function filesApiRoutesUploadFileMultiPartBodyParamsToJSON(filesApiRoutesUploadFileMultiPartBodyParams) { + return JSON.stringify(exports.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema.parse(filesApiRoutesUploadFileMultiPartBodyParams)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchcancelbatchjob.js +var require_jobsapiroutesbatchcancelbatchjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchcancelbatchjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesBatchCancelBatchJobRequestToJSON = jobsApiRoutesBatchCancelBatchJobRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesBatchCancelBatchJobRequestToJSON(jobsApiRoutesBatchCancelBatchJobRequest) { + return JSON.stringify(exports.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema.parse(jobsApiRoutesBatchCancelBatchJobRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjob.js +var require_jobsapiroutesbatchgetbatchjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesBatchGetBatchJobRequestToJSON = jobsApiRoutesBatchGetBatchJobRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema = z3.object({ + jobId: z3.string(), + inline: z3.nullable(z3.boolean()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesBatchGetBatchJobRequestToJSON(jobsApiRoutesBatchGetBatchJobRequest) { + return JSON.stringify(exports.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema.parse(jobsApiRoutesBatchGetBatchJobRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjobs.js +var require_jobsapiroutesbatchgetbatchjobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesbatchgetbatchjobs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = exports.OrderBy$outboundSchema = exports.OrderBy = void 0; + exports.jobsApiRoutesBatchGetBatchJobsRequestToJSON = jobsApiRoutesBatchGetBatchJobsRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.OrderBy = { + Created: "created", + MinusCreated: "-created" + }; + exports.OrderBy$outboundSchema = z3.nativeEnum(exports.OrderBy); + exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + model: z3.nullable(z3.string()).optional(), + agentId: z3.nullable(z3.string()).optional(), + metadata: z3.nullable(z3.record(z3.any())).optional(), + createdAfter: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + createdByMe: z3.boolean().default(false), + status: z3.nullable(z3.array(components.BatchJobStatus$outboundSchema)).optional(), + orderBy: exports.OrderBy$outboundSchema.default("-created") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + agentId: "agent_id", + createdAfter: "created_after", + createdByMe: "created_by_me", + orderBy: "order_by" + }); + }); + function jobsApiRoutesBatchGetBatchJobsRequestToJSON(jobsApiRoutesBatchGetBatchJobsRequest) { + return JSON.stringify(exports.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema.parse(jobsApiRoutesBatchGetBatchJobsRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningarchivefinetunedmodel.js +var require_jobsapiroutesfinetuningarchivefinetunedmodel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningarchivefinetunedmodel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function jobsApiRoutesFineTuningArchiveFineTunedModelRequestToJSON(jobsApiRoutesFineTuningArchiveFineTunedModelRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningArchiveFineTunedModelRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcancelfinetuningjob.js +var require_jobsapiroutesfinetuningcancelfinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcancelfinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON = jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON; + exports.jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesFineTuningCancelFineTuningJobRequestToJSON(jobsApiRoutesFineTuningCancelFineTuningJobRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningCancelFineTuningJobRequest)); + } + exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema = z3.union([ + components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsApiRoutesFineTuningCancelFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningCancelFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcreatefinetuningjob.js +var require_jobsapiroutesfinetuningcreatefinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningcreatefinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = exports.One$inboundSchema = void 0; + exports.oneFromJSON = oneFromJSON; + exports.jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.One$inboundSchema = z3.union([ + components.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function oneFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.One$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'One' from JSON`); + } + exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema = z3.union([ + components.LegacyJobMetadataOut$inboundSchema, + z3.union([ + components.ClassifierJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]) + ]); + function jobsApiRoutesFineTuningCreateFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningCreateFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjob.js +var require_jobsapiroutesfinetuninggetfinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON; + exports.jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesFineTuningGetFineTuningJobRequestToJSON(jobsApiRoutesFineTuningGetFineTuningJobRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningGetFineTuningJobRequest)); + } + exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema = z3.union([ + components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsApiRoutesFineTuningGetFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningGetFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjobs.js +var require_jobsapiroutesfinetuninggetfinetuningjobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuninggetfinetuningjobs.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = exports.Status$outboundSchema = exports.Status = void 0; + exports.jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON = jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.Status = { + Queued: "QUEUED", + Started: "STARTED", + Validating: "VALIDATING", + Validated: "VALIDATED", + Running: "RUNNING", + FailedValidation: "FAILED_VALIDATION", + Failed: "FAILED", + Success: "SUCCESS", + Cancelled: "CANCELLED", + CancellationRequested: "CANCELLATION_REQUESTED" + }; + exports.Status$outboundSchema = z3.nativeEnum(exports.Status); + exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema = z3.object({ + page: z3.number().int().default(0), + pageSize: z3.number().int().default(100), + model: z3.nullable(z3.string()).optional(), + createdAfter: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + createdBefore: z3.nullable(z3.date().transform((v4) => v4.toISOString())).optional(), + createdByMe: z3.boolean().default(false), + status: z3.nullable(exports.Status$outboundSchema).optional(), + wandbProject: z3.nullable(z3.string()).optional(), + wandbName: z3.nullable(z3.string()).optional(), + suffix: z3.nullable(z3.string()).optional() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + pageSize: "page_size", + createdAfter: "created_after", + createdBefore: "created_before", + createdByMe: "created_by_me", + wandbProject: "wandb_project", + wandbName: "wandb_name" + }); + }); + function jobsApiRoutesFineTuningGetFineTuningJobsRequestToJSON(jobsApiRoutesFineTuningGetFineTuningJobsRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema.parse(jobsApiRoutesFineTuningGetFineTuningJobsRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningstartfinetuningjob.js +var require_jobsapiroutesfinetuningstartfinetuningjob = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningstartfinetuningjob.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema = exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON = jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON; + exports.jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON = jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema = z3.object({ + jobId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + jobId: "job_id" + }); + }); + function jobsApiRoutesFineTuningStartFineTuningJobRequestToJSON(jobsApiRoutesFineTuningStartFineTuningJobRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema.parse(jobsApiRoutesFineTuningStartFineTuningJobRequest)); + } + exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema = z3.union([ + components.ClassifierDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("classifier") }).transform((v4) => ({ + jobType: v4.job_type + }))), + components.CompletionDetailedJobOut$inboundSchema.and(z3.object({ job_type: z3.literal("completion") }).transform((v4) => ({ + jobType: v4.job_type + }))) + ]); + function jobsApiRoutesFineTuningStartFineTuningJobResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningStartFineTuningJobResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningunarchivefinetunedmodel.js +var require_jobsapiroutesfinetuningunarchivefinetunedmodel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningunarchivefinetunedmodel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function jobsApiRoutesFineTuningUnarchiveFineTunedModelRequestToJSON(jobsApiRoutesFineTuningUnarchiveFineTunedModelRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningUnarchiveFineTunedModelRequest)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningupdatefinetunedmodel.js +var require_jobsapiroutesfinetuningupdatefinetunedmodel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/jobsapiroutesfinetuningupdatefinetunedmodel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema = exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = void 0; + exports.jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON = jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON; + exports.jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON = jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema = z3.object({ + modelId: z3.string(), + updateFTModelIn: components.UpdateFTModelIn$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id", + updateFTModelIn: "UpdateFTModelIn" + }); + }); + function jobsApiRoutesFineTuningUpdateFineTunedModelRequestToJSON(jobsApiRoutesFineTuningUpdateFineTunedModelRequest) { + return JSON.stringify(exports.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema.parse(jobsApiRoutesFineTuningUpdateFineTunedModelRequest)); + } + exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema = z3.union([ + components.ClassifierFTModelOut$inboundSchema.and(z3.object({ model_type: z3.literal("classifier") }).transform((v4) => ({ + modelType: v4.model_type + }))), + components.CompletionFTModelOut$inboundSchema.and(z3.object({ model_type: z3.literal("completion") }).transform((v4) => ({ + modelType: v4.model_type + }))) + ]); + function jobsApiRoutesFineTuningUpdateFineTunedModelResponseFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'JobsApiRoutesFineTuningUpdateFineTunedModelResponse' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdeletev1.js +var require_librariesdeletev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdeletev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDeleteV1Request$outboundSchema = void 0; + exports.librariesDeleteV1RequestToJSON = librariesDeleteV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDeleteV1Request$outboundSchema = z3.object({ + libraryId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id" + }); + }); + function librariesDeleteV1RequestToJSON(librariesDeleteV1Request) { + return JSON.stringify(exports.LibrariesDeleteV1Request$outboundSchema.parse(librariesDeleteV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsdeletev1.js +var require_librariesdocumentsdeletev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsdeletev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsDeleteV1Request$outboundSchema = void 0; + exports.librariesDocumentsDeleteV1RequestToJSON = librariesDocumentsDeleteV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsDeleteV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsDeleteV1RequestToJSON(librariesDocumentsDeleteV1Request) { + return JSON.stringify(exports.LibrariesDocumentsDeleteV1Request$outboundSchema.parse(librariesDocumentsDeleteV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetextractedtextsignedurlv1.js +var require_librariesdocumentsgetextractedtextsignedurlv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetextractedtextsignedurlv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON = librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetExtractedTextSignedUrlV1RequestToJSON(librariesDocumentsGetExtractedTextSignedUrlV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema.parse(librariesDocumentsGetExtractedTextSignedUrlV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetsignedurlv1.js +var require_librariesdocumentsgetsignedurlv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetsignedurlv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetSignedUrlV1RequestToJSON = librariesDocumentsGetSignedUrlV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetSignedUrlV1RequestToJSON(librariesDocumentsGetSignedUrlV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema.parse(librariesDocumentsGetSignedUrlV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetstatusv1.js +var require_librariesdocumentsgetstatusv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetstatusv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetStatusV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetStatusV1RequestToJSON = librariesDocumentsGetStatusV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetStatusV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetStatusV1RequestToJSON(librariesDocumentsGetStatusV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetStatusV1Request$outboundSchema.parse(librariesDocumentsGetStatusV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgettextcontentv1.js +var require_librariesdocumentsgettextcontentv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgettextcontentv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetTextContentV1RequestToJSON = librariesDocumentsGetTextContentV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetTextContentV1RequestToJSON(librariesDocumentsGetTextContentV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetTextContentV1Request$outboundSchema.parse(librariesDocumentsGetTextContentV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetv1.js +var require_librariesdocumentsgetv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsgetv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsGetV1Request$outboundSchema = void 0; + exports.librariesDocumentsGetV1RequestToJSON = librariesDocumentsGetV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsGetV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsGetV1RequestToJSON(librariesDocumentsGetV1Request) { + return JSON.stringify(exports.LibrariesDocumentsGetV1Request$outboundSchema.parse(librariesDocumentsGetV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentslistv1.js +var require_librariesdocumentslistv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentslistv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsListV1Request$outboundSchema = void 0; + exports.librariesDocumentsListV1RequestToJSON = librariesDocumentsListV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsListV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + search: z3.nullable(z3.string()).optional(), + pageSize: z3.number().int().default(100), + page: z3.number().int().default(0), + filtersAttributes: z3.nullable(z3.string()).optional(), + sortBy: z3.string().default("created_at"), + sortOrder: z3.string().default("desc") + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + pageSize: "page_size", + filtersAttributes: "filters_attributes", + sortBy: "sort_by", + sortOrder: "sort_order" + }); + }); + function librariesDocumentsListV1RequestToJSON(librariesDocumentsListV1Request) { + return JSON.stringify(exports.LibrariesDocumentsListV1Request$outboundSchema.parse(librariesDocumentsListV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsreprocessv1.js +var require_librariesdocumentsreprocessv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsreprocessv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsReprocessV1Request$outboundSchema = void 0; + exports.librariesDocumentsReprocessV1RequestToJSON = librariesDocumentsReprocessV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesDocumentsReprocessV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id" + }); + }); + function librariesDocumentsReprocessV1RequestToJSON(librariesDocumentsReprocessV1Request) { + return JSON.stringify(exports.LibrariesDocumentsReprocessV1Request$outboundSchema.parse(librariesDocumentsReprocessV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsupdatev1.js +var require_librariesdocumentsupdatev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsupdatev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsUpdateV1Request$outboundSchema = void 0; + exports.librariesDocumentsUpdateV1RequestToJSON = librariesDocumentsUpdateV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesDocumentsUpdateV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + documentId: z3.string(), + documentUpdateIn: components.DocumentUpdateIn$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + documentId: "document_id", + documentUpdateIn: "DocumentUpdateIn" + }); + }); + function librariesDocumentsUpdateV1RequestToJSON(librariesDocumentsUpdateV1Request) { + return JSON.stringify(exports.LibrariesDocumentsUpdateV1Request$outboundSchema.parse(librariesDocumentsUpdateV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsuploadv1.js +var require_librariesdocumentsuploadv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesdocumentsuploadv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesDocumentsUploadV1Request$outboundSchema = exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema = void 0; + exports.librariesDocumentsUploadV1DocumentUploadToJSON = librariesDocumentsUploadV1DocumentUploadToJSON; + exports.librariesDocumentsUploadV1RequestToJSON = librariesDocumentsUploadV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var blobs_js_1 = require_blobs(); + var components = __importStar(require_components()); + exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema = z3.object({ + file: components.FileT$outboundSchema.or(blobs_js_1.blobLikeSchema) + }); + function librariesDocumentsUploadV1DocumentUploadToJSON(librariesDocumentsUploadV1DocumentUpload) { + return JSON.stringify(exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema.parse(librariesDocumentsUploadV1DocumentUpload)); + } + exports.LibrariesDocumentsUploadV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + requestBody: z3.lazy(() => exports.LibrariesDocumentsUploadV1DocumentUpload$outboundSchema) + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + requestBody: "RequestBody" + }); + }); + function librariesDocumentsUploadV1RequestToJSON(librariesDocumentsUploadV1Request) { + return JSON.stringify(exports.LibrariesDocumentsUploadV1Request$outboundSchema.parse(librariesDocumentsUploadV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesgetv1.js +var require_librariesgetv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesgetv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesGetV1Request$outboundSchema = void 0; + exports.librariesGetV1RequestToJSON = librariesGetV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesGetV1Request$outboundSchema = z3.object({ + libraryId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id" + }); + }); + function librariesGetV1RequestToJSON(librariesGetV1Request) { + return JSON.stringify(exports.LibrariesGetV1Request$outboundSchema.parse(librariesGetV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharecreatev1.js +var require_librariessharecreatev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharecreatev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesShareCreateV1Request$outboundSchema = void 0; + exports.librariesShareCreateV1RequestToJSON = librariesShareCreateV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesShareCreateV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + sharingIn: components.SharingIn$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + sharingIn: "SharingIn" + }); + }); + function librariesShareCreateV1RequestToJSON(librariesShareCreateV1Request) { + return JSON.stringify(exports.LibrariesShareCreateV1Request$outboundSchema.parse(librariesShareCreateV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharedeletev1.js +var require_librariessharedeletev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharedeletev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesShareDeleteV1Request$outboundSchema = void 0; + exports.librariesShareDeleteV1RequestToJSON = librariesShareDeleteV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesShareDeleteV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + sharingDelete: components.SharingDelete$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + sharingDelete: "SharingDelete" + }); + }); + function librariesShareDeleteV1RequestToJSON(librariesShareDeleteV1Request) { + return JSON.stringify(exports.LibrariesShareDeleteV1Request$outboundSchema.parse(librariesShareDeleteV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharelistv1.js +var require_librariessharelistv1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariessharelistv1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesShareListV1Request$outboundSchema = void 0; + exports.librariesShareListV1RequestToJSON = librariesShareListV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + exports.LibrariesShareListV1Request$outboundSchema = z3.object({ + libraryId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id" + }); + }); + function librariesShareListV1RequestToJSON(librariesShareListV1Request) { + return JSON.stringify(exports.LibrariesShareListV1Request$outboundSchema.parse(librariesShareListV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesupdatev1.js +var require_librariesupdatev1 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/librariesupdatev1.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LibrariesUpdateV1Request$outboundSchema = void 0; + exports.librariesUpdateV1RequestToJSON = librariesUpdateV1RequestToJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var components = __importStar(require_components()); + exports.LibrariesUpdateV1Request$outboundSchema = z3.object({ + libraryId: z3.string(), + libraryInUpdate: components.LibraryInUpdate$outboundSchema + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + libraryId: "library_id", + libraryInUpdate: "LibraryInUpdate" + }); + }); + function librariesUpdateV1RequestToJSON(librariesUpdateV1Request) { + return JSON.stringify(exports.LibrariesUpdateV1Request$outboundSchema.parse(librariesUpdateV1Request)); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/retrievemodelv1modelsmodelidget.js +var require_retrievemodelv1modelsmodelidget = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/retrievemodelv1modelsmodelidget.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema = exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema = void 0; + exports.retrieveModelV1ModelsModelIdGetRequestToJSON = retrieveModelV1ModelsModelIdGetRequestToJSON; + exports.retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON = retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON; + var z3 = __importStar(require_v3()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var components = __importStar(require_components()); + exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema = z3.object({ + modelId: z3.string() + }).transform((v4) => { + return (0, primitives_js_1.remap)(v4, { + modelId: "model_id" + }); + }); + function retrieveModelV1ModelsModelIdGetRequestToJSON(retrieveModelV1ModelsModelIdGetRequest) { + return JSON.stringify(exports.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema.parse(retrieveModelV1ModelsModelIdGetRequest)); + } + exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema = z3.union([ + components.BaseModelCard$inboundSchema.and(z3.object({ type: z3.literal("base") })), + components.FTModelCard$inboundSchema.and(z3.object({ type: z3.literal("fine-tuned") })) + ]); + function retrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGetFromJSON(jsonString) { + return (0, schemas_js_1.safeParse)(jsonString, (x2) => exports.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema.parse(JSON.parse(x2)), `Failed to parse 'RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet' from JSON`); + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/models/operations/index.js +var require_operations = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/models/operations/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_agentsapiv1agentscreateorupdatealias(), exports); + __exportStar(require_agentsapiv1agentsdelete(), exports); + __exportStar(require_agentsapiv1agentsdeletealias(), exports); + __exportStar(require_agentsapiv1agentsget(), exports); + __exportStar(require_agentsapiv1agentsgetversion(), exports); + __exportStar(require_agentsapiv1agentslist(), exports); + __exportStar(require_agentsapiv1agentslistversionaliases(), exports); + __exportStar(require_agentsapiv1agentslistversions(), exports); + __exportStar(require_agentsapiv1agentsupdate(), exports); + __exportStar(require_agentsapiv1agentsupdateversion(), exports); + __exportStar(require_agentsapiv1conversationsappend(), exports); + __exportStar(require_agentsapiv1conversationsappendstream(), exports); + __exportStar(require_agentsapiv1conversationsdelete(), exports); + __exportStar(require_agentsapiv1conversationsget(), exports); + __exportStar(require_agentsapiv1conversationshistory(), exports); + __exportStar(require_agentsapiv1conversationslist(), exports); + __exportStar(require_agentsapiv1conversationsmessages(), exports); + __exportStar(require_agentsapiv1conversationsrestart(), exports); + __exportStar(require_agentsapiv1conversationsrestartstream(), exports); + __exportStar(require_deletemodelv1modelsmodeliddelete(), exports); + __exportStar(require_filesapiroutesdeletefile(), exports); + __exportStar(require_filesapiroutesdownloadfile(), exports); + __exportStar(require_filesapiroutesgetsignedurl(), exports); + __exportStar(require_filesapirouteslistfiles(), exports); + __exportStar(require_filesapiroutesretrievefile(), exports); + __exportStar(require_filesapiroutesuploadfile(), exports); + __exportStar(require_jobsapiroutesbatchcancelbatchjob(), exports); + __exportStar(require_jobsapiroutesbatchgetbatchjob(), exports); + __exportStar(require_jobsapiroutesbatchgetbatchjobs(), exports); + __exportStar(require_jobsapiroutesfinetuningarchivefinetunedmodel(), exports); + __exportStar(require_jobsapiroutesfinetuningcancelfinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuningcreatefinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuninggetfinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuninggetfinetuningjobs(), exports); + __exportStar(require_jobsapiroutesfinetuningstartfinetuningjob(), exports); + __exportStar(require_jobsapiroutesfinetuningunarchivefinetunedmodel(), exports); + __exportStar(require_jobsapiroutesfinetuningupdatefinetunedmodel(), exports); + __exportStar(require_librariesdeletev1(), exports); + __exportStar(require_librariesdocumentsdeletev1(), exports); + __exportStar(require_librariesdocumentsgetextractedtextsignedurlv1(), exports); + __exportStar(require_librariesdocumentsgetsignedurlv1(), exports); + __exportStar(require_librariesdocumentsgetstatusv1(), exports); + __exportStar(require_librariesdocumentsgettextcontentv1(), exports); + __exportStar(require_librariesdocumentsgetv1(), exports); + __exportStar(require_librariesdocumentslistv1(), exports); + __exportStar(require_librariesdocumentsreprocessv1(), exports); + __exportStar(require_librariesdocumentsupdatev1(), exports); + __exportStar(require_librariesdocumentsuploadv1(), exports); + __exportStar(require_librariesgetv1(), exports); + __exportStar(require_librariessharecreatev1(), exports); + __exportStar(require_librariessharedeletev1(), exports); + __exportStar(require_librariessharelistv1(), exports); + __exportStar(require_librariesupdatev1(), exports); + __exportStar(require_retrievemodelv1modelsmodelidget(), exports); + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCancel.js +var require_batchJobsCancel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCancel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsCancel = batchJobsCancel; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function batchJobsCancel(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchCancelBatchJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs/{job_id}/cancel")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_cancel_batch_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCreate.js +var require_batchJobsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsCreate = batchJobsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + function batchJobsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.BatchJobIn$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_create_batch_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsGet.js +var require_batchJobsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsGet = batchJobsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function batchJobsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchGetBatchJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs/{job_id}")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "inline": payload.inline + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_get_batch_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsList.js +var require_batchJobsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/batchJobsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.batchJobsList = batchJobsList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function batchJobsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesBatchGetBatchJobsRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/batch/jobs")(); + const query = (0, encodings_js_1.encodeFormQuery)({ + "agent_id": payload?.agent_id, + "created_after": payload?.created_after, + "created_by_me": payload?.created_by_me, + "metadata": payload?.metadata, + "model": payload?.model, + "order_by": payload?.order_by, + "page": payload?.page, + "page_size": payload?.page_size, + "status": payload?.status + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_batch_get_batch_jobs", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.BatchJobsOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/mistraljobs.js +var require_mistraljobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/mistraljobs.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralJobs = void 0; + var batchJobsCancel_js_1 = require_batchJobsCancel(); + var batchJobsCreate_js_1 = require_batchJobsCreate(); + var batchJobsGet_js_1 = require_batchJobsGet(); + var batchJobsList_js_1 = require_batchJobsList(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var MistralJobs = class extends sdks_js_1.ClientSDK { + /** + * Get Batch Jobs + * + * @remarks + * Get a list of batch jobs for your organization and user. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsList_js_1.batchJobsList)(this, request, options)); + } + /** + * Create Batch Job + * + * @remarks + * Create a new batch job, it will be queued for processing. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsCreate_js_1.batchJobsCreate)(this, request, options)); + } + /** + * Get Batch Job + * + * @remarks + * Get a batch job details by its UUID. + * + * Args: + * inline: If True, return results inline in the response. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsGet_js_1.batchJobsGet)(this, request, options)); + } + /** + * Cancel Batch Job + * + * @remarks + * Request the cancellation of a batch job. + */ + async cancel(request, options) { + return (0, fp_js_1.unwrapAsync)((0, batchJobsCancel_js_1.batchJobsCancel)(this, request, options)); + } + }; + exports.MistralJobs = MistralJobs; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/batch.js +var require_batch = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/batch.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Batch = void 0; + var sdks_js_1 = require_sdks(); + var mistraljobs_js_1 = require_mistraljobs(); + var Batch = class extends sdks_js_1.ClientSDK { + get jobs() { + return this._jobs ?? (this._jobs = new mistraljobs_js_1.MistralJobs(this._options)); + } + }; + exports.Batch = Batch; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppend.js +var require_betaConversationsAppend = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppend.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsAppend = betaConversationsAppend; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsAppend(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsAppendRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationAppendRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_append", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppendStream.js +var require_betaConversationsAppendStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsAppendStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsAppendStream = betaConversationsAppendStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsAppendStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsAppendStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationAppendStreamRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}#stream")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_append_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.ConversationEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsDelete.js +var require_betaConversationsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsDelete = betaConversationsDelete; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsDeleteRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_delete", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGet.js +var require_betaConversationsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsGet = betaConversationsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsGetRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, operations.AgentsApiV1ConversationsGetResponseV1ConversationsGet$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetHistory.js +var require_betaConversationsGetHistory = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetHistory.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsGetHistory = betaConversationsGetHistory; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsGetHistory(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsHistoryRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/history")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_history", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationHistory$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetMessages.js +var require_betaConversationsGetMessages = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsGetMessages.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsGetMessages = betaConversationsGetMessages; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsGetMessages(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsMessagesRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/messages")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_messages", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationMessages$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsList.js +var require_betaConversationsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsList = betaConversationsList; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsListRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations")(); + const query = (0, encodings_js_1.queryJoin)((0, encodings_js_1.encodeFormQuery)({ + "page": payload?.page, + "page_size": payload?.page_size + }), (0, encodings_js_1.encodeJSONQuery)({ + "metadata": payload?.metadata + }, { explode: false })); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_list", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(operations.ResponseBody$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestart.js +var require_betaConversationsRestart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsRestart = betaConversationsRestart; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsRestart(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsRestartRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationRestartRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/restart")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_restart", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestartStream.js +var require_betaConversationsRestartStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsRestartStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsRestartStream = betaConversationsRestartStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaConversationsRestartStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1ConversationsRestartStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.ConversationRestartStreamRequest, { + explode: true + }); + const pathParams = { + conversation_id: (0, encodings_js_1.encodeSimple)("conversation_id", payload.conversation_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations/{conversation_id}/restart#stream")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_restart_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.ConversationEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStart.js +var require_betaConversationsStart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsStart = betaConversationsStart; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaConversationsStart(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ConversationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_start", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ConversationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStartStream.js +var require_betaConversationsStartStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaConversationsStartStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaConversationsStartStream = betaConversationsStartStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaConversationsStartStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ConversationStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/conversations#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_conversations_start_stream", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + return { + value: components.ConversationEvents$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/conversations.js +var require_conversations = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/conversations.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Conversations = void 0; + var betaConversationsAppend_js_1 = require_betaConversationsAppend(); + var betaConversationsAppendStream_js_1 = require_betaConversationsAppendStream(); + var betaConversationsDelete_js_1 = require_betaConversationsDelete(); + var betaConversationsGet_js_1 = require_betaConversationsGet(); + var betaConversationsGetHistory_js_1 = require_betaConversationsGetHistory(); + var betaConversationsGetMessages_js_1 = require_betaConversationsGetMessages(); + var betaConversationsList_js_1 = require_betaConversationsList(); + var betaConversationsRestart_js_1 = require_betaConversationsRestart(); + var betaConversationsRestartStream_js_1 = require_betaConversationsRestartStream(); + var betaConversationsStart_js_1 = require_betaConversationsStart(); + var betaConversationsStartStream_js_1 = require_betaConversationsStartStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Conversations2 = class extends sdks_js_1.ClientSDK { + /** + * Create a conversation and append entries to it. + * + * @remarks + * Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation. + */ + async start(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsStart_js_1.betaConversationsStart)(this, request, options)); + } + /** + * List all created conversations. + * + * @remarks + * Retrieve a list of conversation entities sorted by creation time. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsList_js_1.betaConversationsList)(this, request, options)); + } + /** + * Retrieve a conversation information. + * + * @remarks + * Given a conversation_id retrieve a conversation entity with its attributes. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsGet_js_1.betaConversationsGet)(this, request, options)); + } + /** + * Delete a conversation. + * + * @remarks + * Delete a conversation given a conversation_id. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsDelete_js_1.betaConversationsDelete)(this, request, options)); + } + /** + * Append new entries to an existing conversation. + * + * @remarks + * Run completion on the history of the conversation and the user entries. Return the new created entries. + */ + async append(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsAppend_js_1.betaConversationsAppend)(this, request, options)); + } + /** + * Retrieve all entries in a conversation. + * + * @remarks + * Given a conversation_id retrieve all the entries belonging to that conversation. The entries are sorted in the order they were appended, those can be messages, connectors or function_call. + */ + async getHistory(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsGetHistory_js_1.betaConversationsGetHistory)(this, request, options)); + } + /** + * Retrieve all messages in a conversation. + * + * @remarks + * Given a conversation_id retrieve all the messages belonging to that conversation. This is similar to retrieving all entries except we filter the messages only. + */ + async getMessages(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsGetMessages_js_1.betaConversationsGetMessages)(this, request, options)); + } + /** + * Restart a conversation starting from a given entry. + * + * @remarks + * Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned. + */ + async restart(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsRestart_js_1.betaConversationsRestart)(this, request, options)); + } + /** + * Create a conversation and append entries to it. + * + * @remarks + * Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation. + */ + async startStream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsStartStream_js_1.betaConversationsStartStream)(this, request, options)); + } + /** + * Append new entries to an existing conversation. + * + * @remarks + * Run completion on the history of the conversation and the user entries. Return the new created entries. + */ + async appendStream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsAppendStream_js_1.betaConversationsAppendStream)(this, request, options)); + } + /** + * Restart a conversation starting from a given entry. + * + * @remarks + * Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned. + */ + async restartStream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaConversationsRestartStream_js_1.betaConversationsRestartStream)(this, request, options)); + } + }; + exports.Conversations = Conversations2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesCreate.js +var require_betaLibrariesCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesCreate = betaLibrariesCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaLibrariesCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.LibraryIn$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_create_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(201, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDelete.js +var require_betaLibrariesDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDelete = betaLibrariesDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDeleteV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_delete_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesGet.js +var require_betaLibrariesGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesGet = betaLibrariesGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesGetV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_get_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesList.js +var require_betaLibrariesList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesList = betaLibrariesList; + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + function betaLibrariesList(client, options) { + return new async_js_1.APIPromise($do(client, options)); + } + async function $do(client, options) { + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_list_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ListLibraryOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesUpdate.js +var require_betaLibrariesUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesUpdate = betaLibrariesUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesUpdateV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.LibraryInUpdate, { explode: true }); + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_update_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.LibraryOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesDelete.js +var require_betaLibrariesAccessesDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesAccessesDelete = betaLibrariesAccessesDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesAccessesDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareDeleteV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.SharingDelete, { explode: true }); + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_share_delete_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.SharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesList.js +var require_betaLibrariesAccessesList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesAccessesList = betaLibrariesAccessesList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesAccessesList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareListV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_share_list_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ListSharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesUpdateOrCreate.js +var require_betaLibrariesAccessesUpdateOrCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesAccessesUpdateOrCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesAccessesUpdateOrCreate = betaLibrariesAccessesUpdateOrCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesAccessesUpdateOrCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesShareCreateV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.SharingIn, { explode: true }); + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/share")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_share_create_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.SharingOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/accesses.js +var require_accesses = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/accesses.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Accesses = void 0; + var betaLibrariesAccessesDelete_js_1 = require_betaLibrariesAccessesDelete(); + var betaLibrariesAccessesList_js_1 = require_betaLibrariesAccessesList(); + var betaLibrariesAccessesUpdateOrCreate_js_1 = require_betaLibrariesAccessesUpdateOrCreate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Accesses = class extends sdks_js_1.ClientSDK { + /** + * List all of the access to this library. + * + * @remarks + * Given a library, list all of the Entity that have access and to what level. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesList_js_1.betaLibrariesAccessesList)(this, request, options)); + } + /** + * Create or update an access level. + * + * @remarks + * Given a library id, you can create or update the access level of an entity. You have to be owner of the library to share a library. An owner cannot change their own role. A library cannot be shared outside of the organization. + */ + async updateOrCreate(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesUpdateOrCreate_js_1.betaLibrariesAccessesUpdateOrCreate)(this, request, options)); + } + /** + * Delete an access level. + * + * @remarks + * Given a library id, you can delete the access level of an entity. An owner cannot delete it's own access. You have to be the owner of the library to delete an acces other than yours. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesAccessesDelete_js_1.betaLibrariesAccessesDelete)(this, request, options)); + } + }; + exports.Accesses = Accesses; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsDelete.js +var require_betaLibrariesDocumentsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsDelete = betaLibrariesDocumentsDelete; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsDeleteV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_delete_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsExtractedTextSignedUrl.js +var require_betaLibrariesDocumentsExtractedTextSignedUrl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsExtractedTextSignedUrl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsExtractedTextSignedUrl = betaLibrariesDocumentsExtractedTextSignedUrl; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsExtractedTextSignedUrl(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetExtractedTextSignedUrlV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/extracted-text-signed-url")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_extracted_text_signed_url_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.string()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGet.js +var require_betaLibrariesDocumentsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsGet = betaLibrariesDocumentsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGetSignedUrl.js +var require_betaLibrariesDocumentsGetSignedUrl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsGetSignedUrl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsGetSignedUrl = betaLibrariesDocumentsGetSignedUrl; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsGetSignedUrl(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetSignedUrlV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/signed-url")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_signed_url_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.string()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsList.js +var require_betaLibrariesDocumentsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsList = betaLibrariesDocumentsList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsListV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "filters_attributes": payload.filters_attributes, + "page": payload.page, + "page_size": payload.page_size, + "search": payload.search, + "sort_by": payload.sort_by, + "sort_order": payload.sort_order + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_list_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ListDocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsReprocess.js +var require_betaLibrariesDocumentsReprocess = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsReprocess.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsReprocess = betaLibrariesDocumentsReprocess; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsReprocess(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsReprocessV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/reprocess")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_reprocess_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsStatus.js +var require_betaLibrariesDocumentsStatus = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsStatus.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsStatus = betaLibrariesDocumentsStatus; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsStatus(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetStatusV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/status")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_status_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ProcessingStatusOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsTextContent.js +var require_betaLibrariesDocumentsTextContent = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsTextContent.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsTextContent = betaLibrariesDocumentsTextContent; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsTextContent(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsGetTextContentV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}/text_content")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_get_text_content_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DocumentTextContent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpdate.js +var require_betaLibrariesDocumentsUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsUpdate = betaLibrariesDocumentsUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaLibrariesDocumentsUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsUpdateV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.DocumentUpdateIn, { explode: true }); + const pathParams = { + document_id: (0, encodings_js_1.encodeSimple)("document_id", payload.document_id, { + explode: false, + charEncoding: "percent" + }), + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents/{document_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_update_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpload.js +var require_betaLibrariesDocumentsUpload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaLibrariesDocumentsUpload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaLibrariesDocumentsUpload = betaLibrariesDocumentsUpload; + var encodings_js_1 = require_encodings(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function betaLibrariesDocumentsUpload(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.LibrariesDocumentsUploadV1Request$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + if ((0, blobs_js_1.isBlobLike)(payload.RequestBody.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.RequestBody.file); + } else if ((0, streams_js_1.isReadableStream)(payload.RequestBody.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.RequestBody.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.RequestBody.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.RequestBody.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.RequestBody.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.RequestBody.file.content], { type: contentType }), payload.RequestBody.file.fileName); + } + const pathParams = { + library_id: (0, encodings_js_1.encodeSimple)("library_id", payload.library_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/libraries/{library_id}/documents")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "libraries_documents_upload_v1", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json([200, 201], components.DocumentOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/documents.js +var require_documents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/documents.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Documents = void 0; + var betaLibrariesDocumentsDelete_js_1 = require_betaLibrariesDocumentsDelete(); + var betaLibrariesDocumentsExtractedTextSignedUrl_js_1 = require_betaLibrariesDocumentsExtractedTextSignedUrl(); + var betaLibrariesDocumentsGet_js_1 = require_betaLibrariesDocumentsGet(); + var betaLibrariesDocumentsGetSignedUrl_js_1 = require_betaLibrariesDocumentsGetSignedUrl(); + var betaLibrariesDocumentsList_js_1 = require_betaLibrariesDocumentsList(); + var betaLibrariesDocumentsReprocess_js_1 = require_betaLibrariesDocumentsReprocess(); + var betaLibrariesDocumentsStatus_js_1 = require_betaLibrariesDocumentsStatus(); + var betaLibrariesDocumentsTextContent_js_1 = require_betaLibrariesDocumentsTextContent(); + var betaLibrariesDocumentsUpdate_js_1 = require_betaLibrariesDocumentsUpdate(); + var betaLibrariesDocumentsUpload_js_1 = require_betaLibrariesDocumentsUpload(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Documents2 = class extends sdks_js_1.ClientSDK { + /** + * List documents in a given library. + * + * @remarks + * Given a library, lists the document that have been uploaded to that library. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsList_js_1.betaLibrariesDocumentsList)(this, request, options)); + } + /** + * Upload a new document. + * + * @remarks + * Given a library, upload a new document to that library. It is queued for processing, it status will change it has been processed. The processing has to be completed in order be discoverable for the library search + */ + async upload(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsUpload_js_1.betaLibrariesDocumentsUpload)(this, request, options)); + } + /** + * Retrieve the metadata of a specific document. + * + * @remarks + * Given a library and a document in this library, you can retrieve the metadata of that document. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsGet_js_1.betaLibrariesDocumentsGet)(this, request, options)); + } + /** + * Update the metadata of a specific document. + * + * @remarks + * Given a library and a document in that library, update the name of that document. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsUpdate_js_1.betaLibrariesDocumentsUpdate)(this, request, options)); + } + /** + * Delete a document. + * + * @remarks + * Given a library and a document in that library, delete that document. The document will be deleted from the library and the search index. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsDelete_js_1.betaLibrariesDocumentsDelete)(this, request, options)); + } + /** + * Retrieve the text content of a specific document. + * + * @remarks + * Given a library and a document in that library, you can retrieve the text content of that document if it exists. For documents like pdf, docx and pptx the text content results from our processing using Mistral OCR. + */ + async textContent(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsTextContent_js_1.betaLibrariesDocumentsTextContent)(this, request, options)); + } + /** + * Retrieve the processing status of a specific document. + * + * @remarks + * Given a library and a document in that library, retrieve the processing status of that document. + */ + async status(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsStatus_js_1.betaLibrariesDocumentsStatus)(this, request, options)); + } + /** + * Retrieve the signed URL of a specific document. + * + * @remarks + * Given a library and a document in that library, retrieve the signed URL of a specific document.The url will expire after 30 minutes and can be accessed by anyone with the link. + */ + async getSignedUrl(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsGetSignedUrl_js_1.betaLibrariesDocumentsGetSignedUrl)(this, request, options)); + } + /** + * Retrieve the signed URL of text extracted from a given document. + * + * @remarks + * Given a library and a document in that library, retrieve the signed URL of text extracted. For documents that are sent to the OCR this returns the result of the OCR queries. + */ + async extractedTextSignedUrl(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsExtractedTextSignedUrl_js_1.betaLibrariesDocumentsExtractedTextSignedUrl)(this, request, options)); + } + /** + * Reprocess a document. + * + * @remarks + * Given a library and a document in that library, reprocess that document, it will be billed again. + */ + async reprocess(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDocumentsReprocess_js_1.betaLibrariesDocumentsReprocess)(this, request, options)); + } + }; + exports.Documents = Documents2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/libraries.js +var require_libraries = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/libraries.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Libraries = void 0; + var betaLibrariesCreate_js_1 = require_betaLibrariesCreate(); + var betaLibrariesDelete_js_1 = require_betaLibrariesDelete(); + var betaLibrariesGet_js_1 = require_betaLibrariesGet(); + var betaLibrariesList_js_1 = require_betaLibrariesList(); + var betaLibrariesUpdate_js_1 = require_betaLibrariesUpdate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var accesses_js_1 = require_accesses(); + var documents_js_1 = require_documents(); + var Libraries = class extends sdks_js_1.ClientSDK { + get documents() { + return this._documents ?? (this._documents = new documents_js_1.Documents(this._options)); + } + get accesses() { + return this._accesses ?? (this._accesses = new accesses_js_1.Accesses(this._options)); + } + /** + * List all libraries you have access to. + * + * @remarks + * List all libraries that you have created or have been shared with you. + */ + async list(options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesList_js_1.betaLibrariesList)(this, options)); + } + /** + * Create a new Library. + * + * @remarks + * Create a new Library, you will be marked as the owner and only you will have the possibility to share it with others. When first created this will only be accessible by you. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesCreate_js_1.betaLibrariesCreate)(this, request, options)); + } + /** + * Detailed information about a specific Library. + * + * @remarks + * Given a library id, details information about that Library. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesGet_js_1.betaLibrariesGet)(this, request, options)); + } + /** + * Delete a library and all of it's document. + * + * @remarks + * Given a library id, deletes it together with all documents that have been uploaded to that library. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesDelete_js_1.betaLibrariesDelete)(this, request, options)); + } + /** + * Update a library. + * + * @remarks + * Given a library id, you can update the name and description. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaLibrariesUpdate_js_1.betaLibrariesUpdate)(this, request, options)); + } + }; + exports.Libraries = Libraries; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreate.js +var require_betaAgentsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsCreate = betaAgentsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function betaAgentsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.AgentCreationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/agents")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_create", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreateVersionAlias.js +var require_betaAgentsCreateVersionAlias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsCreateVersionAlias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsCreateVersionAlias = betaAgentsCreateVersionAlias; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsCreateVersionAlias(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsCreateOrUpdateAliasRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "alias": payload.alias, + "version": payload.version + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_create_or_update_alias", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PUT", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.AgentAliasResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDelete.js +var require_betaAgentsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsDelete = betaAgentsDelete; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsDeleteRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_delete", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDeleteVersionAlias.js +var require_betaAgentsDeleteVersionAlias = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsDeleteVersionAlias.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsDeleteVersionAlias = betaAgentsDeleteVersionAlias; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsDeleteVersionAlias(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsDeleteAliasRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "alias": payload.alias + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_delete_alias", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.nil(204, z3.void()), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGet.js +var require_betaAgentsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsGet = betaAgentsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsGetRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "agent_version": payload.agent_version + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGetVersion.js +var require_betaAgentsGetVersion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsGetVersion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsGetVersion = betaAgentsGetVersion; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsGetVersion(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsGetVersionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }), + version: (0, encodings_js_1.encodeSimple)("version", payload.version, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/versions/{version}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_get_version", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsList.js +var require_betaAgentsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsList = betaAgentsList; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents")(); + const query = (0, encodings_js_1.queryJoin)((0, encodings_js_1.encodeFormQuery)({ + "deployment_chat": payload?.deployment_chat, + "id": payload?.id, + "name": payload?.name, + "page": payload?.page, + "page_size": payload?.page_size, + "search": payload?.search, + "sources": payload?.sources + }), (0, encodings_js_1.encodeJSONQuery)({ + "metadata": payload?.metadata + }, { explode: false })); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_list", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(components.Agent$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersionAliases.js +var require_betaAgentsListVersionAliases = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersionAliases.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsListVersionAliases = betaAgentsListVersionAliases; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsListVersionAliases(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListVersionAliasesRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/aliases")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_list_version_aliases", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(components.AgentAliasResponse$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersions.js +var require_betaAgentsListVersions = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsListVersions.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsListVersions = betaAgentsListVersions; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsListVersions(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsListVersionsRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/versions")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "page": payload.page, + "page_size": payload.page_size + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_list_versions", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, z3.array(components.Agent$inboundSchema)), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdate.js +var require_betaAgentsUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsUpdate = betaAgentsUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsUpdateRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.AgentUpdateRequest, { + explode: true + }); + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_update", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdateVersion.js +var require_betaAgentsUpdateVersion = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/betaAgentsUpdateVersion.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.betaAgentsUpdateVersion = betaAgentsUpdateVersion; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function betaAgentsUpdateVersion(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.AgentsApiV1AgentsUpdateVersionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + agent_id: (0, encodings_js_1.encodeSimple)("agent_id", payload.agent_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/agents/{agent_id}/version")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "version": payload.version + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "agents_api_v1_agents_update_version", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.Agent$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/mistralagents.js +var require_mistralagents = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/mistralagents.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MistralAgents = void 0; + var betaAgentsCreate_js_1 = require_betaAgentsCreate(); + var betaAgentsCreateVersionAlias_js_1 = require_betaAgentsCreateVersionAlias(); + var betaAgentsDelete_js_1 = require_betaAgentsDelete(); + var betaAgentsDeleteVersionAlias_js_1 = require_betaAgentsDeleteVersionAlias(); + var betaAgentsGet_js_1 = require_betaAgentsGet(); + var betaAgentsGetVersion_js_1 = require_betaAgentsGetVersion(); + var betaAgentsList_js_1 = require_betaAgentsList(); + var betaAgentsListVersionAliases_js_1 = require_betaAgentsListVersionAliases(); + var betaAgentsListVersions_js_1 = require_betaAgentsListVersions(); + var betaAgentsUpdate_js_1 = require_betaAgentsUpdate(); + var betaAgentsUpdateVersion_js_1 = require_betaAgentsUpdateVersion(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var MistralAgents = class extends sdks_js_1.ClientSDK { + /** + * Create a agent that can be used within a conversation. + * + * @remarks + * Create a new agent giving it instructions, tools, description. The agent is then available to be used as a regular assistant in a conversation or as part of an agent pool from which it can be used. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsCreate_js_1.betaAgentsCreate)(this, request, options)); + } + /** + * List agent entities. + * + * @remarks + * Retrieve a list of agent entities sorted by creation time. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsList_js_1.betaAgentsList)(this, request, options)); + } + /** + * Retrieve an agent entity. + * + * @remarks + * Given an agent, retrieve an agent entity with its attributes. The agent_version parameter can be an integer version number or a string alias. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsGet_js_1.betaAgentsGet)(this, request, options)); + } + /** + * Update an agent entity. + * + * @remarks + * Update an agent attributes and create a new version. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsUpdate_js_1.betaAgentsUpdate)(this, request, options)); + } + /** + * Delete an agent entity. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsDelete_js_1.betaAgentsDelete)(this, request, options)); + } + /** + * Update an agent version. + * + * @remarks + * Switch the version of an agent. + */ + async updateVersion(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsUpdateVersion_js_1.betaAgentsUpdateVersion)(this, request, options)); + } + /** + * List all versions of an agent. + * + * @remarks + * Retrieve all versions for a specific agent with full agent context. Supports pagination. + */ + async listVersions(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsListVersions_js_1.betaAgentsListVersions)(this, request, options)); + } + /** + * Retrieve a specific version of an agent. + * + * @remarks + * Get a specific agent version by version number. + */ + async getVersion(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsGetVersion_js_1.betaAgentsGetVersion)(this, request, options)); + } + /** + * Create or update an agent version alias. + * + * @remarks + * Create a new alias or update an existing alias to point to a specific version. Aliases are unique per agent and can be reassigned to different versions. + */ + async createVersionAlias(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsCreateVersionAlias_js_1.betaAgentsCreateVersionAlias)(this, request, options)); + } + /** + * List all aliases for an agent. + * + * @remarks + * Retrieve all version aliases for a specific agent. + */ + async listVersionAliases(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsListVersionAliases_js_1.betaAgentsListVersionAliases)(this, request, options)); + } + /** + * Delete an agent version alias. + * + * @remarks + * Delete an existing alias for an agent. + */ + async deleteVersionAlias(request, options) { + return (0, fp_js_1.unwrapAsync)((0, betaAgentsDeleteVersionAlias_js_1.betaAgentsDeleteVersionAlias)(this, request, options)); + } + }; + exports.MistralAgents = MistralAgents; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/beta.js +var require_beta = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/beta.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Beta = void 0; + var sdks_js_1 = require_sdks(); + var conversations_js_1 = require_conversations(); + var libraries_js_1 = require_libraries(); + var mistralagents_js_1 = require_mistralagents(); + var Beta3 = class extends sdks_js_1.ClientSDK { + get conversations() { + return this._conversations ?? (this._conversations = new conversations_js_1.Conversations(this._options)); + } + get agents() { + return this._agents ?? (this._agents = new mistralagents_js_1.MistralAgents(this._options)); + } + get libraries() { + return this._libraries ?? (this._libraries = new libraries_js_1.Libraries(this._options)); + } + }; + exports.Beta = Beta3; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/chatComplete.js +var require_chatComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/chatComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.chatComplete = chatComplete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function chatComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatCompletionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/completions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "chat_completion_v1_chat_completions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ChatCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/chatStream.js +var require_chatStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/chatStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.chatStream = chatStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function chatStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/completions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "stream_chat", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + if (rawEvent.data === "[DONE]") + return { done: true }; + return { + value: components.CompletionEvent$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Options.js +var require_Options = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Options.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getDefaultOptions = exports.defaultOptions = exports.jsonDescription = exports.ignoreOverride = void 0; + exports.ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + var jsonDescription = (jsonSchema, def) => { + if (def.description) { + try { + return { + ...jsonSchema, + ...JSON.parse(def.description) + }; + } catch { + } + } + return jsonSchema; + }; + exports.jsonDescription = jsonDescription; + exports.defaultOptions = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" + }; + var getDefaultOptions2 = (options) => typeof options === "string" ? { + ...exports.defaultOptions, + name: options + } : { + ...exports.defaultOptions, + ...options + }; + exports.getDefaultOptions = getDefaultOptions2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Refs.js +var require_Refs = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/Refs.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRefs = void 0; + var Options_js_1 = require_Options(); + var getRefs2 = (options) => { + const _options = (0, Options_js_1.getDefaultOptions)(options); + const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: void 0 + } + ])) + }; + }; + exports.getRefs = getRefs2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js +var require_errorMessages = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/errorMessages.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setResponseValueAndErrors = exports.addErrorMessage = void 0; + function addErrorMessage2(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; + } + } + exports.addErrorMessage = addErrorMessage2; + function setResponseValueAndErrors2(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage2(res, key, errorMessage, refs); + } + exports.setResponseValueAndErrors = setResponseValueAndErrors2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js +var require_getRelativePath = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/getRelativePath.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRelativePath = void 0; + var getRelativePath2 = (pathA, pathB) => { + let i7 = 0; + for (; i7 < pathA.length && i7 < pathB.length; i7++) { + if (pathA[i7] !== pathB[i7]) + break; + } + return [(pathA.length - i7).toString(), ...pathB.slice(i7)].join("/"); + }; + exports.getRelativePath = getRelativePath2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js +var require_any = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/any.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseAnyDef = void 0; + var getRelativePath_js_1 = require_getRelativePath(); + function parseAnyDef2(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" ? (0, getRelativePath_js_1.getRelativePath)(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") + }; + } + exports.parseAnyDef = parseAnyDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js +var require_array = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/array.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseArrayDef = void 0; + var v3_1 = require_v3(); + var errorMessages_js_1 = require_errorMessages(); + var parseDef_js_1 = require_parseDef(); + function parseArrayDef2(def, refs) { + const res = { + type: "array" + }; + if (def.type?._def && def.type?._def?.typeName !== v3_1.ZodFirstPartyTypeKind.ZodAny) { + res.items = (0, parseDef_js_1.parseDef)(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + } + if (def.minLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; + } + exports.parseArrayDef = parseArrayDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js +var require_bigint = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/bigint.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseBigintDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + function parseBigintDef2(def, refs) { + const res = { + type: "integer", + format: "int64" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; + } + exports.parseBigintDef = parseBigintDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js +var require_boolean = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/boolean.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseBooleanDef = void 0; + function parseBooleanDef2() { + return { + type: "boolean" + }; + } + exports.parseBooleanDef = parseBooleanDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js +var require_branded = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/branded.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseBrandedDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseBrandedDef2(_def, refs) { + return (0, parseDef_js_1.parseDef)(_def.type._def, refs); + } + exports.parseBrandedDef = parseBrandedDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js +var require_catch = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/catch.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseCatchDef = void 0; + var parseDef_js_1 = require_parseDef(); + var parseCatchDef2 = (def, refs) => { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + }; + exports.parseCatchDef = parseCatchDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js +var require_date = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/date.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseDateDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + function parseDateDef2(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i7) => parseDateDef2(def, refs, item)) + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time" + }; + case "format:date": + return { + type: "string", + format: "date" + }; + case "integer": + return integerDateParser2(def, refs); + } + } + exports.parseDateDef = parseDateDef2; + var integerDateParser2 = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_js_1.setResponseValueAndErrors)( + res, + "minimum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + case "max": + (0, errorMessages_js_1.setResponseValueAndErrors)( + res, + "maximum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + } + } + return res; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js +var require_default = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/default.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseDefaultDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseDefaultDef2(_def, refs) { + return { + ...(0, parseDef_js_1.parseDef)(_def.innerType._def, refs), + default: _def.defaultValue() + }; + } + exports.parseDefaultDef = parseDefaultDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js +var require_effects = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/effects.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseEffectsDef = void 0; + var parseDef_js_1 = require_parseDef(); + var any_js_1 = require_any(); + function parseEffectsDef2(_def, refs) { + return refs.effectStrategy === "input" ? (0, parseDef_js_1.parseDef)(_def.schema._def, refs) : (0, any_js_1.parseAnyDef)(refs); + } + exports.parseEffectsDef = parseEffectsDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js +var require_enum = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/enum.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseEnumDef = void 0; + function parseEnumDef2(def) { + return { + type: "string", + enum: Array.from(def.values) + }; + } + exports.parseEnumDef = parseEnumDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js +var require_intersection = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/intersection.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseIntersectionDef = void 0; + var parseDef_js_1 = require_parseDef(); + var isJsonSchema7AllOfType2 = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; + }; + function parseIntersectionDef2(def, refs) { + const allOf = [ + (0, parseDef_js_1.parseDef)(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }), + (0, parseDef_js_1.parseDef)(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"] + }) + ].filter((x2) => !!x2); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType2(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) { + unevaluatedProperties = void 0; + } + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else { + unevaluatedProperties = void 0; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; + } + exports.parseIntersectionDef = parseIntersectionDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js +var require_literal = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/literal.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseLiteralDef = void 0; + function parseLiteralDef2(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object" + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value] + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value + }; + } + exports.parseLiteralDef = parseLiteralDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js +var require_string = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/string.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseStringDef = exports.zodPatterns = void 0; + var errorMessages_js_1 = require_errorMessages(); + var emojiRegex5 = void 0; + exports.zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex5 === void 0) { + emojiRegex5 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + } + return emojiRegex5; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ + }; + function parseStringDef2(def, refs) { + const res = { + type: "string" + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case "max": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat2(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat2(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern2(res, exports.zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat2(res, "uri", check.message, refs); + break; + case "uuid": + addFormat2(res, "uuid", check.message, refs); + break; + case "regex": + addPattern2(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern2(res, exports.zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern2(res, exports.zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern2(res, RegExp(`^${escapeLiteralCheckValue2(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern2(res, RegExp(`${escapeLiteralCheckValue2(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat2(res, "date-time", check.message, refs); + break; + case "date": + addFormat2(res, "date", check.message, refs); + break; + case "time": + addFormat2(res, "time", check.message, refs); + break; + case "duration": + addFormat2(res, "duration", check.message, refs); + break; + case "length": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": { + addPattern2(res, RegExp(escapeLiteralCheckValue2(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat2(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat2(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern2(res, exports.zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern2(res, exports.zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern2(res, exports.zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern2(res, exports.zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern2(res, exports.zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern2(res, exports.zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat2(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern2(res, exports.zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern2(res, exports.zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + /* @__PURE__ */ ((_3) => { + })(check); + } + } + } + return res; + } + exports.parseStringDef = parseStringDef2; + function escapeLiteralCheckValue2(literal, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric2(literal) : literal; + } + var ALPHA_NUMERIC2 = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + function escapeNonAlphaNumeric2(source) { + let result = ""; + for (let i7 = 0; i7 < source.length; i7++) { + if (!ALPHA_NUMERIC2.has(source[i7])) { + result += "\\"; + } + result += source[i7]; + } + return result; + } + function addFormat2(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x2) => x2.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format } + } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "format", value, message, refs); + } + } + function addPattern2(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern } + } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags2(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "pattern", stringifyRegExpWithFlags2(regex, refs), message, refs); + } + } + function stringifyRegExpWithFlags2(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + // `.` matches newlines + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i7 = 0; i7 < source.length; i7++) { + if (isEscaped) { + pattern += source[i7]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i7].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i7]; + pattern += `${source[i7 - 2]}-${source[i7]}`.toUpperCase(); + inCharRange = false; + } else if (source[i7 + 1] === "-" && source[i7 + 2]?.match(/[a-z]/)) { + pattern += source[i7]; + inCharRange = true; + } else { + pattern += `${source[i7]}${source[i7].toUpperCase()}`; + } + continue; + } + } else if (source[i7].match(/[a-z]/)) { + pattern += `[${source[i7]}${source[i7].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i7] === "^") { + pattern += `(^|(?<=[\r +]))`; + continue; + } else if (source[i7] === "$") { + pattern += `($|(?=[\r +]))`; + continue; + } + } + if (flags.s && source[i7] === ".") { + pattern += inCharGroup ? `${source[i7]}\r +` : `[${source[i7]}\r +]`; + continue; + } + pattern += source[i7]; + if (source[i7] === "\\") { + isEscaped = true; + } else if (inCharGroup && source[i7] === "]") { + inCharGroup = false; + } else if (!inCharGroup && source[i7] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; + } + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js +var require_record = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/record.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseRecordDef = void 0; + var v3_1 = require_v3(); + var parseDef_js_1 = require_parseDef(); + var string_js_1 = require_string(); + var branded_js_1 = require_branded(); + var any_js_1 = require_any(); + function parseRecordDef2(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key] + }) ?? (0, any_js_1.parseAnyDef)(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + } + const schema = { + type: "object", + additionalProperties: (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") { + return schema; + } + if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const { type, ...keyType } = (0, string_js_1.parseStringDef)(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values + } + }; + } else if (def.keyType?._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3_1.ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = (0, branded_js_1.parseBrandedDef)(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; + } + exports.parseRecordDef = parseRecordDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js +var require_map = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/map.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseMapDef = void 0; + var parseDef_js_1 = require_parseDef(); + var record_js_1 = require_record(); + var any_js_1 = require_any(); + function parseMapDef2(def, refs) { + if (refs.mapStrategy === "record") { + return (0, record_js_1.parseRecordDef)(def, refs); + } + const keys2 = (0, parseDef_js_1.parseDef)(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"] + }) || (0, any_js_1.parseAnyDef)(refs); + const values2 = (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"] + }) || (0, any_js_1.parseAnyDef)(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys2, values2], + minItems: 2, + maxItems: 2 + } + }; + } + exports.parseMapDef = parseMapDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js +var require_nativeEnum = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nativeEnum.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNativeEnumDef = void 0; + function parseNativeEnumDef2(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values2) => typeof values2))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; + } + exports.parseNativeEnumDef = parseNativeEnumDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js +var require_never = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/never.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNeverDef = void 0; + var any_js_1 = require_any(); + function parseNeverDef2(refs) { + return refs.target === "openAi" ? void 0 : { + not: (0, any_js_1.parseAnyDef)({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) + }; + } + exports.parseNeverDef = parseNeverDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js +var require_null = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/null.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNullDef = void 0; + function parseNullDef2(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { + type: "null" + }; + } + exports.parseNullDef = parseNullDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js +var require_union = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/union.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUnionDef = exports.primitiveMappings = void 0; + var parseDef_js_1 = require_parseDef(); + exports.primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" + }; + function parseUnionDef2(def, refs) { + if (refs.target === "openApi3") + return asAnyOf2(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x2) => x2._def.typeName in exports.primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) { + const types2 = options.reduce((types3, x2) => { + const type = exports.primitiveMappings[x2._def.typeName]; + return type && !types3.includes(type) ? [...types3, type] : types3; + }, []); + return { + type: types2.length > 1 ? types2 : types2[0] + }; + } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) { + const types2 = options.reduce((acc, x2) => { + const type = typeof x2._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x2._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types2.length === options.length) { + const uniqueTypes = types2.filter((x2, i7, a3) => a3.indexOf(x2) === i7); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x2) => { + return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value]; + }, []) + }; + } + } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x2) => [ + ...acc, + ...x2._def.values.filter((x3) => !acc.includes(x3)) + ], []) + }; + } + return asAnyOf2(def, refs); + } + exports.parseUnionDef = parseUnionDef2; + var asAnyOf2 = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i7}`] + })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)); + return anyOf.length ? { anyOf } : void 0; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js +var require_nullable = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/nullable.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNullableDef = void 0; + var parseDef_js_1 = require_parseDef(); + var union_js_1 = require_union(); + function parseNullableDef2(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: union_js_1.primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + } + return { + type: [ + union_js_1.primitiveMappings[def.innerType._def.typeName], + "null" + ] + }; + } + if (refs.target === "openApi3") { + const base2 = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }); + if (base2 && "$ref" in base2) + return { allOf: [base2], nullable: true }; + return base2 && { ...base2, nullable: true }; + } + const base = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"] + }); + return base && { anyOf: [base, { type: "null" }] }; + } + exports.parseNullableDef = parseNullableDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js +var require_number = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/number.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseNumberDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + function parseNumberDef2(def, refs) { + const res = { + type: "number" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + (0, errorMessages_js_1.addErrorMessage)(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } else { + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + (0, errorMessages_js_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; + } + exports.parseNumberDef = parseNumberDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js +var require_object = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/object.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseObjectDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseObjectDef2(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) { + continue; + } + let propOptional = safeIsOptional2(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; + } + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; + } + const parsedDef = (0, parseDef_js_1.parseDef)(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName] + }); + if (parsedDef === void 0) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required.push(propName); + } + } + if (required.length) { + result.required = required; + } + const additionalProperties = decideAdditionalProperties2(def, refs); + if (additionalProperties !== void 0) { + result.additionalProperties = additionalProperties; + } + return result; + } + exports.parseObjectDef = parseObjectDef2; + function decideAdditionalProperties2(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return (0, parseDef_js_1.parseDef)(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } + } + function safeIsOptional2(schema) { + try { + return schema.isOptional(); + } catch { + return true; + } + } + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js +var require_optional = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/optional.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseOptionalDef = void 0; + var parseDef_js_1 = require_parseDef(); + var any_js_1 = require_any(); + var parseOptionalDef2 = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + } + const innerSchema = (0, parseDef_js_1.parseDef)(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"] + }); + return innerSchema ? { + anyOf: [ + { + not: (0, any_js_1.parseAnyDef)(refs) + }, + innerSchema + ] + } : (0, any_js_1.parseAnyDef)(refs); + }; + exports.parseOptionalDef = parseOptionalDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js +var require_pipeline = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/pipeline.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parsePipelineDef = void 0; + var parseDef_js_1 = require_parseDef(); + var parsePipelineDef2 = (def, refs) => { + if (refs.pipeStrategy === "input") { + return (0, parseDef_js_1.parseDef)(def.in._def, refs); + } else if (refs.pipeStrategy === "output") { + return (0, parseDef_js_1.parseDef)(def.out._def, refs); + } + const a3 = (0, parseDef_js_1.parseDef)(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }); + const b4 = (0, parseDef_js_1.parseDef)(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"] + }); + return { + allOf: [a3, b4].filter((x2) => x2 !== void 0) + }; + }; + exports.parsePipelineDef = parsePipelineDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js +var require_promise = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/promise.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parsePromiseDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parsePromiseDef2(def, refs) { + return (0, parseDef_js_1.parseDef)(def.type._def, refs); + } + exports.parsePromiseDef = parsePromiseDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js +var require_set = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/set.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseSetDef = void 0; + var errorMessages_js_1 = require_errorMessages(); + var parseDef_js_1 = require_parseDef(); + function parseSetDef2(def, refs) { + const items = (0, parseDef_js_1.parseDef)(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + const schema = { + type: "array", + uniqueItems: true, + items + }; + if (def.minSize) { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + (0, errorMessages_js_1.setResponseValueAndErrors)(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; + } + exports.parseSetDef = parseSetDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js +var require_tuple = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/tuple.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseTupleDef = void 0; + var parseDef_js_1 = require_parseDef(); + function parseTupleDef2(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items.map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i7}`] + })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []), + additionalItems: (0, parseDef_js_1.parseDef)(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + } else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x2, i7) => (0, parseDef_js_1.parseDef)(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i7}`] + })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []) + }; + } + } + exports.parseTupleDef = parseTupleDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js +var require_undefined = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/undefined.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUndefinedDef = void 0; + var any_js_1 = require_any(); + function parseUndefinedDef2(refs) { + return { + not: (0, any_js_1.parseAnyDef)(refs) + }; + } + exports.parseUndefinedDef = parseUndefinedDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js +var require_unknown = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/unknown.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseUnknownDef = void 0; + var any_js_1 = require_any(); + function parseUnknownDef2(refs) { + return (0, any_js_1.parseAnyDef)(refs); + } + exports.parseUnknownDef = parseUnknownDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js +var require_readonly = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parsers/readonly.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseReadonlyDef = void 0; + var parseDef_js_1 = require_parseDef(); + var parseReadonlyDef2 = (def, refs) => { + return (0, parseDef_js_1.parseDef)(def.innerType._def, refs); + }; + exports.parseReadonlyDef = parseReadonlyDef2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/selectParser.js +var require_selectParser = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/selectParser.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.selectParser = void 0; + var v3_1 = require_v3(); + var any_js_1 = require_any(); + var array_js_1 = require_array(); + var bigint_js_1 = require_bigint(); + var boolean_js_1 = require_boolean(); + var branded_js_1 = require_branded(); + var catch_js_1 = require_catch(); + var date_js_1 = require_date(); + var default_js_1 = require_default(); + var effects_js_1 = require_effects(); + var enum_js_1 = require_enum(); + var intersection_js_1 = require_intersection(); + var literal_js_1 = require_literal(); + var map_js_1 = require_map(); + var nativeEnum_js_1 = require_nativeEnum(); + var never_js_1 = require_never(); + var null_js_1 = require_null(); + var nullable_js_1 = require_nullable(); + var number_js_1 = require_number(); + var object_js_1 = require_object(); + var optional_js_1 = require_optional(); + var pipeline_js_1 = require_pipeline(); + var promise_js_1 = require_promise(); + var record_js_1 = require_record(); + var set_js_1 = require_set(); + var string_js_1 = require_string(); + var tuple_js_1 = require_tuple(); + var undefined_js_1 = require_undefined(); + var union_js_1 = require_union(); + var unknown_js_1 = require_unknown(); + var readonly_js_1 = require_readonly(); + var selectParser2 = (def, typeName, refs) => { + switch (typeName) { + case v3_1.ZodFirstPartyTypeKind.ZodString: + return (0, string_js_1.parseStringDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodNumber: + return (0, number_js_1.parseNumberDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodObject: + return (0, object_js_1.parseObjectDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBigInt: + return (0, bigint_js_1.parseBigintDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBoolean: + return (0, boolean_js_1.parseBooleanDef)(); + case v3_1.ZodFirstPartyTypeKind.ZodDate: + return (0, date_js_1.parseDateDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodUndefined: + return (0, undefined_js_1.parseUndefinedDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodNull: + return (0, null_js_1.parseNullDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodArray: + return (0, array_js_1.parseArrayDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodUnion: + case v3_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return (0, union_js_1.parseUnionDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodIntersection: + return (0, intersection_js_1.parseIntersectionDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodTuple: + return (0, tuple_js_1.parseTupleDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodRecord: + return (0, record_js_1.parseRecordDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodLiteral: + return (0, literal_js_1.parseLiteralDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodEnum: + return (0, enum_js_1.parseEnumDef)(def); + case v3_1.ZodFirstPartyTypeKind.ZodNativeEnum: + return (0, nativeEnum_js_1.parseNativeEnumDef)(def); + case v3_1.ZodFirstPartyTypeKind.ZodNullable: + return (0, nullable_js_1.parseNullableDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodOptional: + return (0, optional_js_1.parseOptionalDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodMap: + return (0, map_js_1.parseMapDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodSet: + return (0, set_js_1.parseSetDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodLazy: + return () => def.getter()._def; + case v3_1.ZodFirstPartyTypeKind.ZodPromise: + return (0, promise_js_1.parsePromiseDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodNaN: + case v3_1.ZodFirstPartyTypeKind.ZodNever: + return (0, never_js_1.parseNeverDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodEffects: + return (0, effects_js_1.parseEffectsDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodAny: + return (0, any_js_1.parseAnyDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodUnknown: + return (0, unknown_js_1.parseUnknownDef)(refs); + case v3_1.ZodFirstPartyTypeKind.ZodDefault: + return (0, default_js_1.parseDefaultDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodBranded: + return (0, branded_js_1.parseBrandedDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodReadonly: + return (0, readonly_js_1.parseReadonlyDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodCatch: + return (0, catch_js_1.parseCatchDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodPipeline: + return (0, pipeline_js_1.parsePipelineDef)(def, refs); + case v3_1.ZodFirstPartyTypeKind.ZodFunction: + case v3_1.ZodFirstPartyTypeKind.ZodVoid: + case v3_1.ZodFirstPartyTypeKind.ZodSymbol: + return void 0; + default: + return /* @__PURE__ */ ((_3) => void 0)(typeName); + } + }; + exports.selectParser = selectParser2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseDef.js +var require_parseDef = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseDef.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseDef = void 0; + var Options_js_1 = require_Options(); + var selectParser_js_1 = require_selectParser(); + var getRelativePath_js_1 = require_getRelativePath(); + var any_js_1 = require_any(); + function parseDef2(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== Options_js_1.ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref2(seenItem, refs); + if (seenSchema !== void 0) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = (0, selectParser_js_1.selectParser)(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef2(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta2(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; + } + exports.parseDef = parseDef2; + var get$ref2 = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: (0, getRelativePath_js_1.getRelativePath)(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return (0, any_js_1.parseAnyDef)(refs); + } + return refs.$refStrategy === "seen" ? (0, any_js_1.parseAnyDef)(refs) : void 0; + } + } + }; + var addMeta2 = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js +var require_parseTypes = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/parseTypes.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js +var require_zodToJsonSchema = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/zodToJsonSchema.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.zodToJsonSchema = void 0; + var parseDef_js_1 = require_parseDef(); + var Refs_js_1 = require_Refs(); + var any_js_1 = require_any(); + var zodToJsonSchema2 = (schema, options) => { + const refs = (0, Refs_js_1.getRefs)(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ + ...acc, + [name2]: (0, parseDef_js_1.parseDef)(schema2._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name2] + }, true) ?? (0, any_js_1.parseAnyDef)(refs) + }), {}) : void 0; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main2 = (0, parseDef_js_1.parseDef)(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name] + }, false) ?? (0, any_js_1.parseAnyDef)(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) { + main2.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") + } + }; + } + } + const combined = name === void 0 ? definitions ? { + ...main2, + [refs.definitionPath]: definitions + } : main2 : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main2 + } + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; + }; + exports.zodToJsonSchema = zodToJsonSchema2; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/cjs/index.js +var require_cjs = __commonJS({ + "../pi-mono/node_modules/zod-to-json-schema/dist/cjs/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + __exportStar(require_Options(), exports); + __exportStar(require_Refs(), exports); + __exportStar(require_errorMessages(), exports); + __exportStar(require_getRelativePath(), exports); + __exportStar(require_parseDef(), exports); + __exportStar(require_parseTypes(), exports); + __exportStar(require_any(), exports); + __exportStar(require_array(), exports); + __exportStar(require_bigint(), exports); + __exportStar(require_boolean(), exports); + __exportStar(require_branded(), exports); + __exportStar(require_catch(), exports); + __exportStar(require_date(), exports); + __exportStar(require_default(), exports); + __exportStar(require_effects(), exports); + __exportStar(require_enum(), exports); + __exportStar(require_intersection(), exports); + __exportStar(require_literal(), exports); + __exportStar(require_map(), exports); + __exportStar(require_nativeEnum(), exports); + __exportStar(require_never(), exports); + __exportStar(require_null(), exports); + __exportStar(require_nullable(), exports); + __exportStar(require_number(), exports); + __exportStar(require_object(), exports); + __exportStar(require_optional(), exports); + __exportStar(require_pipeline(), exports); + __exportStar(require_promise(), exports); + __exportStar(require_readonly(), exports); + __exportStar(require_record(), exports); + __exportStar(require_set(), exports); + __exportStar(require_string(), exports); + __exportStar(require_tuple(), exports); + __exportStar(require_undefined(), exports); + __exportStar(require_union(), exports); + __exportStar(require_unknown(), exports); + __exportStar(require_selectParser(), exports); + __exportStar(require_zodToJsonSchema(), exports); + var zodToJsonSchema_js_1 = require_zodToJsonSchema(); + exports.default = zodToJsonSchema_js_1.zodToJsonSchema; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/extra/structChat.js +var require_structChat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/extra/structChat.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.transformToChatCompletionRequest = transformToChatCompletionRequest; + exports.convertToParsedChatCompletionResponse = convertToParsedChatCompletionResponse; + exports.responseFormatFromZodObject = responseFormatFromZodObject; + var zod_to_json_schema_1 = require_cjs(); + function transformToChatCompletionRequest(parsedRequest) { + const { responseFormat, ...rest } = parsedRequest; + const transformedResponseFormat = responseFormatFromZodObject(responseFormat); + return { + ...rest, + responseFormat: transformedResponseFormat + }; + } + function convertToParsedChatCompletionResponse(response, responseFormat) { + if (response.choices === void 0 || response.choices.length === 0) { + return { + ...response, + choices: response.choices === void 0 ? void 0 : [] + }; + } + const parsedChoices = []; + for (const _choice of response.choices) { + if (_choice.message === null || typeof _choice.message === "undefined") { + parsedChoices.push({ ..._choice, message: void 0 }); + } else { + if (_choice.message.content !== null && typeof _choice.message.content !== "undefined" && !Array.isArray(_choice.message.content)) { + parsedChoices.push({ + ..._choice, + message: { + ..._choice.message, + parsed: responseFormat.safeParse(JSON.parse(_choice.message.content)).data + } + }); + } + } + } + return { + ...response, + choices: parsedChoices + }; + } + function responseFormatFromZodObject(responseFormat) { + const responseJsonSchema = (0, zod_to_json_schema_1.zodToJsonSchema)(responseFormat); + const placeholderName = "placeholderName"; + return { + type: "json_schema", + jsonSchema: { + name: placeholderName, + schemaDefinition: responseJsonSchema, + strict: true + } + }; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/chat.js +var require_chat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/chat.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Chat = void 0; + var chatComplete_js_1 = require_chatComplete(); + var chatStream_js_1 = require_chatStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var structChat_js_1 = require_structChat(); + var Chat4 = class extends sdks_js_1.ClientSDK { + // #region sdk-class-body + /** + * Chat Completion with the response parsed in the same format as the input requestFormat. + * + * @remarks + * The response will be parsed back to the initial Zod object passed in the requestFormat field. + */ + async parse(request, options) { + const ccr_request = (0, structChat_js_1.transformToChatCompletionRequest)(request); + const response = await (0, fp_js_1.unwrapAsync)((0, chatComplete_js_1.chatComplete)(this, ccr_request, options)); + const parsed_response = (0, structChat_js_1.convertToParsedChatCompletionResponse)(response, request.responseFormat); + return parsed_response; + } + /** + * Stream chat completion with a parsed request input. + * + * @remarks + * Unlike the .parse method, this method will return a stream of events containing the JSON response. It will not be parsed back to the initial Zod object. + * If you need to parse the stream, see the examples/src/async_structured_outputs.ts file. + */ + async parseStream(request, options) { + const ccr_request = (0, structChat_js_1.transformToChatCompletionRequest)(request); + return (0, fp_js_1.unwrapAsync)((0, chatStream_js_1.chatStream)(this, ccr_request, options)); + } + // #endregion sdk-class-body + /** + * Chat Completion + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, chatComplete_js_1.chatComplete)(this, request, options)); + } + /** + * Stream chat completion + * + * @remarks + * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON. + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, chatStream_js_1.chatStream)(this, request, options)); + } + }; + exports.Chat = Chat4; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassify.js +var require_classifiersClassify = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassify.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersClassify = classifiersClassify; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersClassify(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ClassificationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/classifications")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "classifications_v1_classifications_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ClassificationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassifyChat.js +var require_classifiersClassifyChat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersClassifyChat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersClassifyChat = classifiersClassifyChat; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersClassifyChat(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatClassificationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/classifications")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "chat_classifications_v1_chat_classifications_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ClassificationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerate.js +var require_classifiersModerate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersModerate = classifiersModerate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersModerate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ClassificationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/moderations")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "moderations_v1_moderations_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ModerationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerateChat.js +var require_classifiersModerateChat = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/classifiersModerateChat.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.classifiersModerateChat = classifiersModerateChat; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function classifiersModerateChat(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.ChatModerationRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/chat/moderations")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "chat_moderations_v1_chat_moderations_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.ModerationResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/classifiers.js +var require_classifiers = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/classifiers.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Classifiers = void 0; + var classifiersClassify_js_1 = require_classifiersClassify(); + var classifiersClassifyChat_js_1 = require_classifiersClassifyChat(); + var classifiersModerate_js_1 = require_classifiersModerate(); + var classifiersModerateChat_js_1 = require_classifiersModerateChat(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Classifiers = class extends sdks_js_1.ClientSDK { + /** + * Moderations + */ + async moderate(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersModerate_js_1.classifiersModerate)(this, request, options)); + } + /** + * Chat Moderations + */ + async moderateChat(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersModerateChat_js_1.classifiersModerateChat)(this, request, options)); + } + /** + * Classifications + */ + async classify(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersClassify_js_1.classifiersClassify)(this, request, options)); + } + /** + * Chat Classifications + */ + async classifyChat(request, options) { + return (0, fp_js_1.unwrapAsync)((0, classifiersClassifyChat_js_1.classifiersClassifyChat)(this, request, options)); + } + }; + exports.Classifiers = Classifiers; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/embeddingsCreate.js +var require_embeddingsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/embeddingsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.embeddingsCreate = embeddingsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function embeddingsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.EmbeddingRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/embeddings")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "embeddings_v1_embeddings_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.EmbeddingResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/embeddings.js +var require_embeddings = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/embeddings.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Embeddings = void 0; + var embeddingsCreate_js_1 = require_embeddingsCreate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Embeddings2 = class extends sdks_js_1.ClientSDK { + /** + * Embeddings + * + * @remarks + * Embeddings + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, embeddingsCreate_js_1.embeddingsCreate)(this, request, options)); + } + }; + exports.Embeddings = Embeddings2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDelete.js +var require_filesDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesDelete = filesDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesDeleteFileRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_delete_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.DeleteFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDownload.js +var require_filesDownload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesDownload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesDownload = filesDownload; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesDownload(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesDownloadFileRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}/content")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/octet-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_download_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.stream(200, z3.instanceof(ReadableStream)), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesGetSignedUrl.js +var require_filesGetSignedUrl = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesGetSignedUrl.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesGetSignedUrl = filesGetSignedUrl; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesGetSignedUrl(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesGetSignedUrlRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}/url")(pathParams); + const query = (0, encodings_js_1.encodeFormQuery)({ + "expiry": payload.expiry + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_get_signed_url", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.FileSignedURL$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesList.js +var require_filesList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesList = filesList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesListFilesRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/files")(); + const query = (0, encodings_js_1.encodeFormQuery)({ + "include_total": payload?.include_total, + "mimetypes": payload?.mimetypes, + "page": payload?.page, + "page_size": payload?.page_size, + "purpose": payload?.purpose, + "sample_type": payload?.sample_type, + "search": payload?.search, + "source": payload?.source + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_list_files", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ListFilesOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesRetrieve.js +var require_filesRetrieve = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesRetrieve.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesRetrieve = filesRetrieve; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function filesRetrieve(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesRetrieveFileRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + file_id: (0, encodings_js_1.encodeSimple)("file_id", payload.file_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/files/{file_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_retrieve_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.RetrieveFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/filesUpload.js +var require_filesUpload = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/filesUpload.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filesUpload = filesUpload; + var encodings_js_1 = require_encodings(); + var files_js_1 = require_files(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + var blobs_js_1 = require_blobs(); + var streams_js_1 = require_streams(); + function filesUpload(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.FilesApiRoutesUploadFileMultiPartBodyParams$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = new FormData(); + if ((0, blobs_js_1.isBlobLike)(payload.file)) { + (0, encodings_js_1.appendForm)(body, "file", payload.file); + } else if ((0, streams_js_1.isReadableStream)(payload.file.content)) { + const buffer = await (0, files_js_1.readableStreamToArrayBuffer)(payload.file.content); + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + const blob = new Blob([buffer], { type: contentType }); + (0, encodings_js_1.appendForm)(body, "file", blob, payload.file.fileName); + } else { + const contentType = (0, files_js_1.getContentTypeFromFileName)(payload.file.fileName) || "application/octet-stream"; + (0, encodings_js_1.appendForm)(body, "file", new Blob([payload.file.content], { type: contentType }), payload.file.fileName); + } + if (payload.purpose !== void 0) { + (0, encodings_js_1.appendForm)(body, "purpose", payload.purpose); + } + const path6 = (0, url_js_1.pathToFunc)("/v1/files")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "files_api_routes_upload_file", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.UploadFileOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/files.js +var require_files2 = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/files.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Files = void 0; + var filesDelete_js_1 = require_filesDelete(); + var filesDownload_js_1 = require_filesDownload(); + var filesGetSignedUrl_js_1 = require_filesGetSignedUrl(); + var filesList_js_1 = require_filesList(); + var filesRetrieve_js_1 = require_filesRetrieve(); + var filesUpload_js_1 = require_filesUpload(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Files6 = class extends sdks_js_1.ClientSDK { + /** + * Upload File + * + * @remarks + * Upload a file that can be used across various endpoints. + * + * The size of individual files can be a maximum of 512 MB. The Fine-tuning API only supports .jsonl files. + * + * Please contact us if you need to increase these storage limits. + */ + async upload(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesUpload_js_1.filesUpload)(this, request, options)); + } + /** + * List Files + * + * @remarks + * Returns a list of files that belong to the user's organization. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesList_js_1.filesList)(this, request, options)); + } + /** + * Retrieve File + * + * @remarks + * Returns information about a specific file. + */ + async retrieve(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesRetrieve_js_1.filesRetrieve)(this, request, options)); + } + /** + * Delete File + * + * @remarks + * Delete a file. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesDelete_js_1.filesDelete)(this, request, options)); + } + /** + * Download File + * + * @remarks + * Download a file + */ + async download(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesDownload_js_1.filesDownload)(this, request, options)); + } + /** + * Get Signed Url + */ + async getSignedUrl(request, options) { + return (0, fp_js_1.unwrapAsync)((0, filesGetSignedUrl_js_1.filesGetSignedUrl)(this, request, options)); + } + }; + exports.Files = Files6; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fimComplete.js +var require_fimComplete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fimComplete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fimComplete = fimComplete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function fimComplete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.FIMCompletionRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/fim/completions")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "fim_completion_v1_fim_completions_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.FIMCompletionResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fimStream.js +var require_fimStream = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fimStream.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fimStream = fimStream; + var z3 = __importStar(require_v3()); + var encodings_js_1 = require_encodings(); + var event_streams_js_1 = require_event_streams(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function fimStream(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.FIMCompletionStreamRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/fim/completions#stream")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "text/event-stream" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "stream_fim", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.sse(200, z3.instanceof(ReadableStream).transform((stream2) => { + return new event_streams_js_1.EventStream(stream2, (rawEvent) => { + if (rawEvent.data === "[DONE]") + return { done: true }; + return { + value: components.CompletionEvent$inboundSchema.parse(rawEvent) + }; + }); + })), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/fim.js +var require_fim = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/fim.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Fim = void 0; + var fimComplete_js_1 = require_fimComplete(); + var fimStream_js_1 = require_fimStream(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Fim = class extends sdks_js_1.ClientSDK { + /** + * Fim Completion + * + * @remarks + * FIM completion. + */ + async complete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fimComplete_js_1.fimComplete)(this, request, options)); + } + /** + * Stream fim completion + * + * @remarks + * Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON. + */ + async stream(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fimStream_js_1.fimStream)(this, request, options)); + } + }; + exports.Fim = Fim; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCancel.js +var require_fineTuningJobsCancel = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCancel.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsCancel = fineTuningJobsCancel; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsCancel(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningCancelFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}/cancel")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_cancel_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningCancelFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCreate.js +var require_fineTuningJobsCreate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsCreate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsCreate = fineTuningJobsCreate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsCreate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.JobIn$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_create_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningCreateFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsGet.js +var require_fineTuningJobsGet = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsGet.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsGet = fineTuningJobsGet; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsGet(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningGetFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_get_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningGetFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsList.js +var require_fineTuningJobsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsList = fineTuningJobsList; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsList(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningGetFineTuningJobsRequest$outboundSchema.optional().parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs")(); + const query = (0, encodings_js_1.encodeFormQuery)({ + "created_after": payload?.created_after, + "created_before": payload?.created_before, + "created_by_me": payload?.created_by_me, + "model": payload?.model, + "page": payload?.page, + "page_size": payload?.page_size, + "status": payload?.status, + "suffix": payload?.suffix, + "wandb_name": payload?.wandb_name, + "wandb_project": payload?.wandb_project + }); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_get_fine_tuning_jobs", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + query, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.JobsOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsStart.js +var require_fineTuningJobsStart = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/fineTuningJobsStart.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fineTuningJobsStart = fineTuningJobsStart; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function fineTuningJobsStart(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningStartFineTuningJobRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + job_id: (0, encodings_js_1.encodeSimple)("job_id", payload.job_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/jobs/{job_id}/start")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_start_fine_tuning_job", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningStartFineTuningJobResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/jobs.js +var require_jobs = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/jobs.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Jobs = void 0; + var fineTuningJobsCancel_js_1 = require_fineTuningJobsCancel(); + var fineTuningJobsCreate_js_1 = require_fineTuningJobsCreate(); + var fineTuningJobsGet_js_1 = require_fineTuningJobsGet(); + var fineTuningJobsList_js_1 = require_fineTuningJobsList(); + var fineTuningJobsStart_js_1 = require_fineTuningJobsStart(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Jobs2 = class extends sdks_js_1.ClientSDK { + /** + * Get Fine Tuning Jobs + * + * @remarks + * Get a list of fine-tuning jobs for your organization and user. + */ + async list(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsList_js_1.fineTuningJobsList)(this, request, options)); + } + /** + * Create Fine Tuning Job + * + * @remarks + * Create a new fine-tuning job, it will be queued for processing. + */ + async create(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsCreate_js_1.fineTuningJobsCreate)(this, request, options)); + } + /** + * Get Fine Tuning Job + * + * @remarks + * Get a fine-tuned job details by its UUID. + */ + async get(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsGet_js_1.fineTuningJobsGet)(this, request, options)); + } + /** + * Cancel Fine Tuning Job + * + * @remarks + * Request the cancellation of a fine tuning job. + */ + async cancel(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsCancel_js_1.fineTuningJobsCancel)(this, request, options)); + } + /** + * Start Fine Tuning Job + * + * @remarks + * Request the start of a validated fine tuning job. + */ + async start(request, options) { + return (0, fp_js_1.unwrapAsync)((0, fineTuningJobsStart_js_1.fineTuningJobsStart)(this, request, options)); + } + }; + exports.Jobs = Jobs2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/finetuning.js +var require_finetuning = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/finetuning.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FineTuning = void 0; + var sdks_js_1 = require_sdks(); + var jobs_js_1 = require_jobs(); + var FineTuning2 = class extends sdks_js_1.ClientSDK { + get jobs() { + return this._jobs ?? (this._jobs = new jobs_js_1.Jobs(this._options)); + } + }; + exports.FineTuning = FineTuning2; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsArchive.js +var require_modelsArchive = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsArchive.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsArchive = modelsArchive; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsArchive(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningArchiveFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}/archive")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_archive_fine_tuned_model", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ArchiveFTModelOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsDelete.js +var require_modelsDelete = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsDelete.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsDelete = modelsDelete; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsDelete(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.DeleteModelV1ModelsModelIdDeleteRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/models/{model_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "delete_model_v1_models__model_id__delete", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.DeleteModelOut$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsList.js +var require_modelsList = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsList.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsList = modelsList; + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var async_js_1 = require_async(); + function modelsList(client, options) { + return new async_js_1.APIPromise($do(client, options)); + } + async function $do(client, options) { + const path6 = (0, url_js_1.pathToFunc)("/v1/models")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "list_models_v1_models_get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.ModelList$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsRetrieve.js +var require_modelsRetrieve = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsRetrieve.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsRetrieve = modelsRetrieve; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var errors = __importStar(require_errors2()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsRetrieve(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.RetrieveModelV1ModelsModelIdGetRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/models/{model_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "retrieve_model_v1_models__model_id__get", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "GET", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, operations.RetrieveModelV1ModelsModelIdGetResponseRetrieveModelV1ModelsModelIdGet$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUnarchive.js +var require_modelsUnarchive = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUnarchive.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsUnarchive = modelsUnarchive; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsUnarchive(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningUnarchiveFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}/archive")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_unarchive_fine_tuned_model", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "DELETE", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, components.UnarchiveFTModelOut$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUpdate.js +var require_modelsUpdate = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/modelsUpdate.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.modelsUpdate = modelsUpdate; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var operations = __importStar(require_operations()); + var async_js_1 = require_async(); + function modelsUpdate(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => operations.JobsApiRoutesFineTuningUpdateFineTunedModelRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload.UpdateFTModelIn, { explode: true }); + const pathParams = { + model_id: (0, encodings_js_1.encodeSimple)("model_id", payload.model_id, { + explode: false, + charEncoding: "percent" + }) + }; + const path6 = (0, url_js_1.pathToFunc)("/v1/fine_tuning/models/{model_id}")(pathParams); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "jobs_api_routes_fine_tuning_update_fine_tuned_model", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "PATCH", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const [result] = await M4.match(M4.json(200, operations.JobsApiRoutesFineTuningUpdateFineTunedModelResponse$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/models.js +var require_models = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/models.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Models = void 0; + var modelsArchive_js_1 = require_modelsArchive(); + var modelsDelete_js_1 = require_modelsDelete(); + var modelsList_js_1 = require_modelsList(); + var modelsRetrieve_js_1 = require_modelsRetrieve(); + var modelsUnarchive_js_1 = require_modelsUnarchive(); + var modelsUpdate_js_1 = require_modelsUpdate(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Models5 = class extends sdks_js_1.ClientSDK { + /** + * List Models + * + * @remarks + * List all models available to the user. + */ + async list(options) { + return (0, fp_js_1.unwrapAsync)((0, modelsList_js_1.modelsList)(this, options)); + } + /** + * Retrieve Model + * + * @remarks + * Retrieve information about a model. + */ + async retrieve(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsRetrieve_js_1.modelsRetrieve)(this, request, options)); + } + /** + * Delete Model + * + * @remarks + * Delete a fine-tuned model. + */ + async delete(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsDelete_js_1.modelsDelete)(this, request, options)); + } + /** + * Update Fine Tuned Model + * + * @remarks + * Update a model name or description. + */ + async update(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsUpdate_js_1.modelsUpdate)(this, request, options)); + } + /** + * Archive Fine Tuned Model + * + * @remarks + * Archive a fine-tuned model. + */ + async archive(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsArchive_js_1.modelsArchive)(this, request, options)); + } + /** + * Unarchive Fine Tuned Model + * + * @remarks + * Un-archive a fine-tuned model. + */ + async unarchive(request, options) { + return (0, fp_js_1.unwrapAsync)((0, modelsUnarchive_js_1.modelsUnarchive)(this, request, options)); + } + }; + exports.Models = Models5; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/funcs/ocrProcess.js +var require_ocrProcess = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/funcs/ocrProcess.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ocrProcess = ocrProcess; + var encodings_js_1 = require_encodings(); + var M4 = __importStar(require_matchers()); + var primitives_js_1 = require_primitives(); + var schemas_js_1 = require_schemas(); + var security_js_1 = require_security(); + var url_js_1 = require_url(); + var components = __importStar(require_components()); + var errors = __importStar(require_errors2()); + var async_js_1 = require_async(); + function ocrProcess(client, request, options) { + return new async_js_1.APIPromise($do(client, request, options)); + } + async function $do(client, request, options) { + const parsed = (0, schemas_js_1.safeParse)(request, (value) => components.OCRRequest$outboundSchema.parse(value), "Input validation failed"); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = (0, encodings_js_1.encodeJSON)("body", payload, { explode: true }); + const path6 = (0, url_js_1.pathToFunc)("/v1/ocr")(); + const headers = new Headers((0, primitives_js_1.compactMap)({ + "Content-Type": "application/json", + Accept: "application/json" + })); + const secConfig = await (0, security_js_1.extractSecurity)(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = (0, security_js_1.resolveGlobalSecurity)(securityInput); + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "ocr_v1_ocr_post", + oAuth2Scopes: null, + resolvedSecurity: requestSecurity, + securitySource: client._options.apiKey, + retryConfig: options?.retries || client._options.retryConfig || { strategy: "none" }, + retryCodes: options?.retryCodes || ["429", "500", "502", "503", "504"] + }; + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path6, + headers, + body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1 + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + const doResult = await client._do(req, { + context, + errorCodes: ["422", "4XX", "5XX"], + retryConfig: context.retryConfig, + retryCodes: context.retryCodes + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + const responseFields = { + HttpMeta: { Response: response, Request: req } + }; + const [result] = await M4.match(M4.json(200, components.OCRResponse$inboundSchema), M4.jsonErr(422, errors.HTTPValidationError$inboundSchema), M4.fail("4XX"), M4.fail("5XX"))(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + return [result, { status: "complete", request: req, response }]; + } + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/ocr.js +var require_ocr = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/ocr.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Ocr = void 0; + var ocrProcess_js_1 = require_ocrProcess(); + var sdks_js_1 = require_sdks(); + var fp_js_1 = require_fp(); + var Ocr = class extends sdks_js_1.ClientSDK { + /** + * OCR + */ + async process(request, options) { + return (0, fp_js_1.unwrapAsync)((0, ocrProcess_js_1.ocrProcess)(this, request, options)); + } + }; + exports.Ocr = Ocr; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/sdk/sdk.js +var require_sdk = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/sdk/sdk.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Mistral = void 0; + var sdks_js_1 = require_sdks(); + var agents_js_1 = require_agents(); + var audio_js_1 = require_audio(); + var batch_js_1 = require_batch(); + var beta_js_1 = require_beta(); + var chat_js_1 = require_chat(); + var classifiers_js_1 = require_classifiers(); + var embeddings_js_1 = require_embeddings(); + var files_js_1 = require_files2(); + var fim_js_1 = require_fim(); + var finetuning_js_1 = require_finetuning(); + var models_js_1 = require_models(); + var ocr_js_1 = require_ocr(); + var Mistral3 = class extends sdks_js_1.ClientSDK { + get models() { + return this._models ?? (this._models = new models_js_1.Models(this._options)); + } + get beta() { + return this._beta ?? (this._beta = new beta_js_1.Beta(this._options)); + } + get files() { + return this._files ?? (this._files = new files_js_1.Files(this._options)); + } + get fineTuning() { + return this._fineTuning ?? (this._fineTuning = new finetuning_js_1.FineTuning(this._options)); + } + get batch() { + return this._batch ?? (this._batch = new batch_js_1.Batch(this._options)); + } + get chat() { + return this._chat ?? (this._chat = new chat_js_1.Chat(this._options)); + } + get fim() { + return this._fim ?? (this._fim = new fim_js_1.Fim(this._options)); + } + get agents() { + return this._agents ?? (this._agents = new agents_js_1.Agents(this._options)); + } + get embeddings() { + return this._embeddings ?? (this._embeddings = new embeddings_js_1.Embeddings(this._options)); + } + get classifiers() { + return this._classifiers ?? (this._classifiers = new classifiers_js_1.Classifiers(this._options)); + } + get ocr() { + return this._ocr ?? (this._ocr = new ocr_js_1.Ocr(this._options)); + } + get audio() { + return this._audio ?? (this._audio = new audio_js_1.Audio(this._options)); + } + }; + exports.Mistral = Mistral3; + } +}); + +// ../pi-mono/node_modules/@mistralai/mistralai/index.js +var require_mistralai = __commonJS({ + "../pi-mono/node_modules/@mistralai/mistralai/index.js"(exports) { + "use strict"; + init_process_shim(); + var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + var desc = Object.getOwnPropertyDescriptor(m4, k2); + if (!desc || ("get" in desc ? !m4.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m4[k2]; + } }; + } + Object.defineProperty(o9, k22, desc); + }) : (function(o9, m4, k2, k22) { + if (k22 === void 0) k22 = k2; + o9[k22] = m4[k2]; + })); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o9, v4) { + Object.defineProperty(o9, "default", { enumerable: true, value: v4 }); + }) : function(o9, v4) { + o9["default"] = v4; + }); + var __exportStar = exports && exports.__exportStar || function(m4, exports2) { + for (var p4 in m4) if (p4 !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p4)) __createBinding(exports2, m4, p4); + }; + var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() { + var ownKeys = function(o9) { + ownKeys = Object.getOwnPropertyNames || function(o10) { + var ar = []; + for (var k2 in o10) if (Object.prototype.hasOwnProperty.call(o10, k2)) ar[ar.length] = k2; + return ar; + }; + return ownKeys(o9); + }; + return function(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) { + for (var k2 = ownKeys(mod), i7 = 0; i7 < k2.length; i7++) if (k2[i7] !== "default") __createBinding(result, mod, k2[i7]); + } + __setModuleDefault(result, mod); + return result; + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HTTPClient = exports.files = void 0; + __exportStar(require_config(), exports); + exports.files = __importStar(require_files()); + var http_js_1 = require_http(); + Object.defineProperty(exports, "HTTPClient", { enumerable: true, get: function() { + return http_js_1.HTTPClient; + } }); + __exportStar(require_sdk(), exports); + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s6) { + super(); + if (!exports.IDENTIFIER.test(s6)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s6; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a7; + return (_a7 = this._str) !== null && _a7 !== void 0 ? _a7 : this._str = this._items.reduce((s6, c6) => `${s6}${c6}`, ""); + } + get names() { + var _a7; + return (_a7 = this._names) !== null && _a7 !== void 0 ? _a7 : this._names = this._items.reduce((names2, c6) => { + if (c6 instanceof Name) + names2[c6.str] = (names2[c6.str] || 0) + 1; + return names2; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _3(strs2, ...args) { + const code = [strs2[0]]; + let i7 = 0; + while (i7 < args.length) { + addCodeArg(code, args[i7]); + code.push(strs2[++i7]); + } + return new _Code(code); + } + exports._ = _3; + var plus = new _Code("+"); + function str2(strs2, ...args) { + const expr = [safeStringify(strs2[0])]; + let i7 = 0; + while (i7 < args.length) { + expr.push(plus); + addCodeArg(expr, args[i7]); + expr.push(plus, safeStringify(strs2[++i7])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str2; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate3(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i7 = 1; + while (i7 < expr.length - 1) { + if (expr[i7] === plus) { + const res = mergeExprItems(expr[i7 - 1], expr[i7 + 1]); + if (res !== void 0) { + expr.splice(i7 - 1, 3, res); + continue; + } + expr[i7++] = "+"; + } + i7++; + } + } + function mergeExprItems(a3, b4) { + if (b4 === '""') + return a3; + if (a3 === '""') + return b4; + if (typeof a3 == "string") { + if (b4 instanceof Name || a3[a3.length - 1] !== '"') + return; + if (typeof b4 != "string") + return `${a3.slice(0, -1)}${b4}"`; + if (b4[0] === '"') + return a3.slice(0, -1) + b4.slice(1); + return; + } + if (typeof b4 == "string" && b4[0] === '"' && !(a3 instanceof Name)) + return `"${a3}${b4.slice(1)}`; + return; + } + function strConcat(c1, c22) { + return c22.emptyStr() ? c1 : c1.emptyStr() ? c22 : str2`${c1}${c22}`; + } + exports.strConcat = strConcat; + function interpolate3(x2) { + return typeof x2 == "number" || typeof x2 == "boolean" || x2 === null ? x2 : safeStringify(Array.isArray(x2) ? x2.join(",") : x2); + } + function stringify2(x2) { + return new _Code(safeStringify(x2)); + } + exports.stringify = stringify2; + function safeStringify(x2) { + return JSON.stringify(x2).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _3`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a7, _b; + if (((_b = (_a7 = this._parent) === null || _a7 === void 0 ? void 0 : _a7._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a7; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a7 = value.key) !== null && _a7 !== void 0 ? _a7 : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s6 = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s6.length; + s6[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values2 = this._values) { + return this._reduceValues(values2, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values2 = this._values, usedValues, getCode) { + return this._reduceValues(values2, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values2, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values2) { + const vs = values2[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c6 = valueCode(name); + if (c6) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c6};${this.opts._n}`; + } else if (c6 = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c6}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node2 = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node2 { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names2, constants) { + if (!names2[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names2, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node2 { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names2, constants) { + if (this.lhs instanceof code_1.Name && !names2[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names2, constants); + return this; + } + get names() { + const names2 = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names2, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op2, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op2; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label2 = class extends Node2 { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node2 { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw3 = class extends Node2 { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node2 { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names2, constants) { + this.code = optimizeExpr(this.code, names2, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node2 { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n7) => code + n7.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i7 = nodes.length; + while (i7--) { + const n7 = nodes[i7].optimizeNodes(); + if (Array.isArray(n7)) + nodes.splice(i7, 1, ...n7); + else if (n7) + nodes[i7] = n7; + else + nodes.splice(i7, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names2, constants) { + const { nodes } = this; + let i7 = nodes.length; + while (i7--) { + const n7 = nodes[i7]; + if (n7.optimizeNames(names2, constants)) + continue; + subtractNames(names2, n7.names); + nodes.splice(i7, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names2, n7) => addNames(names2, n7.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e9 = this.else; + if (e9) { + const ns2 = e9.optimizeNodes(); + e9 = this.else = Array.isArray(ns2) ? new Else(ns2) : ns2; + } + if (e9) { + if (cond === false) + return e9 instanceof _If ? e9 : e9.nodes; + if (this.nodes.length) + return this; + return new _If(not(cond), e9 instanceof _If ? [e9] : e9.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names2, constants) { + var _a7; + this.else = (_a7 = this.else) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names2, constants); + if (!(super.optimizeNames(names2, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names2, constants); + return this; + } + get names() { + const names2 = super.names; + addExprNames(names2, this.condition); + if (this.else) + addNames(names2, this.else.names); + return names2; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names2, constants) { + if (!super.optimizeNames(names2, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names2, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from2, to2) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from2; + this.to = to2; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from: from2, to: to2 } = this; + return `for(${varKind} ${name}=${from2}; ${name}<${to2}; ${name}++)` + super.render(opts); + } + get names() { + const names2 = addExprNames(super.names, this.from); + return addExprNames(names2, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names2, constants) { + if (!super.optimizeNames(names2, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names2, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a7, _b; + super.optimizeNodes(); + (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names2, constants) { + var _a7, _b; + super.optimizeNames(names2, constants); + (_a7 = this.catch) === null || _a7 === void 0 ? void 0 : _a7.optimizeNames(names2, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names2, constants); + return this; + } + get names() { + const names2 = super.names; + if (this.catch) + addNames(names2, this.catch.names); + if (this.finally) + addNames(names2, this.finally.names); + return names2; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c6) { + if (typeof c6 == "function") + c6(); + else if (c6 !== code_1.nil) + this._leafNode(new AnyCode(c6)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from2, to2, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from2, to2), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i7) => { + this.var(name, (0, code_1._)`${arr}[${i7}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label2(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error) { + return this._leafNode(new Throw3(error)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n7 = 1) { + while (n7-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N22) { + const n7 = this._currNode; + if (n7 instanceof N1 || N22 && n7 instanceof N22) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N22 ? `${N1.kind}/${N22.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n7 = this._currNode; + if (!(n7 instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n7.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns2 = this._nodes; + return ns2[ns2.length - 1]; + } + set _currNode(node) { + const ns2 = this._nodes; + ns2[ns2.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names2, from2) { + for (const n7 in from2) + names2[n7] = (names2[n7] || 0) + (from2[n7] || 0); + return names2; + } + function addExprNames(names2, from2) { + return from2 instanceof code_1._CodeOrName ? addNames(names2, from2.names) : names2; + } + function optimizeExpr(expr, names2, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c6) => { + if (c6 instanceof code_1.Name) + c6 = replaceName(c6); + if (c6 instanceof code_1._Code) + items.push(...c6._items); + else + items.push(c6); + return items; + }, [])); + function replaceName(n7) { + const c6 = constants[n7.str]; + if (c6 === void 0 || names2[n7.str] !== 1) + return n7; + delete names2[n7.str]; + return c6; + } + function canOptimize(e9) { + return e9 instanceof code_1._Code && e9._items.some((c6) => c6 instanceof code_1.Name && names2[c6.str] === 1 && constants[c6.str] !== void 0); + } + } + function subtractNames(names2, from2) { + for (const n7 in from2) + names2[n7] = (names2[n7] || 0) - (from2[n7] || 0); + } + function not(x2) { + return typeof x2 == "boolean" || typeof x2 == "number" || x2 === null ? !x2 : (0, code_1._)`!${par(x2)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op2) { + return (x2, y4) => x2 === code_1.nil ? y4 : y4 === code_1.nil ? x2 : (0, code_1._)`${par(x2)} ${op2} ${par(y4)}`; + } + function par(x2) { + return x2 instanceof code_1.Name ? x2 : (0, code_1._)`(${x2})`; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/util.js +var require_util2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self: self2 } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self2.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str2) { + return unescapeJsonPointer(decodeURIComponent(str2)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str2) { + return encodeURIComponent(escapeJsonPointer(str2)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str2) { + if (typeof str2 == "number") + return `${str2}`; + return str2.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str2) { + return str2.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f4) { + if (Array.isArray(xs)) { + for (const x2 of xs) + f4(x2); + } else { + f4(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from2, to2, toName) => { + const res = to2 === void 0 ? from2 : to2 instanceof codegen_1.Name ? (from2 instanceof codegen_1.Name ? mergeNames(gen, from2, to2) : mergeToName(gen, from2, to2), to2) : from2 instanceof codegen_1.Name ? (mergeToName(gen, to2, from2), from2) : mergeValues3(from2, to2); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from2, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from2} !== undefined`, () => { + gen.if((0, codegen_1._)`${from2} === true`, () => gen.assign(to2, true), () => gen.assign(to2, (0, codegen_1._)`${to2} || {}`).code((0, codegen_1._)`Object.assign(${to2}, ${from2})`)); + }), + mergeToName: (gen, from2, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => { + if (from2 === true) { + gen.assign(to2, true); + } else { + gen.assign(to2, (0, codegen_1._)`${to2} || {}`); + setEvaluated(gen, to2, from2); + } + }), + mergeValues: (from2, to2) => from2 === true ? true : { ...from2, ...to2 }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from2, to2) => gen.if((0, codegen_1._)`${to2} !== true && ${from2} !== undefined`, () => gen.assign(to2, (0, codegen_1._)`${from2} === true ? true : ${to2} > ${from2} ? ${to2} : ${from2}`)), + mergeToName: (gen, from2, to2) => gen.if((0, codegen_1._)`${to2} !== true`, () => gen.assign(to2, from2 === true ? true : (0, codegen_1._)`${to2} > ${from2} ? ${to2} : ${from2}`)), + mergeValues: (from2, to2) => from2 === true ? true : Math.max(from2, to2), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p4) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p4)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f4) { + return gen.scopeValue("func", { + ref: f4, + code: snippets[f4.code] || (snippets[f4.code] = new code_1._Code(f4.code)) + }); + } + exports.useFunc = useFunc; + var Type4; + (function(Type5) { + Type5[Type5["Num"] = 0] = "Num"; + Type5[Type5["Str"] = 1] = "Str"; + })(Type4 || (exports.Type = Type4 = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber4 = dataPropType === Type4.Num; + return jsPropertySyntax ? isNumber4 ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber4 ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names2 = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names2; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/errors.js +var require_errors3 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i7) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i7}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E3 = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E3.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E3.keyword, keyword], [E3.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E3.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E3.schema, schemaValue], [E3.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E3.propertyName, propertyName]); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x2) { + return typeof x2 == "string" && jsonTypes.has(x2); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self: self2 }, type) { + const group = self2.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a7; + return schema[rule.keyword] !== void 0 || ((_a7 = rule.definition.implements) === null || _a7 === void 0 ? void 0 : _a7.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors3(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types2 = getJSONTypes(schema.type); + const hasNull = types2.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types2.length && schema.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types2.push("null"); + } + return types2; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types2 = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types2.every(rules_1.isJSONType)) + return types2; + throw new Error("type must be JSONType or JSONType[]: " + types2.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types2) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types2, opts.coerceTypes); + const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types2[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types2, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types2, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types2, coerceTypes) { + return coerceTypes ? types2.filter((t6) => COERCIBLE.has(t6) || coerceTypes === "array" && t6 === "array") : []; + } + function coerceData(it, types2, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types2, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t6 of coerceTo) { + if (COERCIBLE.has(t6) || t6 === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t6); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t6) { + switch (t6) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types2 = (0, util_1.toHash)(dataTypes); + if (types2.array && types2.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types2.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types2.null; + delete types2.array; + delete types2.object; + } else { + cond = codegen_1.nil; + } + if (types2.number) + delete types2.integer; + for (const t6 in types2) + cond = (0, codegen_1.and)(cond, checkDataType(t6, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i7) => assignDefault(it, i7, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var names_1 = require_names(); + var util_2 = require_util2(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p4) => p4 !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p4) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p4])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u5 = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u5); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u5})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i7) => { + cxt.subschema({ + keyword, + dataProp: i7, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i7) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i7, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors3(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a7; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a7 = def.valid) !== null && _a7 !== void 0 ? _a7 : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e9) => gen.assign(valid, false).if((0, codegen_1._)`${e9} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e9}.errors`), () => gen.throw(e9))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a8; + gen.if((0, codegen_1.not)((_a8 = def.valid) !== null && _a8 !== void 0 ? _a8 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self2.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// ../pi-mono/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "../pi-mono/node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + init_process_shim(); + module.exports = function equal(a3, b4) { + if (a3 === b4) return true; + if (a3 && b4 && typeof a3 == "object" && typeof b4 == "object") { + if (a3.constructor !== b4.constructor) return false; + var length, i7, keys2; + if (Array.isArray(a3)) { + length = a3.length; + if (length != b4.length) return false; + for (i7 = length; i7-- !== 0; ) + if (!equal(a3[i7], b4[i7])) return false; + return true; + } + if (a3.constructor === RegExp) return a3.source === b4.source && a3.flags === b4.flags; + if (a3.valueOf !== Object.prototype.valueOf) return a3.valueOf() === b4.valueOf(); + if (a3.toString !== Object.prototype.toString) return a3.toString() === b4.toString(); + keys2 = Object.keys(a3); + length = keys2.length; + if (length !== Object.keys(b4).length) return false; + for (i7 = length; i7-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b4, keys2[i7])) return false; + for (i7 = length; i7-- !== 0; ) { + var key = keys2[i7]; + if (!equal(a3[key], b4[key])) return false; + } + return true; + } + return a3 !== a3 && b4 !== b4; + }; + } +}); + +// ../pi-mono/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "../pi-mono/node_modules/json-schema-traverse/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var traverse2 = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post2 = cb.post || function() { + }; + _traverse(opts, pre, post2, schema, "", schema); + }; + traverse2.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse2.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse2.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse2.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post2, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse2.arrayKeywords) { + for (var i7 = 0; i7 < sch.length; i7++) + _traverse(opts, pre, post2, sch[i7], jsonPtr + "/" + key + "/" + i7, rootSchema, jsonPtr, key, schema, i7); + } + } else if (key in traverse2.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post2, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse2.keywords || opts.allKeys && !(key in traverse2.skipKeywords)) { + _traverse(opts, pre, post2, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + } + post2(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str2) { + return str2.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util2(); + var equal = require_fast_deep_equal(); + var traverse2 = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit2 = true) { + if (typeof schema == "boolean") + return true; + if (limit2 === true) + return !hasRef(schema); + if (!limit2) + return false; + return countKeys(schema) <= limit2; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + } + if (count === Infinity) + return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize2) { + if (normalize2 !== false) + id = normalizeId(id); + const p4 = resolver.parse(id); + return _getFullPath(resolver, p4); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p4) { + const serialized = resolver.serialize(p4); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse2(schema, { allKeys: true }, (sch, jsonPtr, _3, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve2 = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve2(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util2(); + var errors_1 = require_errors3(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self: self2 }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self2.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types2 = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types2); + schemaKeywords(it, types2, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self: self2 } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) { + self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types2, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self: self2 } = it; + const { RULES } = self2; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types2); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types2.length === 1 && types2[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types2) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types2); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types2); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types2) { + if (!types2.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types2; + return; + } + types2.forEach((t6) => { + if (!includesType(it.dataTypes, t6)) { + strictTypesError(it, `type "${t6}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types2); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t6) => hasApplicableType(ts, t6))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t6) { + return ts.includes(t6) || t6 === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t6 of it.dataTypes) { + if (includesType(withTypes, t6)) + ts.push(t6); + else if (withTypes.includes("integer") && t6 === "number") + ts.push("integer"); + } + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// ../pi-mono/node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "../pi-mono/node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util2(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a7; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a7 = env.baseId) !== null && _a7 !== void 0 ? _a7 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e9) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e9; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a7; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve2.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a7 = root.localRefs) === null || _a7 === void 0 ? void 0 : _a7[ref]; + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s22) { + return s1.schema === s22.schema && s1.root === s22.root && s1.baseId === s22.baseId; + } + function resolve2(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p4 = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p4); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p4, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p4, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p4, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a7; + if (((_a7 = parsedRef.fragment) === null || _a7 === void 0 ? void 0 : _a7[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return void 0; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "../pi-mono/node_modules/ajv/dist/refs/data.json"(exports, module) { + module.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// ../pi-mono/node_modules/fast-uri/lib/utils.js +var require_utils = __commonJS({ + "../pi-mono/node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + init_process_shim(); + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i7 = 0; + for (i7 = 0; i7 < input.length; i7++) { + code = input[i7].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i7]; + break; + } + for (i7 += 1; i7 < input.length; i7++) { + code = input[i7].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i7]; + } + return acc; + } + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex2 = stringArrayToHexStripped(buffer); + if (hex2 !== "") { + address.push(hex2); + } else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + function getIPV6(input) { + let tokenCount = 0; + const output = { error: false, address: "", zone: "" }; + const address = []; + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i7 = 0; i7 < input.length; i7++) { + const cursor = input[i7]; + if (cursor === "[" || cursor === "]") { + continue; + } + if (cursor === ":") { + if (endipv6Encountered === true) { + endIpv6 = true; + } + if (!consume(buffer, address, output)) { + break; + } + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i7 > 0 && input[i7 - 1] === ":") { + endipv6Encountered = true; + } + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) { + break; + } + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) { + if (consume === consumeIsZone) { + output.zone = buffer.join(""); + } else if (endIpv6) { + address.push(buffer.join("")); + } else { + address.push(stringArrayToHexStripped(buffer)); + } + } + output.address = address.join(""); + return output; + } + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) { + return { host, isIPV6: false }; + } + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { host: newHost, isIPV6: true, escapedHost }; + } else { + return { host, isIPV6: false }; + } + } + function findToken(str2, token) { + let ind = 0; + for (let i7 = 0; i7 < str2.length; i7++) { + if (str2[i7] === token) ind++; + } + return ind; + } + function removeDotSegments(path6) { + let input = path6; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) { + component.scheme = func(component.scheme); + } + if (component.userinfo !== void 0) { + component.userinfo = func(component.userinfo); + } + if (component.host !== void 0) { + component.host = func(component.host); + } + if (component.path !== void 0) { + component.path = func(component.path); + } + if (component.query !== void 0) { + component.query = func(component.query); + } + if (component.fragment !== void 0) { + component.fragment = func(component.fragment); + } + return component; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = component.host; + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// ../pi-mono/node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "../pi-mono/node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + init_process_shim(); + var { isUUID } = require_utils(); + var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path6, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path6 && path6 !== "/" ? path6 : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// ../pi-mono/node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "../pi-mono/node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + function normalize2(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + serialize2(parse3(uri, options), options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse3(serialize2(uri, options), options); + } + return uri; + } + function resolve2(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse3(baseURI, schemelessOptions), parse3(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize2(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse3(serialize2(base, options), options); + relative = parse3(serialize2(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path[0] === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize2(normalizeComponentEncoding(parse3(uriA, options), true), { ...options, skipEscape: true }); + } else if (typeof uriA === "object") { + uriA = serialize2(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }); + } + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize2(normalizeComponentEncoding(parse3(uriB, options), true), { ...options, skipEscape: true }); + } else if (typeof uriB === "object") { + uriB = serialize2(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }); + } + return uriA.toLowerCase() === uriB.toLowerCase(); + } + function serialize2(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) { + component.path = component.path.split("%3A").join(":"); + } + } else { + component.path = unescape(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s6 = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s6 = removeDotSegments(s6); + } + if (authority === void 0 && s6[0] === "/" && s6[1] === "/") { + s6 = "/%2F" + s6.slice(2); + } + uriTokens.push(s6); + } + if (component.query !== void 0) { + uriTokens.push("?", component.query); + } + if (component.fragment !== void 0) { + uriTokens.push("#", component.fragment); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + function parse3(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e9) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e9; + } + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) { + parsed.scheme = unescape(parsed.scheme); + } + if (parsed.host !== void 0) { + parsed.host = unescape(parsed.host); + } + } + if (parsed.path) { + parsed.path = escape(unescape(parsed.path)); + } + if (parsed.fragment) { + parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return parsed; + } + var fastUri = { + SCHEMES, + normalize: normalize2, + resolve: resolve2, + resolveComponent, + equal, + serialize: serialize2, + parse: parse3 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/uri.js +var require_uri = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// ../pi-mono/node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "../pi-mono/node_modules/ajv/dist/core.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util2(); + var $dataRefSchema = require_data(); + var uri_1 = require_uri(); + var defaultRegExp = (str2, flags) => new RegExp(str2, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o9) { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x2, _y2, _z2, _0; + const s6 = o9.strict; + const _optz = (_a7 = o9.code) === null || _a7 === void 0 ? void 0 : _a7.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o9.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o9.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e2 = o9.strictSchema) !== null && _e2 !== void 0 ? _e2 : s6) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o9.strictNumbers) !== null && _g !== void 0 ? _g : s6) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o9.strictTypes) !== null && _j !== void 0 ? _j : s6) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o9.strictTuples) !== null && _l !== void 0 ? _l : s6) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o9.strictRequired) !== null && _o !== void 0 ? _o : s6) !== null && _p !== void 0 ? _p : false, + code: o9.code ? { ...o9.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o9.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o9.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o9.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o9.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o9.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o9.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o9.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x2 = o9.validateSchema) !== null && _x2 !== void 0 ? _x2 : true, + validateFormats: (_y2 = o9.validateFormats) !== null && _y2 !== void 0 ? _y2 : true, + unicodeRegExp: (_z2 = o9.unicodeRegExp) !== null && _z2 !== void 0 ? _z2 : true, + int32range: (_0 = o9.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv3 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v4; + if (typeof schemaKeyRef == "string") { + v4 = this.getSchema(schemaKeyRef); + if (!v4) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v4 = this.compile(schemaKeyRef); + } + const valid = v4(data); + if (!("$async" in v4)) + this.errors = v4.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e9) { + if (!(e9 instanceof ref_error_1.default)) + throw e9; + checkLoaded.call(this, e9); + await loadMissingSchema.call(this, e9.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p4 = this._loading[ref]; + if (p4) + return p4; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k2) => addRule.call(this, k2, definition) : (k2) => definition.type.forEach((t6) => addRule.call(this, k2, definition, t6))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i7 = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i7 >= 0) + group.rules.splice(i7, 1); + } + return this; + } + // Add format + addFormat(name, format2) { + if (typeof format2 == "string") + format2 = new RegExp(format2); + this.formats[name] = format2; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e9) => `${dataVar}${e9.instancePath} ${e9.message}`).reduce((text3, msg) => text3 + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv3.ValidationError = validation_error_1.default; + Ajv3.MissingRefError = ref_error_1.default; + exports.default = Ajv3; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format2 = this.opts.formats[name]; + if (format2) + this.addFormat(name, format2); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger2) { + if (logger2 === false) + return noLogs; + if (logger2 === void 0) + return console; + if (logger2.log && logger2.warn && logger2.error) + return logger2; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a7; + const post2 = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post2) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post2 ? RULES.post : RULES.rules.find(({ type: t6 }) => t6 === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a7 = definition.implements) === null || _a7 === void 0 ? void 0 : _a7.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i7 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i7 >= 0) { + ruleGroup.rules.splice(i7, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util2(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v4 = getValidate(cxt, sch); + callRef(cxt, v4, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v4, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v4, passCxt)}`); + addEvaluatedFrom(v4); + if (!allErrors) + gen.assign(valid, true); + }, (e9) => { + gen.if((0, codegen_1._)`!(${e9} instanceof ${it.ValidationError})`, () => gen.throw(e9)); + addErrorsFrom(e9); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v4, passCxt), () => addEvaluatedFrom(v4), () => addErrorsFrom(v4)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a7; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a7 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a7 === void 0 ? void 0 : _a7.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str2) { + const len = str2.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str2.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str2.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var ucs2length_1 = require_ucs2length(); + var error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op2 = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var util_1 = require_util2(); + var codegen_1 = require_codegen(); + var error = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u5 = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u5}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op2 = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op2 = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op2} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "../pi-mono/node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var equal_1 = require_equal(); + var error = { + message: ({ params: { i: i7, j: j3 } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j3} and ${i7} are identical)`, + params: ({ params: { i: i7, j: j3 } }) => (0, codegen_1._)`{i: ${i7}, j: ${j3}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i7 = gen.let("i", (0, codegen_1._)`${data}.length`); + const j3 = gen.let("j"); + cxt.setParams({ i: i7, j: j3 }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i7} > 1`, () => (canOptimize() ? loopN : loopN2)(i7, j3)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t6) => t6 === "object" || t6 === "array"); + } + function loopN(i7, j3) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i7}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i7}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j3, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i7}`); + }); + } + function loopN2(i7, j3) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i7}--;`, () => gen.for((0, codegen_1._)`${j3} = ${i7}; ${j3}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i7}], ${data}[${j3}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var equal_1 = require_equal(); + var error = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var equal_1 = require_equal(); + var error = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x2, i7) => equalCode(vSchema, i7))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v4) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v4})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i7) { + const sch = schema[i7]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i7}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum2(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i7) => { + cxt.subschema({ keyword, dataProp: i7, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i7) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i7}`, () => cxt.subschema({ + keyword, + schemaProp: i7, + dataProp: i7 + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l5 = schArr.length; + const fullTuple = l5 === sch.minItems && (l5 === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l5}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i7) => { + cxt.subschema({ + keyword: "contains", + dataProp: i7, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util2(); + var error = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p4) => (0, codegen_1._)`${key} === ${p4}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p4) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p4)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util2(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p4) => !(0, util_1.alwaysValidSchema)(it, schema[p4])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var util_2 = require_util2(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p4) => (0, util_1.alwaysValidSchema)(it, schema[p4])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i7) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i7, + compositeRule: true + }, schValid); + } + if (i7 > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i7}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i7); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i7) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i7 }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util2(); + var error = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util2(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self: self2 } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format2 = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format2, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format2}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format2}(${data}) : ${format2}(${data}))` : (0, codegen_1._)`${format2}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data}))`; + return (0, codegen_1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self2.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format2, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self2.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format2 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format(); + var format2 = [format_1.default]; + exports.default = format2; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types2 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// ../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "../pi-mono/node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types2(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util2(); + var error = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a7; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i7 = 0; i7 < oneOf.length; i7++) { + let sch = oneOf[i7]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a7 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a7 === void 0 ? void 0 : _a7[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i7); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i7) { + if (sch.const) { + addMapping(sch.const, i7); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i7); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i7) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i7; + } + } + } + }; + exports.default = def; + } +}); + +// ../pi-mono/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "../pi-mono/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { + module.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// ../pi-mono/node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "../pi-mono/node_modules/ajv/dist/ajv.js"(exports, module) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv3 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v4) => this.addVocabulary(v4)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv3; + module.exports = exports = Ajv3; + module.exports.Ajv = Ajv3; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv3; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// ../pi-mono/node_modules/ajv-formats/dist/formats.js +var require_formats = __commonJS({ + "../pi-mono/node_modules/ajv-formats/dist/formats.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { validate, compare }; + } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date(str2) { + const matches = DATE.exec(str2); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d22) { + if (!(d1 && d22)) + return void 0; + if (d1 > d22) + return 1; + if (d1 < d22) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str2) { + const matches = TIME.exec(str2); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min <= 59 && sec < 60) + return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s22) { + if (!(s1 && s22)) + return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t22 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf(); + if (!(t1 && t22)) + return void 0; + return t1 - t22; + } + function compareIsoTime(t1, t22) { + if (!(t1 && t22)) + return void 0; + const a1 = TIME.exec(t1); + const a22 = TIME.exec(t22); + if (!(a1 && a22)) + return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t22 = a22[1] + a22[2] + a22[3]; + if (t1 > t22) + return 1; + if (t1 < t22) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str2) { + const dateTime = str2.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d22 = new Date(dt2).valueOf(); + if (!(d1 && d22)) + return void 0; + return d1 - d22; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d22, t22] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d22); + if (res === void 0) + return void 0; + return res || compareTime(t1, t22); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str2) { + return NOT_URI_FRAGMENT.test(str2) && URI.test(str2); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str2) { + BYTE.lastIndex = 0; + return BYTE.test(str2); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str2) { + if (Z_ANCHOR.test(str2)) + return false; + try { + new RegExp(str2); + return true; + } catch (e9) { + return false; + } + } + } +}); + +// ../pi-mono/node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "../pi-mono/node_modules/ajv-formats/dist/limit.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self: self2 } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self2.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format2 = fCxt.schema; + const fmtDef = self2.formats[format2]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format2}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format2, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format2)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv3) => { + ajv3.addKeyword(exports.formatLimitDefinition); + return ajv3; + }; + exports.default = formatLimitPlugin; + } +}); + +// ../pi-mono/node_modules/ajv-formats/dist/index.js +var require_dist2 = __commonJS({ + "../pi-mono/node_modules/ajv-formats/dist/index.js"(exports, module) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv3, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats3(ajv3, opts, formats_1.fullFormats, fullName); + return ajv3; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats3(ajv3, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv3); + return ajv3; + }; + formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f4 = formats[name]; + if (!f4) + throw new Error(`Unknown format "${name}"`); + return f4; + }; + function addFormats3(ajv3, list, fs, exportName) { + var _a7; + var _b; + (_a7 = (_b = ajv3.opts.code).formats) !== null && _a7 !== void 0 ? _a7 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f4 of list) + ajv3.addFormat(f4, fs[f4]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; + } +}); + +// ../pi-mono/packages/ai/dist/api-registry.js +function wrapStream2(api, stream2) { + return (model, context, options) => { + if (model.api !== api) { + throw new Error(`Mismatched api: ${model.api} expected ${api}`); + } + return stream2(model, context, options); + }; +} +function wrapStreamSimple2(api, streamSimple3) { + return (model, context, options) => { + if (model.api !== api) { + throw new Error(`Mismatched api: ${model.api} expected ${api}`); + } + return streamSimple3(model, context, options); + }; +} +function registerApiProvider2(provider, sourceId) { + apiProviderRegistry2.set(provider.api, { + provider: { + api: provider.api, + stream: wrapStream2(provider.api, provider.stream), + streamSimple: wrapStreamSimple2(provider.api, provider.streamSimple) + }, + sourceId + }); +} +function getApiProvider2(api) { + return apiProviderRegistry2.get(api)?.provider; +} +var apiProviderRegistry2; +var init_api_registry = __esm({ + "../pi-mono/packages/ai/dist/api-registry.js"() { + "use strict"; + init_process_shim(); + apiProviderRegistry2 = /* @__PURE__ */ new Map(); + } +}); + +// ../pi-mono/packages/ai/dist/env-api-keys.js +function hasVertexAdcCredentials2() { + if (cachedVertexAdcCredentialsExists2 === null) { + if (!_existsSync2 || !_homedir2 || !_join2) { + const isNode = typeof process !== "undefined" && (process.versions?.node || process.versions?.bun); + if (!isNode) { + cachedVertexAdcCredentialsExists2 = false; + } + return false; + } + const gacPath = process.env.GOOGLE_APPLICATION_CREDENTIALS; + if (gacPath) { + cachedVertexAdcCredentialsExists2 = _existsSync2(gacPath); + } else { + cachedVertexAdcCredentialsExists2 = _existsSync2(_join2(_homedir2(), ".config", "gcloud", "application_default_credentials.json")); + } + } + return cachedVertexAdcCredentialsExists2; +} +function getEnvApiKey2(provider) { + if (provider === "github-copilot") { + return process.env.COPILOT_GITHUB_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN; + } + if (provider === "anthropic") { + return process.env.ANTHROPIC_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY; + } + if (provider === "google-vertex") { + if (process.env.GOOGLE_CLOUD_API_KEY) { + return process.env.GOOGLE_CLOUD_API_KEY; + } + const hasCredentials = hasVertexAdcCredentials2(); + const hasProject = !!(process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT); + const hasLocation = !!process.env.GOOGLE_CLOUD_LOCATION; + if (hasCredentials && hasProject && hasLocation) { + return ""; + } + } + if (provider === "amazon-bedrock") { + if (process.env.AWS_PROFILE || process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY || process.env.AWS_BEARER_TOKEN_BEDROCK || process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI || process.env.AWS_WEB_IDENTITY_TOKEN_FILE) { + return ""; + } + } + const envMap = { + openai: "OPENAI_API_KEY", + "azure-openai-responses": "AZURE_OPENAI_API_KEY", + google: "GEMINI_API_KEY", + groq: "GROQ_API_KEY", + cerebras: "CEREBRAS_API_KEY", + xai: "XAI_API_KEY", + openrouter: "OPENROUTER_API_KEY", + "vercel-ai-gateway": "AI_GATEWAY_API_KEY", + zai: "ZAI_API_KEY", + mistral: "MISTRAL_API_KEY", + minimax: "MINIMAX_API_KEY", + "minimax-cn": "MINIMAX_CN_API_KEY", + huggingface: "HF_TOKEN", + opencode: "OPENCODE_API_KEY", + "opencode-go": "OPENCODE_API_KEY", + "kimi-coding": "KIMI_API_KEY" + }; + const envVar = envMap[provider]; + return envVar ? process.env[envVar] : void 0; +} +var _existsSync2, _homedir2, _join2, dynamicImport4, NODE_FS_SPECIFIER2, NODE_OS_SPECIFIER3, NODE_PATH_SPECIFIER2, cachedVertexAdcCredentialsExists2; +var init_env_api_keys = __esm({ + "../pi-mono/packages/ai/dist/env-api-keys.js"() { + "use strict"; + init_process_shim(); + _existsSync2 = null; + _homedir2 = null; + _join2 = null; + dynamicImport4 = (specifier) => import(specifier); + NODE_FS_SPECIFIER2 = "node:fs"; + NODE_OS_SPECIFIER3 = "node:os"; + NODE_PATH_SPECIFIER2 = "node:path"; + if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) { + dynamicImport4(NODE_FS_SPECIFIER2).then((m4) => { + _existsSync2 = m4.existsSync; + }); + dynamicImport4(NODE_OS_SPECIFIER3).then((m4) => { + _homedir2 = m4.homedir; + }); + dynamicImport4(NODE_PATH_SPECIFIER2).then((m4) => { + _join2 = m4.join; + }); + } + cachedVertexAdcCredentialsExists2 = null; + } +}); + +// ../pi-mono/packages/ai/dist/models.generated.js +var MODELS2; +var init_models_generated = __esm({ + "../pi-mono/packages/ai/dist/models.generated.js"() { + "use strict"; + init_process_shim(); + MODELS2 = { + "amazon-bedrock": { + "amazon.nova-2-lite-v1:0": { + id: "amazon.nova-2-lite-v1:0", + name: "Nova 2 Lite", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.33, + output: 2.75, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "amazon.nova-lite-v1:0": { + id: "amazon.nova-lite-v1:0", + name: "Nova Lite", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.06, + output: 0.24, + cacheRead: 0.015, + cacheWrite: 0 + }, + contextWindow: 3e5, + maxTokens: 8192 + }, + "amazon.nova-micro-v1:0": { + id: "amazon.nova-micro-v1:0", + name: "Nova Micro", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.035, + output: 0.14, + cacheRead: 875e-5, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "amazon.nova-premier-v1:0": { + id: "amazon.nova-premier-v1:0", + name: "Nova Premier", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 12.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 16384 + }, + "amazon.nova-pro-v1:0": { + id: "amazon.nova-pro-v1:0", + name: "Nova Pro", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.8, + output: 3.2, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 3e5, + maxTokens: 8192 + }, + "anthropic.claude-3-5-haiku-20241022-v1:0": { + id: "anthropic.claude-3-5-haiku-20241022-v1:0", + name: "Claude Haiku 3.5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.8, + output: 4, + cacheRead: 0.08, + cacheWrite: 1 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic.claude-3-5-sonnet-20240620-v1:0": { + id: "anthropic.claude-3-5-sonnet-20240620-v1:0", + name: "Claude Sonnet 3.5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic.claude-3-5-sonnet-20241022-v2:0": { + id: "anthropic.claude-3-5-sonnet-20241022-v2:0", + name: "Claude Sonnet 3.5 v2", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic.claude-3-7-sonnet-20250219-v1:0": { + id: "anthropic.claude-3-7-sonnet-20250219-v1:0", + name: "Claude Sonnet 3.7", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic.claude-3-haiku-20240307-v1:0": { + id: "anthropic.claude-3-haiku-20240307-v1:0", + name: "Claude Haiku 3", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.25, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "anthropic.claude-haiku-4-5-20251001-v1:0": { + id: "anthropic.claude-haiku-4-5-20251001-v1:0", + name: "Claude Haiku 4.5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic.claude-opus-4-1-20250805-v1:0": { + id: "anthropic.claude-opus-4-1-20250805-v1:0", + name: "Claude Opus 4.1", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "anthropic.claude-opus-4-20250514-v1:0": { + id: "anthropic.claude-opus-4-20250514-v1:0", + name: "Claude Opus 4", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "anthropic.claude-opus-4-5-20251101-v1:0": { + id: "anthropic.claude-opus-4-5-20251101-v1:0", + name: "Claude Opus 4.5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic.claude-opus-4-6-v1": { + id: "anthropic.claude-opus-4-6-v1", + name: "Claude Opus 4.6", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "anthropic.claude-sonnet-4-20250514-v1:0": { + id: "anthropic.claude-sonnet-4-20250514-v1:0", + name: "Claude Sonnet 4", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic.claude-sonnet-4-5-20250929-v1:0": { + id: "anthropic.claude-sonnet-4-5-20250929-v1:0", + name: "Claude Sonnet 4.5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic.claude-sonnet-4-6": { + id: "anthropic.claude-sonnet-4-6", + name: "Claude Sonnet 4.6", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "deepseek.r1-v1:0": { + id: "deepseek.r1-v1:0", + name: "DeepSeek-R1", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 1.35, + output: 5.4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32768 + }, + "deepseek.v3-v1:0": { + id: "deepseek.v3-v1:0", + name: "DeepSeek-V3.1", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.58, + output: 1.68, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 81920 + }, + "deepseek.v3.2": { + id: "deepseek.v3.2", + name: "DeepSeek-V3.2", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.62, + output: 1.85, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 81920 + }, + "eu.anthropic.claude-haiku-4-5-20251001-v1:0": { + id: "eu.anthropic.claude-haiku-4-5-20251001-v1:0", + name: "Claude Haiku 4.5 (EU)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "eu.anthropic.claude-opus-4-5-20251101-v1:0": { + id: "eu.anthropic.claude-opus-4-5-20251101-v1:0", + name: "Claude Opus 4.5 (EU)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "eu.anthropic.claude-opus-4-6-v1": { + id: "eu.anthropic.claude-opus-4-6-v1", + name: "Claude Opus 4.6 (EU)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "eu.anthropic.claude-sonnet-4-20250514-v1:0": { + id: "eu.anthropic.claude-sonnet-4-20250514-v1:0", + name: "Claude Sonnet 4 (EU)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "eu.anthropic.claude-sonnet-4-5-20250929-v1:0": { + id: "eu.anthropic.claude-sonnet-4-5-20250929-v1:0", + name: "Claude Sonnet 4.5 (EU)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "eu.anthropic.claude-sonnet-4-6": { + id: "eu.anthropic.claude-sonnet-4-6", + name: "Claude Sonnet 4.6 (EU)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "global.anthropic.claude-haiku-4-5-20251001-v1:0": { + id: "global.anthropic.claude-haiku-4-5-20251001-v1:0", + name: "Claude Haiku 4.5 (Global)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "global.anthropic.claude-opus-4-5-20251101-v1:0": { + id: "global.anthropic.claude-opus-4-5-20251101-v1:0", + name: "Claude Opus 4.5 (Global)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "global.anthropic.claude-opus-4-6-v1": { + id: "global.anthropic.claude-opus-4-6-v1", + name: "Claude Opus 4.6 (Global)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "global.anthropic.claude-sonnet-4-20250514-v1:0": { + id: "global.anthropic.claude-sonnet-4-20250514-v1:0", + name: "Claude Sonnet 4 (Global)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "global.anthropic.claude-sonnet-4-5-20250929-v1:0": { + id: "global.anthropic.claude-sonnet-4-5-20250929-v1:0", + name: "Claude Sonnet 4.5 (Global)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "global.anthropic.claude-sonnet-4-6": { + id: "global.anthropic.claude-sonnet-4-6", + name: "Claude Sonnet 4.6 (Global)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "google.gemma-3-27b-it": { + id: "google.gemma-3-27b-it", + name: "Google Gemma 3 27B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.12, + output: 0.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 202752, + maxTokens: 8192 + }, + "google.gemma-3-4b-it": { + id: "google.gemma-3-4b-it", + name: "Gemma 3 4B IT", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.04, + output: 0.08, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama3-1-405b-instruct-v1:0": { + id: "meta.llama3-1-405b-instruct-v1:0", + name: "Llama 3.1 405B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 2.4, + output: 2.4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama3-1-70b-instruct-v1:0": { + id: "meta.llama3-1-70b-instruct-v1:0", + name: "Llama 3.1 70B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.72, + output: 0.72, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama3-1-8b-instruct-v1:0": { + id: "meta.llama3-1-8b-instruct-v1:0", + name: "Llama 3.1 8B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.22, + output: 0.22, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama3-2-11b-instruct-v1:0": { + id: "meta.llama3-2-11b-instruct-v1:0", + name: "Llama 3.2 11B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.16, + output: 0.16, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama3-2-1b-instruct-v1:0": { + id: "meta.llama3-2-1b-instruct-v1:0", + name: "Llama 3.2 1B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.1, + output: 0.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131e3, + maxTokens: 4096 + }, + "meta.llama3-2-3b-instruct-v1:0": { + id: "meta.llama3-2-3b-instruct-v1:0", + name: "Llama 3.2 3B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131e3, + maxTokens: 4096 + }, + "meta.llama3-2-90b-instruct-v1:0": { + id: "meta.llama3-2-90b-instruct-v1:0", + name: "Llama 3.2 90B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.72, + output: 0.72, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama3-3-70b-instruct-v1:0": { + id: "meta.llama3-3-70b-instruct-v1:0", + name: "Llama 3.3 70B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.72, + output: 0.72, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "meta.llama4-maverick-17b-instruct-v1:0": { + id: "meta.llama4-maverick-17b-instruct-v1:0", + name: "Llama 4 Maverick 17B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.24, + output: 0.97, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 16384 + }, + "meta.llama4-scout-17b-instruct-v1:0": { + id: "meta.llama4-scout-17b-instruct-v1:0", + name: "Llama 4 Scout 17B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.17, + output: 0.66, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 35e5, + maxTokens: 16384 + }, + "minimax.minimax-m2": { + id: "minimax.minimax-m2", + name: "MiniMax M2", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204608, + maxTokens: 128e3 + }, + "minimax.minimax-m2.1": { + id: "minimax.minimax-m2.1", + name: "MiniMax M2.1", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "mistral.devstral-2-123b": { + id: "mistral.devstral-2-123b", + name: "Devstral 2 123B", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 8192 + }, + "mistral.magistral-small-2509": { + id: "mistral.magistral-small-2509", + name: "Magistral Small 1.2", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e4 + }, + "mistral.ministral-3-14b-instruct": { + id: "mistral.ministral-3-14b-instruct", + name: "Ministral 14B 3.0", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.2, + output: 0.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "mistral.ministral-3-3b-instruct": { + id: "mistral.ministral-3-3b-instruct", + name: "Ministral 3 3B", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 8192 + }, + "mistral.ministral-3-8b-instruct": { + id: "mistral.ministral-3-8b-instruct", + name: "Ministral 3 8B", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "mistral.mistral-large-3-675b-instruct": { + id: "mistral.mistral-large-3-675b-instruct", + name: "Mistral Large 3", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 8192 + }, + "mistral.pixtral-large-2502-v1:0": { + id: "mistral.pixtral-large-2502-v1:0", + name: "Pixtral Large (25.02)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "mistral.voxtral-mini-3b-2507": { + id: "mistral.voxtral-mini-3b-2507", + name: "Voxtral Mini 3B 2507", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.04, + output: 0.04, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "mistral.voxtral-small-24b-2507": { + id: "mistral.voxtral-small-24b-2507", + name: "Voxtral Small 24B 2507", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.35, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32e3, + maxTokens: 8192 + }, + "moonshot.kimi-k2-thinking": { + id: "moonshot.kimi-k2-thinking", + name: "Kimi K2 Thinking", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "moonshotai.kimi-k2.5": { + id: "moonshotai.kimi-k2.5", + name: "Kimi K2.5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "nvidia.nemotron-nano-12b-v2": { + id: "nvidia.nemotron-nano-12b-v2", + name: "NVIDIA Nemotron Nano 12B v2 VL BF16", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.2, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "nvidia.nemotron-nano-3-30b": { + id: "nvidia.nemotron-nano-3-30b", + name: "NVIDIA Nemotron Nano 3 30B", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.06, + output: 0.24, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "nvidia.nemotron-nano-9b-v2": { + id: "nvidia.nemotron-nano-9b-v2", + name: "NVIDIA Nemotron Nano 9B v2", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.06, + output: 0.23, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai.gpt-oss-120b-1:0": { + id: "openai.gpt-oss-120b-1:0", + name: "gpt-oss-120b", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai.gpt-oss-20b-1:0": { + id: "openai.gpt-oss-20b-1:0", + name: "gpt-oss-20b", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.07, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai.gpt-oss-safeguard-120b": { + id: "openai.gpt-oss-safeguard-120b", + name: "GPT OSS Safeguard 120B", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai.gpt-oss-safeguard-20b": { + id: "openai.gpt-oss-safeguard-20b", + name: "GPT OSS Safeguard 20B", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.07, + output: 0.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "qwen.qwen3-235b-a22b-2507-v1:0": { + id: "qwen.qwen3-235b-a22b-2507-v1:0", + name: "Qwen3 235B A22B 2507", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.22, + output: 0.88, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 131072 + }, + "qwen.qwen3-32b-v1:0": { + id: "qwen.qwen3-32b-v1:0", + name: "Qwen3 32B (dense)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 16384, + maxTokens: 16384 + }, + "qwen.qwen3-coder-30b-a3b-v1:0": { + id: "qwen.qwen3-coder-30b-a3b-v1:0", + name: "Qwen3 Coder 30B A3B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 131072 + }, + "qwen.qwen3-coder-480b-a35b-v1:0": { + id: "qwen.qwen3-coder-480b-a35b-v1:0", + name: "Qwen3 Coder 480B A35B Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.22, + output: 1.8, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + }, + "qwen.qwen3-next-80b-a3b": { + id: "qwen.qwen3-next-80b-a3b", + name: "Qwen/Qwen3-Next-80B-A3B-Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.14, + output: 1.4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262e3, + maxTokens: 262e3 + }, + "qwen.qwen3-vl-235b-a22b": { + id: "qwen.qwen3-vl-235b-a22b", + name: "Qwen/Qwen3-VL-235B-A22B-Instruct", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.3, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262e3, + maxTokens: 262e3 + }, + "us.anthropic.claude-haiku-4-5-20251001-v1:0": { + id: "us.anthropic.claude-haiku-4-5-20251001-v1:0", + name: "Claude Haiku 4.5 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "us.anthropic.claude-opus-4-1-20250805-v1:0": { + id: "us.anthropic.claude-opus-4-1-20250805-v1:0", + name: "Claude Opus 4.1 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "us.anthropic.claude-opus-4-20250514-v1:0": { + id: "us.anthropic.claude-opus-4-20250514-v1:0", + name: "Claude Opus 4 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "us.anthropic.claude-opus-4-5-20251101-v1:0": { + id: "us.anthropic.claude-opus-4-5-20251101-v1:0", + name: "Claude Opus 4.5 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "us.anthropic.claude-opus-4-6-v1": { + id: "us.anthropic.claude-opus-4-6-v1", + name: "Claude Opus 4.6 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "us.anthropic.claude-sonnet-4-20250514-v1:0": { + id: "us.anthropic.claude-sonnet-4-20250514-v1:0", + name: "Claude Sonnet 4 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "us.anthropic.claude-sonnet-4-5-20250929-v1:0": { + id: "us.anthropic.claude-sonnet-4-5-20250929-v1:0", + name: "Claude Sonnet 4.5 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "us.anthropic.claude-sonnet-4-6": { + id: "us.anthropic.claude-sonnet-4-6", + name: "Claude Sonnet 4.6 (US)", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "writer.palmyra-x4-v1:0": { + id: "writer.palmyra-x4-v1:0", + name: "Palmyra X4", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 2.5, + output: 10, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 122880, + maxTokens: 8192 + }, + "writer.palmyra-x5-v1:0": { + id: "writer.palmyra-x5-v1:0", + name: "Palmyra X5", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 104e4, + maxTokens: 8192 + }, + "zai.glm-4.7": { + id: "zai.glm-4.7", + name: "GLM-4.7", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "zai.glm-4.7-flash": { + id: "zai.glm-4.7-flash", + name: "GLM-4.7-Flash", + api: "bedrock-converse-stream", + provider: "amazon-bedrock", + baseUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + reasoning: true, + input: ["text"], + cost: { + input: 0.07, + output: 0.4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 131072 + } + }, + "anthropic": { + "claude-3-5-haiku-20241022": { + id: "claude-3-5-haiku-20241022", + name: "Claude Haiku 3.5", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.8, + output: 4, + cacheRead: 0.08, + cacheWrite: 1 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "claude-3-5-haiku-latest": { + id: "claude-3-5-haiku-latest", + name: "Claude Haiku 3.5 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.8, + output: 4, + cacheRead: 0.08, + cacheWrite: 1 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "claude-3-5-sonnet-20240620": { + id: "claude-3-5-sonnet-20240620", + name: "Claude Sonnet 3.5", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "claude-3-5-sonnet-20241022": { + id: "claude-3-5-sonnet-20241022", + name: "Claude Sonnet 3.5 v2", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "claude-3-7-sonnet-20250219": { + id: "claude-3-7-sonnet-20250219", + name: "Claude Sonnet 3.7", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-3-7-sonnet-latest": { + id: "claude-3-7-sonnet-latest", + name: "Claude Sonnet 3.7 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-3-haiku-20240307": { + id: "claude-3-haiku-20240307", + name: "Claude Haiku 3", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.25, + cacheRead: 0.03, + cacheWrite: 0.3 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "claude-3-opus-20240229": { + id: "claude-3-opus-20240229", + name: "Claude Opus 3", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "claude-3-sonnet-20240229": { + id: "claude-3-sonnet-20240229", + name: "Claude Sonnet 3", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 0.3 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "claude-haiku-4-5": { + id: "claude-haiku-4-5", + name: "Claude Haiku 4.5 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-haiku-4-5-20251001": { + id: "claude-haiku-4-5-20251001", + name: "Claude Haiku 4.5", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-opus-4-0": { + id: "claude-opus-4-0", + name: "Claude Opus 4 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "claude-opus-4-1": { + id: "claude-opus-4-1", + name: "Claude Opus 4.1 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "claude-opus-4-1-20250805": { + id: "claude-opus-4-1-20250805", + name: "Claude Opus 4.1", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "claude-opus-4-20250514": { + id: "claude-opus-4-20250514", + name: "Claude Opus 4", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "claude-opus-4-5": { + id: "claude-opus-4-5", + name: "Claude Opus 4.5 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-opus-4-5-20251101": { + id: "claude-opus-4-5-20251101", + name: "Claude Opus 4.5", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-opus-4-6": { + id: "claude-opus-4-6", + name: "Claude Opus 4.6", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "claude-sonnet-4-0": { + id: "claude-sonnet-4-0", + name: "Claude Sonnet 4 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-20250514": { + id: "claude-sonnet-4-20250514", + name: "Claude Sonnet 4", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-5": { + id: "claude-sonnet-4-5", + name: "Claude Sonnet 4.5 (latest)", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-5-20250929": { + id: "claude-sonnet-4-5-20250929", + name: "Claude Sonnet 4.5", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-6": { + id: "claude-sonnet-4-6", + name: "Claude Sonnet 4.6", + api: "anthropic-messages", + provider: "anthropic", + baseUrl: "https://api.anthropic.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + } + }, + "azure-openai-responses": { + "codex-mini-latest": { + id: "codex-mini-latest", + name: "Codex Mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text"], + cost: { + input: 1.5, + output: 6, + cacheRead: 0.375, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "gpt-4": { + id: "gpt-4", + name: "GPT-4", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text"], + cost: { + input: 30, + output: 60, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 8192 + }, + "gpt-4-turbo": { + id: "gpt-4-turbo", + name: "GPT-4 Turbo", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 10, + output: 30, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "gpt-4.1": { + id: "gpt-4.1", + name: "GPT-4.1", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "gpt-4.1-mini": { + id: "gpt-4.1-mini", + name: "GPT-4.1 mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.4, + output: 1.6, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "gpt-4.1-nano": { + id: "gpt-4.1-nano", + name: "GPT-4.1 nano", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "gpt-4o": { + id: "gpt-4o", + name: "GPT-4o", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-4o-2024-05-13": { + id: "gpt-4o-2024-05-13", + name: "GPT-4o (2024-05-13)", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 5, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "gpt-4o-2024-08-06": { + id: "gpt-4o-2024-08-06", + name: "GPT-4o (2024-08-06)", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-4o-2024-11-20": { + id: "gpt-4o-2024-11-20", + name: "GPT-4o (2024-11-20)", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-4o-mini": { + id: "gpt-4o-mini", + name: "GPT-4o mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.08, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5": { + id: "gpt-5", + name: "GPT-5", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-chat-latest": { + id: "gpt-5-chat-latest", + name: "GPT-5 Chat Latest", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5-codex": { + id: "gpt-5-codex", + name: "GPT-5-Codex", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-mini": { + id: "gpt-5-mini", + name: "GPT-5 Mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-nano": { + id: "gpt-5-nano", + name: "GPT-5 Nano", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.05, + output: 0.4, + cacheRead: 5e-3, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-pro": { + id: "gpt-5-pro", + name: "GPT-5 Pro", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 120, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 272e3 + }, + "gpt-5.1": { + id: "gpt-5.1", + name: "GPT-5.1", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.13, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-chat-latest": { + id: "gpt-5.1-chat-latest", + name: "GPT-5.1 Chat", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5.1-codex": { + id: "gpt-5.1-codex", + name: "GPT-5.1 Codex", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex-max": { + id: "gpt-5.1-codex-max", + name: "GPT-5.1 Codex Max", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex-mini": { + id: "gpt-5.1-codex-mini", + name: "GPT-5.1 Codex mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2": { + id: "gpt-5.2", + name: "GPT-5.2", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2-chat-latest": { + id: "gpt-5.2-chat-latest", + name: "GPT-5.2 Chat", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5.2-codex": { + id: "gpt-5.2-codex", + name: "GPT-5.2 Codex", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2-pro": { + id: "gpt-5.2-pro", + name: "GPT-5.2 Pro", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 21, + output: 168, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.3-codex": { + id: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.3-codex-spark": { + id: "gpt-5.3-codex-spark", + name: "GPT-5.3 Codex Spark", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "gpt-5.4": { + id: "gpt-5.4", + name: "GPT-5.4", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 15, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.4-pro": { + id: "gpt-5.4-pro", + name: "GPT-5.4 Pro", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 30, + output: 180, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "o1": { + id: "o1", + name: "o1", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 60, + cacheRead: 7.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o1-pro": { + id: "o1-pro", + name: "o1-pro", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 150, + output: 600, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3": { + id: "o3", + name: "o3", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3-deep-research": { + id: "o3-deep-research", + name: "o3-deep-research", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 10, + output: 40, + cacheRead: 2.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3-mini": { + id: "o3-mini", + name: "o3-mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.55, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3-pro": { + id: "o3-pro", + name: "o3-pro", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 20, + output: 80, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o4-mini": { + id: "o4-mini", + name: "o4-mini", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.28, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o4-mini-deep-research": { + id: "o4-mini-deep-research", + name: "o4-mini-deep-research", + api: "azure-openai-responses", + provider: "azure-openai-responses", + baseUrl: "", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + } + }, + "cerebras": { + "gpt-oss-120b": { + id: "gpt-oss-120b", + name: "GPT OSS 120B", + api: "openai-completions", + provider: "cerebras", + baseUrl: "https://api.cerebras.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.25, + output: 0.69, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "llama3.1-8b": { + id: "llama3.1-8b", + name: "Llama 3.1 8B", + api: "openai-completions", + provider: "cerebras", + baseUrl: "https://api.cerebras.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.1, + output: 0.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32e3, + maxTokens: 8e3 + }, + "qwen-3-235b-a22b-instruct-2507": { + id: "qwen-3-235b-a22b-instruct-2507", + name: "Qwen 3 235B Instruct", + api: "openai-completions", + provider: "cerebras", + baseUrl: "https://api.cerebras.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.6, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131e3, + maxTokens: 32e3 + }, + "zai-glm-4.7": { + id: "zai-glm-4.7", + name: "Z.AI GLM-4.7", + api: "openai-completions", + provider: "cerebras", + baseUrl: "https://api.cerebras.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2.25, + output: 2.75, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4e4 + } + }, + "github-copilot": { + "claude-haiku-4.5": { + id: "claude-haiku-4.5", + name: "Claude Haiku 4.5", + api: "anthropic-messages", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "claude-opus-4.5": { + id: "claude-opus-4.5", + name: "Claude Opus 4.5", + api: "anthropic-messages", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "claude-opus-4.6": { + id: "claude-opus-4.6", + name: "Claude Opus 4.6", + api: "anthropic-messages", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "claude-sonnet-4": { + id: "claude-sonnet-4", + name: "Claude Sonnet 4", + api: "anthropic-messages", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16e3 + }, + "claude-sonnet-4.5": { + id: "claude-sonnet-4.5", + name: "Claude Sonnet 4.5", + api: "anthropic-messages", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "claude-sonnet-4.6": { + id: "claude-sonnet-4.6", + name: "Claude Sonnet 4.6", + api: "anthropic-messages", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "gemini-2.5-pro": { + id: "gemini-2.5-pro", + name: "Gemini 2.5 Pro", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "gemini-3-flash-preview": { + id: "gemini-3-flash-preview", + name: "Gemini 3 Flash", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "gemini-3-pro-preview": { + id: "gemini-3-pro-preview", + name: "Gemini 3 Pro Preview", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "gemini-3.1-pro-preview": { + id: "gemini-3.1-pro-preview", + name: "Gemini 3.1 Pro Preview", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "gpt-4.1": { + id: "gpt-4.1", + name: "GPT-4.1", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 64e3, + maxTokens: 16384 + }, + "gpt-4o": { + id: "gpt-4o", + name: "GPT-4o", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 64e3, + maxTokens: 16384 + }, + "gpt-5": { + id: "gpt-5", + name: "GPT-5", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "gpt-5-mini": { + id: "gpt-5-mini", + name: "GPT-5-mini", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "gpt-5.1": { + id: "gpt-5.1", + name: "GPT-5.1", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "gpt-5.1-codex": { + id: "gpt-5.1-codex", + name: "GPT-5.1-Codex", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "gpt-5.1-codex-max": { + id: "gpt-5.1-codex-max", + name: "GPT-5.1-Codex-max", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "gpt-5.1-codex-mini": { + id: "gpt-5.1-codex-mini", + name: "GPT-5.1-Codex-mini", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "gpt-5.2": { + id: "gpt-5.2", + name: "GPT-5.2", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 264e3, + maxTokens: 64e3 + }, + "gpt-5.2-codex": { + id: "gpt-5.2-codex", + name: "GPT-5.2-Codex", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.3-codex": { + id: "gpt-5.3-codex", + name: "GPT-5.3-Codex", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.4": { + id: "gpt-5.4", + name: "GPT-5.4", + api: "openai-responses", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "grok-code-fast-1": { + id: "grok-code-fast-1", + name: "Grok Code Fast 1", + api: "openai-completions", + provider: "github-copilot", + baseUrl: "https://api.individual.githubcopilot.com", + headers: { "User-Agent": "GitHubCopilotChat/0.35.0", "Editor-Version": "vscode/1.107.0", "Editor-Plugin-Version": "copilot-chat/0.35.0", "Copilot-Integration-Id": "vscode-chat" }, + compat: { "supportsStore": false, "supportsDeveloperRole": false, "supportsReasoningEffort": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + } + }, + "google": { + "gemini-1.5-flash": { + id: "gemini-1.5-flash", + name: "Gemini 1.5 Flash", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0.01875, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 8192 + }, + "gemini-1.5-flash-8b": { + id: "gemini-1.5-flash-8b", + name: "Gemini 1.5 Flash-8B", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.0375, + output: 0.15, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 8192 + }, + "gemini-1.5-pro": { + id: "gemini-1.5-pro", + name: "Gemini 1.5 Pro", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.25, + output: 5, + cacheRead: 0.3125, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 8192 + }, + "gemini-2.0-flash": { + id: "gemini-2.0-flash", + name: "Gemini 2.0 Flash", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "gemini-2.0-flash-lite": { + id: "gemini-2.0-flash-lite", + name: "Gemini 2.0 Flash Lite", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "gemini-2.5-flash": { + id: "gemini-2.5-flash", + name: "Gemini 2.5 Flash", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-lite": { + id: "gemini-2.5-flash-lite", + name: "Gemini 2.5 Flash Lite", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-lite-preview-06-17": { + id: "gemini-2.5-flash-lite-preview-06-17", + name: "Gemini 2.5 Flash Lite Preview 06-17", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-lite-preview-09-2025": { + id: "gemini-2.5-flash-lite-preview-09-2025", + name: "Gemini 2.5 Flash Lite Preview 09-25", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-preview-04-17": { + id: "gemini-2.5-flash-preview-04-17", + name: "Gemini 2.5 Flash Preview 04-17", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.0375, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-preview-05-20": { + id: "gemini-2.5-flash-preview-05-20", + name: "Gemini 2.5 Flash Preview 05-20", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.0375, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-preview-09-2025": { + id: "gemini-2.5-flash-preview-09-2025", + name: "Gemini 2.5 Flash Preview 09-25", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-pro": { + id: "gemini-2.5-pro", + name: "Gemini 2.5 Pro", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.31, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-pro-preview-05-06": { + id: "gemini-2.5-pro-preview-05-06", + name: "Gemini 2.5 Pro Preview 05-06", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.31, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-pro-preview-06-05": { + id: "gemini-2.5-pro-preview-06-05", + name: "Gemini 2.5 Pro Preview 06-05", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.31, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3-flash-preview": { + id: "gemini-3-flash-preview", + name: "Gemini 3 Flash Preview", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 3, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3-pro-preview": { + id: "gemini-3-pro-preview", + name: "Gemini 3 Pro Preview", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "gemini-3.1-flash-lite-preview": { + id: "gemini-3.1-flash-lite-preview", + name: "Gemini 3.1 Flash Lite Preview", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.5, + cacheRead: 0.025, + cacheWrite: 1 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3.1-pro-preview": { + id: "gemini-3.1-pro-preview", + name: "Gemini 3.1 Pro Preview", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3.1-pro-preview-customtools": { + id: "gemini-3.1-pro-preview-customtools", + name: "Gemini 3.1 Pro Preview Custom Tools", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-flash-latest": { + id: "gemini-flash-latest", + name: "Gemini Flash Latest", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-flash-lite-latest": { + id: "gemini-flash-lite-latest", + name: "Gemini Flash-Lite Latest", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-live-2.5-flash": { + id: "gemini-live-2.5-flash", + name: "Gemini Live 2.5 Flash", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8e3 + }, + "gemini-live-2.5-flash-preview-native-audio": { + id: "gemini-live-2.5-flash-preview-native-audio", + name: "Gemini Live 2.5 Flash Preview Native Audio", + api: "google-generative-ai", + provider: "google", + baseUrl: "https://generativelanguage.googleapis.com/v1beta", + reasoning: true, + input: ["text"], + cost: { + input: 0.5, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + } + }, + "google-antigravity": { + "claude-opus-4-5-thinking": { + id: "claude-opus-4-5-thinking", + name: "Claude Opus 4.5 Thinking (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-opus-4-6-thinking": { + id: "claude-opus-4-6-thinking", + name: "Claude Opus 4.6 Thinking (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 128e3 + }, + "claude-sonnet-4-5": { + id: "claude-sonnet-4-5", + name: "Claude Sonnet 4.5 (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-5-thinking": { + id: "claude-sonnet-4-5-thinking", + name: "Claude Sonnet 4.5 Thinking (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-6": { + id: "claude-sonnet-4-6", + name: "Claude Sonnet 4.6 (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "gemini-3-flash": { + id: "gemini-3-flash", + name: "Gemini 3 Flash (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 3, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gemini-3.1-pro-high": { + id: "gemini-3.1-pro-high", + name: "Gemini 3.1 Pro High (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 2.375 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gemini-3.1-pro-low": { + id: "gemini-3.1-pro-low", + name: "Gemini 3.1 Pro Low (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 2.375 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gpt-oss-120b-medium": { + id: "gpt-oss-120b-medium", + name: "GPT-OSS 120B Medium (Antigravity)", + api: "google-gemini-cli", + provider: "google-antigravity", + baseUrl: "https://daily-cloudcode-pa.sandbox.googleapis.com", + reasoning: false, + input: ["text"], + cost: { + input: 0.09, + output: 0.36, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + } + }, + "google-gemini-cli": { + "gemini-2.0-flash": { + id: "gemini-2.0-flash", + name: "Gemini 2.0 Flash (Cloud Code Assist)", + api: "google-gemini-cli", + provider: "google-gemini-cli", + baseUrl: "https://cloudcode-pa.googleapis.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "gemini-2.5-flash": { + id: "gemini-2.5-flash", + name: "Gemini 2.5 Flash (Cloud Code Assist)", + api: "google-gemini-cli", + provider: "google-gemini-cli", + baseUrl: "https://cloudcode-pa.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gemini-2.5-pro": { + id: "gemini-2.5-pro", + name: "Gemini 2.5 Pro (Cloud Code Assist)", + api: "google-gemini-cli", + provider: "google-gemini-cli", + baseUrl: "https://cloudcode-pa.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gemini-3-flash-preview": { + id: "gemini-3-flash-preview", + name: "Gemini 3 Flash Preview (Cloud Code Assist)", + api: "google-gemini-cli", + provider: "google-gemini-cli", + baseUrl: "https://cloudcode-pa.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gemini-3-pro-preview": { + id: "gemini-3-pro-preview", + name: "Gemini 3 Pro Preview (Cloud Code Assist)", + api: "google-gemini-cli", + provider: "google-gemini-cli", + baseUrl: "https://cloudcode-pa.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "gemini-3.1-pro-preview": { + id: "gemini-3.1-pro-preview", + name: "Gemini 3.1 Pro Preview (Cloud Code Assist)", + api: "google-gemini-cli", + provider: "google-gemini-cli", + baseUrl: "https://cloudcode-pa.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65535 + } + }, + "google-vertex": { + "gemini-1.5-flash": { + id: "gemini-1.5-flash", + name: "Gemini 1.5 Flash (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0.01875, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 8192 + }, + "gemini-1.5-flash-8b": { + id: "gemini-1.5-flash-8b", + name: "Gemini 1.5 Flash-8B (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.0375, + output: 0.15, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 8192 + }, + "gemini-1.5-pro": { + id: "gemini-1.5-pro", + name: "Gemini 1.5 Pro (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.25, + output: 5, + cacheRead: 0.3125, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 8192 + }, + "gemini-2.0-flash": { + id: "gemini-2.0-flash", + name: "Gemini 2.0 Flash (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.0375, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "gemini-2.0-flash-lite": { + id: "gemini-2.0-flash-lite", + name: "Gemini 2.0 Flash Lite (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0.01875, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash": { + id: "gemini-2.5-flash", + name: "Gemini 2.5 Flash (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-lite": { + id: "gemini-2.5-flash-lite", + name: "Gemini 2.5 Flash Lite (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-flash-lite-preview-09-2025": { + id: "gemini-2.5-flash-lite-preview-09-2025", + name: "Gemini 2.5 Flash Lite Preview 09-25 (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-2.5-pro": { + id: "gemini-2.5-pro", + name: "Gemini 2.5 Pro (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3-flash-preview": { + id: "gemini-3-flash-preview", + name: "Gemini 3 Flash Preview (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 3, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3-pro-preview": { + id: "gemini-3-pro-preview", + name: "Gemini 3 Pro Preview (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "gemini-3.1-pro-preview": { + id: "gemini-3.1-pro-preview", + name: "Gemini 3.1 Pro Preview (Vertex)", + api: "google-vertex", + provider: "google-vertex", + baseUrl: "https://{location}-aiplatform.googleapis.com", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + } + }, + "groq": { + "deepseek-r1-distill-llama-70b": { + id: "deepseek-r1-distill-llama-70b", + name: "DeepSeek R1 Distill Llama 70B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.75, + output: 0.99, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "gemma2-9b-it": { + id: "gemma2-9b-it", + name: "Gemma 2 9B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.2, + output: 0.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 8192 + }, + "llama-3.1-8b-instant": { + id: "llama-3.1-8b-instant", + name: "Llama 3.1 8B Instant", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.05, + output: 0.08, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "llama-3.3-70b-versatile": { + id: "llama-3.3-70b-versatile", + name: "Llama 3.3 70B Versatile", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.59, + output: 0.79, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "llama3-70b-8192": { + id: "llama3-70b-8192", + name: "Llama 3 70B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.59, + output: 0.79, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 8192 + }, + "llama3-8b-8192": { + id: "llama3-8b-8192", + name: "Llama 3 8B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.05, + output: 0.08, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 8192 + }, + "meta-llama/llama-4-maverick-17b-128e-instruct": { + id: "meta-llama/llama-4-maverick-17b-128e-instruct", + name: "Llama 4 Maverick 17B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.2, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "meta-llama/llama-4-scout-17b-16e-instruct": { + id: "meta-llama/llama-4-scout-17b-16e-instruct", + name: "Llama 4 Scout 17B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.11, + output: 0.34, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "mistral-saba-24b": { + id: "mistral-saba-24b", + name: "Mistral Saba 24B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.79, + output: 0.79, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 32768 + }, + "moonshotai/kimi-k2-instruct": { + id: "moonshotai/kimi-k2-instruct", + name: "Kimi K2 Instruct", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "moonshotai/kimi-k2-instruct-0905": { + id: "moonshotai/kimi-k2-instruct-0905", + name: "Kimi K2 Instruct 0905", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 16384 + }, + "openai/gpt-oss-120b": { + id: "openai/gpt-oss-120b", + name: "GPT OSS 120B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + }, + "openai/gpt-oss-20b": { + id: "openai/gpt-oss-20b", + name: "GPT OSS 20B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + }, + "qwen-qwq-32b": { + id: "qwen-qwq-32b", + name: "Qwen QwQ 32B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.29, + output: 0.39, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "qwen/qwen3-32b": { + id: "qwen/qwen3-32b", + name: "Qwen3 32B", + api: "openai-completions", + provider: "groq", + baseUrl: "https://api.groq.com/openai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.29, + output: 0.59, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + } + }, + "huggingface": { + "MiniMaxAI/MiniMax-M2.1": { + id: "MiniMaxAI/MiniMax-M2.1", + name: "MiniMax-M2.1", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "MiniMaxAI/MiniMax-M2.5": { + id: "MiniMaxAI/MiniMax-M2.5", + name: "MiniMax-M2.5", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "Qwen/Qwen3-235B-A22B-Thinking-2507": { + id: "Qwen/Qwen3-235B-A22B-Thinking-2507", + name: "Qwen3-235B-A22B-Thinking-2507", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 131072 + }, + "Qwen/Qwen3-Coder-480B-A35B-Instruct": { + id: "Qwen/Qwen3-Coder-480B-A35B-Instruct", + name: "Qwen3-Coder-480B-A35B-Instruct", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 66536 + }, + "Qwen/Qwen3-Coder-Next": { + id: "Qwen/Qwen3-Coder-Next", + name: "Qwen3-Coder-Next", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: false, + input: ["text"], + cost: { + input: 0.2, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "Qwen/Qwen3-Next-80B-A3B-Instruct": { + id: "Qwen/Qwen3-Next-80B-A3B-Instruct", + name: "Qwen3-Next-80B-A3B-Instruct", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: false, + input: ["text"], + cost: { + input: 0.25, + output: 1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 66536 + }, + "Qwen/Qwen3-Next-80B-A3B-Thinking": { + id: "Qwen/Qwen3-Next-80B-A3B-Thinking", + name: "Qwen3-Next-80B-A3B-Thinking", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: false, + input: ["text"], + cost: { + input: 0.3, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 131072 + }, + "Qwen/Qwen3.5-397B-A17B": { + id: "Qwen/Qwen3.5-397B-A17B", + name: "Qwen3.5-397B-A17B", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 3.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "XiaomiMiMo/MiMo-V2-Flash": { + id: "XiaomiMiMo/MiMo-V2-Flash", + name: "MiMo-V2-Flash", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.1, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "deepseek-ai/DeepSeek-R1-0528": { + id: "deepseek-ai/DeepSeek-R1-0528", + name: "DeepSeek-R1-0528", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 3, + output: 5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 163840 + }, + "deepseek-ai/DeepSeek-V3.2": { + id: "deepseek-ai/DeepSeek-V3.2", + name: "DeepSeek-V3.2", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.28, + output: 0.4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 65536 + }, + "moonshotai/Kimi-K2-Instruct": { + id: "moonshotai/Kimi-K2-Instruct", + name: "Kimi-K2-Instruct", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "moonshotai/Kimi-K2-Instruct-0905": { + id: "moonshotai/Kimi-K2-Instruct-0905", + name: "Kimi-K2-Instruct-0905", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 16384 + }, + "moonshotai/Kimi-K2-Thinking": { + id: "moonshotai/Kimi-K2-Thinking", + name: "Kimi-K2-Thinking", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.5, + cacheRead: 0.15, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "moonshotai/Kimi-K2.5": { + id: "moonshotai/Kimi-K2.5", + name: "Kimi-K2.5", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 3, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "zai-org/GLM-4.7": { + id: "zai-org/GLM-4.7", + name: "GLM-4.7", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "zai-org/GLM-4.7-Flash": { + id: "zai-org/GLM-4.7-Flash", + name: "GLM-4.7-Flash", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 128e3 + }, + "zai-org/GLM-5": { + id: "zai-org/GLM-5", + name: "GLM-5", + api: "openai-completions", + provider: "huggingface", + baseUrl: "https://router.huggingface.co/v1", + compat: { "supportsDeveloperRole": false }, + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3.2, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 202752, + maxTokens: 131072 + } + }, + "kimi-coding": { + "k2p5": { + id: "k2p5", + name: "Kimi K2.5", + api: "anthropic-messages", + provider: "kimi-coding", + baseUrl: "https://api.kimi.com/coding", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "kimi-k2-thinking": { + id: "kimi-k2-thinking", + name: "Kimi K2 Thinking", + api: "anthropic-messages", + provider: "kimi-coding", + baseUrl: "https://api.kimi.com/coding", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + } + }, + "minimax": { + "MiniMax-M2": { + id: "MiniMax-M2", + name: "MiniMax-M2", + api: "anthropic-messages", + provider: "minimax", + baseUrl: "https://api.minimax.io/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 196608, + maxTokens: 128e3 + }, + "MiniMax-M2.1": { + id: "MiniMax-M2.1", + name: "MiniMax-M2.1", + api: "anthropic-messages", + provider: "minimax", + baseUrl: "https://api.minimax.io/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "MiniMax-M2.5": { + id: "MiniMax-M2.5", + name: "MiniMax-M2.5", + api: "anthropic-messages", + provider: "minimax", + baseUrl: "https://api.minimax.io/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "MiniMax-M2.5-highspeed": { + id: "MiniMax-M2.5-highspeed", + name: "MiniMax-M2.5-highspeed", + api: "anthropic-messages", + provider: "minimax", + baseUrl: "https://api.minimax.io/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.4, + cacheRead: 0.06, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131072 + } + }, + "minimax-cn": { + "MiniMax-M2": { + id: "MiniMax-M2", + name: "MiniMax-M2", + api: "anthropic-messages", + provider: "minimax-cn", + baseUrl: "https://api.minimaxi.com/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 196608, + maxTokens: 128e3 + }, + "MiniMax-M2.1": { + id: "MiniMax-M2.1", + name: "MiniMax-M2.1", + api: "anthropic-messages", + provider: "minimax-cn", + baseUrl: "https://api.minimaxi.com/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "MiniMax-M2.5": { + id: "MiniMax-M2.5", + name: "MiniMax-M2.5", + api: "anthropic-messages", + provider: "minimax-cn", + baseUrl: "https://api.minimaxi.com/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "MiniMax-M2.5-highspeed": { + id: "MiniMax-M2.5-highspeed", + name: "MiniMax-M2.5-highspeed", + api: "anthropic-messages", + provider: "minimax-cn", + baseUrl: "https://api.minimaxi.com/anthropic", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.4, + cacheRead: 0.06, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131072 + } + }, + "mistral": { + "codestral-latest": { + id: "codestral-latest", + name: "Codestral (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.3, + output: 0.9, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 4096 + }, + "devstral-2512": { + id: "devstral-2512", + name: "Devstral 2", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "devstral-medium-2507": { + id: "devstral-medium-2507", + name: "Devstral Medium", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "devstral-medium-latest": { + id: "devstral-medium-latest", + name: "Devstral 2 (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "devstral-small-2505": { + id: "devstral-small-2505", + name: "Devstral Small 2505", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.1, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "devstral-small-2507": { + id: "devstral-small-2507", + name: "Devstral Small", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.1, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "labs-devstral-small-2512": { + id: "labs-devstral-small-2512", + name: "Devstral Small 2", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "magistral-medium-latest": { + id: "magistral-medium-latest", + name: "Magistral Medium (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: true, + input: ["text"], + cost: { + input: 2, + output: 5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "magistral-small": { + id: "magistral-small", + name: "Magistral Small", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: true, + input: ["text"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "ministral-3b-latest": { + id: "ministral-3b-latest", + name: "Ministral 3B (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.04, + output: 0.04, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "ministral-8b-latest": { + id: "ministral-8b-latest", + name: "Ministral 8B (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.1, + output: 0.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "mistral-large-2411": { + id: "mistral-large-2411", + name: "Mistral Large 2.1", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "mistral-large-2512": { + id: "mistral-large-2512", + name: "Mistral Large 3", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "mistral-large-latest": { + id: "mistral-large-latest", + name: "Mistral Large (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "mistral-medium-2505": { + id: "mistral-medium-2505", + name: "Mistral Medium 3", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "mistral-medium-2508": { + id: "mistral-medium-2508", + name: "Mistral Medium 3.1", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "mistral-medium-latest": { + id: "mistral-medium-latest", + name: "Mistral Medium (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.4, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "mistral-nemo": { + id: "mistral-nemo", + name: "Mistral Nemo", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "mistral-small-2506": { + id: "mistral-small-2506", + name: "Mistral Small 3.2", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "mistral-small-latest": { + id: "mistral-small-latest", + name: "Mistral Small (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "open-mistral-7b": { + id: "open-mistral-7b", + name: "Mistral 7B", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.25, + output: 0.25, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8e3, + maxTokens: 8e3 + }, + "open-mixtral-8x22b": { + id: "open-mixtral-8x22b", + name: "Mixtral 8x22B", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 64e3, + maxTokens: 64e3 + }, + "open-mixtral-8x7b": { + id: "open-mixtral-8x7b", + name: "Mixtral 8x7B", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text"], + cost: { + input: 0.7, + output: 0.7, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32e3, + maxTokens: 32e3 + }, + "pixtral-12b": { + id: "pixtral-12b", + name: "Pixtral 12B", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "pixtral-large-latest": { + id: "pixtral-large-latest", + name: "Pixtral Large (latest)", + api: "mistral-conversations", + provider: "mistral", + baseUrl: "https://api.mistral.ai", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + } + }, + "openai": { + "codex-mini-latest": { + id: "codex-mini-latest", + name: "Codex Mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text"], + cost: { + input: 1.5, + output: 6, + cacheRead: 0.375, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "gpt-4": { + id: "gpt-4", + name: "GPT-4", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text"], + cost: { + input: 30, + output: 60, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 8192 + }, + "gpt-4-turbo": { + id: "gpt-4-turbo", + name: "GPT-4 Turbo", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 10, + output: 30, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "gpt-4.1": { + id: "gpt-4.1", + name: "GPT-4.1", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "gpt-4.1-mini": { + id: "gpt-4.1-mini", + name: "GPT-4.1 mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.4, + output: 1.6, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "gpt-4.1-nano": { + id: "gpt-4.1-nano", + name: "GPT-4.1 nano", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.1, + output: 0.4, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "gpt-4o": { + id: "gpt-4o", + name: "GPT-4o", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-4o-2024-05-13": { + id: "gpt-4o-2024-05-13", + name: "GPT-4o (2024-05-13)", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 5, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "gpt-4o-2024-08-06": { + id: "gpt-4o-2024-08-06", + name: "GPT-4o (2024-08-06)", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-4o-2024-11-20": { + id: "gpt-4o-2024-11-20", + name: "GPT-4o (2024-11-20)", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-4o-mini": { + id: "gpt-4o-mini", + name: "GPT-4o mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.08, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5": { + id: "gpt-5", + name: "GPT-5", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-chat-latest": { + id: "gpt-5-chat-latest", + name: "GPT-5 Chat Latest", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5-codex": { + id: "gpt-5-codex", + name: "GPT-5-Codex", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-mini": { + id: "gpt-5-mini", + name: "GPT-5 Mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-nano": { + id: "gpt-5-nano", + name: "GPT-5 Nano", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.05, + output: 0.4, + cacheRead: 5e-3, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-pro": { + id: "gpt-5-pro", + name: "GPT-5 Pro", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 120, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 272e3 + }, + "gpt-5.1": { + id: "gpt-5.1", + name: "GPT-5.1", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.13, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-chat-latest": { + id: "gpt-5.1-chat-latest", + name: "GPT-5.1 Chat", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5.1-codex": { + id: "gpt-5.1-codex", + name: "GPT-5.1 Codex", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex-max": { + id: "gpt-5.1-codex-max", + name: "GPT-5.1 Codex Max", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex-mini": { + id: "gpt-5.1-codex-mini", + name: "GPT-5.1 Codex mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2": { + id: "gpt-5.2", + name: "GPT-5.2", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2-chat-latest": { + id: "gpt-5.2-chat-latest", + name: "GPT-5.2 Chat", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "gpt-5.2-codex": { + id: "gpt-5.2-codex", + name: "GPT-5.2 Codex", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2-pro": { + id: "gpt-5.2-pro", + name: "GPT-5.2 Pro", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 21, + output: 168, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.3-codex": { + id: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.3-codex-spark": { + id: "gpt-5.3-codex-spark", + name: "GPT-5.3 Codex Spark", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "gpt-5.4": { + id: "gpt-5.4", + name: "GPT-5.4", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 15, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.4-pro": { + id: "gpt-5.4-pro", + name: "GPT-5.4 Pro", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 30, + output: 180, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "o1": { + id: "o1", + name: "o1", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 60, + cacheRead: 7.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o1-pro": { + id: "o1-pro", + name: "o1-pro", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 150, + output: 600, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3": { + id: "o3", + name: "o3", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3-deep-research": { + id: "o3-deep-research", + name: "o3-deep-research", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 10, + output: 40, + cacheRead: 2.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3-mini": { + id: "o3-mini", + name: "o3-mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.55, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o3-pro": { + id: "o3-pro", + name: "o3-pro", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 20, + output: 80, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o4-mini": { + id: "o4-mini", + name: "o4-mini", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.28, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "o4-mini-deep-research": { + id: "o4-mini-deep-research", + name: "o4-mini-deep-research", + api: "openai-responses", + provider: "openai", + baseUrl: "https://api.openai.com/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + } + }, + "openai-codex": { + "gpt-5.1": { + id: "gpt-5.1", + name: "GPT-5.1", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.1-codex-max": { + id: "gpt-5.1-codex-max", + name: "GPT-5.1 Codex Max", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.1-codex-mini": { + id: "gpt-5.1-codex-mini", + name: "GPT-5.1 Codex Mini", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.2": { + id: "gpt-5.2", + name: "GPT-5.2", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.2-codex": { + id: "gpt-5.2-codex", + name: "GPT-5.2 Codex", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.3-codex": { + id: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.3-codex-spark": { + id: "gpt-5.3-codex-spark", + name: "GPT-5.3 Codex Spark", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "gpt-5.4": { + id: "gpt-5.4", + name: "GPT-5.4", + api: "openai-codex-responses", + provider: "openai-codex", + baseUrl: "https://chatgpt.com/backend-api", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 15, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + } + }, + "opencode": { + "big-pickle": { + id: "big-pickle", + name: "Big Pickle", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 128e3 + }, + "claude-3-5-haiku": { + id: "claude-3-5-haiku", + name: "Claude Haiku 3.5", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.8, + output: 4, + cacheRead: 0.08, + cacheWrite: 1 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "claude-haiku-4-5": { + id: "claude-haiku-4-5", + name: "Claude Haiku 4.5", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.1, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-opus-4-1": { + id: "claude-opus-4-1", + name: "Claude Opus 4.1", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "claude-opus-4-5": { + id: "claude-opus-4-5", + name: "Claude Opus 4.5", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-opus-4-6": { + id: "claude-opus-4-6", + name: "Claude Opus 4.6", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "claude-sonnet-4": { + id: "claude-sonnet-4", + name: "Claude Sonnet 4", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-5": { + id: "claude-sonnet-4-5", + name: "Claude Sonnet 4.5", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "claude-sonnet-4-6": { + id: "claude-sonnet-4-6", + name: "Claude Sonnet 4.6", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "gemini-3-flash": { + id: "gemini-3-flash", + name: "Gemini 3 Flash", + api: "google-generative-ai", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 3, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3-pro": { + id: "gemini-3-pro", + name: "Gemini 3 Pro", + api: "google-generative-ai", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "gemini-3.1-pro": { + id: "gemini-3.1-pro", + name: "Gemini 3.1 Pro Preview", + api: "google-generative-ai", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "glm-4.6": { + id: "glm-4.6", + name: "GLM-4.6", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "glm-4.7": { + id: "glm-4.7", + name: "GLM-4.7", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "glm-5": { + id: "glm-5", + name: "GLM-5", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3.2, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "gpt-5": { + id: "gpt-5", + name: "GPT-5", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.07, + output: 8.5, + cacheRead: 0.107, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-codex": { + id: "gpt-5-codex", + name: "GPT-5 Codex", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.07, + output: 8.5, + cacheRead: 0.107, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5-nano": { + id: "gpt-5-nano", + name: "GPT-5 Nano", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1": { + id: "gpt-5.1", + name: "GPT-5.1", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.07, + output: 8.5, + cacheRead: 0.107, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex": { + id: "gpt-5.1-codex", + name: "GPT-5.1 Codex", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.07, + output: 8.5, + cacheRead: 0.107, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex-max": { + id: "gpt-5.1-codex-max", + name: "GPT-5.1 Codex Max", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.1-codex-mini": { + id: "gpt-5.1-codex-mini", + name: "GPT-5.1 Codex Mini", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.025, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2": { + id: "gpt-5.2", + name: "GPT-5.2", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.2-codex": { + id: "gpt-5.2-codex", + name: "GPT-5.2 Codex", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.3-codex": { + id: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "gpt-5.4": { + id: "gpt-5.4", + name: "GPT-5.4", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 15, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 272e3, + maxTokens: 128e3 + }, + "gpt-5.4-pro": { + id: "gpt-5.4-pro", + name: "GPT-5.4 Pro", + api: "openai-responses", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 30, + output: 180, + cacheRead: 30, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "kimi-k2.5": { + id: "kimi-k2.5", + name: "Kimi K2.5", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 3, + cacheRead: 0.08, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "mimo-v2-flash-free": { + id: "mimo-v2-flash-free", + name: "MiMo V2 Flash Free", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "minimax-m2.1": { + id: "minimax-m2.1", + name: "MiniMax M2.1", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "minimax-m2.5": { + id: "minimax-m2.5", + name: "MiniMax M2.5", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.06, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "minimax-m2.5-free": { + id: "minimax-m2.5-free", + name: "MiniMax M2.5 Free", + api: "anthropic-messages", + provider: "opencode", + baseUrl: "https://opencode.ai/zen", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "nemotron-3-super-free": { + id: "nemotron-3-super-free", + name: "Nemotron 3 Super Free", + api: "openai-completions", + provider: "opencode", + baseUrl: "https://opencode.ai/zen/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 128e3 + } + }, + "opencode-go": { + "glm-5": { + id: "glm-5", + name: "GLM-5", + api: "openai-completions", + provider: "opencode-go", + baseUrl: "https://opencode.ai/zen/go/v1", + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3.2, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "kimi-k2.5": { + id: "kimi-k2.5", + name: "Kimi K2.5", + api: "openai-completions", + provider: "opencode-go", + baseUrl: "https://opencode.ai/zen/go/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 3, + cacheRead: 0.1, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "minimax-m2.5": { + id: "minimax-m2.5", + name: "MiniMax M2.5", + api: "anthropic-messages", + provider: "opencode-go", + baseUrl: "https://opencode.ai/zen/go", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + } + }, + "openrouter": { + "ai21/jamba-large-1.7": { + id: "ai21/jamba-large-1.7", + name: "AI21: Jamba Large 1.7", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 8, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 4096 + }, + "alibaba/tongyi-deepresearch-30b-a3b": { + id: "alibaba/tongyi-deepresearch-30b-a3b", + name: "Tongyi DeepResearch 30B A3B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.09, + output: 0.44999999999999996, + cacheRead: 0.09, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "allenai/olmo-3.1-32b-instruct": { + id: "allenai/olmo-3.1-32b-instruct", + name: "AllenAI: Olmo 3.1 32B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 65536, + maxTokens: 4096 + }, + "amazon/nova-2-lite-v1": { + id: "amazon/nova-2-lite-v1", + name: "Amazon: Nova 2 Lite", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65535 + }, + "amazon/nova-lite-v1": { + id: "amazon/nova-lite-v1", + name: "Amazon: Nova Lite 1.0", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.06, + output: 0.24, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 3e5, + maxTokens: 5120 + }, + "amazon/nova-micro-v1": { + id: "amazon/nova-micro-v1", + name: "Amazon: Nova Micro 1.0", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.035, + output: 0.14, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 5120 + }, + "amazon/nova-premier-v1": { + id: "amazon/nova-premier-v1", + name: "Amazon: Nova Premier 1.0", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 12.5, + cacheRead: 0.625, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 32e3 + }, + "amazon/nova-pro-v1": { + id: "amazon/nova-pro-v1", + name: "Amazon: Nova Pro 1.0", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.7999999999999999, + output: 3.1999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 3e5, + maxTokens: 5120 + }, + "anthropic/claude-3-haiku": { + id: "anthropic/claude-3-haiku", + name: "Anthropic: Claude 3 Haiku", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.25, + cacheRead: 0.03, + cacheWrite: 0.3 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "anthropic/claude-3.5-haiku": { + id: "anthropic/claude-3.5-haiku", + name: "Anthropic: Claude 3.5 Haiku", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.7999999999999999, + output: 4, + cacheRead: 0.08, + cacheWrite: 1 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic/claude-3.5-sonnet": { + id: "anthropic/claude-3.5-sonnet", + name: "Anthropic: Claude 3.5 Sonnet", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 6, + output: 30, + cacheRead: 0.6, + cacheWrite: 7.5 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic/claude-3.7-sonnet": { + id: "anthropic/claude-3.7-sonnet", + name: "Anthropic: Claude 3.7 Sonnet", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-3.7-sonnet:thinking": { + id: "anthropic/claude-3.7-sonnet:thinking", + name: "Anthropic: Claude 3.7 Sonnet (thinking)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-haiku-4.5": { + id: "anthropic/claude-haiku-4.5", + name: "Anthropic: Claude Haiku 4.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.09999999999999999, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-opus-4": { + id: "anthropic/claude-opus-4", + name: "Anthropic: Claude Opus 4", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "anthropic/claude-opus-4.1": { + id: "anthropic/claude-opus-4.1", + name: "Anthropic: Claude Opus 4.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "anthropic/claude-opus-4.5": { + id: "anthropic/claude-opus-4.5", + name: "Anthropic: Claude Opus 4.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-opus-4.6": { + id: "anthropic/claude-opus-4.6", + name: "Anthropic: Claude Opus 4.6", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "anthropic/claude-sonnet-4": { + id: "anthropic/claude-sonnet-4", + name: "Anthropic: Claude Sonnet 4", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-sonnet-4.5": { + id: "anthropic/claude-sonnet-4.5", + name: "Anthropic: Claude Sonnet 4.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "anthropic/claude-sonnet-4.6": { + id: "anthropic/claude-sonnet-4.6", + name: "Anthropic: Claude Sonnet 4.6", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "arcee-ai/trinity-large-preview:free": { + id: "arcee-ai/trinity-large-preview:free", + name: "Arcee AI: Trinity Large Preview (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131e3, + maxTokens: 4096 + }, + "arcee-ai/trinity-mini": { + id: "arcee-ai/trinity-mini", + name: "Arcee AI: Trinity Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.045, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "arcee-ai/trinity-mini:free": { + id: "arcee-ai/trinity-mini:free", + name: "Arcee AI: Trinity Mini (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "arcee-ai/virtuoso-large": { + id: "arcee-ai/virtuoso-large", + name: "Arcee AI: Virtuoso Large", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.75, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 64e3 + }, + "auto": { + id: "auto", + name: "Auto", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "baidu/ernie-4.5-21b-a3b": { + id: "baidu/ernie-4.5-21b-a3b", + name: "Baidu: ERNIE 4.5 21B A3B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.07, + output: 0.28, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 12e4, + maxTokens: 8e3 + }, + "baidu/ernie-4.5-vl-28b-a3b": { + id: "baidu/ernie-4.5-vl-28b-a3b", + name: "Baidu: ERNIE 4.5 VL 28B A3B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.14, + output: 0.56, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 3e4, + maxTokens: 8e3 + }, + "bytedance-seed/seed-1.6": { + id: "bytedance-seed/seed-1.6", + name: "ByteDance Seed: Seed 1.6", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "bytedance-seed/seed-1.6-flash": { + id: "bytedance-seed/seed-1.6-flash", + name: "ByteDance Seed: Seed 1.6 Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "bytedance-seed/seed-2.0-lite": { + id: "bytedance-seed/seed-2.0-lite", + name: "ByteDance Seed: Seed-2.0-Lite", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 131072 + }, + "bytedance-seed/seed-2.0-mini": { + id: "bytedance-seed/seed-2.0-mini", + name: "ByteDance Seed: Seed-2.0-Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 131072 + }, + "cohere/command-r-08-2024": { + id: "cohere/command-r-08-2024", + name: "Cohere: Command R (08-2024)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "cohere/command-r-plus-08-2024": { + id: "cohere/command-r-plus-08-2024", + name: "Cohere: Command R+ (08-2024)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2.5, + output: 10, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "deepseek/deepseek-chat": { + id: "deepseek/deepseek-chat", + name: "DeepSeek: DeepSeek V3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.32, + output: 0.8899999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 163840 + }, + "deepseek/deepseek-chat-v3-0324": { + id: "deepseek/deepseek-chat-v3-0324", + name: "DeepSeek: DeepSeek V3 0324", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.77, + cacheRead: 0.135, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 4096 + }, + "deepseek/deepseek-chat-v3.1": { + id: "deepseek/deepseek-chat-v3.1", + name: "DeepSeek: DeepSeek V3.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 0.75, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 7168 + }, + "deepseek/deepseek-r1": { + id: "deepseek/deepseek-r1", + name: "DeepSeek: R1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.7, + output: 2.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 64e3, + maxTokens: 16e3 + }, + "deepseek/deepseek-r1-0528": { + id: "deepseek/deepseek-r1-0528", + name: "DeepSeek: R1 0528", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.44999999999999996, + output: 2.1500000000000004, + cacheRead: 0.22499999999999998, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 65536 + }, + "deepseek/deepseek-v3.1-terminus": { + id: "deepseek/deepseek-v3.1-terminus", + name: "DeepSeek: DeepSeek V3.1 Terminus", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.21, + output: 0.7899999999999999, + cacheRead: 0.1300000002, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 4096 + }, + "deepseek/deepseek-v3.2": { + id: "deepseek/deepseek-v3.2", + name: "DeepSeek: DeepSeek V3.2", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.26, + output: 0.38, + cacheRead: 0.13, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 4096 + }, + "deepseek/deepseek-v3.2-exp": { + id: "deepseek/deepseek-v3.2-exp", + name: "DeepSeek: DeepSeek V3.2 Exp", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.27, + output: 0.41, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 65536 + }, + "essentialai/rnj-1-instruct": { + id: "essentialai/rnj-1-instruct", + name: "EssentialAI: Rnj 1 Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 4096 + }, + "google/gemini-2.0-flash-001": { + id: "google/gemini-2.0-flash-001", + name: "Google: Gemini 2.0 Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.024999999999999998, + cacheWrite: 0.08333333333333334 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "google/gemini-2.0-flash-lite-001": { + id: "google/gemini-2.0-flash-lite-001", + name: "Google: Gemini 2.0 Flash Lite", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "google/gemini-2.5-flash": { + id: "google/gemini-2.5-flash", + name: "Google: Gemini 2.5 Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.03, + cacheWrite: 0.08333333333333334 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "google/gemini-2.5-flash-lite": { + id: "google/gemini-2.5-flash-lite", + name: "Google: Gemini 2.5 Flash Lite", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.01, + cacheWrite: 0.08333333333333334 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "google/gemini-2.5-flash-lite-preview-09-2025": { + id: "google/gemini-2.5-flash-lite-preview-09-2025", + name: "Google: Gemini 2.5 Flash Lite Preview 09-2025", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.01, + cacheWrite: 0.08333333333333334 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-2.5-pro": { + id: "google/gemini-2.5-pro", + name: "Google: Gemini 2.5 Pro", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0.375 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-2.5-pro-preview": { + id: "google/gemini-2.5-pro-preview", + name: "Google: Gemini 2.5 Pro Preview 06-05", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0.375 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-2.5-pro-preview-05-06": { + id: "google/gemini-2.5-pro-preview-05-06", + name: "Google: Gemini 2.5 Pro Preview 05-06", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0.375 + }, + contextWindow: 1048576, + maxTokens: 65535 + }, + "google/gemini-3-flash-preview": { + id: "google/gemini-3-flash-preview", + name: "Google: Gemini 3 Flash Preview", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 3, + cacheRead: 0.049999999999999996, + cacheWrite: 0.08333333333333334 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-3-pro-preview": { + id: "google/gemini-3-pro-preview", + name: "Google: Gemini 3 Pro Preview", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.19999999999999998, + cacheWrite: 0.375 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-3.1-flash-lite-preview": { + id: "google/gemini-3.1-flash-lite-preview", + name: "Google: Gemini 3.1 Flash Lite Preview", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.5, + cacheRead: 0.024999999999999998, + cacheWrite: 0.08333333333333334 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-3.1-pro-preview": { + id: "google/gemini-3.1-pro-preview", + name: "Google: Gemini 3.1 Pro Preview", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.19999999999999998, + cacheWrite: 0.375 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-3.1-pro-preview-customtools": { + id: "google/gemini-3.1-pro-preview-customtools", + name: "Google: Gemini 3.1 Pro Preview Custom Tools", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.19999999999999998, + cacheWrite: 0.375 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemma-3-27b-it": { + id: "google/gemma-3-27b-it", + name: "Google: Gemma 3 27B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.03, + output: 0.11, + cacheRead: 0.015, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 65536 + }, + "google/gemma-3-27b-it:free": { + id: "google/gemma-3-27b-it:free", + name: "Google: Gemma 3 27B (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "inception/mercury": { + id: "inception/mercury", + name: "Inception: Mercury", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.25, + output: 0.75, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "inception/mercury-2": { + id: "inception/mercury-2", + name: "Inception: Mercury 2", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.25, + output: 0.75, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 5e4 + }, + "inception/mercury-coder": { + id: "inception/mercury-coder", + name: "Inception: Mercury Coder", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.25, + output: 0.75, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "kwaipilot/kat-coder-pro": { + id: "kwaipilot/kat-coder-pro", + name: "Kwaipilot: KAT-Coder-Pro V1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.207, + output: 0.828, + cacheRead: 0.0414, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 128e3 + }, + "meituan/longcat-flash-chat": { + id: "meituan/longcat-flash-chat", + name: "Meituan: LongCat Flash Chat", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.7999999999999999, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "meta-llama/llama-3-8b-instruct": { + id: "meta-llama/llama-3-8b-instruct", + name: "Meta: Llama 3 8B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.03, + output: 0.04, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 16384 + }, + "meta-llama/llama-3.1-70b-instruct": { + id: "meta-llama/llama-3.1-70b-instruct", + name: "Meta: Llama 3.1 70B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "meta-llama/llama-3.1-8b-instruct": { + id: "meta-llama/llama-3.1-8b-instruct", + name: "Meta: Llama 3.1 8B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.02, + output: 0.049999999999999996, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 16384, + maxTokens: 16384 + }, + "meta-llama/llama-3.3-70b-instruct": { + id: "meta-llama/llama-3.3-70b-instruct", + name: "Meta: Llama 3.3 70B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.32, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "meta-llama/llama-3.3-70b-instruct:free": { + id: "meta-llama/llama-3.3-70b-instruct:free", + name: "Meta: Llama 3.3 70B Instruct (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "meta-llama/llama-4-maverick": { + id: "meta-llama/llama-4-maverick", + name: "Meta: Llama 4 Maverick", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 16384 + }, + "meta-llama/llama-4-scout": { + id: "meta-llama/llama-4-scout", + name: "Meta: Llama 4 Scout", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.08, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 327680, + maxTokens: 16384 + }, + "minimax/minimax-m1": { + id: "minimax/minimax-m1", + name: "MiniMax: MiniMax M1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 2.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 4e4 + }, + "minimax/minimax-m2": { + id: "minimax/minimax-m2", + name: "MiniMax: MiniMax M2", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.255, + output: 1, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 196608, + maxTokens: 196608 + }, + "minimax/minimax-m2.1": { + id: "minimax/minimax-m2.1", + name: "MiniMax: MiniMax M2.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.27, + output: 0.95, + cacheRead: 0.0290000007, + cacheWrite: 0 + }, + contextWindow: 196608, + maxTokens: 4096 + }, + "minimax/minimax-m2.5": { + id: "minimax/minimax-m2.5", + name: "MiniMax: MiniMax M2.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.25, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 196608, + maxTokens: 196608 + }, + "minimax/minimax-m2.5:free": { + id: "minimax/minimax-m2.5:free", + name: "MiniMax: MiniMax M2.5 (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 196608, + maxTokens: 196608 + }, + "mistralai/codestral-2508": { + id: "mistralai/codestral-2508", + name: "Mistral: Codestral 2508", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.3, + output: 0.8999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 4096 + }, + "mistralai/devstral-2512": { + id: "mistralai/devstral-2512", + name: "Mistral: Devstral 2 2512", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "mistralai/devstral-medium": { + id: "mistralai/devstral-medium", + name: "Mistral: Devstral Medium", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/devstral-small": { + id: "mistralai/devstral-small", + name: "Mistral: Devstral Small 1.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/ministral-14b-2512": { + id: "mistralai/ministral-14b-2512", + name: "Mistral: Ministral 3 14B 2512", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.19999999999999998, + output: 0.19999999999999998, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "mistralai/ministral-3b-2512": { + id: "mistralai/ministral-3b-2512", + name: "Mistral: Ministral 3 3B 2512", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.09999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/ministral-8b-2512": { + id: "mistralai/ministral-8b-2512", + name: "Mistral: Ministral 3 8B 2512", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "mistralai/mistral-large": { + id: "mistralai/mistral-large", + name: "Mistral Large", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "mistralai/mistral-large-2407": { + id: "mistralai/mistral-large-2407", + name: "Mistral Large 2407", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/mistral-large-2411": { + id: "mistralai/mistral-large-2411", + name: "Mistral Large 2411", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/mistral-large-2512": { + id: "mistralai/mistral-large-2512", + name: "Mistral: Mistral Large 3 2512", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "mistralai/mistral-medium-3": { + id: "mistralai/mistral-medium-3", + name: "Mistral: Mistral Medium 3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/mistral-medium-3.1": { + id: "mistralai/mistral-medium-3.1", + name: "Mistral: Mistral Medium 3.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/mistral-nemo": { + id: "mistralai/mistral-nemo", + name: "Mistral: Mistral Nemo", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.02, + output: 0.04, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "mistralai/mistral-saba": { + id: "mistralai/mistral-saba", + name: "Mistral: Saba", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 4096 + }, + "mistralai/mistral-small-24b-instruct-2501": { + id: "mistralai/mistral-small-24b-instruct-2501", + name: "Mistral: Mistral Small 3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.049999999999999996, + output: 0.08, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 16384 + }, + "mistralai/mistral-small-3.1-24b-instruct:free": { + id: "mistralai/mistral-small-3.1-24b-instruct:free", + name: "Mistral: Mistral Small 3.1 24B (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "mistralai/mistral-small-3.2-24b-instruct": { + id: "mistralai/mistral-small-3.2-24b-instruct", + name: "Mistral: Mistral Small 3.2 24B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.06, + output: 0.18, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "mistralai/mistral-small-creative": { + id: "mistralai/mistral-small-creative", + name: "Mistral: Mistral Small Creative", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 4096 + }, + "mistralai/mixtral-8x22b-instruct": { + id: "mistralai/mixtral-8x22b-instruct", + name: "Mistral: Mixtral 8x22B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 65536, + maxTokens: 4096 + }, + "mistralai/mixtral-8x7b-instruct": { + id: "mistralai/mixtral-8x7b-instruct", + name: "Mistral: Mixtral 8x7B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.54, + output: 0.54, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 16384 + }, + "mistralai/pixtral-large-2411": { + id: "mistralai/pixtral-large-2411", + name: "Mistral: Pixtral Large 2411", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "mistralai/voxtral-small-24b-2507": { + id: "mistralai/voxtral-small-24b-2507", + name: "Mistral: Voxtral Small 24B 2507", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32e3, + maxTokens: 4096 + }, + "moonshotai/kimi-k2": { + id: "moonshotai/kimi-k2", + name: "MoonshotAI: Kimi K2 0711", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.55, + output: 2.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131e3, + maxTokens: 4096 + }, + "moonshotai/kimi-k2-0905": { + id: "moonshotai/kimi-k2-0905", + name: "MoonshotAI: Kimi K2 0905", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0.15, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "moonshotai/kimi-k2-thinking": { + id: "moonshotai/kimi-k2-thinking", + name: "MoonshotAI: Kimi K2 Thinking", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.47, + output: 2, + cacheRead: 0.14100000000000001, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "moonshotai/kimi-k2.5": { + id: "moonshotai/kimi-k2.5", + name: "MoonshotAI: Kimi K2.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.41, + output: 2.06, + cacheRead: 0.07, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "nex-agi/deepseek-v3.1-nex-n1": { + id: "nex-agi/deepseek-v3.1-nex-n1", + name: "Nex AGI: DeepSeek V3.1 Nex N1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.27, + output: 1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 163840 + }, + "nvidia/llama-3.1-nemotron-70b-instruct": { + id: "nvidia/llama-3.1-nemotron-70b-instruct", + name: "NVIDIA: Llama 3.1 Nemotron 70B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1.2, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "nvidia/llama-3.3-nemotron-super-49b-v1.5": { + id: "nvidia/llama-3.3-nemotron-super-49b-v1.5", + name: "NVIDIA: Llama 3.3 Nemotron Super 49B V1.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "nvidia/nemotron-3-nano-30b-a3b": { + id: "nvidia/nemotron-3-nano-30b-a3b", + name: "NVIDIA: Nemotron 3 Nano 30B A3B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.049999999999999996, + output: 0.19999999999999998, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "nvidia/nemotron-3-nano-30b-a3b:free": { + id: "nvidia/nemotron-3-nano-30b-a3b:free", + name: "NVIDIA: Nemotron 3 Nano 30B A3B (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 4096 + }, + "nvidia/nemotron-3-super-120b-a12b:free": { + id: "nvidia/nemotron-3-super-120b-a12b:free", + name: "NVIDIA: Nemotron 3 Super (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "nvidia/nemotron-nano-12b-v2-vl:free": { + id: "nvidia/nemotron-nano-12b-v2-vl:free", + name: "NVIDIA: Nemotron Nano 12B 2 VL (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "nvidia/nemotron-nano-9b-v2": { + id: "nvidia/nemotron-nano-9b-v2", + name: "NVIDIA: Nemotron Nano 9B V2", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.04, + output: 0.16, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "nvidia/nemotron-nano-9b-v2:free": { + id: "nvidia/nemotron-nano-9b-v2:free", + name: "NVIDIA: Nemotron Nano 9B V2 (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai/gpt-3.5-turbo": { + id: "openai/gpt-3.5-turbo", + name: "OpenAI: GPT-3.5 Turbo", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 16385, + maxTokens: 4096 + }, + "openai/gpt-3.5-turbo-0613": { + id: "openai/gpt-3.5-turbo-0613", + name: "OpenAI: GPT-3.5 Turbo (older v0613)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4095, + maxTokens: 4096 + }, + "openai/gpt-3.5-turbo-16k": { + id: "openai/gpt-3.5-turbo-16k", + name: "OpenAI: GPT-3.5 Turbo 16k", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 3, + output: 4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 16385, + maxTokens: 4096 + }, + "openai/gpt-4": { + id: "openai/gpt-4", + name: "OpenAI: GPT-4", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 30, + output: 60, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8191, + maxTokens: 4096 + }, + "openai/gpt-4-0314": { + id: "openai/gpt-4-0314", + name: "OpenAI: GPT-4 (older v0314)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 30, + output: 60, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8191, + maxTokens: 4096 + }, + "openai/gpt-4-1106-preview": { + id: "openai/gpt-4-1106-preview", + name: "OpenAI: GPT-4 Turbo (older v1106)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 10, + output: 30, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai/gpt-4-turbo": { + id: "openai/gpt-4-turbo", + name: "OpenAI: GPT-4 Turbo", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 10, + output: 30, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai/gpt-4-turbo-preview": { + id: "openai/gpt-4-turbo-preview", + name: "OpenAI: GPT-4 Turbo Preview", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 10, + output: 30, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai/gpt-4.1": { + id: "openai/gpt-4.1", + name: "OpenAI: GPT-4.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "openai/gpt-4.1-mini": { + id: "openai/gpt-4.1-mini", + name: "OpenAI: GPT-4.1 Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 1.5999999999999999, + cacheRead: 0.09999999999999999, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "openai/gpt-4.1-nano": { + id: "openai/gpt-4.1-nano", + name: "OpenAI: GPT-4.1 Nano", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "openai/gpt-4o": { + id: "openai/gpt-4o", + name: "OpenAI: GPT-4o", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o-2024-05-13": { + id: "openai/gpt-4o-2024-05-13", + name: "OpenAI: GPT-4o (2024-05-13)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 5, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai/gpt-4o-2024-08-06": { + id: "openai/gpt-4o-2024-08-06", + name: "OpenAI: GPT-4o (2024-08-06)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o-2024-11-20": { + id: "openai/gpt-4o-2024-11-20", + name: "OpenAI: GPT-4o (2024-11-20)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o-audio-preview": { + id: "openai/gpt-4o-audio-preview", + name: "OpenAI: GPT-4o Audio", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2.5, + output: 10, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o-mini": { + id: "openai/gpt-4o-mini", + name: "OpenAI: GPT-4o-mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o-mini-2024-07-18": { + id: "openai/gpt-4o-mini-2024-07-18", + name: "OpenAI: GPT-4o-mini (2024-07-18)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o:extended": { + id: "openai/gpt-4o:extended", + name: "OpenAI: GPT-4o (extended)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 6, + output: 18, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "openai/gpt-5": { + id: "openai/gpt-5", + name: "OpenAI: GPT-5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-codex": { + id: "openai/gpt-5-codex", + name: "OpenAI: GPT-5 Codex", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-image": { + id: "openai/gpt-5-image", + name: "OpenAI: GPT-5 Image", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 10, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-image-mini": { + id: "openai/gpt-5-image-mini", + name: "OpenAI: GPT-5 Image Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 2, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-mini": { + id: "openai/gpt-5-mini", + name: "OpenAI: GPT-5 Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-nano": { + id: "openai/gpt-5-nano", + name: "OpenAI: GPT-5 Nano", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.049999999999999996, + output: 0.39999999999999997, + cacheRead: 5e-3, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-pro": { + id: "openai/gpt-5-pro", + name: "OpenAI: GPT-5 Pro", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 120, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1": { + id: "openai/gpt-5.1", + name: "OpenAI: GPT-5.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1-chat": { + id: "openai/gpt-5.1-chat", + name: "OpenAI: GPT-5.1 Chat", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5.1-codex": { + id: "openai/gpt-5.1-codex", + name: "OpenAI: GPT-5.1-Codex", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1-codex-max": { + id: "openai/gpt-5.1-codex-max", + name: "OpenAI: GPT-5.1-Codex-Max", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1-codex-mini": { + id: "openai/gpt-5.1-codex-mini", + name: "OpenAI: GPT-5.1-Codex-Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 1e5 + }, + "openai/gpt-5.2": { + id: "openai/gpt-5.2", + name: "OpenAI: GPT-5.2", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.2-chat": { + id: "openai/gpt-5.2-chat", + name: "OpenAI: GPT-5.2 Chat", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5.2-codex": { + id: "openai/gpt-5.2-codex", + name: "OpenAI: GPT-5.2-Codex", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.2-pro": { + id: "openai/gpt-5.2-pro", + name: "OpenAI: GPT-5.2 Pro", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 21, + output: 168, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.3-chat": { + id: "openai/gpt-5.3-chat", + name: "OpenAI: GPT-5.3 Chat", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5.3-codex": { + id: "openai/gpt-5.3-codex", + name: "OpenAI: GPT-5.3-Codex", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.4": { + id: "openai/gpt-5.4", + name: "OpenAI: GPT-5.4", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 15, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "openai/gpt-5.4-pro": { + id: "openai/gpt-5.4-pro", + name: "OpenAI: GPT-5.4 Pro", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 30, + output: 180, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "openai/gpt-oss-120b": { + id: "openai/gpt-oss-120b", + name: "OpenAI: gpt-oss-120b", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.039, + output: 0.19, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "openai/gpt-oss-120b:free": { + id: "openai/gpt-oss-120b:free", + name: "OpenAI: gpt-oss-120b (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "openai/gpt-oss-20b": { + id: "openai/gpt-oss-20b", + name: "OpenAI: gpt-oss-20b", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.03, + output: 0.14, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "openai/gpt-oss-20b:free": { + id: "openai/gpt-oss-20b:free", + name: "OpenAI: gpt-oss-20b (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "openai/gpt-oss-safeguard-20b": { + id: "openai/gpt-oss-safeguard-20b", + name: "OpenAI: gpt-oss-safeguard-20b", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0.037, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + }, + "openai/o1": { + id: "openai/o1", + name: "OpenAI: o1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 15, + output: 60, + cacheRead: 7.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3": { + id: "openai/o3", + name: "OpenAI: o3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-deep-research": { + id: "openai/o3-deep-research", + name: "OpenAI: o3 Deep Research", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 10, + output: 40, + cacheRead: 2.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-mini": { + id: "openai/o3-mini", + name: "OpenAI: o3 Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.55, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-mini-high": { + id: "openai/o3-mini-high", + name: "OpenAI: o3 Mini High", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.55, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-pro": { + id: "openai/o3-pro", + name: "OpenAI: o3 Pro", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 20, + output: 80, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o4-mini": { + id: "openai/o4-mini", + name: "OpenAI: o4 Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.275, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o4-mini-deep-research": { + id: "openai/o4-mini-deep-research", + name: "OpenAI: o4 Mini Deep Research", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o4-mini-high": { + id: "openai/o4-mini-high", + name: "OpenAI: o4 Mini High", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.275, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openrouter/auto": { + id: "openrouter/auto", + name: "Auto Router", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: -1e6, + output: -1e6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 4096 + }, + "openrouter/free": { + id: "openrouter/free", + name: "Free Models Router", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "openrouter/healer-alpha": { + id: "openrouter/healer-alpha", + name: "Healer Alpha", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32e3 + }, + "openrouter/hunter-alpha": { + id: "openrouter/hunter-alpha", + name: "Hunter Alpha", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 32e3 + }, + "prime-intellect/intellect-3": { + id: "prime-intellect/intellect-3", + name: "Prime Intellect: INTELLECT-3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 1.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "qwen/qwen-2.5-72b-instruct": { + id: "qwen/qwen-2.5-72b-instruct", + name: "Qwen2.5 72B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.12, + output: 0.39, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 16384 + }, + "qwen/qwen-2.5-7b-instruct": { + id: "qwen/qwen-2.5-7b-instruct", + name: "Qwen: Qwen2.5 7B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.04, + output: 0.09999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 4096 + }, + "qwen/qwen-max": { + id: "qwen/qwen-max", + name: "Qwen: Qwen-Max ", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1.04, + output: 4.16, + cacheRead: 0.20800000000000002, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 8192 + }, + "qwen/qwen-plus": { + id: "qwen/qwen-plus", + name: "Qwen: Qwen-Plus", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 1.2, + cacheRead: 0.08, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 32768 + }, + "qwen/qwen-plus-2025-07-28": { + id: "qwen/qwen-plus-2025-07-28", + name: "Qwen: Qwen Plus 0728", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.26, + output: 0.78, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 32768 + }, + "qwen/qwen-plus-2025-07-28:thinking": { + id: "qwen/qwen-plus-2025-07-28:thinking", + name: "Qwen: Qwen Plus 0728 (thinking)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.26, + output: 0.78, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 32768 + }, + "qwen/qwen-turbo": { + id: "qwen/qwen-turbo", + name: "Qwen: Qwen-Turbo", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.0325, + output: 0.13, + cacheRead: 0.006500000000000001, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "qwen/qwen-vl-max": { + id: "qwen/qwen-vl-max", + name: "Qwen: Qwen VL Max", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.7999999999999999, + output: 3.1999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-14b": { + id: "qwen/qwen3-14b", + name: "Qwen: Qwen3 14B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.06, + output: 0.24, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 40960 + }, + "qwen/qwen3-235b-a22b": { + id: "qwen/qwen3-235b-a22b", + name: "Qwen: Qwen3 235B A22B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.45499999999999996, + output: 1.8199999999999998, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "qwen/qwen3-235b-a22b-2507": { + id: "qwen/qwen3-235b-a22b-2507", + name: "Qwen: Qwen3 235B A22B Instruct 2507", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.071, + output: 0.09999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "qwen/qwen3-235b-a22b-thinking-2507": { + id: "qwen/qwen3-235b-a22b-thinking-2507", + name: "Qwen: Qwen3 235B A22B Thinking 2507", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.11, + output: 0.6, + cacheRead: 0.055, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "qwen/qwen3-30b-a3b": { + id: "qwen/qwen3-30b-a3b", + name: "Qwen: Qwen3 30B A3B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.08, + output: 0.28, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 40960 + }, + "qwen/qwen3-30b-a3b-instruct-2507": { + id: "qwen/qwen3-30b-a3b-instruct-2507", + name: "Qwen: Qwen3 30B A3B Instruct 2507", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 262144 + }, + "qwen/qwen3-30b-a3b-thinking-2507": { + id: "qwen/qwen3-30b-a3b-thinking-2507", + name: "Qwen: Qwen3 30B A3B Thinking 2507", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.051, + output: 0.33999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 4096 + }, + "qwen/qwen3-32b": { + id: "qwen/qwen3-32b", + name: "Qwen: Qwen3 32B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.08, + output: 0.24, + cacheRead: 0.04, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 40960 + }, + "qwen/qwen3-4b:free": { + id: "qwen/qwen3-4b:free", + name: "Qwen: Qwen3 4B (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 4096 + }, + "qwen/qwen3-8b": { + id: "qwen/qwen3-8b", + name: "Qwen: Qwen3 8B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.049999999999999996, + output: 0.39999999999999997, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 8192 + }, + "qwen/qwen3-coder": { + id: "qwen/qwen3-coder", + name: "Qwen: Qwen3 Coder 480B A35B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.22, + output: 1, + cacheRead: 0.022, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "qwen/qwen3-coder-30b-a3b-instruct": { + id: "qwen/qwen3-coder-30b-a3b-instruct", + name: "Qwen: Qwen3 Coder 30B A3B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.07, + output: 0.27, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 16e4, + maxTokens: 32768 + }, + "qwen/qwen3-coder-flash": { + id: "qwen/qwen3-coder-flash", + name: "Qwen: Qwen3 Coder Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.195, + output: 0.975, + cacheRead: 0.039, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "qwen/qwen3-coder-next": { + id: "qwen/qwen3-coder-next", + name: "Qwen: Qwen3 Coder Next", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.12, + output: 0.75, + cacheRead: 0.06, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "qwen/qwen3-coder-plus": { + id: "qwen/qwen3-coder-plus", + name: "Qwen: Qwen3 Coder Plus", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.65, + output: 3.25, + cacheRead: 0.13, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "qwen/qwen3-coder:free": { + id: "qwen/qwen3-coder:free", + name: "Qwen: Qwen3 Coder 480B A35B (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262e3, + maxTokens: 262e3 + }, + "qwen/qwen3-max": { + id: "qwen/qwen3-max", + name: "Qwen: Qwen3 Max", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1.2, + output: 6, + cacheRead: 0.24, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "qwen/qwen3-max-thinking": { + id: "qwen/qwen3-max-thinking", + name: "Qwen: Qwen3 Max Thinking", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.78, + output: 3.9, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "qwen/qwen3-next-80b-a3b-instruct": { + id: "qwen/qwen3-next-80b-a3b-instruct", + name: "Qwen: Qwen3 Next 80B A3B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09, + output: 1.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "qwen/qwen3-next-80b-a3b-instruct:free": { + id: "qwen/qwen3-next-80b-a3b-instruct:free", + name: "Qwen: Qwen3 Next 80B A3B Instruct (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "qwen/qwen3-next-80b-a3b-thinking": { + id: "qwen/qwen3-next-80b-a3b-thinking", + name: "Qwen: Qwen3 Next 80B A3B Thinking", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.0975, + output: 0.78, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-vl-235b-a22b-instruct": { + id: "qwen/qwen3-vl-235b-a22b-instruct", + name: "Qwen: Qwen3 VL 235B A22B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.19999999999999998, + output: 0.88, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 4096 + }, + "qwen/qwen3-vl-235b-a22b-thinking": { + id: "qwen/qwen3-vl-235b-a22b-thinking", + name: "Qwen: Qwen3 VL 235B A22B Thinking", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.26, + output: 2.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-vl-30b-a3b-instruct": { + id: "qwen/qwen3-vl-30b-a3b-instruct", + name: "Qwen: Qwen3 VL 30B A3B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.13, + output: 0.52, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-vl-30b-a3b-thinking": { + id: "qwen/qwen3-vl-30b-a3b-thinking", + name: "Qwen: Qwen3 VL 30B A3B Thinking", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.13, + output: 1.56, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-vl-32b-instruct": { + id: "qwen/qwen3-vl-32b-instruct", + name: "Qwen: Qwen3 VL 32B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.10400000000000001, + output: 0.41600000000000004, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-vl-8b-instruct": { + id: "qwen/qwen3-vl-8b-instruct", + name: "Qwen: Qwen3 VL 8B Instruct", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.08, + output: 0.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3-vl-8b-thinking": { + id: "qwen/qwen3-vl-8b-thinking", + name: "Qwen: Qwen3 VL 8B Thinking", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.117, + output: 1.365, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 32768 + }, + "qwen/qwen3.5-122b-a10b": { + id: "qwen/qwen3.5-122b-a10b", + name: "Qwen: Qwen3.5-122B-A10B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.26, + output: 2.08, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "qwen/qwen3.5-27b": { + id: "qwen/qwen3.5-27b", + name: "Qwen: Qwen3.5-27B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.195, + output: 1.56, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "qwen/qwen3.5-35b-a3b": { + id: "qwen/qwen3.5-35b-a3b", + name: "Qwen: Qwen3.5-35B-A3B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.1625, + output: 1.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "qwen/qwen3.5-397b-a17b": { + id: "qwen/qwen3.5-397b-a17b", + name: "Qwen: Qwen3.5 397B A17B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.39, + output: 2.34, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "qwen/qwen3.5-9b": { + id: "qwen/qwen3.5-9b", + name: "Qwen: Qwen3.5-9B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.049999999999999996, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 4096 + }, + "qwen/qwen3.5-flash-02-23": { + id: "qwen/qwen3.5-flash-02-23", + name: "Qwen: Qwen3.5-Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "qwen/qwen3.5-plus-02-15": { + id: "qwen/qwen3.5-plus-02-15", + name: "Qwen: Qwen3.5 Plus 2026-02-15", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.26, + output: 1.56, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "qwen/qwq-32b": { + id: "qwen/qwq-32b", + name: "Qwen: QwQ 32B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 32768 + }, + "relace/relace-search": { + id: "relace/relace-search", + name: "Relace: Relace Search", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 128e3 + }, + "sao10k/l3-euryale-70b": { + id: "sao10k/l3-euryale-70b", + name: "Sao10k: Llama 3 Euryale 70B v2.1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 1.48, + output: 1.48, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 8192 + }, + "sao10k/l3.1-euryale-70b": { + id: "sao10k/l3.1-euryale-70b", + name: "Sao10K: Llama 3.1 Euryale 70B v2.2", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.85, + output: 0.85, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "stepfun/step-3.5-flash": { + id: "stepfun/step-3.5-flash", + name: "StepFun: Step 3.5 Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0.02, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "stepfun/step-3.5-flash:free": { + id: "stepfun/step-3.5-flash:free", + name: "StepFun: Step 3.5 Flash (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "thedrummer/rocinante-12b": { + id: "thedrummer/rocinante-12b", + name: "TheDrummer: Rocinante 12B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.16999999999999998, + output: 0.43, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 32768 + }, + "thedrummer/unslopnemo-12b": { + id: "thedrummer/unslopnemo-12b", + name: "TheDrummer: UnslopNemo 12B", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 32768 + }, + "tngtech/deepseek-r1t2-chimera": { + id: "tngtech/deepseek-r1t2-chimera", + name: "TNG: DeepSeek R1T2 Chimera", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.25, + output: 0.85, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 163840 + }, + "upstage/solar-pro-3": { + id: "upstage/solar-pro-3", + name: "Upstage: Solar Pro 3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.015, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "x-ai/grok-3": { + id: "x-ai/grok-3", + name: "xAI: Grok 3", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "x-ai/grok-3-beta": { + id: "x-ai/grok-3-beta", + name: "xAI: Grok 3 Beta", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "x-ai/grok-3-mini": { + id: "x-ai/grok-3-mini", + name: "xAI: Grok 3 Mini", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 0.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "x-ai/grok-3-mini-beta": { + id: "x-ai/grok-3-mini-beta", + name: "xAI: Grok 3 Mini Beta", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 0.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "x-ai/grok-4": { + id: "x-ai/grok-4", + name: "xAI: Grok 4", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 4096 + }, + "x-ai/grok-4-fast": { + id: "x-ai/grok-4-fast", + name: "xAI: Grok 4 Fast", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.19999999999999998, + output: 0.5, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "x-ai/grok-4.1-fast": { + id: "x-ai/grok-4.1-fast", + name: "xAI: Grok 4.1 Fast", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.19999999999999998, + output: 0.5, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "x-ai/grok-4.20-beta": { + id: "x-ai/grok-4.20-beta", + name: "xAI: Grok 4.20 Beta", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 4096 + }, + "x-ai/grok-code-fast-1": { + id: "x-ai/grok-code-fast-1", + name: "xAI: Grok Code Fast 1", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 1.5, + cacheRead: 0.02, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 1e4 + }, + "xiaomi/mimo-v2-flash": { + id: "xiaomi/mimo-v2-flash", + name: "Xiaomi: MiMo-V2-Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.09, + output: 0.29, + cacheRead: 0.045, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 65536 + }, + "z-ai/glm-4-32b": { + id: "z-ai/glm-4-32b", + name: "Z.ai: GLM 4 32B ", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.09999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "z-ai/glm-4.5": { + id: "z-ai/glm-4.5", + name: "Z.ai: GLM 4.5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 98304 + }, + "z-ai/glm-4.5-air": { + id: "z-ai/glm-4.5-air", + name: "Z.ai: GLM 4.5 Air", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.13, + output: 0.85, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 98304 + }, + "z-ai/glm-4.5-air:free": { + id: "z-ai/glm-4.5-air:free", + name: "Z.ai: GLM 4.5 Air (free)", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 96e3 + }, + "z-ai/glm-4.5v": { + id: "z-ai/glm-4.5v", + name: "Z.ai: GLM 4.5V", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 1.7999999999999998, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 65536, + maxTokens: 16384 + }, + "z-ai/glm-4.6": { + id: "z-ai/glm-4.6", + name: "Z.ai: GLM 4.6", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.39, + output: 1.9, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 204800 + }, + "z-ai/glm-4.6v": { + id: "z-ai/glm-4.6v", + name: "Z.ai: GLM 4.6V", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 0.8999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "z-ai/glm-4.7": { + id: "z-ai/glm-4.7", + name: "Z.ai: GLM 4.7", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.38, + output: 1.9800000000000002, + cacheRead: 0.19, + cacheWrite: 0 + }, + contextWindow: 202752, + maxTokens: 4096 + }, + "z-ai/glm-4.7-flash": { + id: "z-ai/glm-4.7-flash", + name: "Z.ai: GLM 4.7 Flash", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.06, + output: 0.39999999999999997, + cacheRead: 0.0100000002, + cacheWrite: 0 + }, + contextWindow: 202752, + maxTokens: 4096 + }, + "z-ai/glm-5": { + id: "z-ai/glm-5", + name: "Z.ai: GLM 5", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 1.9, + cacheRead: 0.119, + cacheWrite: 0 + }, + contextWindow: 202752, + maxTokens: 131072 + }, + "z-ai/glm-5-turbo": { + id: "z-ai/glm-5-turbo", + name: "Z.ai: GLM 5 Turbo", + api: "openai-completions", + provider: "openrouter", + baseUrl: "https://openrouter.ai/api/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.96, + output: 3.1999999999999997, + cacheRead: 0.192, + cacheWrite: 0 + }, + contextWindow: 202752, + maxTokens: 131072 + } + }, + "vercel-ai-gateway": { + "alibaba/qwen-3-14b": { + id: "alibaba/qwen-3-14b", + name: "Qwen3-14B", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.06, + output: 0.24, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 16384 + }, + "alibaba/qwen-3-235b": { + id: "alibaba/qwen-3-235b", + name: "Qwen3-235B-A22B", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.071, + output: 0.463, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 16384 + }, + "alibaba/qwen-3-30b": { + id: "alibaba/qwen-3-30b", + name: "Qwen3-30B-A3B", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.08, + output: 0.29, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 40960, + maxTokens: 16384 + }, + "alibaba/qwen-3-32b": { + id: "alibaba/qwen-3-32b", + name: "Qwen 3 32B", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.29, + output: 0.59, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 40960 + }, + "alibaba/qwen3-235b-a22b-thinking": { + id: "alibaba/qwen3-235b-a22b-thinking", + name: "Qwen3 235B A22B Thinking 2507", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.9000000000000004, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262114, + maxTokens: 262114 + }, + "alibaba/qwen3-coder": { + id: "alibaba/qwen3-coder", + name: "Qwen3 Coder 480B A35B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.39999999999999997, + output: 1.5999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 66536 + }, + "alibaba/qwen3-coder-30b-a3b": { + id: "alibaba/qwen3-coder-30b-a3b", + name: "Qwen 3 Coder 30B A3B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 8192 + }, + "alibaba/qwen3-coder-next": { + id: "alibaba/qwen3-coder-next", + name: "Qwen3 Coder Next", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.5, + output: 1.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "alibaba/qwen3-coder-plus": { + id: "alibaba/qwen3-coder-plus", + name: "Qwen3 Coder Plus", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 1, + output: 5, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "alibaba/qwen3-max": { + id: "alibaba/qwen3-max", + name: "Qwen3 Max", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 1.2, + output: 6, + cacheRead: 0.24, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "alibaba/qwen3-max-preview": { + id: "alibaba/qwen3-max-preview", + name: "Qwen3 Max Preview", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 1.2, + output: 6, + cacheRead: 0.24, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32768 + }, + "alibaba/qwen3-max-thinking": { + id: "alibaba/qwen3-max-thinking", + name: "Qwen 3 Max Thinking", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 1.2, + output: 6, + cacheRead: 0.24, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 65536 + }, + "alibaba/qwen3-vl-thinking": { + id: "alibaba/qwen3-vl-thinking", + name: "Qwen3 VL 235B A22B Thinking", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.22, + output: 0.88, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "alibaba/qwen3.5-flash": { + id: "alibaba/qwen3.5-flash", + name: "Qwen 3.5 Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 1e-3, + cacheWrite: 0.125 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "alibaba/qwen3.5-plus": { + id: "alibaba/qwen3.5-plus", + name: "Qwen 3.5 Plus", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 2.4, + cacheRead: 0.04, + cacheWrite: 0.5 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "anthropic/claude-3-haiku": { + id: "anthropic/claude-3-haiku", + name: "Claude 3 Haiku", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.25, + cacheRead: 0.03, + cacheWrite: 0.3 + }, + contextWindow: 2e5, + maxTokens: 4096 + }, + "anthropic/claude-3.5-haiku": { + id: "anthropic/claude-3.5-haiku", + name: "Claude 3.5 Haiku", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.7999999999999999, + output: 4, + cacheRead: 0.08, + cacheWrite: 1 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic/claude-3.5-sonnet": { + id: "anthropic/claude-3.5-sonnet", + name: "Claude 3.5 Sonnet", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic/claude-3.5-sonnet-20240620": { + id: "anthropic/claude-3.5-sonnet-20240620", + name: "Claude 3.5 Sonnet (2024-06-20)", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic/claude-3.7-sonnet": { + id: "anthropic/claude-3.7-sonnet", + name: "Claude 3.7 Sonnet", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 2e5, + maxTokens: 8192 + }, + "anthropic/claude-haiku-4.5": { + id: "anthropic/claude-haiku-4.5", + name: "Claude Haiku 4.5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1, + output: 5, + cacheRead: 0.09999999999999999, + cacheWrite: 1.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-opus-4": { + id: "anthropic/claude-opus-4", + name: "Claude Opus 4", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "anthropic/claude-opus-4.1": { + id: "anthropic/claude-opus-4.1", + name: "Claude Opus 4.1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 75, + cacheRead: 1.5, + cacheWrite: 18.75 + }, + contextWindow: 2e5, + maxTokens: 32e3 + }, + "anthropic/claude-opus-4.5": { + id: "anthropic/claude-opus-4.5", + name: "Claude Opus 4.5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 2e5, + maxTokens: 64e3 + }, + "anthropic/claude-opus-4.6": { + id: "anthropic/claude-opus-4.6", + name: "Claude Opus 4.6", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 5, + output: 25, + cacheRead: 0.5, + cacheWrite: 6.25 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "anthropic/claude-sonnet-4": { + id: "anthropic/claude-sonnet-4", + name: "Claude Sonnet 4", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "anthropic/claude-sonnet-4.5": { + id: "anthropic/claude-sonnet-4.5", + name: "Claude Sonnet 4.5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "anthropic/claude-sonnet-4.6": { + id: "anthropic/claude-sonnet-4.6", + name: "Claude Sonnet 4.6", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.3, + cacheWrite: 3.75 + }, + contextWindow: 1e6, + maxTokens: 128e3 + }, + "arcee-ai/trinity-large-preview": { + id: "arcee-ai/trinity-large-preview", + name: "Trinity Large Preview", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.25, + output: 1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131e3, + maxTokens: 131e3 + }, + "bytedance/seed-1.6": { + id: "bytedance/seed-1.6", + name: "Seed 1.6", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 32e3 + }, + "cohere/command-a": { + id: "cohere/command-a", + name: "Command A", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 2.5, + output: 10, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 8e3 + }, + "deepseek/deepseek-r1": { + id: "deepseek/deepseek-r1", + name: "DeepSeek-R1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 1.35, + output: 5.4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "deepseek/deepseek-v3": { + id: "deepseek/deepseek-v3", + name: "DeepSeek V3 0324", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.77, + output: 0.77, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 16384 + }, + "deepseek/deepseek-v3.1": { + id: "deepseek/deepseek-v3.1", + name: "DeepSeek-V3.1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.5, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 163840, + maxTokens: 16384 + }, + "deepseek/deepseek-v3.1-terminus": { + id: "deepseek/deepseek-v3.1-terminus", + name: "DeepSeek V3.1 Terminus", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.27, + output: 1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + }, + "deepseek/deepseek-v3.2": { + id: "deepseek/deepseek-v3.2", + name: "DeepSeek V3.2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.26, + output: 0.38, + cacheRead: 0.13, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8e3 + }, + "deepseek/deepseek-v3.2-thinking": { + id: "deepseek/deepseek-v3.2-thinking", + name: "DeepSeek V3.2 Thinking", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.28, + output: 0.42, + cacheRead: 0.028, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "google/gemini-2.0-flash": { + id: "google/gemini-2.0-flash", + name: "Gemini 2.0 Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "google/gemini-2.0-flash-lite": { + id: "google/gemini-2.0-flash-lite", + name: "Gemini 2.0 Flash Lite", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 8192 + }, + "google/gemini-2.5-flash": { + id: "google/gemini-2.5-flash", + name: "Gemini 2.5 Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "google/gemini-2.5-flash-lite": { + id: "google/gemini-2.5-flash-lite", + name: "Gemini 2.5 Flash Lite", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-2.5-flash-lite-preview-09-2025": { + id: "google/gemini-2.5-flash-lite-preview-09-2025", + name: "Gemini 2.5 Flash Lite Preview 09-2025", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-2.5-flash-preview-09-2025": { + id: "google/gemini-2.5-flash-preview-09-2025", + name: "Gemini 2.5 Flash Preview 09-2025", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 2.5, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65536 + }, + "google/gemini-2.5-pro": { + id: "google/gemini-2.5-pro", + name: "Gemini 2.5 Pro", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 1048576, + maxTokens: 65536 + }, + "google/gemini-3-flash": { + id: "google/gemini-3-flash", + name: "Gemini 3 Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.5, + output: 3, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65e3 + }, + "google/gemini-3-pro-preview": { + id: "google/gemini-3-pro-preview", + name: "Gemini 3 Pro Preview", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "google/gemini-3.1-flash-lite-preview": { + id: "google/gemini-3.1-flash-lite-preview", + name: "Gemini 3.1 Flash Lite Preview", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 65e3 + }, + "google/gemini-3.1-pro-preview": { + id: "google/gemini-3.1-pro-preview", + name: "Gemini 3.1 Pro Preview", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 12, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 1e6, + maxTokens: 64e3 + }, + "inception/mercury-2": { + id: "inception/mercury-2", + name: "Mercury 2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.25, + output: 0.75, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 128e3 + }, + "inception/mercury-coder-small": { + id: "inception/mercury-coder-small", + name: "Mercury Coder Small Beta", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.25, + output: 1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32e3, + maxTokens: 16384 + }, + "meituan/longcat-flash-chat": { + id: "meituan/longcat-flash-chat", + name: "LongCat Flash Chat", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 1e5 + }, + "meituan/longcat-flash-thinking": { + id: "meituan/longcat-flash-thinking", + name: "LongCat Flash Thinking", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.15, + output: 1.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "meta/llama-3.1-70b": { + id: "meta/llama-3.1-70b", + name: "Llama 3.1 70B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.72, + output: 0.72, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "meta/llama-3.1-8b": { + id: "meta/llama-3.1-8b", + name: "Llama 3.1 8B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.09999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "meta/llama-3.2-11b": { + id: "meta/llama-3.2-11b", + name: "Llama 3.2 11B Vision Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.16, + output: 0.16, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "meta/llama-3.2-90b": { + id: "meta/llama-3.2-90b", + name: "Llama 3.2 90B Vision Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.72, + output: 0.72, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "meta/llama-3.3-70b": { + id: "meta/llama-3.3-70b", + name: "Llama 3.3 70B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.72, + output: 0.72, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "meta/llama-4-maverick": { + id: "meta/llama-4-maverick", + name: "Llama 4 Maverick 17B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.24, + output: 0.9700000000000001, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "meta/llama-4-scout": { + id: "meta/llama-4-scout", + name: "Llama 4 Scout 17B Instruct", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.16999999999999998, + output: 0.66, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "minimax/minimax-m2": { + id: "minimax/minimax-m2", + name: "MiniMax M2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 205e3, + maxTokens: 205e3 + }, + "minimax/minimax-m2.1": { + id: "minimax/minimax-m2.1", + name: "MiniMax M2.1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "minimax/minimax-m2.1-lightning": { + id: "minimax/minimax-m2.1-lightning", + name: "MiniMax M2.1 Lightning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 2.4, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "minimax/minimax-m2.5": { + id: "minimax/minimax-m2.5", + name: "MiniMax M2.5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 1.2, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 204800, + maxTokens: 131e3 + }, + "minimax/minimax-m2.5-highspeed": { + id: "minimax/minimax-m2.5-highspeed", + name: "MiniMax M2.5 High Speed", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.4, + cacheRead: 0.03, + cacheWrite: 0.375 + }, + contextWindow: 4096, + maxTokens: 4096 + }, + "mistral/codestral": { + id: "mistral/codestral", + name: "Mistral Codestral", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.3, + output: 0.8999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "mistral/devstral-2": { + id: "mistral/devstral-2", + name: "Devstral 2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "mistral/devstral-small": { + id: "mistral/devstral-small", + name: "Devstral Small 1.1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "mistral/devstral-small-2": { + id: "mistral/devstral-small-2", + name: "Devstral Small 2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "mistral/ministral-3b": { + id: "mistral/ministral-3b", + name: "Ministral 3B", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.04, + output: 0.04, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "mistral/ministral-8b": { + id: "mistral/ministral-8b", + name: "Ministral 8B", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.09999999999999999, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "mistral/mistral-medium": { + id: "mistral/mistral-medium", + name: "Mistral Medium 3.1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 64e3 + }, + "mistral/mistral-small": { + id: "mistral/mistral-small", + name: "Mistral Small", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32e3, + maxTokens: 4e3 + }, + "mistral/pixtral-12b": { + id: "mistral/pixtral-12b", + name: "Pixtral 12B 2409", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "mistral/pixtral-large": { + id: "mistral/pixtral-large", + name: "Pixtral Large", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4e3 + }, + "moonshotai/kimi-k2": { + id: "moonshotai/kimi-k2", + name: "Kimi K2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.6, + output: 2.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 16384 + }, + "moonshotai/kimi-k2-0905": { + id: "moonshotai/kimi-k2-0905", + name: "Kimi K2 0905", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.6, + output: 2.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 16384 + }, + "moonshotai/kimi-k2-thinking": { + id: "moonshotai/kimi-k2-thinking", + name: "Kimi K2 Thinking", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.5, + cacheRead: 0.15, + cacheWrite: 0 + }, + contextWindow: 262114, + maxTokens: 262114 + }, + "moonshotai/kimi-k2-thinking-turbo": { + id: "moonshotai/kimi-k2-thinking-turbo", + name: "Kimi K2 Thinking Turbo", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 1.15, + output: 8, + cacheRead: 0.15, + cacheWrite: 0 + }, + contextWindow: 262114, + maxTokens: 262114 + }, + "moonshotai/kimi-k2-turbo": { + id: "moonshotai/kimi-k2-turbo", + name: "Kimi K2 Turbo", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 2.4, + output: 10, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 16384 + }, + "moonshotai/kimi-k2.5": { + id: "moonshotai/kimi-k2.5", + name: "Kimi K2.5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 3, + cacheRead: 0.09999999999999999, + cacheWrite: 0 + }, + contextWindow: 262114, + maxTokens: 262114 + }, + "nvidia/nemotron-nano-12b-v2-vl": { + id: "nvidia/nemotron-nano-12b-v2-vl", + name: "Nvidia Nemotron Nano 12B V2 VL", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.19999999999999998, + output: 0.6, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "nvidia/nemotron-nano-9b-v2": { + id: "nvidia/nemotron-nano-9b-v2", + name: "Nvidia Nemotron Nano 9B V2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.06, + output: 0.22999999999999998, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "openai/gpt-4-turbo": { + id: "openai/gpt-4-turbo", + name: "GPT-4 Turbo", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 10, + output: 30, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 4096 + }, + "openai/gpt-4.1": { + id: "openai/gpt-4.1", + name: "GPT-4.1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "openai/gpt-4.1-mini": { + id: "openai/gpt-4.1-mini", + name: "GPT-4.1 mini", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.39999999999999997, + output: 1.5999999999999999, + cacheRead: 0.09999999999999999, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "openai/gpt-4.1-nano": { + id: "openai/gpt-4.1-nano", + name: "GPT-4.1 nano", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.09999999999999999, + output: 0.39999999999999997, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 1047576, + maxTokens: 32768 + }, + "openai/gpt-4o": { + id: "openai/gpt-4o", + name: "GPT-4o", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2.5, + output: 10, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-4o-mini": { + id: "openai/gpt-4o-mini", + name: "GPT-4o mini", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.15, + output: 0.6, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5": { + id: "openai/gpt-5", + name: "GPT-5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-chat": { + id: "openai/gpt-5-chat", + name: "GPT 5 Chat", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5-codex": { + id: "openai/gpt-5-codex", + name: "GPT-5-Codex", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-mini": { + id: "openai/gpt-5-mini", + name: "GPT-5 mini", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-nano": { + id: "openai/gpt-5-nano", + name: "GPT-5 nano", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.049999999999999996, + output: 0.39999999999999997, + cacheRead: 5e-3, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5-pro": { + id: "openai/gpt-5-pro", + name: "GPT-5 pro", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 120, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 272e3 + }, + "openai/gpt-5.1-codex": { + id: "openai/gpt-5.1-codex", + name: "GPT-5.1-Codex", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1-codex-max": { + id: "openai/gpt-5.1-codex-max", + name: "GPT 5.1 Codex Max", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1-codex-mini": { + id: "openai/gpt-5.1-codex-mini", + name: "GPT 5.1 Codex Mini", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.25, + output: 2, + cacheRead: 0.024999999999999998, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.1-instant": { + id: "openai/gpt-5.1-instant", + name: "GPT-5.1 Instant", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5.1-thinking": { + id: "openai/gpt-5.1-thinking", + name: "GPT 5.1 Thinking", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.25, + output: 10, + cacheRead: 0.125, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.2": { + id: "openai/gpt-5.2", + name: "GPT 5.2", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.2-chat": { + id: "openai/gpt-5.2-chat", + name: "GPT 5.2 Chat", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5.2-codex": { + id: "openai/gpt-5.2-codex", + name: "GPT 5.2 Codex", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.2-pro": { + id: "openai/gpt-5.2-pro", + name: "GPT 5.2 ", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 21, + output: 168, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.3-chat": { + id: "openai/gpt-5.3-chat", + name: "GPT-5.3 Chat", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 16384 + }, + "openai/gpt-5.3-codex": { + id: "openai/gpt-5.3-codex", + name: "GPT 5.3 Codex", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.75, + output: 14, + cacheRead: 0.175, + cacheWrite: 0 + }, + contextWindow: 4e5, + maxTokens: 128e3 + }, + "openai/gpt-5.4": { + id: "openai/gpt-5.4", + name: "GPT 5.4", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2.5, + output: 15, + cacheRead: 0.25, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "openai/gpt-5.4-pro": { + id: "openai/gpt-5.4-pro", + name: "GPT 5.4 Pro", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 30, + output: 180, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 105e4, + maxTokens: 128e3 + }, + "openai/gpt-oss-20b": { + id: "openai/gpt-oss-20b", + name: "gpt-oss-20b", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.07, + output: 0.3, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 8192 + }, + "openai/gpt-oss-safeguard-20b": { + id: "openai/gpt-oss-safeguard-20b", + name: "gpt-oss-safeguard-20b", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.075, + output: 0.3, + cacheRead: 0.037, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 65536 + }, + "openai/o1": { + id: "openai/o1", + name: "o1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 15, + output: 60, + cacheRead: 7.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3": { + id: "openai/o3", + name: "o3", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 8, + cacheRead: 0.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-deep-research": { + id: "openai/o3-deep-research", + name: "o3-deep-research", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 10, + output: 40, + cacheRead: 2.5, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-mini": { + id: "openai/o3-mini", + name: "o3-mini", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.55, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o3-pro": { + id: "openai/o3-pro", + name: "o3 Pro", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 20, + output: 80, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "openai/o4-mini": { + id: "openai/o4-mini", + name: "o4-mini", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 1.1, + output: 4.4, + cacheRead: 0.275, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 1e5 + }, + "perplexity/sonar": { + id: "perplexity/sonar", + name: "Sonar", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 1, + output: 1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 127e3, + maxTokens: 8e3 + }, + "perplexity/sonar-pro": { + id: "perplexity/sonar-pro", + name: "Sonar Pro", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 8e3 + }, + "prime-intellect/intellect-3": { + id: "prime-intellect/intellect-3", + name: "INTELLECT 3", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 1.1, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "vercel/v0-1.0-md": { + id: "vercel/v0-1.0-md", + name: "v0-1.0-md", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32e3 + }, + "vercel/v0-1.5-md": { + id: "vercel/v0-1.5-md", + name: "v0-1.5-md", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32768 + }, + "xai/grok-2-vision": { + id: "xai/grok-2-vision", + name: "Grok 2 Vision", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 10, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 32768, + maxTokens: 32768 + }, + "xai/grok-3": { + id: "xai/grok-3", + name: "Grok 3 Beta", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 3, + output: 15, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "xai/grok-3-fast": { + id: "xai/grok-3-fast", + name: "Grok 3 Fast Beta", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 5, + output: 25, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "xai/grok-3-mini": { + id: "xai/grok-3-mini", + name: "Grok 3 Mini Beta", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.3, + output: 0.5, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "xai/grok-3-mini-fast": { + id: "xai/grok-3-mini-fast", + name: "Grok 3 Mini Fast Beta", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.6, + output: 4, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 131072 + }, + "xai/grok-4": { + id: "xai/grok-4", + name: "Grok 4", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "xai/grok-4-fast-non-reasoning": { + id: "xai/grok-4-fast-non-reasoning", + name: "Grok 4 Fast Non-Reasoning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.5, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 256e3 + }, + "xai/grok-4-fast-reasoning": { + id: "xai/grok-4-fast-reasoning", + name: "Grok 4 Fast Reasoning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.5, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 256e3 + }, + "xai/grok-4.1-fast-non-reasoning": { + id: "xai/grok-4.1-fast-non-reasoning", + name: "Grok 4.1 Fast Non-Reasoning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.5, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "xai/grok-4.1-fast-reasoning": { + id: "xai/grok-4.1-fast-reasoning", + name: "Grok 4.1 Fast Reasoning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 0.5, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "xai/grok-4.20-multi-agent-beta": { + id: "xai/grok-4.20-multi-agent-beta", + name: "Grok 4.20 Multi Agent Beta", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 2, + output: 6, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 2e6 + }, + "xai/grok-4.20-non-reasoning-beta": { + id: "xai/grok-4.20-non-reasoning-beta", + name: "Grok 4.20 Beta Non-Reasoning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 2e6 + }, + "xai/grok-4.20-reasoning-beta": { + id: "xai/grok-4.20-reasoning-beta", + name: "Grok 4.20 Beta Reasoning", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 2e6 + }, + "xai/grok-code-fast-1": { + id: "xai/grok-code-fast-1", + name: "Grok Code Fast 1", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 1.5, + cacheRead: 0.02, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 256e3 + }, + "xiaomi/mimo-v2-flash": { + id: "xiaomi/mimo-v2-flash", + name: "MiMo V2 Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.09999999999999999, + output: 0.3, + cacheRead: 0.02, + cacheWrite: 0 + }, + contextWindow: 262144, + maxTokens: 32e3 + }, + "zai/glm-4.5": { + id: "zai/glm-4.5", + name: "GLM-4.5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 96e3 + }, + "zai/glm-4.5-air": { + id: "zai/glm-4.5-air", + name: "GLM 4.5 Air", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.19999999999999998, + output: 1.1, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 96e3 + }, + "zai/glm-4.5v": { + id: "zai/glm-4.5v", + name: "GLM 4.5V", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.6, + output: 1.7999999999999998, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 66e3, + maxTokens: 16e3 + }, + "zai/glm-4.6": { + id: "zai/glm-4.6", + name: "GLM 4.6", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.44999999999999996, + output: 1.7999999999999998, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 96e3 + }, + "zai/glm-4.6v": { + id: "zai/glm-4.6v", + name: "GLM-4.6V", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 0.8999999999999999, + cacheRead: 0.049999999999999996, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 24e3 + }, + "zai/glm-4.6v-flash": { + id: "zai/glm-4.6v-flash", + name: "GLM-4.6V-Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 24e3 + }, + "zai/glm-4.7": { + id: "zai/glm-4.7", + name: "GLM 4.7", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 12e4 + }, + "zai/glm-4.7-flash": { + id: "zai/glm-4.7-flash", + name: "GLM 4.7 Flash", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.07, + output: 0.39999999999999997, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 131e3 + }, + "zai/glm-4.7-flashx": { + id: "zai/glm-4.7-flashx", + name: "GLM 4.7 FlashX", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 0.06, + output: 0.39999999999999997, + cacheRead: 0.01, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 128e3 + }, + "zai/glm-5": { + id: "zai/glm-5", + name: "GLM 5", + api: "anthropic-messages", + provider: "vercel-ai-gateway", + baseUrl: "https://ai-gateway.vercel.sh", + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3.1999999999999997, + cacheRead: 0.19999999999999998, + cacheWrite: 0 + }, + contextWindow: 202800, + maxTokens: 131100 + } + }, + "xai": { + "grok-2": { + id: "grok-2", + name: "Grok 2", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 10, + cacheRead: 2, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-2-1212": { + id: "grok-2-1212", + name: "Grok 2 (1212)", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 10, + cacheRead: 2, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-2-latest": { + id: "grok-2-latest", + name: "Grok 2 Latest", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 2, + output: 10, + cacheRead: 2, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-2-vision": { + id: "grok-2-vision", + name: "Grok 2 Vision", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 10, + cacheRead: 2, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 4096 + }, + "grok-2-vision-1212": { + id: "grok-2-vision-1212", + name: "Grok 2 Vision (1212)", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 10, + cacheRead: 2, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 4096 + }, + "grok-2-vision-latest": { + id: "grok-2-vision-latest", + name: "Grok 2 Vision Latest", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 10, + cacheRead: 2, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 4096 + }, + "grok-3": { + id: "grok-3", + name: "Grok 3", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-fast": { + id: "grok-3-fast", + name: "Grok 3 Fast", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 5, + output: 25, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-fast-latest": { + id: "grok-3-fast-latest", + name: "Grok 3 Fast Latest", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 5, + output: 25, + cacheRead: 1.25, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-latest": { + id: "grok-3-latest", + name: "Grok 3 Latest", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-mini": { + id: "grok-3-mini", + name: "Grok 3 Mini", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 0.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-mini-fast": { + id: "grok-3-mini-fast", + name: "Grok 3 Mini Fast", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 4, + cacheRead: 0.15, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-mini-fast-latest": { + id: "grok-3-mini-fast-latest", + name: "Grok 3 Mini Fast Latest", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 4, + cacheRead: 0.15, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-3-mini-latest": { + id: "grok-3-mini-latest", + name: "Grok 3 Mini Latest", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.3, + output: 0.5, + cacheRead: 0.075, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 8192 + }, + "grok-4": { + id: "grok-4", + name: "Grok 4", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 3, + output: 15, + cacheRead: 0.75, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 64e3 + }, + "grok-4-1-fast": { + id: "grok-4-1-fast", + name: "Grok 4.1 Fast", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.2, + output: 0.5, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-4-1-fast-non-reasoning": { + id: "grok-4-1-fast-non-reasoning", + name: "Grok 4.1 Fast (Non-Reasoning)", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.2, + output: 0.5, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-4-fast": { + id: "grok-4-fast", + name: "Grok 4 Fast", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.2, + output: 0.5, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-4-fast-non-reasoning": { + id: "grok-4-fast-non-reasoning", + name: "Grok 4 Fast (Non-Reasoning)", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 0.2, + output: 0.5, + cacheRead: 0.05, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-4.20-beta-latest-non-reasoning": { + id: "grok-4.20-beta-latest-non-reasoning", + name: "Grok 4.20 Beta (Non-Reasoning)", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-4.20-beta-latest-reasoning": { + id: "grok-4.20-beta-latest-reasoning", + name: "Grok 4.20 Beta (Reasoning)", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-4.20-multi-agent-beta-latest": { + id: "grok-4.20-multi-agent-beta-latest", + name: "Grok 4.20 Multi-Agent Beta", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text", "image"], + cost: { + input: 2, + output: 6, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 2e6, + maxTokens: 3e4 + }, + "grok-beta": { + id: "grok-beta", + name: "Grok Beta", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text"], + cost: { + input: 5, + output: 15, + cacheRead: 5, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 4096 + }, + "grok-code-fast-1": { + id: "grok-code-fast-1", + name: "Grok Code Fast 1", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: true, + input: ["text"], + cost: { + input: 0.2, + output: 1.5, + cacheRead: 0.02, + cacheWrite: 0 + }, + contextWindow: 256e3, + maxTokens: 1e4 + }, + "grok-vision-beta": { + id: "grok-vision-beta", + name: "Grok Vision Beta", + api: "openai-completions", + provider: "xai", + baseUrl: "https://api.x.ai/v1", + reasoning: false, + input: ["text", "image"], + cost: { + input: 5, + output: 15, + cacheRead: 5, + cacheWrite: 0 + }, + contextWindow: 8192, + maxTokens: 4096 + } + }, + "zai": { + "glm-4.5": { + id: "glm-4.5", + name: "GLM-4.5", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 98304 + }, + "glm-4.5-air": { + id: "glm-4.5-air", + name: "GLM-4.5-Air", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 0.2, + output: 1.1, + cacheRead: 0.03, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 98304 + }, + "glm-4.5-flash": { + id: "glm-4.5-flash", + name: "GLM-4.5-Flash", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 131072, + maxTokens: 98304 + }, + "glm-4.5v": { + id: "glm-4.5v", + name: "GLM-4.5V", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.6, + output: 1.8, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 64e3, + maxTokens: 16384 + }, + "glm-4.6": { + id: "glm-4.6", + name: "GLM-4.6", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "glm-4.6v": { + id: "glm-4.6v", + name: "GLM-4.6V", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text", "image"], + cost: { + input: 0.3, + output: 0.9, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 128e3, + maxTokens: 32768 + }, + "glm-4.7": { + id: "glm-4.7", + name: "GLM-4.7", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 0.6, + output: 2.2, + cacheRead: 0.11, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + }, + "glm-4.7-flash": { + id: "glm-4.7-flash", + name: "GLM-4.7-Flash", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow: 2e5, + maxTokens: 131072 + }, + "glm-5": { + id: "glm-5", + name: "GLM-5", + api: "openai-completions", + provider: "zai", + baseUrl: "https://api.z.ai/api/coding/paas/v4", + compat: { "supportsDeveloperRole": false, "thinkingFormat": "zai" }, + reasoning: true, + input: ["text"], + cost: { + input: 1, + output: 3.2, + cacheRead: 0.2, + cacheWrite: 0 + }, + contextWindow: 204800, + maxTokens: 131072 + } + } + }; + } +}); + +// ../pi-mono/packages/ai/dist/models.js +function getModel2(provider, modelId) { + const providerModels = modelRegistry2.get(provider); + return providerModels?.get(modelId); +} +function getProviders() { + return Array.from(modelRegistry2.keys()); +} +function getModels(provider) { + const models = modelRegistry2.get(provider); + return models ? Array.from(models.values()) : []; +} +function calculateCost2(model, usage) { + usage.cost.input = model.cost.input / 1e6 * usage.input; + usage.cost.output = model.cost.output / 1e6 * usage.output; + usage.cost.cacheRead = model.cost.cacheRead / 1e6 * usage.cacheRead; + usage.cost.cacheWrite = model.cost.cacheWrite / 1e6 * usage.cacheWrite; + usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite; + return usage.cost; +} +function supportsXhigh2(model) { + if (model.id.includes("gpt-5.2") || model.id.includes("gpt-5.3") || model.id.includes("gpt-5.4")) { + return true; + } + if (model.id.includes("opus-4-6") || model.id.includes("opus-4.6")) { + return true; + } + return false; +} +function modelsAreEqual(a3, b4) { + if (!a3 || !b4) + return false; + return a3.id === b4.id && a3.provider === b4.provider; +} +var modelRegistry2; +var init_models4 = __esm({ + "../pi-mono/packages/ai/dist/models.js"() { + "use strict"; + init_process_shim(); + init_models_generated(); + modelRegistry2 = /* @__PURE__ */ new Map(); + for (const [provider, models] of Object.entries(MODELS2)) { + const providerModels = /* @__PURE__ */ new Map(); + for (const [id, model] of Object.entries(models)) { + providerModels.set(id, model); + } + modelRegistry2.set(provider, providerModels); + } + } +}); + +// ../pi-mono/packages/ai/dist/utils/event-stream.js +var EventStream3, AssistantMessageEventStream2; +var init_event_stream = __esm({ + "../pi-mono/packages/ai/dist/utils/event-stream.js"() { + "use strict"; + init_process_shim(); + EventStream3 = class { + isComplete; + extractResult; + queue = []; + waiting = []; + done = false; + finalResultPromise; + resolveFinalResult; + constructor(isComplete, extractResult) { + this.isComplete = isComplete; + this.extractResult = extractResult; + this.finalResultPromise = new Promise((resolve2) => { + this.resolveFinalResult = resolve2; + }); + } + push(event) { + if (this.done) + return; + if (this.isComplete(event)) { + this.done = true; + this.resolveFinalResult(this.extractResult(event)); + } + const waiter = this.waiting.shift(); + if (waiter) { + waiter({ value: event, done: false }); + } else { + this.queue.push(event); + } + } + end(result) { + this.done = true; + if (result !== void 0) { + this.resolveFinalResult(result); + } + while (this.waiting.length > 0) { + const waiter = this.waiting.shift(); + waiter({ value: void 0, done: true }); + } + } + async *[Symbol.asyncIterator]() { + while (true) { + if (this.queue.length > 0) { + yield this.queue.shift(); + } else if (this.done) { + return; + } else { + const result = await new Promise((resolve2) => this.waiting.push(resolve2)); + if (result.done) + return; + yield result.value; + } + } + } + result() { + return this.finalResultPromise; + } + }; + AssistantMessageEventStream2 = class extends EventStream3 { + constructor() { + super((event) => event.type === "done" || event.type === "error", (event) => { + if (event.type === "done") { + return event.message; + } else if (event.type === "error") { + return event.error; + } + throw new Error("Unexpected event type for final result"); + }); + } + }; + } +}); + +// ../pi-mono/packages/ai/dist/utils/json-parse.js +function parseStreamingJson2(partialJson) { + if (!partialJson || partialJson.trim() === "") { + return {}; + } + try { + return JSON.parse(partialJson); + } catch { + try { + const result = (0, import_partial_json2.parse)(partialJson); + return result ?? {}; + } catch { + return {}; + } + } +} +var import_partial_json2; +var init_json_parse = __esm({ + "../pi-mono/packages/ai/dist/utils/json-parse.js"() { + "use strict"; + init_process_shim(); + import_partial_json2 = __toESM(require_dist(), 1); + } +}); + +// ../pi-mono/packages/ai/dist/utils/sanitize-unicode.js +function sanitizeSurrogates2(text3) { + return text3.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + if (msg.role === "user" && Array.isArray(msg.content)) { + return msg.content.some((c6) => c6.type === "image"); + } + if (msg.role === "toolResult" && Array.isArray(msg.content)) { + return msg.content.some((c6) => c6.type === "image"); + } + return false; + }); +} +function buildCopilotDynamicHeaders2(params) { + const headers = { + "X-Initiator": inferCopilotInitiator2(params.messages), + "Openai-Intent": "conversation-edits" + }; + if (params.hasImages) { + headers["Copilot-Vision-Request"] = "true"; + } + return headers; +} +var init_github_copilot_headers = __esm({ + "../pi-mono/packages/ai/dist/providers/github-copilot-headers.js"() { + "use strict"; + init_process_shim(); + } +}); + +// ../pi-mono/packages/ai/dist/providers/simple-options.js +function buildBaseOptions2(model, options, apiKey) { + return { + temperature: options?.temperature, + maxTokens: options?.maxTokens || Math.min(model.maxTokens, 32e3), + signal: options?.signal, + apiKey: apiKey || options?.apiKey, + cacheRetention: options?.cacheRetention, + sessionId: options?.sessionId, + headers: options?.headers, + onPayload: options?.onPayload, + maxRetryDelayMs: options?.maxRetryDelayMs, + metadata: options?.metadata + }; +} +function clampReasoning2(effort) { + return effort === "xhigh" ? "high" : effort; +} +function adjustMaxTokensForThinking2(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) { + const defaultBudgets = { + minimal: 1024, + low: 2048, + medium: 8192, + high: 16384 + }; + const budgets = { ...defaultBudgets, ...customBudgets }; + const minOutputTokens = 1024; + const level = clampReasoning2(reasoningLevel); + let thinkingBudget = budgets[level]; + const maxTokens = Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens); + if (maxTokens <= thinkingBudget) { + thinkingBudget = Math.max(0, maxTokens - minOutputTokens); + } + return { maxTokens, thinkingBudget }; +} +var init_simple_options = __esm({ + "../pi-mono/packages/ai/dist/providers/simple-options.js"() { + "use strict"; + init_process_shim(); + } +}); + +// ../pi-mono/packages/ai/dist/providers/transform-messages.js +function transformMessages2(messages, model, normalizeToolCallId3) { + const toolCallIdMap = /* @__PURE__ */ new Map(); + const transformed = messages.map((msg) => { + if (msg.role === "user") { + return msg; + } + if (msg.role === "toolResult") { + const normalizedId = toolCallIdMap.get(msg.toolCallId); + if (normalizedId && normalizedId !== msg.toolCallId) { + return { ...msg, toolCallId: normalizedId }; + } + return msg; + } + if (msg.role === "assistant") { + const assistantMsg = msg; + const isSameModel = assistantMsg.provider === model.provider && assistantMsg.api === model.api && assistantMsg.model === model.id; + const transformedContent = assistantMsg.content.flatMap((block) => { + if (block.type === "thinking") { + if (block.redacted) { + return isSameModel ? block : []; + } + if (isSameModel && block.thinkingSignature) + return block; + if (!block.thinking || block.thinking.trim() === "") + return []; + if (isSameModel) + return block; + return { + type: "text", + text: block.thinking + }; + } + if (block.type === "text") { + if (isSameModel) + return block; + return { + type: "text", + text: block.text + }; + } + if (block.type === "toolCall") { + const toolCall = block; + let normalizedToolCall = toolCall; + if (!isSameModel && toolCall.thoughtSignature) { + normalizedToolCall = { ...toolCall }; + delete normalizedToolCall.thoughtSignature; + } + if (!isSameModel && normalizeToolCallId3) { + const normalizedId = normalizeToolCallId3(toolCall.id, model, assistantMsg); + if (normalizedId !== toolCall.id) { + toolCallIdMap.set(toolCall.id, normalizedId); + normalizedToolCall = { ...normalizedToolCall, id: normalizedId }; + } + } + return normalizedToolCall; + } + return block; + }); + return { + ...assistantMsg, + content: transformedContent + }; + } + return msg; + }); + const result = []; + let pendingToolCalls = []; + let existingToolResultIds = /* @__PURE__ */ new Set(); + for (let i7 = 0; i7 < transformed.length; i7++) { + const msg = transformed[i7]; + if (msg.role === "assistant") { + if (pendingToolCalls.length > 0) { + for (const tc of pendingToolCalls) { + if (!existingToolResultIds.has(tc.id)) { + result.push({ + role: "toolResult", + toolCallId: tc.id, + toolName: tc.name, + content: [{ type: "text", text: "No result provided" }], + isError: true, + timestamp: Date.now() + }); + } + } + pendingToolCalls = []; + existingToolResultIds = /* @__PURE__ */ new Set(); + } + const assistantMsg = msg; + if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") { + continue; + } + const toolCalls = assistantMsg.content.filter((b4) => b4.type === "toolCall"); + if (toolCalls.length > 0) { + pendingToolCalls = toolCalls; + existingToolResultIds = /* @__PURE__ */ new Set(); + } + result.push(msg); + } else if (msg.role === "toolResult") { + existingToolResultIds.add(msg.toolCallId); + result.push(msg); + } else if (msg.role === "user") { + if (pendingToolCalls.length > 0) { + for (const tc of pendingToolCalls) { + if (!existingToolResultIds.has(tc.id)) { + result.push({ + role: "toolResult", + toolCallId: tc.id, + toolName: tc.name, + content: [{ type: "text", text: "No result provided" }], + isError: true, + timestamp: Date.now() + }); + } + } + pendingToolCalls = []; + existingToolResultIds = /* @__PURE__ */ new Set(); + } + result.push(msg); + } else { + result.push(msg); + } + } + return result; +} +var init_transform_messages = __esm({ + "../pi-mono/packages/ai/dist/providers/transform-messages.js"() { + "use strict"; + init_process_shim(); + } +}); + +// ../pi-mono/packages/ai/dist/providers/anthropic.js +function resolveCacheRetention3(cacheRetention) { + if (cacheRetention) { + return cacheRetention; + } + if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") { + return "long"; + } + return "short"; +} +function getCacheControl2(baseUrl, cacheRetention) { + const retention = resolveCacheRetention3(cacheRetention); + if (retention === "none") { + return { retention }; + } + const ttl = retention === "long" && baseUrl.includes("api.anthropic.com") ? "1h" : void 0; + return { + retention, + cacheControl: { type: "ephemeral", ...ttl && { ttl } } + }; +} +function convertContentBlocks2(content) { + const hasImages = content.some((c6) => c6.type === "image"); + if (!hasImages) { + return sanitizeSurrogates2(content.map((c6) => c6.text).join("\n")); + } + const blocks = content.map((block) => { + if (block.type === "text") { + return { + type: "text", + text: sanitizeSurrogates2(block.text) + }; + } + return { + type: "image", + source: { + type: "base64", + media_type: block.mimeType, + data: block.data + } + }; + }); + const hasText = blocks.some((b4) => b4.type === "text"); + if (!hasText) { + blocks.unshift({ + type: "text", + text: "(see attached image)" + }); + } + return blocks; +} +function mergeHeaders2(...headerSources) { + const merged = {}; + for (const headers of headerSources) { + if (headers) { + Object.assign(merged, headers); + } + } + return merged; +} +function supportsAdaptiveThinking2(modelId) { + return modelId.includes("opus-4-6") || modelId.includes("opus-4.6") || modelId.includes("sonnet-4-6") || modelId.includes("sonnet-4.6"); +} +function mapThinkingLevelToEffort2(level, modelId) { + switch (level) { + case "minimal": + return "low"; + case "low": + return "low"; + case "medium": + return "medium"; + case "high": + return "high"; + case "xhigh": + return modelId.includes("opus-4-6") || modelId.includes("opus-4.6") ? "max" : "high"; + default: + return "high"; + } +} +function isOAuthToken2(apiKey) { + return apiKey.includes("sk-ant-oat"); +} +function createClient7(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders) { + const needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking2(model.id); + if (model.provider === "github-copilot") { + const betaFeatures2 = []; + if (needsInterleavedBeta) { + betaFeatures2.push("interleaved-thinking-2025-05-14"); + } + const client2 = new Anthropic({ + apiKey: null, + authToken: apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + defaultHeaders: mergeHeaders2({ + accept: "application/json", + "anthropic-dangerous-direct-browser-access": "true", + ...betaFeatures2.length > 0 ? { "anthropic-beta": betaFeatures2.join(",") } : {} + }, model.headers, dynamicHeaders, optionsHeaders) + }); + return { client: client2, isOAuthToken: false }; + } + const betaFeatures = ["fine-grained-tool-streaming-2025-05-14"]; + if (needsInterleavedBeta) { + betaFeatures.push("interleaved-thinking-2025-05-14"); + } + if (isOAuthToken2(apiKey)) { + const client2 = new Anthropic({ + apiKey: null, + authToken: apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + defaultHeaders: mergeHeaders2({ + accept: "application/json", + "anthropic-dangerous-direct-browser-access": "true", + "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`, + "user-agent": `claude-cli/${claudeCodeVersion2}`, + "x-app": "cli" + }, model.headers, optionsHeaders) + }); + return { client: client2, isOAuthToken: true }; + } + const client = new Anthropic({ + apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + defaultHeaders: mergeHeaders2({ + accept: "application/json", + "anthropic-dangerous-direct-browser-access": "true", + "anthropic-beta": betaFeatures.join(",") + }, model.headers, optionsHeaders) + }); + return { client, isOAuthToken: false }; +} +function buildParams7(model, context, isOAuthToken3, options) { + const { cacheControl } = getCacheControl2(model.baseUrl, options?.cacheRetention); + const params = { + model: model.id, + messages: convertMessages4(context.messages, model, isOAuthToken3, cacheControl), + max_tokens: options?.maxTokens || model.maxTokens / 3 | 0, + stream: true + }; + if (isOAuthToken3) { + params.system = [ + { + type: "text", + text: "You are Claude Code, Anthropic's official CLI for Claude.", + ...cacheControl ? { cache_control: cacheControl } : {} + } + ]; + if (context.systemPrompt) { + params.system.push({ + type: "text", + text: sanitizeSurrogates2(context.systemPrompt), + ...cacheControl ? { cache_control: cacheControl } : {} + }); + } + } else if (context.systemPrompt) { + params.system = [ + { + type: "text", + text: sanitizeSurrogates2(context.systemPrompt), + ...cacheControl ? { cache_control: cacheControl } : {} + } + ]; + } + if (options?.temperature !== void 0 && !options?.thinkingEnabled) { + params.temperature = options.temperature; + } + if (context.tools) { + params.tools = convertTools4(context.tools, isOAuthToken3); + } + if (options?.thinkingEnabled && model.reasoning) { + if (supportsAdaptiveThinking2(model.id)) { + params.thinking = { type: "adaptive" }; + if (options.effort) { + params.output_config = { effort: options.effort }; + } + } else { + params.thinking = { + type: "enabled", + budget_tokens: options.thinkingBudgetTokens || 1024 + }; + } + } + if (options?.metadata) { + const userId = options.metadata.user_id; + if (typeof userId === "string") { + params.metadata = { user_id: userId }; + } + } + if (options?.toolChoice) { + if (typeof options.toolChoice === "string") { + params.tool_choice = { type: options.toolChoice }; + } else { + params.tool_choice = options.toolChoice; + } + } + return params; +} +function normalizeToolCallId2(id) { + return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64); +} +function convertMessages4(messages, model, isOAuthToken3, cacheControl) { + const params = []; + const transformedMessages = transformMessages2(messages, model, normalizeToolCallId2); + for (let i7 = 0; i7 < transformedMessages.length; i7++) { + const msg = transformedMessages[i7]; + if (msg.role === "user") { + if (typeof msg.content === "string") { + if (msg.content.trim().length > 0) { + params.push({ + role: "user", + content: sanitizeSurrogates2(msg.content) + }); + } + } else { + const blocks = msg.content.map((item) => { + if (item.type === "text") { + return { + type: "text", + text: sanitizeSurrogates2(item.text) + }; + } else { + return { + type: "image", + source: { + type: "base64", + media_type: item.mimeType, + data: item.data + } + }; + } + }); + let filteredBlocks = !model?.input.includes("image") ? blocks.filter((b4) => b4.type !== "image") : blocks; + filteredBlocks = filteredBlocks.filter((b4) => { + if (b4.type === "text") { + return b4.text.trim().length > 0; + } + return true; + }); + if (filteredBlocks.length === 0) + continue; + params.push({ + role: "user", + content: filteredBlocks + }); + } + } else if (msg.role === "assistant") { + const blocks = []; + for (const block of msg.content) { + if (block.type === "text") { + if (block.text.trim().length === 0) + continue; + blocks.push({ + type: "text", + text: sanitizeSurrogates2(block.text) + }); + } else if (block.type === "thinking") { + if (block.redacted) { + blocks.push({ + type: "redacted_thinking", + data: block.thinkingSignature + }); + continue; + } + if (block.thinking.trim().length === 0) + continue; + if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) { + blocks.push({ + type: "text", + text: sanitizeSurrogates2(block.thinking) + }); + } else { + blocks.push({ + type: "thinking", + thinking: sanitizeSurrogates2(block.thinking), + signature: block.thinkingSignature + }); + } + } else if (block.type === "toolCall") { + blocks.push({ + type: "tool_use", + id: block.id, + name: isOAuthToken3 ? toClaudeCodeName2(block.name) : block.name, + input: block.arguments ?? {} + }); + } + } + if (blocks.length === 0) + continue; + params.push({ + role: "assistant", + content: blocks + }); + } else if (msg.role === "toolResult") { + const toolResults = []; + toolResults.push({ + type: "tool_result", + tool_use_id: msg.toolCallId, + content: convertContentBlocks2(msg.content), + is_error: msg.isError + }); + let j3 = i7 + 1; + while (j3 < transformedMessages.length && transformedMessages[j3].role === "toolResult") { + const nextMsg = transformedMessages[j3]; + toolResults.push({ + type: "tool_result", + tool_use_id: nextMsg.toolCallId, + content: convertContentBlocks2(nextMsg.content), + is_error: nextMsg.isError + }); + j3++; + } + i7 = j3 - 1; + params.push({ + role: "user", + content: toolResults + }); + } + } + if (cacheControl && params.length > 0) { + const lastMessage = params[params.length - 1]; + if (lastMessage.role === "user") { + if (Array.isArray(lastMessage.content)) { + const lastBlock = lastMessage.content[lastMessage.content.length - 1]; + if (lastBlock && (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result")) { + lastBlock.cache_control = cacheControl; + } + } else if (typeof lastMessage.content === "string") { + lastMessage.content = [ + { + type: "text", + text: lastMessage.content, + cache_control: cacheControl + } + ]; + } + } + } + return params; +} +function convertTools4(tools, isOAuthToken3) { + if (!tools) + return []; + return tools.map((tool) => { + const jsonSchema = tool.parameters; + return { + name: isOAuthToken3 ? toClaudeCodeName2(tool.name) : tool.name, + description: tool.description, + input_schema: { + type: "object", + properties: jsonSchema.properties || {}, + required: jsonSchema.required || [] + } + }; + }); +} +function mapStopReason5(reason) { + switch (reason) { + case "end_turn": + return "stop"; + case "max_tokens": + return "length"; + case "tool_use": + return "toolUse"; + case "refusal": + return "error"; + case "pause_turn": + return "stop"; + case "stop_sequence": + return "stop"; + // We don't supply stop sequences, so this should never happen + case "sensitive": + return "error"; + default: + throw new Error(`Unhandled stop reason: ${reason}`); + } +} +var claudeCodeVersion2, claudeCodeTools2, ccToolLookup2, toClaudeCodeName2, fromClaudeCodeName2, streamAnthropic2, streamSimpleAnthropic2; +var init_anthropic = __esm({ + "../pi-mono/packages/ai/dist/providers/anthropic.js"() { + "use strict"; + init_process_shim(); + init_sdk(); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_json_parse(); + init_sanitize_unicode(); + init_github_copilot_headers(); + init_simple_options(); + init_transform_messages(); + claudeCodeVersion2 = "2.1.75"; + claudeCodeTools2 = [ + "Read", + "Write", + "Edit", + "Bash", + "Grep", + "Glob", + "AskUserQuestion", + "EnterPlanMode", + "ExitPlanMode", + "KillShell", + "NotebookEdit", + "Skill", + "Task", + "TaskOutput", + "TodoWrite", + "WebFetch", + "WebSearch" + ]; + ccToolLookup2 = new Map(claudeCodeTools2.map((t6) => [t6.toLowerCase(), t6])); + toClaudeCodeName2 = (name) => ccToolLookup2.get(name.toLowerCase()) ?? name; + fromClaudeCodeName2 = (name, tools) => { + if (tools && tools.length > 0) { + const lowerName = name.toLowerCase(); + const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName); + if (matchedTool) + return matchedTool.name; + } + return name; + }; + streamAnthropic2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = options?.apiKey ?? getEnvApiKey2(model.provider) ?? ""; + let copilotDynamicHeaders; + if (model.provider === "github-copilot") { + const hasImages = hasCopilotVisionInput2(context.messages); + copilotDynamicHeaders = buildCopilotDynamicHeaders2({ + messages: context.messages, + hasImages + }); + } + const { client, isOAuthToken: isOAuthToken3 } = createClient7(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders); + let params = buildParams7(model, context, isOAuthToken3, options); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== void 0) { + params = nextParams; + } + const anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal }); + stream2.push({ type: "start", partial: output }); + const blocks = output.content; + for await (const event of anthropicStream) { + if (event.type === "message_start") { + output.usage.input = event.message.usage.input_tokens || 0; + output.usage.output = event.message.usage.output_tokens || 0; + output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0; + output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0; + output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite; + calculateCost2(model, output.usage); + } else if (event.type === "content_block_start") { + if (event.content_block.type === "text") { + const block = { + type: "text", + text: "", + index: event.index + }; + output.content.push(block); + stream2.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output }); + } else if (event.content_block.type === "thinking") { + const block = { + type: "thinking", + thinking: "", + thinkingSignature: "", + index: event.index + }; + output.content.push(block); + stream2.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output }); + } else if (event.content_block.type === "redacted_thinking") { + const block = { + type: "thinking", + thinking: "[Reasoning redacted]", + thinkingSignature: event.content_block.data, + redacted: true, + index: event.index + }; + output.content.push(block); + stream2.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output }); + } else if (event.content_block.type === "tool_use") { + const block = { + type: "toolCall", + id: event.content_block.id, + name: isOAuthToken3 ? fromClaudeCodeName2(event.content_block.name, context.tools) : event.content_block.name, + arguments: event.content_block.input ?? {}, + partialJson: "", + index: event.index + }; + output.content.push(block); + stream2.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output }); + } + } else if (event.type === "content_block_delta") { + if (event.delta.type === "text_delta") { + const index2 = blocks.findIndex((b4) => b4.index === event.index); + const block = blocks[index2]; + if (block && block.type === "text") { + block.text += event.delta.text; + stream2.push({ + type: "text_delta", + contentIndex: index2, + delta: event.delta.text, + partial: output + }); + } + } else if (event.delta.type === "thinking_delta") { + const index2 = blocks.findIndex((b4) => b4.index === event.index); + const block = blocks[index2]; + if (block && block.type === "thinking") { + block.thinking += event.delta.thinking; + stream2.push({ + type: "thinking_delta", + contentIndex: index2, + delta: event.delta.thinking, + partial: output + }); + } + } else if (event.delta.type === "input_json_delta") { + const index2 = blocks.findIndex((b4) => b4.index === event.index); + const block = blocks[index2]; + if (block && block.type === "toolCall") { + block.partialJson += event.delta.partial_json; + block.arguments = parseStreamingJson2(block.partialJson); + stream2.push({ + type: "toolcall_delta", + contentIndex: index2, + delta: event.delta.partial_json, + partial: output + }); + } + } else if (event.delta.type === "signature_delta") { + const index2 = blocks.findIndex((b4) => b4.index === event.index); + const block = blocks[index2]; + if (block && block.type === "thinking") { + block.thinkingSignature = block.thinkingSignature || ""; + block.thinkingSignature += event.delta.signature; + } + } + } else if (event.type === "content_block_stop") { + const index2 = blocks.findIndex((b4) => b4.index === event.index); + const block = blocks[index2]; + if (block) { + delete block.index; + if (block.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: index2, + content: block.text, + partial: output + }); + } else if (block.type === "thinking") { + stream2.push({ + type: "thinking_end", + contentIndex: index2, + content: block.thinking, + partial: output + }); + } else if (block.type === "toolCall") { + block.arguments = parseStreamingJson2(block.partialJson); + delete block.partialJson; + stream2.push({ + type: "toolcall_end", + contentIndex: index2, + toolCall: block, + partial: output + }); + } + } + } else if (event.type === "message_delta") { + if (event.delta.stop_reason) { + output.stopReason = mapStopReason5(event.delta.stop_reason); + } + if (event.usage.input_tokens != null) { + output.usage.input = event.usage.input_tokens; + } + if (event.usage.output_tokens != null) { + output.usage.output = event.usage.output_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + output.usage.cacheRead = event.usage.cache_read_input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + output.usage.cacheWrite = event.usage.cache_creation_input_tokens; + } + output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite; + calculateCost2(model, output.usage); + } + } + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) + delete block.index; + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleAnthropic2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + if (!options?.reasoning) { + return streamAnthropic2(model, context, { ...base, thinkingEnabled: false }); + } + if (supportsAdaptiveThinking2(model.id)) { + const effort = mapThinkingLevelToEffort2(options.reasoning, model.id); + return streamAnthropic2(model, context, { + ...base, + thinkingEnabled: true, + effort + }); + } + const adjusted = adjustMaxTokensForThinking2(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets); + return streamAnthropic2(model, context, { + ...base, + maxTokens: adjusted.maxTokens, + thinkingEnabled: true, + thinkingBudgetTokens: adjusted.thinkingBudget + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/utils/hash.js +function shortHash2(str2) { + let h12 = 3735928559; + let h23 = 1103547991; + for (let i7 = 0; i7 < str2.length; i7++) { + const ch = str2.charCodeAt(i7); + h12 = Math.imul(h12 ^ ch, 2654435761); + h23 = Math.imul(h23 ^ ch, 1597334677); + } + h12 = Math.imul(h12 ^ h12 >>> 16, 2246822507) ^ Math.imul(h23 ^ h23 >>> 13, 3266489909); + h23 = Math.imul(h23 ^ h23 >>> 16, 2246822507) ^ Math.imul(h12 ^ h12 >>> 13, 3266489909); + return (h23 >>> 0).toString(36) + (h12 >>> 0).toString(36); +} +var init_hash = __esm({ + "../pi-mono/packages/ai/dist/utils/hash.js"() { + "use strict"; + init_process_shim(); + } +}); + +// ../pi-mono/packages/ai/dist/providers/openai-responses-shared.js +function encodeTextSignatureV12(id, phase) { + const payload = { v: 1, id }; + if (phase) + payload.phase = phase; + return JSON.stringify(payload); +} +function parseTextSignature2(signature) { + if (!signature) + return void 0; + if (signature.startsWith("{")) { + try { + const parsed = JSON.parse(signature); + if (parsed.v === 1 && typeof parsed.id === "string") { + if (parsed.phase === "commentary" || parsed.phase === "final_answer") { + return { id: parsed.id, phase: parsed.phase }; + } + return { id: parsed.id }; + } + } catch { + } + } + return { id: signature }; +} +function convertResponsesMessages2(model, context, allowedToolCallProviders, options) { + const messages = []; + const normalizeToolCallId3 = (id) => { + if (!allowedToolCallProviders.has(model.provider)) + return id; + if (!id.includes("|")) + return id; + const [callId, itemId] = id.split("|"); + const sanitizedCallId = callId.replace(/[^a-zA-Z0-9_-]/g, "_"); + let sanitizedItemId = itemId.replace(/[^a-zA-Z0-9_-]/g, "_"); + if (!sanitizedItemId.startsWith("fc")) { + sanitizedItemId = `fc_${sanitizedItemId}`; + } + let normalizedCallId = sanitizedCallId.length > 64 ? sanitizedCallId.slice(0, 64) : sanitizedCallId; + let normalizedItemId = sanitizedItemId.length > 64 ? sanitizedItemId.slice(0, 64) : sanitizedItemId; + normalizedCallId = normalizedCallId.replace(/_+$/, ""); + normalizedItemId = normalizedItemId.replace(/_+$/, ""); + return `${normalizedCallId}|${normalizedItemId}`; + }; + const transformedMessages = transformMessages2(context.messages, model, normalizeToolCallId3); + const includeSystemPrompt = options?.includeSystemPrompt ?? true; + if (includeSystemPrompt && context.systemPrompt) { + const role = model.reasoning ? "developer" : "system"; + messages.push({ + role, + content: sanitizeSurrogates2(context.systemPrompt) + }); + } + let msgIndex = 0; + for (const msg of transformedMessages) { + if (msg.role === "user") { + if (typeof msg.content === "string") { + messages.push({ + role: "user", + content: [{ type: "input_text", text: sanitizeSurrogates2(msg.content) }] + }); + } else { + const content = msg.content.map((item) => { + if (item.type === "text") { + return { + type: "input_text", + text: sanitizeSurrogates2(item.text) + }; + } + return { + type: "input_image", + detail: "auto", + image_url: `data:${item.mimeType};base64,${item.data}` + }; + }); + const filteredContent = !model.input.includes("image") ? content.filter((c6) => c6.type !== "input_image") : content; + if (filteredContent.length === 0) + continue; + messages.push({ + role: "user", + content: filteredContent + }); + } + } else if (msg.role === "assistant") { + const output = []; + const assistantMsg = msg; + const isDifferentModel = assistantMsg.model !== model.id && assistantMsg.provider === model.provider && assistantMsg.api === model.api; + for (const block of msg.content) { + if (block.type === "thinking") { + if (block.thinkingSignature) { + const reasoningItem = JSON.parse(block.thinkingSignature); + output.push(reasoningItem); + } + } else if (block.type === "text") { + const textBlock = block; + const parsedSignature = parseTextSignature2(textBlock.textSignature); + let msgId = parsedSignature?.id; + if (!msgId) { + msgId = `msg_${msgIndex}`; + } else if (msgId.length > 64) { + msgId = `msg_${shortHash2(msgId)}`; + } + output.push({ + type: "message", + role: "assistant", + content: [{ type: "output_text", text: sanitizeSurrogates2(textBlock.text), annotations: [] }], + status: "completed", + id: msgId, + phase: parsedSignature?.phase + }); + } else if (block.type === "toolCall") { + const toolCall = block; + const [callId, itemIdRaw] = toolCall.id.split("|"); + let itemId = itemIdRaw; + if (isDifferentModel && itemId?.startsWith("fc_")) { + itemId = void 0; + } + output.push({ + type: "function_call", + id: itemId, + call_id: callId, + name: toolCall.name, + arguments: JSON.stringify(toolCall.arguments) + }); + } + } + if (output.length === 0) + continue; + messages.push(...output); + } else if (msg.role === "toolResult") { + const textResult = msg.content.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n"); + const hasImages = msg.content.some((c6) => c6.type === "image"); + const hasText = textResult.length > 0; + const [callId] = msg.toolCallId.split("|"); + let output; + if (hasImages && model.input.includes("image")) { + const contentParts = []; + if (hasText) { + contentParts.push({ + type: "input_text", + text: sanitizeSurrogates2(textResult) + }); + } + for (const block of msg.content) { + if (block.type === "image") { + contentParts.push({ + type: "input_image", + detail: "auto", + image_url: `data:${block.mimeType};base64,${block.data}` + }); + } + } + output = contentParts; + } else { + output = sanitizeSurrogates2(hasText ? textResult : "(see attached image)"); + } + messages.push({ + type: "function_call_output", + call_id: callId, + output + }); + } + msgIndex++; + } + return messages; +} +function convertResponsesTools2(tools, options) { + const strict = options?.strict === void 0 ? false : options.strict; + return tools.map((tool) => ({ + type: "function", + name: tool.name, + description: tool.description, + parameters: tool.parameters, + // TypeBox already generates JSON Schema + strict + })); +} +async function processResponsesStream2(openaiStream, output, stream2, model, options) { + let currentItem = null; + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + for await (const event of openaiStream) { + if (event.type === "response.output_item.added") { + const item = event.item; + if (item.type === "reasoning") { + currentItem = item; + currentBlock = { type: "thinking", thinking: "" }; + output.content.push(currentBlock); + stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } else if (item.type === "message") { + currentItem = item; + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } else if (item.type === "function_call") { + currentItem = item; + currentBlock = { + type: "toolCall", + id: `${item.call_id}|${item.id}`, + name: item.name, + arguments: {}, + partialJson: item.arguments || "" + }; + output.content.push(currentBlock); + stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output }); + } + } else if (event.type === "response.reasoning_summary_part.added") { + if (currentItem && currentItem.type === "reasoning") { + currentItem.summary = currentItem.summary || []; + currentItem.summary.push(event.part); + } + } else if (event.type === "response.reasoning_summary_text.delta") { + if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") { + currentItem.summary = currentItem.summary || []; + const lastPart = currentItem.summary[currentItem.summary.length - 1]; + if (lastPart) { + currentBlock.thinking += event.delta; + lastPart.text += event.delta; + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: event.delta, + partial: output + }); + } + } + } else if (event.type === "response.reasoning_summary_part.done") { + if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") { + currentItem.summary = currentItem.summary || []; + const lastPart = currentItem.summary[currentItem.summary.length - 1]; + if (lastPart) { + currentBlock.thinking += "\n\n"; + lastPart.text += "\n\n"; + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: "\n\n", + partial: output + }); + } + } + } else if (event.type === "response.content_part.added") { + if (currentItem?.type === "message") { + currentItem.content = currentItem.content || []; + if (event.part.type === "output_text" || event.part.type === "refusal") { + currentItem.content.push(event.part); + } + } + } else if (event.type === "response.output_text.delta") { + if (currentItem?.type === "message" && currentBlock?.type === "text") { + if (!currentItem.content || currentItem.content.length === 0) { + continue; + } + const lastPart = currentItem.content[currentItem.content.length - 1]; + if (lastPart?.type === "output_text") { + currentBlock.text += event.delta; + lastPart.text += event.delta; + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: event.delta, + partial: output + }); + } + } + } else if (event.type === "response.refusal.delta") { + if (currentItem?.type === "message" && currentBlock?.type === "text") { + if (!currentItem.content || currentItem.content.length === 0) { + continue; + } + const lastPart = currentItem.content[currentItem.content.length - 1]; + if (lastPart?.type === "refusal") { + currentBlock.text += event.delta; + lastPart.refusal += event.delta; + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: event.delta, + partial: output + }); + } + } + } else if (event.type === "response.function_call_arguments.delta") { + if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") { + currentBlock.partialJson += event.delta; + currentBlock.arguments = parseStreamingJson2(currentBlock.partialJson); + stream2.push({ + type: "toolcall_delta", + contentIndex: blockIndex(), + delta: event.delta, + partial: output + }); + } + } else if (event.type === "response.function_call_arguments.done") { + if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") { + currentBlock.partialJson = event.arguments; + currentBlock.arguments = parseStreamingJson2(currentBlock.partialJson); + } + } else if (event.type === "response.output_item.done") { + const item = event.item; + if (item.type === "reasoning" && currentBlock?.type === "thinking") { + currentBlock.thinking = item.summary?.map((s6) => s6.text).join("\n\n") || ""; + currentBlock.thinkingSignature = JSON.stringify(item); + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + currentBlock = null; + } else if (item.type === "message" && currentBlock?.type === "text") { + currentBlock.text = item.content.map((c6) => c6.type === "output_text" ? c6.text : c6.refusal).join(""); + currentBlock.textSignature = encodeTextSignatureV12(item.id, item.phase ?? void 0); + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + currentBlock = null; + } else if (item.type === "function_call") { + const args = currentBlock?.type === "toolCall" && currentBlock.partialJson ? parseStreamingJson2(currentBlock.partialJson) : parseStreamingJson2(item.arguments || "{}"); + const toolCall = { + type: "toolCall", + id: `${item.call_id}|${item.id}`, + name: item.name, + arguments: args + }; + currentBlock = null; + stream2.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output }); + } + } else if (event.type === "response.completed") { + const response = event.response; + if (response?.usage) { + const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0; + output.usage = { + // OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input + input: (response.usage.input_tokens || 0) - cachedTokens, + output: response.usage.output_tokens || 0, + cacheRead: cachedTokens, + cacheWrite: 0, + totalTokens: response.usage.total_tokens || 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }; + } + calculateCost2(model, output.usage); + if (options?.applyServiceTierPricing) { + const serviceTier = response?.service_tier ?? options.serviceTier; + options.applyServiceTierPricing(output.usage, serviceTier); + } + output.stopReason = mapStopReason6(response?.status); + if (output.content.some((b4) => b4.type === "toolCall") && output.stopReason === "stop") { + output.stopReason = "toolUse"; + } + } else if (event.type === "error") { + throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error"); + } else if (event.type === "response.failed") { + const error = event.response?.error; + const details = event.response?.incomplete_details; + const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)"; + throw new Error(msg); + } + } +} +function mapStopReason6(status) { + if (!status) + return "stop"; + switch (status) { + case "completed": + return "stop"; + case "incomplete": + return "length"; + case "failed": + case "cancelled": + return "error"; + // These two are wonky ... + case "in_progress": + case "queued": + return "stop"; + default: { + const _exhaustive = status; + throw new Error(`Unhandled stop reason: ${_exhaustive}`); + } + } +} +var init_openai_responses_shared = __esm({ + "../pi-mono/packages/ai/dist/providers/openai-responses-shared.js"() { + "use strict"; + init_process_shim(); + init_models4(); + init_hash(); + init_json_parse(); + init_sanitize_unicode(); + init_transform_messages(); + } +}); + +// ../pi-mono/packages/ai/dist/providers/azure-openai-responses.js +function parseDeploymentNameMap2(value) { + const map3 = /* @__PURE__ */ new Map(); + if (!value) + return map3; + for (const entry of value.split(",")) { + const trimmed = entry.trim(); + if (!trimmed) + continue; + const [modelId, deploymentName] = trimmed.split("=", 2); + if (!modelId || !deploymentName) + continue; + map3.set(modelId.trim(), deploymentName.trim()); + } + return map3; +} +function resolveDeploymentName2(model, options) { + if (options?.azureDeploymentName) { + return options.azureDeploymentName; + } + const mappedDeployment = parseDeploymentNameMap2(process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(model.id); + return mappedDeployment || model.id; +} +function normalizeAzureBaseUrl2(baseUrl) { + return baseUrl.replace(/\/+$/, ""); +} +function buildDefaultBaseUrl2(resourceName2) { + return `https://${resourceName2}.openai.azure.com/openai/v1`; +} +function resolveAzureConfig2(model, options) { + const apiVersion = options?.azureApiVersion || process.env.AZURE_OPENAI_API_VERSION || DEFAULT_AZURE_API_VERSION2; + const baseUrl = options?.azureBaseUrl?.trim() || process.env.AZURE_OPENAI_BASE_URL?.trim() || void 0; + const resourceName2 = options?.azureResourceName || process.env.AZURE_OPENAI_RESOURCE_NAME; + let resolvedBaseUrl = baseUrl; + if (!resolvedBaseUrl && resourceName2) { + resolvedBaseUrl = buildDefaultBaseUrl2(resourceName2); + } + if (!resolvedBaseUrl && model.baseUrl) { + resolvedBaseUrl = model.baseUrl; + } + if (!resolvedBaseUrl) { + throw new Error("Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl."); + } + return { + baseUrl: normalizeAzureBaseUrl2(resolvedBaseUrl), + apiVersion + }; +} +function createClient8(model, apiKey, options) { + if (!apiKey) { + if (!process.env.AZURE_OPENAI_API_KEY) { + throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument."); + } + apiKey = process.env.AZURE_OPENAI_API_KEY; + } + const headers = { ...model.headers }; + if (options?.headers) { + Object.assign(headers, options.headers); + } + const { baseUrl, apiVersion } = resolveAzureConfig2(model, options); + return new AzureOpenAI({ + apiKey, + apiVersion, + dangerouslyAllowBrowser: true, + defaultHeaders: headers, + baseURL: baseUrl + }); +} +function buildParams8(model, context, options, deploymentName) { + const messages = convertResponsesMessages2(model, context, AZURE_TOOL_CALL_PROVIDERS2); + const params = { + model: deploymentName, + input: messages, + stream: true, + prompt_cache_key: options?.sessionId + }; + if (options?.maxTokens) { + params.max_output_tokens = options?.maxTokens; + } + if (options?.temperature !== void 0) { + params.temperature = options?.temperature; + } + if (context.tools) { + params.tools = convertResponsesTools2(context.tools); + } + if (model.reasoning) { + if (options?.reasoningEffort || options?.reasoningSummary) { + params.reasoning = { + effort: options?.reasoningEffort || "medium", + summary: options?.reasoningSummary || "auto" + }; + params.include = ["reasoning.encrypted_content"]; + } else { + if (model.name.toLowerCase().startsWith("gpt-5")) { + messages.push({ + role: "developer", + content: [ + { + type: "input_text", + text: "# Juice: 0 !important" + } + ] + }); + } + } + } + return params; +} +var DEFAULT_AZURE_API_VERSION2, AZURE_TOOL_CALL_PROVIDERS2, streamAzureOpenAIResponses2, streamSimpleAzureOpenAIResponses2; +var init_azure_openai_responses = __esm({ + "../pi-mono/packages/ai/dist/providers/azure-openai-responses.js"() { + "use strict"; + init_process_shim(); + init_openai(); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_openai_responses_shared(); + init_simple_options(); + DEFAULT_AZURE_API_VERSION2 = "v1"; + AZURE_TOOL_CALL_PROVIDERS2 = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode", "azure-openai-responses"]); + streamAzureOpenAIResponses2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const deploymentName = resolveDeploymentName2(model, options); + const output = { + role: "assistant", + content: [], + api: "azure-openai-responses", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider) || ""; + const client = createClient8(model, apiKey, options); + let params = buildParams8(model, context, options, deploymentName); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== void 0) { + params = nextParams; + } + const openaiStream = await client.responses.create(params, options?.signal ? { signal: options.signal } : void 0); + stream2.push({ type: "start", partial: output }); + await processResponsesStream2(openaiStream, output, stream2, model); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) + delete block.index; + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleAzureOpenAIResponses2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + const reasoningEffort = supportsXhigh2(model) ? options?.reasoning : clampReasoning2(options?.reasoning); + return streamAzureOpenAIResponses2(model, context, { + ...base, + reasoningEffort + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/google-shared.js +function isThinkingPart2(part) { + return part.thought === true; +} +function retainThoughtSignature2(existing, incoming) { + if (typeof incoming === "string" && incoming.length > 0) + return incoming; + return existing; +} +function isValidThoughtSignature2(signature) { + if (!signature) + return false; + if (signature.length % 4 !== 0) + return false; + return base64SignaturePattern2.test(signature); +} +function resolveThoughtSignature2(isSameProviderAndModel, signature) { + return isSameProviderAndModel && isValidThoughtSignature2(signature) ? signature : void 0; +} +function requiresToolCallId2(modelId) { + return modelId.startsWith("claude-") || modelId.startsWith("gpt-oss-"); +} +function convertMessages5(model, context) { + const contents = []; + const normalizeToolCallId3 = (id) => { + if (!requiresToolCallId2(model.id)) + return id; + return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64); + }; + const transformedMessages = transformMessages2(context.messages, model, normalizeToolCallId3); + for (const msg of transformedMessages) { + if (msg.role === "user") { + if (typeof msg.content === "string") { + contents.push({ + role: "user", + parts: [{ text: sanitizeSurrogates2(msg.content) }] + }); + } else { + const parts = msg.content.map((item) => { + if (item.type === "text") { + return { text: sanitizeSurrogates2(item.text) }; + } else { + return { + inlineData: { + mimeType: item.mimeType, + data: item.data + } + }; + } + }); + const filteredParts = !model.input.includes("image") ? parts.filter((p4) => p4.text !== void 0) : parts; + if (filteredParts.length === 0) + continue; + contents.push({ + role: "user", + parts: filteredParts + }); + } + } else if (msg.role === "assistant") { + const parts = []; + const isSameProviderAndModel = msg.provider === model.provider && msg.model === model.id; + for (const block of msg.content) { + if (block.type === "text") { + if (!block.text || block.text.trim() === "") + continue; + const thoughtSignature = resolveThoughtSignature2(isSameProviderAndModel, block.textSignature); + parts.push({ + text: sanitizeSurrogates2(block.text), + ...thoughtSignature && { thoughtSignature } + }); + } else if (block.type === "thinking") { + if (!block.thinking || block.thinking.trim() === "") + continue; + if (isSameProviderAndModel) { + const thoughtSignature = resolveThoughtSignature2(isSameProviderAndModel, block.thinkingSignature); + parts.push({ + thought: true, + text: sanitizeSurrogates2(block.thinking), + ...thoughtSignature && { thoughtSignature } + }); + } else { + parts.push({ + text: sanitizeSurrogates2(block.thinking) + }); + } + } else if (block.type === "toolCall") { + const thoughtSignature = resolveThoughtSignature2(isSameProviderAndModel, block.thoughtSignature); + const isGemini3 = model.id.toLowerCase().includes("gemini-3"); + const effectiveSignature = thoughtSignature || (isGemini3 ? SKIP_THOUGHT_SIGNATURE2 : void 0); + const part = { + functionCall: { + name: block.name, + args: block.arguments ?? {}, + ...requiresToolCallId2(model.id) ? { id: block.id } : {} + }, + ...effectiveSignature && { thoughtSignature: effectiveSignature } + }; + parts.push(part); + } + } + if (parts.length === 0) + continue; + contents.push({ + role: "model", + parts + }); + } else if (msg.role === "toolResult") { + const textContent = msg.content.filter((c6) => c6.type === "text"); + const textResult = textContent.map((c6) => c6.text).join("\n"); + const imageContent = model.input.includes("image") ? msg.content.filter((c6) => c6.type === "image") : []; + const hasText = textResult.length > 0; + const hasImages = imageContent.length > 0; + const supportsMultimodalFunctionResponse = model.id.includes("gemini-3"); + const responseValue = hasText ? sanitizeSurrogates2(textResult) : hasImages ? "(see attached image)" : ""; + const imageParts = imageContent.map((imageBlock) => ({ + inlineData: { + mimeType: imageBlock.mimeType, + data: imageBlock.data + } + })); + const includeId = requiresToolCallId2(model.id); + const functionResponsePart = { + functionResponse: { + name: msg.toolName, + response: msg.isError ? { error: responseValue } : { output: responseValue }, + // Nest images inside functionResponse.parts for Gemini 3 + ...hasImages && supportsMultimodalFunctionResponse && { parts: imageParts }, + ...includeId ? { id: msg.toolCallId } : {} + } + }; + const lastContent = contents[contents.length - 1]; + if (lastContent?.role === "user" && lastContent.parts?.some((p4) => p4.functionResponse)) { + lastContent.parts.push(functionResponsePart); + } else { + contents.push({ + role: "user", + parts: [functionResponsePart] + }); + } + if (hasImages && !supportsMultimodalFunctionResponse) { + contents.push({ + role: "user", + parts: [{ text: "Tool result image:" }, ...imageParts] + }); + } + } + } + return contents; +} +function convertTools5(tools, useParameters = false) { + if (tools.length === 0) + return void 0; + return [ + { + functionDeclarations: tools.map((tool) => ({ + name: tool.name, + description: tool.description, + ...useParameters ? { parameters: tool.parameters } : { parametersJsonSchema: tool.parameters } + })) + } + ]; +} +function mapToolChoice3(choice) { + switch (choice) { + case "auto": + return FunctionCallingConfigMode.AUTO; + case "none": + return FunctionCallingConfigMode.NONE; + case "any": + return FunctionCallingConfigMode.ANY; + default: + return FunctionCallingConfigMode.AUTO; + } +} +function mapStopReason7(reason) { + switch (reason) { + case FinishReason.STOP: + return "stop"; + case FinishReason.MAX_TOKENS: + return "length"; + case FinishReason.BLOCKLIST: + case FinishReason.PROHIBITED_CONTENT: + case FinishReason.SPII: + case FinishReason.SAFETY: + case FinishReason.IMAGE_SAFETY: + case FinishReason.IMAGE_PROHIBITED_CONTENT: + case FinishReason.IMAGE_RECITATION: + case FinishReason.IMAGE_OTHER: + case FinishReason.RECITATION: + case FinishReason.FINISH_REASON_UNSPECIFIED: + case FinishReason.OTHER: + case FinishReason.LANGUAGE: + case FinishReason.MALFORMED_FUNCTION_CALL: + case FinishReason.UNEXPECTED_TOOL_CALL: + case FinishReason.NO_IMAGE: + return "error"; + default: { + const _exhaustive = reason; + throw new Error(`Unhandled stop reason: ${_exhaustive}`); + } + } +} +function mapStopReasonString2(reason) { + switch (reason) { + case "STOP": + return "stop"; + case "MAX_TOKENS": + return "length"; + default: + return "error"; + } +} +var base64SignaturePattern2, SKIP_THOUGHT_SIGNATURE2; +var init_google_shared = __esm({ + "../pi-mono/packages/ai/dist/providers/google-shared.js"() { + "use strict"; + init_process_shim(); + init_web(); + init_sanitize_unicode(); + init_transform_messages(); + base64SignaturePattern2 = /^[A-Za-z0-9+/]+={0,2}$/; + SKIP_THOUGHT_SIGNATURE2 = "skip_thought_signature_validator"; + } +}); + +// ../pi-mono/packages/ai/dist/providers/google.js +function createClient9(model, apiKey, optionsHeaders) { + const httpOptions = {}; + if (model.baseUrl) { + httpOptions.baseUrl = model.baseUrl; + httpOptions.apiVersion = ""; + } + if (model.headers || optionsHeaders) { + httpOptions.headers = { ...model.headers, ...optionsHeaders }; + } + return new GoogleGenAI({ + apiKey, + httpOptions: Object.keys(httpOptions).length > 0 ? httpOptions : void 0 + }); +} +function buildParams9(model, context, options = {}) { + const contents = convertMessages5(model, context); + const generationConfig = {}; + if (options.temperature !== void 0) { + generationConfig.temperature = options.temperature; + } + if (options.maxTokens !== void 0) { + generationConfig.maxOutputTokens = options.maxTokens; + } + const config = { + ...Object.keys(generationConfig).length > 0 && generationConfig, + ...context.systemPrompt && { systemInstruction: sanitizeSurrogates2(context.systemPrompt) }, + ...context.tools && context.tools.length > 0 && { tools: convertTools5(context.tools) } + }; + if (context.tools && context.tools.length > 0 && options.toolChoice) { + config.toolConfig = { + functionCallingConfig: { + mode: mapToolChoice3(options.toolChoice) + } + }; + } else { + config.toolConfig = void 0; + } + if (options.thinking?.enabled && model.reasoning) { + const thinkingConfig = { includeThoughts: true }; + if (options.thinking.level !== void 0) { + thinkingConfig.thinkingLevel = options.thinking.level; + } else if (options.thinking.budgetTokens !== void 0) { + thinkingConfig.thinkingBudget = options.thinking.budgetTokens; + } + config.thinkingConfig = thinkingConfig; + } + if (options.signal) { + if (options.signal.aborted) { + throw new Error("Request aborted"); + } + config.abortSignal = options.signal; + } + const params = { + model: model.id, + contents, + config + }; + return params; +} +function isGemini3ProModel4(model) { + return /gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase()); +} +function isGemini3FlashModel4(model) { + return /gemini-3(?:\.\d+)?-flash/.test(model.id.toLowerCase()); +} +function getGemini3ThinkingLevel3(effort, model) { + if (isGemini3ProModel4(model)) { + switch (effort) { + case "minimal": + case "low": + return "LOW"; + case "medium": + case "high": + return "HIGH"; + } + } + switch (effort) { + case "minimal": + return "MINIMAL"; + case "low": + return "LOW"; + case "medium": + return "MEDIUM"; + case "high": + return "HIGH"; + } +} +function getGoogleBudget3(model, effort, customBudgets) { + if (customBudgets?.[effort] !== void 0) { + return customBudgets[effort]; + } + if (model.id.includes("2.5-pro")) { + const budgets = { + minimal: 128, + low: 2048, + medium: 8192, + high: 32768 + }; + return budgets[effort]; + } + if (model.id.includes("2.5-flash")) { + const budgets = { + minimal: 128, + low: 2048, + medium: 8192, + high: 24576 + }; + return budgets[effort]; + } + return -1; +} +var toolCallCounter4, streamGoogle2, streamSimpleGoogle2; +var init_google = __esm({ + "../pi-mono/packages/ai/dist/providers/google.js"() { + "use strict"; + init_process_shim(); + init_web(); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_sanitize_unicode(); + init_google_shared(); + init_simple_options(); + toolCallCounter4 = 0; + streamGoogle2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: "google-generative-ai", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider) || ""; + const client = createClient9(model, apiKey, options?.headers); + let params = buildParams9(model, context, options); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== void 0) { + params = nextParams; + } + const googleStream = await client.models.generateContentStream(params); + stream2.push({ type: "start", partial: output }); + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + for await (const chunk of googleStream) { + const candidate = chunk.candidates?.[0]; + if (candidate?.content?.parts) { + for (const part of candidate.content.parts) { + if (part.text !== void 0) { + const isThinking = isThinkingPart2(part); + if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") { + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blocks.length - 1, + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + } + if (isThinking) { + currentBlock = { type: "thinking", thinking: "", thinkingSignature: void 0 }; + output.content.push(currentBlock); + stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } else { + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + } + if (currentBlock.type === "thinking") { + currentBlock.thinking += part.text; + currentBlock.thinkingSignature = retainThoughtSignature2(currentBlock.thinkingSignature, part.thoughtSignature); + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output + }); + } else { + currentBlock.text += part.text; + currentBlock.textSignature = retainThoughtSignature2(currentBlock.textSignature, part.thoughtSignature); + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output + }); + } + } + if (part.functionCall) { + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + currentBlock = null; + } + const providedId = part.functionCall.id; + const needsNewId = !providedId || output.content.some((b4) => b4.type === "toolCall" && b4.id === providedId); + const toolCallId = needsNewId ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter4}` : providedId; + const toolCall = { + type: "toolCall", + id: toolCallId, + name: part.functionCall.name || "", + arguments: part.functionCall.args ?? {}, + ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature } + }; + output.content.push(toolCall); + stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output }); + stream2.push({ + type: "toolcall_delta", + contentIndex: blockIndex(), + delta: JSON.stringify(toolCall.arguments), + partial: output + }); + stream2.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output }); + } + } + } + if (candidate?.finishReason) { + output.stopReason = mapStopReason7(candidate.finishReason); + if (output.content.some((b4) => b4.type === "toolCall")) { + output.stopReason = "toolUse"; + } + } + if (chunk.usageMetadata) { + output.usage = { + input: chunk.usageMetadata.promptTokenCount || 0, + output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0), + cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0, + cacheWrite: 0, + totalTokens: chunk.usageMetadata.totalTokenCount || 0, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + total: 0 + } + }; + calculateCost2(model, output.usage); + } + } + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + } + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) { + if ("index" in block) { + delete block.index; + } + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleGoogle2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + if (!options?.reasoning) { + return streamGoogle2(model, context, { ...base, thinking: { enabled: false } }); + } + const effort = clampReasoning2(options.reasoning); + const googleModel = model; + if (isGemini3ProModel4(googleModel) || isGemini3FlashModel4(googleModel)) { + return streamGoogle2(model, context, { + ...base, + thinking: { + enabled: true, + level: getGemini3ThinkingLevel3(effort, googleModel) + } + }); + } + return streamGoogle2(model, context, { + ...base, + thinking: { + enabled: true, + budgetTokens: getGoogleBudget3(googleModel, effort, options.thinkingBudgets) + } + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/google-gemini-cli.js +function getAntigravityHeaders2() { + const version6 = process.env.PI_AI_ANTIGRAVITY_VERSION || DEFAULT_ANTIGRAVITY_VERSION2; + return { + "User-Agent": `antigravity/${version6} darwin/arm64` + }; +} +function extractRetryDelay2(errorText, response) { + const normalizeDelay = (ms) => ms > 0 ? Math.ceil(ms + 1e3) : void 0; + const headers = response instanceof Headers ? response : response?.headers; + if (headers) { + const retryAfter = headers.get("retry-after"); + if (retryAfter) { + const retryAfterSeconds = Number(retryAfter); + if (Number.isFinite(retryAfterSeconds)) { + const delay = normalizeDelay(retryAfterSeconds * 1e3); + if (delay !== void 0) { + return delay; + } + } + const retryAfterDate = new Date(retryAfter); + const retryAfterMs = retryAfterDate.getTime(); + if (!Number.isNaN(retryAfterMs)) { + const delay = normalizeDelay(retryAfterMs - Date.now()); + if (delay !== void 0) { + return delay; + } + } + } + const rateLimitReset = headers.get("x-ratelimit-reset"); + if (rateLimitReset) { + const resetSeconds = Number.parseInt(rateLimitReset, 10); + if (!Number.isNaN(resetSeconds)) { + const delay = normalizeDelay(resetSeconds * 1e3 - Date.now()); + if (delay !== void 0) { + return delay; + } + } + } + const rateLimitResetAfter = headers.get("x-ratelimit-reset-after"); + if (rateLimitResetAfter) { + const resetAfterSeconds = Number(rateLimitResetAfter); + if (Number.isFinite(resetAfterSeconds)) { + const delay = normalizeDelay(resetAfterSeconds * 1e3); + if (delay !== void 0) { + return delay; + } + } + } + } + const durationMatch = errorText.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i); + if (durationMatch) { + const hours = durationMatch[1] ? parseInt(durationMatch[1], 10) : 0; + const minutes = durationMatch[2] ? parseInt(durationMatch[2], 10) : 0; + const seconds = parseFloat(durationMatch[3]); + if (!Number.isNaN(seconds)) { + const totalMs = ((hours * 60 + minutes) * 60 + seconds) * 1e3; + const delay = normalizeDelay(totalMs); + if (delay !== void 0) { + return delay; + } + } + } + const retryInMatch = errorText.match(/Please retry in ([0-9.]+)(ms|s)/i); + if (retryInMatch?.[1]) { + const value = parseFloat(retryInMatch[1]); + if (!Number.isNaN(value) && value > 0) { + const ms = retryInMatch[2].toLowerCase() === "ms" ? value : value * 1e3; + const delay = normalizeDelay(ms); + if (delay !== void 0) { + return delay; + } + } + } + const retryDelayMatch = errorText.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i); + if (retryDelayMatch?.[1]) { + const value = parseFloat(retryDelayMatch[1]); + if (!Number.isNaN(value) && value > 0) { + const ms = retryDelayMatch[2].toLowerCase() === "ms" ? value : value * 1e3; + const delay = normalizeDelay(ms); + if (delay !== void 0) { + return delay; + } + } + } + return void 0; +} +function needsClaudeThinkingBetaHeader2(model) { + return model.provider === "google-antigravity" && model.id.startsWith("claude-") && model.reasoning; +} +function isGemini3ProModel5(modelId) { + return /gemini-3(?:\.1)?-pro/.test(modelId.toLowerCase()); +} +function isGemini3FlashModel5(modelId) { + return /gemini-3(?:\.1)?-flash/.test(modelId.toLowerCase()); +} +function isGemini3Model2(modelId) { + return isGemini3ProModel5(modelId) || isGemini3FlashModel5(modelId); +} +function isRetryableError3(status, errorText) { + if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) { + return true; + } + return /resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(errorText); +} +function extractErrorMessage2(errorText) { + try { + const parsed = JSON.parse(errorText); + if (parsed.error?.message) { + return parsed.error.message; + } + } catch { + } + return errorText; +} +function sleep6(ms, signal) { + return new Promise((resolve2, reject) => { + if (signal?.aborted) { + reject(new Error("Request was aborted")); + return; + } + const timeout = setTimeout(resolve2, ms); + signal?.addEventListener("abort", () => { + clearTimeout(timeout); + reject(new Error("Request was aborted")); + }); + }); +} +function buildRequest2(model, context, projectId, options = {}, isAntigravity = false) { + const contents = convertMessages5(model, context); + const generationConfig = {}; + if (options.temperature !== void 0) { + generationConfig.temperature = options.temperature; + } + if (options.maxTokens !== void 0) { + generationConfig.maxOutputTokens = options.maxTokens; + } + if (options.thinking?.enabled && model.reasoning) { + generationConfig.thinkingConfig = { + includeThoughts: true + }; + if (options.thinking.level !== void 0) { + generationConfig.thinkingConfig.thinkingLevel = options.thinking.level; + } else if (options.thinking.budgetTokens !== void 0) { + generationConfig.thinkingConfig.thinkingBudget = options.thinking.budgetTokens; + } + } + const request = { + contents + }; + request.sessionId = options.sessionId; + if (context.systemPrompt) { + request.systemInstruction = { + parts: [{ text: sanitizeSurrogates2(context.systemPrompt) }] + }; + } + if (Object.keys(generationConfig).length > 0) { + request.generationConfig = generationConfig; + } + if (context.tools && context.tools.length > 0) { + const useParameters = model.id.startsWith("claude-"); + request.tools = convertTools5(context.tools, useParameters); + if (options.toolChoice) { + request.toolConfig = { + functionCallingConfig: { + mode: mapToolChoice3(options.toolChoice) + } + }; + } + } + if (isAntigravity) { + const existingParts = request.systemInstruction?.parts ?? []; + request.systemInstruction = { + role: "user", + parts: [ + { text: ANTIGRAVITY_SYSTEM_INSTRUCTION2 }, + { text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION2}[/ignore]` }, + ...existingParts + ] + }; + } + return { + project: projectId, + model: model.id, + request, + ...isAntigravity ? { requestType: "agent" } : {}, + userAgent: isAntigravity ? "antigravity" : "pi-coding-agent", + requestId: `${isAntigravity ? "agent" : "pi"}-${Date.now()}-${Math.random().toString(36).slice(2, 11)}` + }; +} +function getGeminiCliThinkingLevel2(effort, modelId) { + if (isGemini3ProModel5(modelId)) { + switch (effort) { + case "minimal": + case "low": + return "LOW"; + case "medium": + case "high": + return "HIGH"; + } + } + switch (effort) { + case "minimal": + return "MINIMAL"; + case "low": + return "LOW"; + case "medium": + return "MEDIUM"; + case "high": + return "HIGH"; + } +} +var DEFAULT_ENDPOINT2, ANTIGRAVITY_DAILY_ENDPOINT2, ANTIGRAVITY_AUTOPUSH_ENDPOINT2, ANTIGRAVITY_ENDPOINT_FALLBACKS2, GEMINI_CLI_HEADERS2, DEFAULT_ANTIGRAVITY_VERSION2, ANTIGRAVITY_SYSTEM_INSTRUCTION2, toolCallCounter5, MAX_RETRIES3, BASE_DELAY_MS3, MAX_EMPTY_STREAM_RETRIES2, EMPTY_STREAM_BASE_DELAY_MS2, CLAUDE_THINKING_BETA_HEADER2, streamGoogleGeminiCli2, streamSimpleGoogleGeminiCli2; +var init_google_gemini_cli = __esm({ + "../pi-mono/packages/ai/dist/providers/google-gemini-cli.js"() { + "use strict"; + init_process_shim(); + init_models4(); + init_event_stream(); + init_sanitize_unicode(); + init_google_shared(); + init_simple_options(); + DEFAULT_ENDPOINT2 = "https://cloudcode-pa.googleapis.com"; + ANTIGRAVITY_DAILY_ENDPOINT2 = "https://daily-cloudcode-pa.sandbox.googleapis.com"; + ANTIGRAVITY_AUTOPUSH_ENDPOINT2 = "https://autopush-cloudcode-pa.sandbox.googleapis.com"; + ANTIGRAVITY_ENDPOINT_FALLBACKS2 = [ + ANTIGRAVITY_DAILY_ENDPOINT2, + ANTIGRAVITY_AUTOPUSH_ENDPOINT2, + DEFAULT_ENDPOINT2 + ]; + GEMINI_CLI_HEADERS2 = { + "User-Agent": "google-cloud-sdk vscode_cloudshelleditor/0.1", + "X-Goog-Api-Client": "gl-node/22.17.0", + "Client-Metadata": JSON.stringify({ + ideType: "IDE_UNSPECIFIED", + platform: "PLATFORM_UNSPECIFIED", + pluginType: "GEMINI" + }) + }; + DEFAULT_ANTIGRAVITY_VERSION2 = "1.18.4"; + ANTIGRAVITY_SYSTEM_INSTRUCTION2 = "You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.**Absolute paths only****Proactiveness**"; + toolCallCounter5 = 0; + MAX_RETRIES3 = 3; + BASE_DELAY_MS3 = 1e3; + MAX_EMPTY_STREAM_RETRIES2 = 2; + EMPTY_STREAM_BASE_DELAY_MS2 = 500; + CLAUDE_THINKING_BETA_HEADER2 = "interleaved-thinking-2025-05-14"; + streamGoogleGeminiCli2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: "google-gemini-cli", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKeyRaw = options?.apiKey; + if (!apiKeyRaw) { + throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate."); + } + let accessToken; + let projectId; + try { + const parsed = JSON.parse(apiKeyRaw); + accessToken = parsed.token; + projectId = parsed.projectId; + } catch { + throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate."); + } + if (!accessToken || !projectId) { + throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate."); + } + const isAntigravity = model.provider === "google-antigravity"; + const baseUrl = model.baseUrl?.trim(); + const endpoints = baseUrl ? [baseUrl] : isAntigravity ? ANTIGRAVITY_ENDPOINT_FALLBACKS2 : [DEFAULT_ENDPOINT2]; + let requestBody = buildRequest2(model, context, projectId, options, isAntigravity); + const nextRequestBody = await options?.onPayload?.(requestBody, model); + if (nextRequestBody !== void 0) { + requestBody = nextRequestBody; + } + const headers = isAntigravity ? getAntigravityHeaders2() : GEMINI_CLI_HEADERS2; + const requestHeaders = { + Authorization: `Bearer ${accessToken}`, + "Content-Type": "application/json", + Accept: "text/event-stream", + ...headers, + ...needsClaudeThinkingBetaHeader2(model) ? { "anthropic-beta": CLAUDE_THINKING_BETA_HEADER2 } : {}, + ...options?.headers + }; + const requestBodyJson = JSON.stringify(requestBody); + let response; + let lastError; + let requestUrl; + let endpointIndex = 0; + for (let attempt = 0; attempt <= MAX_RETRIES3; attempt++) { + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + try { + const endpoint = endpoints[endpointIndex]; + requestUrl = `${endpoint}/v1internal:streamGenerateContent?alt=sse`; + response = await fetch(requestUrl, { + method: "POST", + headers: requestHeaders, + body: requestBodyJson, + signal: options?.signal + }); + if (response.ok) { + break; + } + const errorText = await response.text(); + if ((response.status === 403 || response.status === 404) && endpointIndex < endpoints.length - 1) { + endpointIndex++; + continue; + } + if (attempt < MAX_RETRIES3 && isRetryableError3(response.status, errorText)) { + if (endpointIndex < endpoints.length - 1) { + endpointIndex++; + } + const serverDelay = extractRetryDelay2(errorText, response); + const delayMs = serverDelay ?? BASE_DELAY_MS3 * 2 ** attempt; + const maxDelayMs = options?.maxRetryDelayMs ?? 6e4; + if (maxDelayMs > 0 && serverDelay && serverDelay > maxDelayMs) { + const delaySeconds = Math.ceil(serverDelay / 1e3); + throw new Error(`Server requested ${delaySeconds}s retry delay (max: ${Math.ceil(maxDelayMs / 1e3)}s). ${extractErrorMessage2(errorText)}`); + } + await sleep6(delayMs, options?.signal); + continue; + } + throw new Error(`Cloud Code Assist API error (${response.status}): ${extractErrorMessage2(errorText)}`); + } catch (error) { + if (error instanceof Error) { + if (error.name === "AbortError" || error.message === "Request was aborted") { + throw new Error("Request was aborted"); + } + } + lastError = error instanceof Error ? error : new Error(String(error)); + if (lastError.message === "fetch failed" && lastError.cause instanceof Error) { + lastError = new Error(`Network error: ${lastError.cause.message}`); + } + if (attempt < MAX_RETRIES3) { + const delayMs = BASE_DELAY_MS3 * 2 ** attempt; + await sleep6(delayMs, options?.signal); + continue; + } + throw lastError; + } + } + if (!response || !response.ok) { + throw lastError ?? new Error("Failed to get response after retries"); + } + let started = false; + const ensureStarted = () => { + if (!started) { + stream2.push({ type: "start", partial: output }); + started = true; + } + }; + const resetOutput = () => { + output.content = []; + output.usage = { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }; + output.stopReason = "stop"; + output.errorMessage = void 0; + output.timestamp = Date.now(); + started = false; + }; + const streamResponse = async (activeResponse) => { + if (!activeResponse.body) { + throw new Error("No response body"); + } + let hasContent = false; + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + const reader = activeResponse.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + const abortHandler = () => { + void reader.cancel().catch(() => { + }); + }; + options?.signal?.addEventListener("abort", abortHandler); + try { + while (true) { + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + const { done, value } = await reader.read(); + if (done) + break; + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop() || ""; + for (const line of lines) { + if (!line.startsWith("data:")) + continue; + const jsonStr = line.slice(5).trim(); + if (!jsonStr) + continue; + let chunk; + try { + chunk = JSON.parse(jsonStr); + } catch { + continue; + } + const responseData = chunk.response; + if (!responseData) + continue; + const candidate = responseData.candidates?.[0]; + if (candidate?.content?.parts) { + for (const part of candidate.content.parts) { + if (part.text !== void 0) { + hasContent = true; + const isThinking = isThinkingPart2(part); + if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") { + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blocks.length - 1, + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + } + if (isThinking) { + currentBlock = { type: "thinking", thinking: "", thinkingSignature: void 0 }; + output.content.push(currentBlock); + ensureStarted(); + stream2.push({ + type: "thinking_start", + contentIndex: blockIndex(), + partial: output + }); + } else { + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + ensureStarted(); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + } + if (currentBlock.type === "thinking") { + currentBlock.thinking += part.text; + currentBlock.thinkingSignature = retainThoughtSignature2(currentBlock.thinkingSignature, part.thoughtSignature); + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output + }); + } else { + currentBlock.text += part.text; + currentBlock.textSignature = retainThoughtSignature2(currentBlock.textSignature, part.thoughtSignature); + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output + }); + } + } + if (part.functionCall) { + hasContent = true; + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + currentBlock = null; + } + const providedId = part.functionCall.id; + const needsNewId = !providedId || output.content.some((b4) => b4.type === "toolCall" && b4.id === providedId); + const toolCallId = needsNewId ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter5}` : providedId; + const toolCall = { + type: "toolCall", + id: toolCallId, + name: part.functionCall.name || "", + arguments: part.functionCall.args ?? {}, + ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature } + }; + output.content.push(toolCall); + ensureStarted(); + stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output }); + stream2.push({ + type: "toolcall_delta", + contentIndex: blockIndex(), + delta: JSON.stringify(toolCall.arguments), + partial: output + }); + stream2.push({ + type: "toolcall_end", + contentIndex: blockIndex(), + toolCall, + partial: output + }); + } + } + } + if (candidate?.finishReason) { + output.stopReason = mapStopReasonString2(candidate.finishReason); + if (output.content.some((b4) => b4.type === "toolCall")) { + output.stopReason = "toolUse"; + } + } + if (responseData.usageMetadata) { + const promptTokens = responseData.usageMetadata.promptTokenCount || 0; + const cacheReadTokens = responseData.usageMetadata.cachedContentTokenCount || 0; + output.usage = { + input: promptTokens - cacheReadTokens, + output: (responseData.usageMetadata.candidatesTokenCount || 0) + (responseData.usageMetadata.thoughtsTokenCount || 0), + cacheRead: cacheReadTokens, + cacheWrite: 0, + totalTokens: responseData.usageMetadata.totalTokenCount || 0, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + total: 0 + } + }; + calculateCost2(model, output.usage); + } + } + } + } finally { + options?.signal?.removeEventListener("abort", abortHandler); + } + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + } + return hasContent; + }; + let receivedContent = false; + let currentResponse = response; + for (let emptyAttempt = 0; emptyAttempt <= MAX_EMPTY_STREAM_RETRIES2; emptyAttempt++) { + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (emptyAttempt > 0) { + const backoffMs = EMPTY_STREAM_BASE_DELAY_MS2 * 2 ** (emptyAttempt - 1); + await sleep6(backoffMs, options?.signal); + if (!requestUrl) { + throw new Error("Missing request URL"); + } + currentResponse = await fetch(requestUrl, { + method: "POST", + headers: requestHeaders, + body: requestBodyJson, + signal: options?.signal + }); + if (!currentResponse.ok) { + const retryErrorText = await currentResponse.text(); + throw new Error(`Cloud Code Assist API error (${currentResponse.status}): ${retryErrorText}`); + } + } + const streamed = await streamResponse(currentResponse); + if (streamed) { + receivedContent = true; + break; + } + if (emptyAttempt < MAX_EMPTY_STREAM_RETRIES2) { + resetOutput(); + } + } + if (!receivedContent) { + throw new Error("Cloud Code Assist API returned an empty response"); + } + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) { + if ("index" in block) { + delete block.index; + } + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleGoogleGeminiCli2 = (model, context, options) => { + const apiKey = options?.apiKey; + if (!apiKey) { + throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate."); + } + const base = buildBaseOptions2(model, options, apiKey); + if (!options?.reasoning) { + return streamGoogleGeminiCli2(model, context, { + ...base, + thinking: { enabled: false } + }); + } + const effort = clampReasoning2(options.reasoning); + if (isGemini3Model2(model.id)) { + return streamGoogleGeminiCli2(model, context, { + ...base, + thinking: { + enabled: true, + level: getGeminiCliThinkingLevel2(effort, model.id) + } + }); + } + const defaultBudgets = { + minimal: 1024, + low: 2048, + medium: 8192, + high: 16384 + }; + const budgets = { ...defaultBudgets, ...options.thinkingBudgets }; + const minOutputTokens = 1024; + let thinkingBudget = budgets[effort]; + const maxTokens = Math.min((base.maxTokens || 0) + thinkingBudget, model.maxTokens); + if (maxTokens <= thinkingBudget) { + thinkingBudget = Math.max(0, maxTokens - minOutputTokens); + } + return streamGoogleGeminiCli2(model, context, { + ...base, + maxTokens, + thinking: { + enabled: true, + budgetTokens: thinkingBudget + } + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/google-vertex.js +function createClient10(model, project, location, optionsHeaders) { + const httpOptions = {}; + if (model.headers || optionsHeaders) { + httpOptions.headers = { ...model.headers, ...optionsHeaders }; + } + const hasHttpOptions = Object.values(httpOptions).some(Boolean); + return new GoogleGenAI({ + vertexai: true, + project, + location, + apiVersion: API_VERSION2, + httpOptions: hasHttpOptions ? httpOptions : void 0 + }); +} +function createClientWithApiKey2(model, apiKey, optionsHeaders) { + const httpOptions = {}; + if (model.headers || optionsHeaders) { + httpOptions.headers = { ...model.headers, ...optionsHeaders }; + } + const hasHttpOptions = Object.values(httpOptions).some(Boolean); + return new GoogleGenAI({ + vertexai: true, + apiKey, + apiVersion: API_VERSION2, + httpOptions: hasHttpOptions ? httpOptions : void 0 + }); +} +function resolveApiKey2(options) { + return options?.apiKey || process.env.GOOGLE_CLOUD_API_KEY; +} +function resolveProject2(options) { + const project = options?.project || process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT; + if (!project) { + throw new Error("Vertex AI requires a project ID. Set GOOGLE_CLOUD_PROJECT/GCLOUD_PROJECT or pass project in options."); + } + return project; +} +function resolveLocation2(options) { + const location = options?.location || process.env.GOOGLE_CLOUD_LOCATION; + if (!location) { + throw new Error("Vertex AI requires a location. Set GOOGLE_CLOUD_LOCATION or pass location in options."); + } + return location; +} +function buildParams10(model, context, options = {}) { + const contents = convertMessages5(model, context); + const generationConfig = {}; + if (options.temperature !== void 0) { + generationConfig.temperature = options.temperature; + } + if (options.maxTokens !== void 0) { + generationConfig.maxOutputTokens = options.maxTokens; + } + const config = { + ...Object.keys(generationConfig).length > 0 && generationConfig, + ...context.systemPrompt && { systemInstruction: sanitizeSurrogates2(context.systemPrompt) }, + ...context.tools && context.tools.length > 0 && { tools: convertTools5(context.tools) } + }; + if (context.tools && context.tools.length > 0 && options.toolChoice) { + config.toolConfig = { + functionCallingConfig: { + mode: mapToolChoice3(options.toolChoice) + } + }; + } else { + config.toolConfig = void 0; + } + if (options.thinking?.enabled && model.reasoning) { + const thinkingConfig = { includeThoughts: true }; + if (options.thinking.level !== void 0) { + thinkingConfig.thinkingLevel = THINKING_LEVEL_MAP2[options.thinking.level]; + } else if (options.thinking.budgetTokens !== void 0) { + thinkingConfig.thinkingBudget = options.thinking.budgetTokens; + } + config.thinkingConfig = thinkingConfig; + } + if (options.signal) { + if (options.signal.aborted) { + throw new Error("Request aborted"); + } + config.abortSignal = options.signal; + } + const params = { + model: model.id, + contents, + config + }; + return params; +} +function isGemini3ProModel6(model) { + return /gemini-3(?:\.\d+)?-pro/.test(model.id.toLowerCase()); +} +function isGemini3FlashModel6(model) { + return /gemini-3(?:\.\d+)?-flash/.test(model.id.toLowerCase()); +} +function getGemini3ThinkingLevel4(effort, model) { + if (isGemini3ProModel6(model)) { + switch (effort) { + case "minimal": + case "low": + return "LOW"; + case "medium": + case "high": + return "HIGH"; + } + } + switch (effort) { + case "minimal": + return "MINIMAL"; + case "low": + return "LOW"; + case "medium": + return "MEDIUM"; + case "high": + return "HIGH"; + } +} +function getGoogleBudget4(model, effort, customBudgets) { + if (customBudgets?.[effort] !== void 0) { + return customBudgets[effort]; + } + if (model.id.includes("2.5-pro")) { + const budgets = { + minimal: 128, + low: 2048, + medium: 8192, + high: 32768 + }; + return budgets[effort]; + } + if (model.id.includes("2.5-flash")) { + const budgets = { + minimal: 128, + low: 2048, + medium: 8192, + high: 24576 + }; + return budgets[effort]; + } + return -1; +} +var API_VERSION2, THINKING_LEVEL_MAP2, toolCallCounter6, streamGoogleVertex2, streamSimpleGoogleVertex2; +var init_google_vertex = __esm({ + "../pi-mono/packages/ai/dist/providers/google-vertex.js"() { + "use strict"; + init_process_shim(); + init_web(); + init_models4(); + init_event_stream(); + init_sanitize_unicode(); + init_google_shared(); + init_simple_options(); + API_VERSION2 = "v1"; + THINKING_LEVEL_MAP2 = { + THINKING_LEVEL_UNSPECIFIED: ThinkingLevel.THINKING_LEVEL_UNSPECIFIED, + MINIMAL: ThinkingLevel.MINIMAL, + LOW: ThinkingLevel.LOW, + MEDIUM: ThinkingLevel.MEDIUM, + HIGH: ThinkingLevel.HIGH + }; + toolCallCounter6 = 0; + streamGoogleVertex2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: "google-vertex", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = resolveApiKey2(options); + const client = apiKey ? createClientWithApiKey2(model, apiKey, options?.headers) : createClient10(model, resolveProject2(options), resolveLocation2(options), options?.headers); + let params = buildParams10(model, context, options); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== void 0) { + params = nextParams; + } + const googleStream = await client.models.generateContentStream(params); + stream2.push({ type: "start", partial: output }); + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + for await (const chunk of googleStream) { + const candidate = chunk.candidates?.[0]; + if (candidate?.content?.parts) { + for (const part of candidate.content.parts) { + if (part.text !== void 0) { + const isThinking = isThinkingPart2(part); + if (!currentBlock || isThinking && currentBlock.type !== "thinking" || !isThinking && currentBlock.type !== "text") { + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blocks.length - 1, + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + } + if (isThinking) { + currentBlock = { type: "thinking", thinking: "", thinkingSignature: void 0 }; + output.content.push(currentBlock); + stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } else { + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + } + if (currentBlock.type === "thinking") { + currentBlock.thinking += part.text; + currentBlock.thinkingSignature = retainThoughtSignature2(currentBlock.thinkingSignature, part.thoughtSignature); + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output + }); + } else { + currentBlock.text += part.text; + currentBlock.textSignature = retainThoughtSignature2(currentBlock.textSignature, part.thoughtSignature); + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: part.text, + partial: output + }); + } + } + if (part.functionCall) { + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + currentBlock = null; + } + const providedId = part.functionCall.id; + const needsNewId = !providedId || output.content.some((b4) => b4.type === "toolCall" && b4.id === providedId); + const toolCallId = needsNewId ? `${part.functionCall.name}_${Date.now()}_${++toolCallCounter6}` : providedId; + const toolCall = { + type: "toolCall", + id: toolCallId, + name: part.functionCall.name || "", + arguments: part.functionCall.args ?? {}, + ...part.thoughtSignature && { thoughtSignature: part.thoughtSignature } + }; + output.content.push(toolCall); + stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output }); + stream2.push({ + type: "toolcall_delta", + contentIndex: blockIndex(), + delta: JSON.stringify(toolCall.arguments), + partial: output + }); + stream2.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output }); + } + } + } + if (candidate?.finishReason) { + output.stopReason = mapStopReason7(candidate.finishReason); + if (output.content.some((b4) => b4.type === "toolCall")) { + output.stopReason = "toolUse"; + } + } + if (chunk.usageMetadata) { + output.usage = { + input: chunk.usageMetadata.promptTokenCount || 0, + output: (chunk.usageMetadata.candidatesTokenCount || 0) + (chunk.usageMetadata.thoughtsTokenCount || 0), + cacheRead: chunk.usageMetadata.cachedContentTokenCount || 0, + cacheWrite: 0, + totalTokens: chunk.usageMetadata.totalTokenCount || 0, + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + total: 0 + } + }; + calculateCost2(model, output.usage); + } + } + if (currentBlock) { + if (currentBlock.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: currentBlock.text, + partial: output + }); + } else { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: currentBlock.thinking, + partial: output + }); + } + } + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) { + if ("index" in block) { + delete block.index; + } + } + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleGoogleVertex2 = (model, context, options) => { + const base = buildBaseOptions2(model, options, void 0); + if (!options?.reasoning) { + return streamGoogleVertex2(model, context, { + ...base, + thinking: { enabled: false } + }); + } + const effort = clampReasoning2(options.reasoning); + const geminiModel = model; + if (isGemini3ProModel6(geminiModel) || isGemini3FlashModel6(geminiModel)) { + return streamGoogleVertex2(model, context, { + ...base, + thinking: { + enabled: true, + level: getGemini3ThinkingLevel4(effort, geminiModel) + } + }); + } + return streamGoogleVertex2(model, context, { + ...base, + thinking: { + enabled: true, + budgetTokens: getGoogleBudget4(geminiModel, effort, options.thinkingBudgets) + } + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/mistral.js +function createOutput2(model) { + return { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; +} +function createMistralToolCallIdNormalizer2() { + const idMap = /* @__PURE__ */ new Map(); + const reverseMap = /* @__PURE__ */ new Map(); + return (id) => { + const existing = idMap.get(id); + if (existing) + return existing; + let attempt = 0; + while (true) { + const candidate = deriveMistralToolCallId2(id, attempt); + const owner = reverseMap.get(candidate); + if (!owner || owner === id) { + idMap.set(id, candidate); + reverseMap.set(candidate, id); + return candidate; + } + attempt++; + } + }; +} +function deriveMistralToolCallId2(id, attempt) { + const normalized = id.replace(/[^a-zA-Z0-9]/g, ""); + if (attempt === 0 && normalized.length === MISTRAL_TOOL_CALL_ID_LENGTH2) + return normalized; + const seedBase = normalized || id; + const seed = attempt === 0 ? seedBase : `${seedBase}:${attempt}`; + return shortHash2(seed).replace(/[^a-zA-Z0-9]/g, "").slice(0, MISTRAL_TOOL_CALL_ID_LENGTH2); +} +function formatMistralError2(error) { + if (error instanceof Error) { + const sdkError = error; + const statusCode = typeof sdkError.statusCode === "number" ? sdkError.statusCode : void 0; + const bodyText = typeof sdkError.body === "string" ? sdkError.body.trim() : void 0; + if (statusCode !== void 0 && bodyText) { + return `Mistral API error (${statusCode}): ${truncateErrorText2(bodyText, MAX_MISTRAL_ERROR_BODY_CHARS2)}`; + } + if (statusCode !== void 0) + return `Mistral API error (${statusCode}): ${error.message}`; + return error.message; + } + return safeJsonStringify2(error); +} +function truncateErrorText2(text3, maxChars) { + if (text3.length <= maxChars) + return text3; + return `${text3.slice(0, maxChars)}... [truncated ${text3.length - maxChars} chars]`; +} +function safeJsonStringify2(value) { + try { + const serialized = JSON.stringify(value); + return serialized === void 0 ? String(value) : serialized; + } catch { + return String(value); + } +} +function buildRequestOptions2(model, options) { + const requestOptions = {}; + if (options?.signal) + requestOptions.signal = options.signal; + requestOptions.retries = { strategy: "none" }; + const headers = {}; + if (model.headers) + Object.assign(headers, model.headers); + if (options?.headers) + Object.assign(headers, options.headers); + if (options?.sessionId && !headers["x-affinity"]) { + headers["x-affinity"] = options.sessionId; + } + if (Object.keys(headers).length > 0) { + requestOptions.headers = headers; + } + return requestOptions; +} +function buildChatPayload2(model, context, messages, options) { + const payload = { + model: model.id, + stream: true, + messages: toChatMessages2(messages, model.input.includes("image")) + }; + if (context.tools?.length) + payload.tools = toFunctionTools2(context.tools); + if (options?.temperature !== void 0) + payload.temperature = options.temperature; + if (options?.maxTokens !== void 0) + payload.maxTokens = options.maxTokens; + if (options?.toolChoice) + payload.toolChoice = mapToolChoice4(options.toolChoice); + if (options?.promptMode) + payload.promptMode = options.promptMode; + if (context.systemPrompt) { + payload.messages.unshift({ + role: "system", + content: sanitizeSurrogates2(context.systemPrompt) + }); + } + return payload; +} +async function consumeChatStream2(model, output, stream2, mistralStream) { + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + const toolBlocksByKey = /* @__PURE__ */ new Map(); + const finishCurrentBlock = (block) => { + if (!block) + return; + if (block.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: block.text, + partial: output + }); + return; + } + if (block.type === "thinking") { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: block.thinking, + partial: output + }); + } + }; + for await (const event of mistralStream) { + const chunk = event.data; + if (chunk.usage) { + output.usage.input = chunk.usage.promptTokens || 0; + output.usage.output = chunk.usage.completionTokens || 0; + output.usage.cacheRead = 0; + output.usage.cacheWrite = 0; + output.usage.totalTokens = chunk.usage.totalTokens || output.usage.input + output.usage.output; + calculateCost2(model, output.usage); + } + const choice = chunk.choices[0]; + if (!choice) + continue; + if (choice.finishReason) { + output.stopReason = mapChatStopReason2(choice.finishReason); + } + const delta = choice.delta; + if (delta.content !== null && delta.content !== void 0) { + const contentItems = typeof delta.content === "string" ? [delta.content] : delta.content; + for (const item of contentItems) { + if (typeof item === "string") { + const textDelta = sanitizeSurrogates2(item); + if (!currentBlock || currentBlock.type !== "text") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + currentBlock.text += textDelta; + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: textDelta, + partial: output + }); + continue; + } + if (item.type === "thinking") { + const deltaText = item.thinking.map((part) => "text" in part ? part.text : "").filter((text3) => text3.length > 0).join(""); + const thinkingDelta = sanitizeSurrogates2(deltaText); + if (!thinkingDelta) + continue; + if (!currentBlock || currentBlock.type !== "thinking") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "thinking", thinking: "" }; + output.content.push(currentBlock); + stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } + currentBlock.thinking += thinkingDelta; + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta: thinkingDelta, + partial: output + }); + continue; + } + if (item.type === "text") { + const textDelta = sanitizeSurrogates2(item.text); + if (!currentBlock || currentBlock.type !== "text") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + currentBlock.text += textDelta; + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: textDelta, + partial: output + }); + } + } + } + const toolCalls = delta.toolCalls || []; + for (const toolCall of toolCalls) { + if (currentBlock) { + finishCurrentBlock(currentBlock); + currentBlock = null; + } + const callId = toolCall.id && toolCall.id !== "null" ? toolCall.id : deriveMistralToolCallId2(`toolcall:${toolCall.index ?? 0}`, 0); + const key = `${callId}:${toolCall.index || 0}`; + const existingIndex = toolBlocksByKey.get(key); + let block; + if (existingIndex !== void 0) { + const existing = output.content[existingIndex]; + if (existing?.type === "toolCall") { + block = existing; + } + } + if (!block) { + block = { + type: "toolCall", + id: callId, + name: toolCall.function.name, + arguments: {}, + partialArgs: "" + }; + output.content.push(block); + toolBlocksByKey.set(key, output.content.length - 1); + stream2.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output }); + } + const argsDelta = typeof toolCall.function.arguments === "string" ? toolCall.function.arguments : JSON.stringify(toolCall.function.arguments || {}); + block.partialArgs = (block.partialArgs || "") + argsDelta; + block.arguments = parseStreamingJson2(block.partialArgs); + stream2.push({ + type: "toolcall_delta", + contentIndex: toolBlocksByKey.get(key), + delta: argsDelta, + partial: output + }); + } + } + finishCurrentBlock(currentBlock); + for (const index2 of toolBlocksByKey.values()) { + const block = output.content[index2]; + if (block.type !== "toolCall") + continue; + const toolBlock = block; + toolBlock.arguments = parseStreamingJson2(toolBlock.partialArgs); + delete toolBlock.partialArgs; + stream2.push({ + type: "toolcall_end", + contentIndex: index2, + toolCall: toolBlock, + partial: output + }); + } +} +function toFunctionTools2(tools) { + return tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + strict: false + } + })); +} +function toChatMessages2(messages, supportsImages) { + const result = []; + for (const msg of messages) { + if (msg.role === "user") { + if (typeof msg.content === "string") { + result.push({ role: "user", content: sanitizeSurrogates2(msg.content) }); + continue; + } + const hadImages = msg.content.some((item) => item.type === "image"); + const content = msg.content.filter((item) => item.type === "text" || supportsImages).map((item) => { + if (item.type === "text") + return { type: "text", text: sanitizeSurrogates2(item.text) }; + return { type: "image_url", imageUrl: `data:${item.mimeType};base64,${item.data}` }; + }); + if (content.length > 0) { + result.push({ role: "user", content }); + continue; + } + if (hadImages && !supportsImages) { + result.push({ role: "user", content: "(image omitted: model does not support images)" }); + } + continue; + } + if (msg.role === "assistant") { + const contentParts = []; + const toolCalls = []; + for (const block of msg.content) { + if (block.type === "text") { + if (block.text.trim().length > 0) { + contentParts.push({ type: "text", text: sanitizeSurrogates2(block.text) }); + } + continue; + } + if (block.type === "thinking") { + if (block.thinking.trim().length > 0) { + contentParts.push({ + type: "thinking", + thinking: [{ type: "text", text: sanitizeSurrogates2(block.thinking) }] + }); + } + continue; + } + toolCalls.push({ + id: block.id, + type: "function", + function: { name: block.name, arguments: JSON.stringify(block.arguments || {}) } + }); + } + const assistantMessage = { role: "assistant" }; + if (contentParts.length > 0) + assistantMessage.content = contentParts; + if (toolCalls.length > 0) + assistantMessage.toolCalls = toolCalls; + if (contentParts.length > 0 || toolCalls.length > 0) + result.push(assistantMessage); + continue; + } + const toolContent = []; + const textResult = msg.content.filter((part) => part.type === "text").map((part) => part.type === "text" ? sanitizeSurrogates2(part.text) : "").join("\n"); + const hasImages = msg.content.some((part) => part.type === "image"); + const toolText = buildToolResultText2(textResult, hasImages, supportsImages, msg.isError); + toolContent.push({ type: "text", text: toolText }); + for (const part of msg.content) { + if (!supportsImages) + continue; + if (part.type !== "image") + continue; + toolContent.push({ + type: "image_url", + imageUrl: `data:${part.mimeType};base64,${part.data}` + }); + } + result.push({ + role: "tool", + toolCallId: msg.toolCallId, + name: msg.toolName, + content: toolContent + }); + } + return result; +} +function buildToolResultText2(text3, hasImages, supportsImages, isError2) { + const trimmed = text3.trim(); + const errorPrefix = isError2 ? "[tool error] " : ""; + if (trimmed.length > 0) { + const imageSuffix = hasImages && !supportsImages ? "\n[tool image omitted: model does not support images]" : ""; + return `${errorPrefix}${trimmed}${imageSuffix}`; + } + if (hasImages) { + if (supportsImages) { + return isError2 ? "[tool error] (see attached image)" : "(see attached image)"; + } + return isError2 ? "[tool error] (image omitted: model does not support images)" : "(image omitted: model does not support images)"; + } + return isError2 ? "[tool error] (no tool output)" : "(no tool output)"; +} +function mapToolChoice4(choice) { + if (!choice) + return void 0; + if (choice === "auto" || choice === "none" || choice === "any" || choice === "required") { + return choice; + } + return { + type: "function", + function: { name: choice.function.name } + }; +} +function mapChatStopReason2(reason) { + if (reason === null) + return "stop"; + switch (reason) { + case "stop": + return "stop"; + case "length": + case "model_length": + return "length"; + case "tool_calls": + return "toolUse"; + case "error": + return "error"; + default: + return "stop"; + } +} +var import_mistralai2, MISTRAL_TOOL_CALL_ID_LENGTH2, MAX_MISTRAL_ERROR_BODY_CHARS2, streamMistral2, streamSimpleMistral2; +var init_mistral = __esm({ + "../pi-mono/packages/ai/dist/providers/mistral.js"() { + "use strict"; + init_process_shim(); + import_mistralai2 = __toESM(require_mistralai(), 1); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_hash(); + init_json_parse(); + init_sanitize_unicode(); + init_simple_options(); + init_transform_messages(); + MISTRAL_TOOL_CALL_ID_LENGTH2 = 9; + MAX_MISTRAL_ERROR_BODY_CHARS2 = 4e3; + streamMistral2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = createOutput2(model); + try { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const mistral = new import_mistralai2.Mistral({ + apiKey, + serverURL: model.baseUrl + }); + const normalizeMistralToolCallId = createMistralToolCallIdNormalizer2(); + const transformedMessages = transformMessages2(context.messages, model, (id) => normalizeMistralToolCallId(id)); + let payload = buildChatPayload2(model, context, transformedMessages, options); + const nextPayload = await options?.onPayload?.(payload, model); + if (nextPayload !== void 0) { + payload = nextPayload; + } + const mistralStream = await mistral.chat.stream(payload, buildRequestOptions2(model, options)); + stream2.push({ type: "start", partial: output }); + await consumeChatStream2(model, output, stream2, mistralStream); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = formatMistralError2(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleMistral2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + const reasoning = clampReasoning2(options?.reasoning); + return streamMistral2(model, context, { + ...base, + promptMode: model.reasoning && reasoning ? "reasoning" : void 0 + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/openai-completions.js +function hasToolHistory2(messages) { + for (const msg of messages) { + if (msg.role === "toolResult") { + return true; + } + if (msg.role === "assistant") { + if (msg.content.some((block) => block.type === "toolCall")) { + return true; + } + } + } + return false; +} +function createClient11(model, context, apiKey, optionsHeaders) { + if (!apiKey) { + if (!process.env.OPENAI_API_KEY) { + throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument."); + } + apiKey = process.env.OPENAI_API_KEY; + } + const headers = { ...model.headers }; + if (model.provider === "github-copilot") { + const hasImages = hasCopilotVisionInput2(context.messages); + const copilotHeaders = buildCopilotDynamicHeaders2({ + messages: context.messages, + hasImages + }); + Object.assign(headers, copilotHeaders); + } + if (optionsHeaders) { + Object.assign(headers, optionsHeaders); + } + return new OpenAI({ + apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + defaultHeaders: headers + }); +} +function buildParams11(model, context, options) { + const compat = getCompat2(model); + const messages = convertMessages6(model, context, compat); + maybeAddOpenRouterAnthropicCacheControl2(model, messages); + const params = { + model: model.id, + messages, + stream: true + }; + if (compat.supportsUsageInStreaming !== false) { + params.stream_options = { include_usage: true }; + } + if (compat.supportsStore) { + params.store = false; + } + if (options?.maxTokens) { + if (compat.maxTokensField === "max_tokens") { + params.max_tokens = options.maxTokens; + } else { + params.max_completion_tokens = options.maxTokens; + } + } + if (options?.temperature !== void 0) { + params.temperature = options.temperature; + } + if (context.tools) { + params.tools = convertTools6(context.tools, compat); + } else if (hasToolHistory2(context.messages)) { + params.tools = []; + } + if (options?.toolChoice) { + params.tool_choice = options.toolChoice; + } + if (compat.thinkingFormat === "zai" && model.reasoning) { + params.enable_thinking = !!options?.reasoningEffort; + } else if (compat.thinkingFormat === "qwen" && model.reasoning) { + params.enable_thinking = !!options?.reasoningEffort; + } else if (compat.thinkingFormat === "qwen-chat-template" && model.reasoning) { + params.chat_template_kwargs = { enable_thinking: !!options?.reasoningEffort }; + } else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) { + params.reasoning_effort = mapReasoningEffort2(options.reasoningEffort, compat.reasoningEffortMap); + } + if (model.baseUrl.includes("openrouter.ai") && model.compat?.openRouterRouting) { + params.provider = model.compat.openRouterRouting; + } + if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) { + const routing = model.compat.vercelGatewayRouting; + if (routing.only || routing.order) { + const gatewayOptions = {}; + if (routing.only) + gatewayOptions.only = routing.only; + if (routing.order) + gatewayOptions.order = routing.order; + params.providerOptions = { gateway: gatewayOptions }; + } + } + return params; +} +function mapReasoningEffort2(effort, reasoningEffortMap) { + return reasoningEffortMap[effort] ?? effort; +} +function maybeAddOpenRouterAnthropicCacheControl2(model, messages) { + if (model.provider !== "openrouter" || !model.id.startsWith("anthropic/")) + return; + for (let i7 = messages.length - 1; i7 >= 0; i7--) { + const msg = messages[i7]; + if (msg.role !== "user" && msg.role !== "assistant") + continue; + const content = msg.content; + if (typeof content === "string") { + msg.content = [ + Object.assign({ type: "text", text: content }, { cache_control: { type: "ephemeral" } }) + ]; + return; + } + if (!Array.isArray(content)) + continue; + for (let j3 = content.length - 1; j3 >= 0; j3--) { + const part = content[j3]; + if (part?.type === "text") { + Object.assign(part, { cache_control: { type: "ephemeral" } }); + return; + } + } + } +} +function convertMessages6(model, context, compat) { + const params = []; + const normalizeToolCallId3 = (id) => { + if (id.includes("|")) { + const [callId] = id.split("|"); + return callId.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40); + } + if (model.provider === "openai") + return id.length > 40 ? id.slice(0, 40) : id; + return id; + }; + const transformedMessages = transformMessages2(context.messages, model, (id) => normalizeToolCallId3(id)); + if (context.systemPrompt) { + const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole; + const role = useDeveloperRole ? "developer" : "system"; + params.push({ role, content: sanitizeSurrogates2(context.systemPrompt) }); + } + let lastRole = null; + for (let i7 = 0; i7 < transformedMessages.length; i7++) { + const msg = transformedMessages[i7]; + if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") { + params.push({ + role: "assistant", + content: "I have processed the tool results." + }); + } + if (msg.role === "user") { + if (typeof msg.content === "string") { + params.push({ + role: "user", + content: sanitizeSurrogates2(msg.content) + }); + } else { + const content = msg.content.map((item) => { + if (item.type === "text") { + return { + type: "text", + text: sanitizeSurrogates2(item.text) + }; + } else { + return { + type: "image_url", + image_url: { + url: `data:${item.mimeType};base64,${item.data}` + } + }; + } + }); + const filteredContent = !model.input.includes("image") ? content.filter((c6) => c6.type !== "image_url") : content; + if (filteredContent.length === 0) + continue; + params.push({ + role: "user", + content: filteredContent + }); + } + } else if (msg.role === "assistant") { + const assistantMsg = { + role: "assistant", + content: compat.requiresAssistantAfterToolResult ? "" : null + }; + const textBlocks = msg.content.filter((b4) => b4.type === "text"); + const nonEmptyTextBlocks = textBlocks.filter((b4) => b4.text && b4.text.trim().length > 0); + if (nonEmptyTextBlocks.length > 0) { + assistantMsg.content = nonEmptyTextBlocks.map((b4) => sanitizeSurrogates2(b4.text)).join(""); + } + const thinkingBlocks = msg.content.filter((b4) => b4.type === "thinking"); + const nonEmptyThinkingBlocks = thinkingBlocks.filter((b4) => b4.thinking && b4.thinking.trim().length > 0); + if (nonEmptyThinkingBlocks.length > 0) { + if (compat.requiresThinkingAsText) { + const thinkingText = nonEmptyThinkingBlocks.map((b4) => b4.thinking).join("\n\n"); + const textContent = assistantMsg.content; + if (textContent) { + textContent.unshift({ type: "text", text: thinkingText }); + } else { + assistantMsg.content = [{ type: "text", text: thinkingText }]; + } + } else { + const signature = nonEmptyThinkingBlocks[0].thinkingSignature; + if (signature && signature.length > 0) { + assistantMsg[signature] = nonEmptyThinkingBlocks.map((b4) => b4.thinking).join("\n"); + } + } + } + const toolCalls = msg.content.filter((b4) => b4.type === "toolCall"); + if (toolCalls.length > 0) { + assistantMsg.tool_calls = toolCalls.map((tc) => ({ + id: tc.id, + type: "function", + function: { + name: tc.name, + arguments: JSON.stringify(tc.arguments) + } + })); + const reasoningDetails = toolCalls.filter((tc) => tc.thoughtSignature).map((tc) => { + try { + return JSON.parse(tc.thoughtSignature); + } catch { + return null; + } + }).filter(Boolean); + if (reasoningDetails.length > 0) { + assistantMsg.reasoning_details = reasoningDetails; + } + } + const content = assistantMsg.content; + const hasContent = content !== null && content !== void 0 && (typeof content === "string" ? content.length > 0 : content.length > 0); + if (!hasContent && !assistantMsg.tool_calls) { + continue; + } + params.push(assistantMsg); + } else if (msg.role === "toolResult") { + const imageBlocks = []; + let j3 = i7; + for (; j3 < transformedMessages.length && transformedMessages[j3].role === "toolResult"; j3++) { + const toolMsg = transformedMessages[j3]; + const textResult = toolMsg.content.filter((c6) => c6.type === "text").map((c6) => c6.text).join("\n"); + const hasImages = toolMsg.content.some((c6) => c6.type === "image"); + const hasText = textResult.length > 0; + const toolResultMsg = { + role: "tool", + content: sanitizeSurrogates2(hasText ? textResult : "(see attached image)"), + tool_call_id: toolMsg.toolCallId + }; + if (compat.requiresToolResultName && toolMsg.toolName) { + toolResultMsg.name = toolMsg.toolName; + } + params.push(toolResultMsg); + if (hasImages && model.input.includes("image")) { + for (const block of toolMsg.content) { + if (block.type === "image") { + imageBlocks.push({ + type: "image_url", + image_url: { + url: `data:${block.mimeType};base64,${block.data}` + } + }); + } + } + } + } + i7 = j3 - 1; + if (imageBlocks.length > 0) { + if (compat.requiresAssistantAfterToolResult) { + params.push({ + role: "assistant", + content: "I have processed the tool results." + }); + } + params.push({ + role: "user", + content: [ + { + type: "text", + text: "Attached image(s) from tool result:" + }, + ...imageBlocks + ] + }); + lastRole = "user"; + } else { + lastRole = "toolResult"; + } + continue; + } + lastRole = msg.role; + } + return params; +} +function convertTools6(tools, compat) { + return tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + // TypeBox already generates JSON Schema + // Only include strict if provider supports it. Some reject unknown fields. + ...compat.supportsStrictMode !== false && { strict: false } + } + })); +} +function parseChunkUsage2(rawUsage, model) { + const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens || 0; + const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens || 0; + const input = (rawUsage.prompt_tokens || 0) - cachedTokens; + const outputTokens = (rawUsage.completion_tokens || 0) + reasoningTokens; + const usage = { + input, + output: outputTokens, + cacheRead: cachedTokens, + cacheWrite: 0, + totalTokens: input + outputTokens + cachedTokens, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }; + calculateCost2(model, usage); + return usage; +} +function mapStopReason8(reason) { + if (reason === null) + return "stop"; + switch (reason) { + case "stop": + case "end": + return "stop"; + case "length": + return "length"; + case "function_call": + case "tool_calls": + return "toolUse"; + case "content_filter": + return "error"; + default: { + const _exhaustive = reason; + throw new Error(`Unhandled stop reason: ${_exhaustive}`); + } + } +} +function detectCompat2(model) { + const provider = model.provider; + const baseUrl = model.baseUrl; + const isZai = provider === "zai" || baseUrl.includes("api.z.ai"); + const isNonStandard = provider === "cerebras" || baseUrl.includes("cerebras.ai") || provider === "xai" || baseUrl.includes("api.x.ai") || baseUrl.includes("chutes.ai") || baseUrl.includes("deepseek.com") || isZai || provider === "opencode" || baseUrl.includes("opencode.ai"); + const useMaxTokens = baseUrl.includes("chutes.ai"); + const isGrok = provider === "xai" || baseUrl.includes("api.x.ai"); + const isGroq = provider === "groq" || baseUrl.includes("groq.com"); + const reasoningEffortMap = isGroq && model.id === "qwen/qwen3-32b" ? { + minimal: "default", + low: "default", + medium: "default", + high: "default", + xhigh: "default" + } : {}; + return { + supportsStore: !isNonStandard, + supportsDeveloperRole: !isNonStandard, + supportsReasoningEffort: !isGrok && !isZai, + reasoningEffortMap, + supportsUsageInStreaming: true, + maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens", + requiresToolResultName: false, + requiresAssistantAfterToolResult: false, + requiresThinkingAsText: false, + thinkingFormat: isZai ? "zai" : "openai", + openRouterRouting: {}, + vercelGatewayRouting: {}, + supportsStrictMode: true + }; +} +function getCompat2(model) { + const detected = detectCompat2(model); + if (!model.compat) + return detected; + return { + supportsStore: model.compat.supportsStore ?? detected.supportsStore, + supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole, + supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort, + reasoningEffortMap: model.compat.reasoningEffortMap ?? detected.reasoningEffortMap, + supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming, + maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField, + requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName, + requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult, + requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText, + thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat, + openRouterRouting: model.compat.openRouterRouting ?? {}, + vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting, + supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode + }; +} +var streamOpenAICompletions2, streamSimpleOpenAICompletions2; +var init_openai_completions = __esm({ + "../pi-mono/packages/ai/dist/providers/openai-completions.js"() { + "use strict"; + init_process_shim(); + init_openai(); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_json_parse(); + init_sanitize_unicode(); + init_github_copilot_headers(); + init_simple_options(); + init_transform_messages(); + streamOpenAICompletions2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider) || ""; + const client = createClient11(model, context, apiKey, options?.headers); + let params = buildParams11(model, context, options); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== void 0) { + params = nextParams; + } + const openaiStream = await client.chat.completions.create(params, { signal: options?.signal }); + stream2.push({ type: "start", partial: output }); + let currentBlock = null; + const blocks = output.content; + const blockIndex = () => blocks.length - 1; + const finishCurrentBlock = (block) => { + if (block) { + if (block.type === "text") { + stream2.push({ + type: "text_end", + contentIndex: blockIndex(), + content: block.text, + partial: output + }); + } else if (block.type === "thinking") { + stream2.push({ + type: "thinking_end", + contentIndex: blockIndex(), + content: block.thinking, + partial: output + }); + } else if (block.type === "toolCall") { + block.arguments = parseStreamingJson2(block.partialArgs); + delete block.partialArgs; + stream2.push({ + type: "toolcall_end", + contentIndex: blockIndex(), + toolCall: block, + partial: output + }); + } + } + }; + for await (const chunk of openaiStream) { + if (chunk.usage) { + output.usage = parseChunkUsage2(chunk.usage, model); + } + const choice = chunk.choices?.[0]; + if (!choice) + continue; + if (!chunk.usage && choice.usage) { + output.usage = parseChunkUsage2(choice.usage, model); + } + if (choice.finish_reason) { + output.stopReason = mapStopReason8(choice.finish_reason); + } + if (choice.delta) { + if (choice.delta.content !== null && choice.delta.content !== void 0 && choice.delta.content.length > 0) { + if (!currentBlock || currentBlock.type !== "text") { + finishCurrentBlock(currentBlock); + currentBlock = { type: "text", text: "" }; + output.content.push(currentBlock); + stream2.push({ type: "text_start", contentIndex: blockIndex(), partial: output }); + } + if (currentBlock.type === "text") { + currentBlock.text += choice.delta.content; + stream2.push({ + type: "text_delta", + contentIndex: blockIndex(), + delta: choice.delta.content, + partial: output + }); + } + } + const reasoningFields = ["reasoning_content", "reasoning", "reasoning_text"]; + let foundReasoningField = null; + for (const field of reasoningFields) { + if (choice.delta[field] !== null && choice.delta[field] !== void 0 && choice.delta[field].length > 0) { + if (!foundReasoningField) { + foundReasoningField = field; + break; + } + } + } + if (foundReasoningField) { + if (!currentBlock || currentBlock.type !== "thinking") { + finishCurrentBlock(currentBlock); + currentBlock = { + type: "thinking", + thinking: "", + thinkingSignature: foundReasoningField + }; + output.content.push(currentBlock); + stream2.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output }); + } + if (currentBlock.type === "thinking") { + const delta = choice.delta[foundReasoningField]; + currentBlock.thinking += delta; + stream2.push({ + type: "thinking_delta", + contentIndex: blockIndex(), + delta, + partial: output + }); + } + } + if (choice?.delta?.tool_calls) { + for (const toolCall of choice.delta.tool_calls) { + if (!currentBlock || currentBlock.type !== "toolCall" || toolCall.id && currentBlock.id !== toolCall.id) { + finishCurrentBlock(currentBlock); + currentBlock = { + type: "toolCall", + id: toolCall.id || "", + name: toolCall.function?.name || "", + arguments: {}, + partialArgs: "" + }; + output.content.push(currentBlock); + stream2.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output }); + } + if (currentBlock.type === "toolCall") { + if (toolCall.id) + currentBlock.id = toolCall.id; + if (toolCall.function?.name) + currentBlock.name = toolCall.function.name; + let delta = ""; + if (toolCall.function?.arguments) { + delta = toolCall.function.arguments; + currentBlock.partialArgs += toolCall.function.arguments; + currentBlock.arguments = parseStreamingJson2(currentBlock.partialArgs); + } + stream2.push({ + type: "toolcall_delta", + contentIndex: blockIndex(), + delta, + partial: output + }); + } + } + } + const reasoningDetails = choice.delta.reasoning_details; + if (reasoningDetails && Array.isArray(reasoningDetails)) { + for (const detail of reasoningDetails) { + if (detail.type === "reasoning.encrypted" && detail.id && detail.data) { + const matchingToolCall = output.content.find((b4) => b4.type === "toolCall" && b4.id === detail.id); + if (matchingToolCall) { + matchingToolCall.thoughtSignature = JSON.stringify(detail); + } + } + } + } + } + } + finishCurrentBlock(currentBlock); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) + delete block.index; + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + const rawMetadata = error?.error?.metadata?.raw; + if (rawMetadata) + output.errorMessage += ` +${rawMetadata}`; + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleOpenAICompletions2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + const reasoningEffort = supportsXhigh2(model) ? options?.reasoning : clampReasoning2(options?.reasoning); + const toolChoice = options?.toolChoice; + return streamOpenAICompletions2(model, context, { + ...base, + reasoningEffort, + toolChoice + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/openai-responses.js +function resolveCacheRetention4(cacheRetention) { + if (cacheRetention) { + return cacheRetention; + } + if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") { + return "long"; + } + return "short"; +} +function getPromptCacheRetention2(baseUrl, cacheRetention) { + if (cacheRetention !== "long") { + return void 0; + } + if (baseUrl.includes("api.openai.com")) { + return "24h"; + } + return void 0; +} +function createClient12(model, context, apiKey, optionsHeaders) { + if (!apiKey) { + if (!process.env.OPENAI_API_KEY) { + throw new Error("OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument."); + } + apiKey = process.env.OPENAI_API_KEY; + } + const headers = { ...model.headers }; + if (model.provider === "github-copilot") { + const hasImages = hasCopilotVisionInput2(context.messages); + const copilotHeaders = buildCopilotDynamicHeaders2({ + messages: context.messages, + hasImages + }); + Object.assign(headers, copilotHeaders); + } + if (optionsHeaders) { + Object.assign(headers, optionsHeaders); + } + return new OpenAI({ + apiKey, + baseURL: model.baseUrl, + dangerouslyAllowBrowser: true, + defaultHeaders: headers + }); +} +function buildParams12(model, context, options) { + const messages = convertResponsesMessages2(model, context, OPENAI_TOOL_CALL_PROVIDERS2); + const cacheRetention = resolveCacheRetention4(options?.cacheRetention); + const params = { + model: model.id, + input: messages, + stream: true, + prompt_cache_key: cacheRetention === "none" ? void 0 : options?.sessionId, + prompt_cache_retention: getPromptCacheRetention2(model.baseUrl, cacheRetention), + store: false + }; + if (options?.maxTokens) { + params.max_output_tokens = options?.maxTokens; + } + if (options?.temperature !== void 0) { + params.temperature = options?.temperature; + } + if (options?.serviceTier !== void 0) { + params.service_tier = options.serviceTier; + } + if (context.tools) { + params.tools = convertResponsesTools2(context.tools); + } + if (model.reasoning) { + if (options?.reasoningEffort || options?.reasoningSummary) { + params.reasoning = { + effort: options?.reasoningEffort || "medium", + summary: options?.reasoningSummary || "auto" + }; + params.include = ["reasoning.encrypted_content"]; + } else { + if (model.name.startsWith("gpt-5")) { + messages.push({ + role: "developer", + content: [ + { + type: "input_text", + text: "# Juice: 0 !important" + } + ] + }); + } + } + } + return params; +} +function getServiceTierCostMultiplier2(serviceTier) { + switch (serviceTier) { + case "flex": + return 0.5; + case "priority": + return 2; + default: + return 1; + } +} +function applyServiceTierPricing2(usage, serviceTier) { + const multiplier = getServiceTierCostMultiplier2(serviceTier); + if (multiplier === 1) + return; + usage.cost.input *= multiplier; + usage.cost.output *= multiplier; + usage.cost.cacheRead *= multiplier; + usage.cost.cacheWrite *= multiplier; + usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite; +} +var OPENAI_TOOL_CALL_PROVIDERS2, streamOpenAIResponses2, streamSimpleOpenAIResponses2; +var init_openai_responses = __esm({ + "../pi-mono/packages/ai/dist/providers/openai-responses.js"() { + "use strict"; + init_process_shim(); + init_openai(); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_github_copilot_headers(); + init_openai_responses_shared(); + init_simple_options(); + OPENAI_TOOL_CALL_PROVIDERS2 = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]); + streamOpenAIResponses2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider) || ""; + const client = createClient12(model, context, apiKey, options?.headers); + let params = buildParams12(model, context, options); + const nextParams = await options?.onPayload?.(params, model); + if (nextParams !== void 0) { + params = nextParams; + } + const openaiStream = await client.responses.create(params, options?.signal ? { signal: options.signal } : void 0); + stream2.push({ type: "start", partial: output }); + await processResponsesStream2(openaiStream, output, stream2, model, { + serviceTier: options?.serviceTier, + applyServiceTierPricing: applyServiceTierPricing2 + }); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + if (output.stopReason === "aborted" || output.stopReason === "error") { + throw new Error("An unknown error occurred"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + for (const block of output.content) + delete block.index; + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleOpenAIResponses2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + const reasoningEffort = supportsXhigh2(model) ? options?.reasoning : clampReasoning2(options?.reasoning); + return streamOpenAIResponses2(model, context, { + ...base, + reasoningEffort + }); + }; + } +}); + +// ../pi-mono/packages/ai/dist/providers/openai-codex-responses.js +function isRetryableError4(status, errorText) { + if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) { + return true; + } + return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText); +} +function sleep7(ms, signal) { + return new Promise((resolve2, reject) => { + if (signal?.aborted) { + reject(new Error("Request was aborted")); + return; + } + const timeout = setTimeout(resolve2, ms); + signal?.addEventListener("abort", () => { + clearTimeout(timeout); + reject(new Error("Request was aborted")); + }); + }); +} +function buildRequestBody2(model, context, options) { + const messages = convertResponsesMessages2(model, context, CODEX_TOOL_CALL_PROVIDERS2, { + includeSystemPrompt: false + }); + const body = { + model: model.id, + store: false, + stream: true, + instructions: context.systemPrompt, + input: messages, + text: { verbosity: options?.textVerbosity || "medium" }, + include: ["reasoning.encrypted_content"], + prompt_cache_key: options?.sessionId, + tool_choice: "auto", + parallel_tool_calls: true + }; + if (options?.temperature !== void 0) { + body.temperature = options.temperature; + } + if (context.tools) { + body.tools = convertResponsesTools2(context.tools, { strict: null }); + } + if (options?.reasoningEffort !== void 0) { + body.reasoning = { + effort: clampReasoningEffort2(model.id, options.reasoningEffort), + summary: options.reasoningSummary ?? "auto" + }; + } + return body; +} +function clampReasoningEffort2(modelId, effort) { + const id = modelId.includes("/") ? modelId.split("/").pop() : modelId; + if ((id.startsWith("gpt-5.2") || id.startsWith("gpt-5.3") || id.startsWith("gpt-5.4")) && effort === "minimal") + return "low"; + if (id === "gpt-5.1" && effort === "xhigh") + return "high"; + if (id === "gpt-5.1-codex-mini") + return effort === "high" || effort === "xhigh" ? "high" : "medium"; + return effort; +} +function resolveCodexUrl2(baseUrl) { + const raw = baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL2; + const normalized = raw.replace(/\/+$/, ""); + if (normalized.endsWith("/codex/responses")) + return normalized; + if (normalized.endsWith("/codex")) + return `${normalized}/responses`; + return `${normalized}/codex/responses`; +} +function resolveCodexWebSocketUrl2(baseUrl) { + const url = new URL(resolveCodexUrl2(baseUrl)); + if (url.protocol === "https:") + url.protocol = "wss:"; + if (url.protocol === "http:") + url.protocol = "ws:"; + return url.toString(); +} +async function processStream2(response, output, stream2, model) { + await processResponsesStream2(mapCodexEvents2(parseSSE2(response)), output, stream2, model); +} +async function* mapCodexEvents2(events) { + for await (const event of events) { + const type = typeof event.type === "string" ? event.type : void 0; + if (!type) + continue; + if (type === "error") { + const code = event.code || ""; + const message = event.message || ""; + throw new Error(`Codex error: ${message || code || JSON.stringify(event)}`); + } + if (type === "response.failed") { + const msg = event.response?.error?.message; + throw new Error(msg || "Codex response failed"); + } + if (type === "response.done" || type === "response.completed" || type === "response.incomplete") { + const response = event.response; + const normalizedResponse = response ? { ...response, status: normalizeCodexStatus2(response.status) } : response; + yield { ...event, type: "response.completed", response: normalizedResponse }; + return; + } + yield event; + } +} +function normalizeCodexStatus2(status) { + if (typeof status !== "string") + return void 0; + return CODEX_RESPONSE_STATUSES2.has(status) ? status : void 0; +} +async function* parseSSE2(response) { + if (!response.body) + return; + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) + break; + buffer += decoder.decode(value, { stream: true }); + let idx = buffer.indexOf("\n\n"); + while (idx !== -1) { + const chunk = buffer.slice(0, idx); + buffer = buffer.slice(idx + 2); + const dataLines = chunk.split("\n").filter((l5) => l5.startsWith("data:")).map((l5) => l5.slice(5).trim()); + if (dataLines.length > 0) { + const data = dataLines.join("\n").trim(); + if (data && data !== "[DONE]") { + try { + yield JSON.parse(data); + } catch { + } + } + } + idx = buffer.indexOf("\n\n"); + } + } + } finally { + try { + await reader.cancel(); + } catch { + } + try { + reader.releaseLock(); + } catch { + } + } +} +function getWebSocketConstructor2() { + const ctor = globalThis.WebSocket; + if (typeof ctor !== "function") + return null; + return ctor; +} +function headersToRecord2(headers) { + const out = {}; + for (const [key, value] of headers.entries()) { + out[key] = value; + } + return out; +} +function getWebSocketReadyState2(socket) { + const readyState = socket.readyState; + return typeof readyState === "number" ? readyState : void 0; +} +function isWebSocketReusable2(socket) { + const readyState = getWebSocketReadyState2(socket); + return readyState === void 0 || readyState === 1; +} +function closeWebSocketSilently2(socket, code = 1e3, reason = "done") { + try { + socket.close(code, reason); + } catch { + } +} +function scheduleSessionWebSocketExpiry2(sessionId, entry) { + if (entry.idleTimer) { + clearTimeout(entry.idleTimer); + } + entry.idleTimer = setTimeout(() => { + if (entry.busy) + return; + closeWebSocketSilently2(entry.socket, 1e3, "idle_timeout"); + websocketSessionCache2.delete(sessionId); + }, SESSION_WEBSOCKET_CACHE_TTL_MS2); +} +async function connectWebSocket2(url, headers, signal) { + const WebSocketCtor = getWebSocketConstructor2(); + if (!WebSocketCtor) { + throw new Error("WebSocket transport is not available in this runtime"); + } + const wsHeaders = headersToRecord2(headers); + delete wsHeaders["OpenAI-Beta"]; + return new Promise((resolve2, reject) => { + let settled = false; + let socket; + try { + socket = new WebSocketCtor(url, { headers: wsHeaders }); + } catch (error) { + reject(error instanceof Error ? error : new Error(String(error))); + return; + } + const onOpen = () => { + if (settled) + return; + settled = true; + cleanup(); + resolve2(socket); + }; + const onError = (event) => { + const error = extractWebSocketError2(event); + if (settled) + return; + settled = true; + cleanup(); + reject(error); + }; + const onClose = (event) => { + const error = extractWebSocketCloseError2(event); + if (settled) + return; + settled = true; + cleanup(); + reject(error); + }; + const onAbort = () => { + if (settled) + return; + settled = true; + cleanup(); + socket.close(1e3, "aborted"); + reject(new Error("Request was aborted")); + }; + const cleanup = () => { + socket.removeEventListener("open", onOpen); + socket.removeEventListener("error", onError); + socket.removeEventListener("close", onClose); + signal?.removeEventListener("abort", onAbort); + }; + socket.addEventListener("open", onOpen); + socket.addEventListener("error", onError); + socket.addEventListener("close", onClose); + signal?.addEventListener("abort", onAbort); + }); +} +async function acquireWebSocket2(url, headers, sessionId, signal) { + if (!sessionId) { + const socket2 = await connectWebSocket2(url, headers, signal); + return { + socket: socket2, + release: ({ keep } = {}) => { + if (keep === false) { + closeWebSocketSilently2(socket2); + return; + } + closeWebSocketSilently2(socket2); + } + }; + } + const cached = websocketSessionCache2.get(sessionId); + if (cached) { + if (cached.idleTimer) { + clearTimeout(cached.idleTimer); + cached.idleTimer = void 0; + } + if (!cached.busy && isWebSocketReusable2(cached.socket)) { + cached.busy = true; + return { + socket: cached.socket, + release: ({ keep } = {}) => { + if (!keep || !isWebSocketReusable2(cached.socket)) { + closeWebSocketSilently2(cached.socket); + websocketSessionCache2.delete(sessionId); + return; + } + cached.busy = false; + scheduleSessionWebSocketExpiry2(sessionId, cached); + } + }; + } + if (cached.busy) { + const socket2 = await connectWebSocket2(url, headers, signal); + return { + socket: socket2, + release: () => { + closeWebSocketSilently2(socket2); + } + }; + } + if (!isWebSocketReusable2(cached.socket)) { + closeWebSocketSilently2(cached.socket); + websocketSessionCache2.delete(sessionId); + } + } + const socket = await connectWebSocket2(url, headers, signal); + const entry = { socket, busy: true }; + websocketSessionCache2.set(sessionId, entry); + return { + socket, + release: ({ keep } = {}) => { + if (!keep || !isWebSocketReusable2(entry.socket)) { + closeWebSocketSilently2(entry.socket); + if (entry.idleTimer) + clearTimeout(entry.idleTimer); + if (websocketSessionCache2.get(sessionId) === entry) { + websocketSessionCache2.delete(sessionId); + } + return; + } + entry.busy = false; + scheduleSessionWebSocketExpiry2(sessionId, entry); + } + }; +} +function extractWebSocketError2(event) { + if (event && typeof event === "object" && "message" in event) { + const message = event.message; + if (typeof message === "string" && message.length > 0) { + return new Error(message); + } + } + return new Error("WebSocket error"); +} +function extractWebSocketCloseError2(event) { + if (event && typeof event === "object") { + const code = "code" in event ? event.code : void 0; + const reason = "reason" in event ? event.reason : void 0; + const codeText = typeof code === "number" ? ` ${code}` : ""; + const reasonText = typeof reason === "string" && reason.length > 0 ? ` ${reason}` : ""; + return new Error(`WebSocket closed${codeText}${reasonText}`.trim()); + } + return new Error("WebSocket closed"); +} +async function decodeWebSocketData2(data) { + if (typeof data === "string") + return data; + if (data instanceof ArrayBuffer) { + return new TextDecoder().decode(new Uint8Array(data)); + } + if (ArrayBuffer.isView(data)) { + const view = data; + return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength)); + } + if (data && typeof data === "object" && "arrayBuffer" in data) { + const blobLike = data; + const arrayBuffer = await blobLike.arrayBuffer(); + return new TextDecoder().decode(new Uint8Array(arrayBuffer)); + } + return null; +} +async function* parseWebSocket2(socket, signal) { + const queue = []; + let pending = null; + let done = false; + let failed = null; + let sawCompletion = false; + const wake = () => { + if (!pending) + return; + const resolve2 = pending; + pending = null; + resolve2(); + }; + const onMessage = (event) => { + void (async () => { + if (!event || typeof event !== "object" || !("data" in event)) + return; + const text3 = await decodeWebSocketData2(event.data); + if (!text3) + return; + try { + const parsed = JSON.parse(text3); + const type = typeof parsed.type === "string" ? parsed.type : ""; + if (type === "response.completed" || type === "response.done" || type === "response.incomplete") { + sawCompletion = true; + done = true; + } + queue.push(parsed); + wake(); + } catch { + } + })(); + }; + const onError = (event) => { + failed = extractWebSocketError2(event); + done = true; + wake(); + }; + const onClose = (event) => { + if (sawCompletion) { + done = true; + wake(); + return; + } + if (!failed) { + failed = extractWebSocketCloseError2(event); + } + done = true; + wake(); + }; + const onAbort = () => { + failed = new Error("Request was aborted"); + done = true; + wake(); + }; + socket.addEventListener("message", onMessage); + socket.addEventListener("error", onError); + socket.addEventListener("close", onClose); + signal?.addEventListener("abort", onAbort); + try { + while (true) { + if (signal?.aborted) { + throw new Error("Request was aborted"); + } + if (queue.length > 0) { + yield queue.shift(); + continue; + } + if (done) + break; + await new Promise((resolve2) => { + pending = resolve2; + }); + } + if (failed) { + throw failed; + } + if (!sawCompletion) { + throw new Error("WebSocket stream closed before response.completed"); + } + } finally { + socket.removeEventListener("message", onMessage); + socket.removeEventListener("error", onError); + socket.removeEventListener("close", onClose); + signal?.removeEventListener("abort", onAbort); + } +} +async function processWebSocketStream2(url, body, headers, output, stream2, model, onStart, options) { + const { socket, release } = await acquireWebSocket2(url, headers, options?.sessionId, options?.signal); + let keepConnection = true; + try { + socket.send(JSON.stringify({ type: "response.create", ...body })); + onStart(); + stream2.push({ type: "start", partial: output }); + await processResponsesStream2(mapCodexEvents2(parseWebSocket2(socket, options?.signal)), output, stream2, model); + if (options?.signal?.aborted) { + keepConnection = false; + } + } catch (error) { + keepConnection = false; + throw error; + } finally { + release({ keep: keepConnection }); + } +} +async function parseErrorResponse2(response) { + const raw = await response.text(); + let message = raw || response.statusText || "Request failed"; + let friendlyMessage; + try { + const parsed = JSON.parse(raw); + const err = parsed?.error; + if (err) { + const code = err.code || err.type || ""; + if (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) { + const plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : ""; + const mins = err.resets_at ? Math.max(0, Math.round((err.resets_at * 1e3 - Date.now()) / 6e4)) : void 0; + const when = mins !== void 0 ? ` Try again in ~${mins} min.` : ""; + friendlyMessage = `You have hit your ChatGPT usage limit${plan}.${when}`.trim(); + } + message = err.message || friendlyMessage || message; + } + } catch { + } + return { message, friendlyMessage }; +} +function extractAccountId2(token) { + try { + const parts = token.split("."); + if (parts.length !== 3) + throw new Error("Invalid token"); + const payload = JSON.parse(atob(parts[1])); + const accountId = payload?.[JWT_CLAIM_PATH2]?.chatgpt_account_id; + if (!accountId) + throw new Error("No account ID in token"); + return accountId; + } catch { + throw new Error("Failed to extract accountId from token"); + } +} +function createCodexRequestId2() { + if (typeof globalThis.crypto?.randomUUID === "function") { + return globalThis.crypto.randomUUID(); + } + return `codex_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`; +} +function buildBaseCodexHeaders2(initHeaders, additionalHeaders, accountId, token) { + const headers = new Headers(initHeaders); + for (const [key, value] of Object.entries(additionalHeaders || {})) { + headers.set(key, value); + } + headers.set("Authorization", `Bearer ${token}`); + headers.set("chatgpt-account-id", accountId); + headers.set("originator", "pi"); + const userAgent = _os2 ? `pi (${_os2.platform()} ${_os2.release()}; ${_os2.arch()})` : "pi (browser)"; + headers.set("User-Agent", userAgent); + return headers; +} +function buildSSEHeaders2(initHeaders, additionalHeaders, accountId, token, sessionId) { + const headers = buildBaseCodexHeaders2(initHeaders, additionalHeaders, accountId, token); + headers.set("OpenAI-Beta", "responses=experimental"); + headers.set("accept", "text/event-stream"); + headers.set("content-type", "application/json"); + if (sessionId) { + headers.set("session_id", sessionId); + } + return headers; +} +function buildWebSocketHeaders2(initHeaders, additionalHeaders, accountId, token, requestId) { + const headers = buildBaseCodexHeaders2(initHeaders, additionalHeaders, accountId, token); + headers.delete("accept"); + headers.delete("content-type"); + headers.delete("OpenAI-Beta"); + headers.delete("openai-beta"); + headers.set("OpenAI-Beta", OPENAI_BETA_RESPONSES_WEBSOCKETS2); + headers.set("x-client-request-id", requestId); + headers.set("session_id", requestId); + return headers; +} +var _os2, dynamicImport5, NODE_OS_SPECIFIER4, DEFAULT_CODEX_BASE_URL2, JWT_CLAIM_PATH2, MAX_RETRIES4, BASE_DELAY_MS4, CODEX_TOOL_CALL_PROVIDERS2, CODEX_RESPONSE_STATUSES2, streamOpenAICodexResponses2, streamSimpleOpenAICodexResponses2, OPENAI_BETA_RESPONSES_WEBSOCKETS2, SESSION_WEBSOCKET_CACHE_TTL_MS2, websocketSessionCache2; +var init_openai_codex_responses = __esm({ + "../pi-mono/packages/ai/dist/providers/openai-codex-responses.js"() { + "use strict"; + init_process_shim(); + init_env_api_keys(); + init_models4(); + init_event_stream(); + init_openai_responses_shared(); + init_simple_options(); + _os2 = null; + dynamicImport5 = (specifier) => import(specifier); + NODE_OS_SPECIFIER4 = "node:os"; + if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) { + dynamicImport5(NODE_OS_SPECIFIER4).then((m4) => { + _os2 = m4; + }); + } + DEFAULT_CODEX_BASE_URL2 = "https://chatgpt.com/backend-api"; + JWT_CLAIM_PATH2 = "https://api.openai.com/auth"; + MAX_RETRIES4 = 3; + BASE_DELAY_MS4 = 1e3; + CODEX_TOOL_CALL_PROVIDERS2 = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]); + CODEX_RESPONSE_STATUSES2 = /* @__PURE__ */ new Set([ + "completed", + "incomplete", + "failed", + "cancelled", + "queued", + "in_progress" + ]); + streamOpenAICodexResponses2 = (model, context, options) => { + const stream2 = new AssistantMessageEventStream2(); + (async () => { + const output = { + role: "assistant", + content: [], + api: "openai-codex-responses", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "stop", + timestamp: Date.now() + }; + try { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider) || ""; + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const accountId = extractAccountId2(apiKey); + let body = buildRequestBody2(model, context, options); + const nextBody = await options?.onPayload?.(body, model); + if (nextBody !== void 0) { + body = nextBody; + } + const websocketRequestId = options?.sessionId || createCodexRequestId2(); + const sseHeaders = buildSSEHeaders2(model.headers, options?.headers, accountId, apiKey, options?.sessionId); + const websocketHeaders = buildWebSocketHeaders2(model.headers, options?.headers, accountId, apiKey, websocketRequestId); + const bodyJson = JSON.stringify(body); + const transport = options?.transport || "sse"; + if (transport !== "sse") { + let websocketStarted = false; + try { + await processWebSocketStream2(resolveCodexWebSocketUrl2(model.baseUrl), body, websocketHeaders, output, stream2, model, () => { + websocketStarted = true; + }, options); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + stream2.push({ + type: "done", + reason: output.stopReason, + message: output + }); + stream2.end(); + return; + } catch (error) { + if (transport === "websocket" || websocketStarted) { + throw error; + } + } + } + let response; + let lastError; + for (let attempt = 0; attempt <= MAX_RETRIES4; attempt++) { + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + try { + response = await fetch(resolveCodexUrl2(model.baseUrl), { + method: "POST", + headers: sseHeaders, + body: bodyJson, + signal: options?.signal + }); + if (response.ok) { + break; + } + const errorText = await response.text(); + if (attempt < MAX_RETRIES4 && isRetryableError4(response.status, errorText)) { + const delayMs = BASE_DELAY_MS4 * 2 ** attempt; + await sleep7(delayMs, options?.signal); + continue; + } + const fakeResponse = new Response(errorText, { + status: response.status, + statusText: response.statusText + }); + const info2 = await parseErrorResponse2(fakeResponse); + throw new Error(info2.friendlyMessage || info2.message); + } catch (error) { + if (error instanceof Error) { + if (error.name === "AbortError" || error.message === "Request was aborted") { + throw new Error("Request was aborted"); + } + } + lastError = error instanceof Error ? error : new Error(String(error)); + if (attempt < MAX_RETRIES4 && !lastError.message.includes("usage limit")) { + const delayMs = BASE_DELAY_MS4 * 2 ** attempt; + await sleep7(delayMs, options?.signal); + continue; + } + throw lastError; + } + } + if (!response?.ok) { + throw lastError ?? new Error("Failed after retries"); + } + if (!response.body) { + throw new Error("No response body"); + } + stream2.push({ type: "start", partial: output }); + await processStream2(response, output, stream2, model); + if (options?.signal?.aborted) { + throw new Error("Request was aborted"); + } + stream2.push({ type: "done", reason: output.stopReason, message: output }); + stream2.end(); + } catch (error) { + output.stopReason = options?.signal?.aborted ? "aborted" : "error"; + output.errorMessage = error instanceof Error ? error.message : String(error); + stream2.push({ type: "error", reason: output.stopReason, error: output }); + stream2.end(); + } + })(); + return stream2; + }; + streamSimpleOpenAICodexResponses2 = (model, context, options) => { + const apiKey = options?.apiKey || getEnvApiKey2(model.provider); + if (!apiKey) { + throw new Error(`No API key for provider: ${model.provider}`); + } + const base = buildBaseOptions2(model, options, apiKey); + const reasoningEffort = supportsXhigh2(model) ? options?.reasoning : clampReasoning2(options?.reasoning); + return streamOpenAICodexResponses2(model, context, { + ...base, + reasoningEffort + }); + }; + OPENAI_BETA_RESPONSES_WEBSOCKETS2 = "responses_websockets=2026-02-06"; + SESSION_WEBSOCKET_CACHE_TTL_MS2 = 5 * 60 * 1e3; + websocketSessionCache2 = /* @__PURE__ */ new Map(); + } +}); + +// ../pi-mono/packages/ai/dist/providers/register-builtins.js +async function loadBedrockProviderModule2() { + if (bedrockProviderModuleOverride2) { + return bedrockProviderModuleOverride2; + } + const module = await dynamicImport6(BEDROCK_PROVIDER_SPECIFIER2); + return module; +} +function forwardStream2(target, source) { + (async () => { + for await (const event of source) { + target.push(event); + } + target.end(); + })(); +} +function createLazyLoadErrorMessage2(model, error) { + return { + role: "assistant", + content: [], + api: "bedrock-converse-stream", + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } + }, + stopReason: "error", + errorMessage: error instanceof Error ? error.message : String(error), + timestamp: Date.now() + }; +} +function streamBedrockLazy2(model, context, options) { + const outer = new AssistantMessageEventStream2(); + loadBedrockProviderModule2().then((module) => { + const inner2 = module.streamBedrock(model, context, options); + forwardStream2(outer, inner2); + }).catch((error) => { + const message = createLazyLoadErrorMessage2(model, error); + outer.push({ type: "error", reason: "error", error: message }); + outer.end(message); + }); + return outer; +} +function streamSimpleBedrockLazy2(model, context, options) { + const outer = new AssistantMessageEventStream2(); + loadBedrockProviderModule2().then((module) => { + const inner2 = module.streamSimpleBedrock(model, context, options); + forwardStream2(outer, inner2); + }).catch((error) => { + const message = createLazyLoadErrorMessage2(model, error); + outer.push({ type: "error", reason: "error", error: message }); + outer.end(message); + }); + return outer; +} +function registerBuiltInApiProviders2() { + registerApiProvider2({ + api: "anthropic-messages", + stream: streamAnthropic2, + streamSimple: streamSimpleAnthropic2 + }); + registerApiProvider2({ + api: "openai-completions", + stream: streamOpenAICompletions2, + streamSimple: streamSimpleOpenAICompletions2 + }); + registerApiProvider2({ + api: "mistral-conversations", + stream: streamMistral2, + streamSimple: streamSimpleMistral2 + }); + registerApiProvider2({ + api: "openai-responses", + stream: streamOpenAIResponses2, + streamSimple: streamSimpleOpenAIResponses2 + }); + registerApiProvider2({ + api: "azure-openai-responses", + stream: streamAzureOpenAIResponses2, + streamSimple: streamSimpleAzureOpenAIResponses2 + }); + registerApiProvider2({ + api: "openai-codex-responses", + stream: streamOpenAICodexResponses2, + streamSimple: streamSimpleOpenAICodexResponses2 + }); + registerApiProvider2({ + api: "google-generative-ai", + stream: streamGoogle2, + streamSimple: streamSimpleGoogle2 + }); + registerApiProvider2({ + api: "google-gemini-cli", + stream: streamGoogleGeminiCli2, + streamSimple: streamSimpleGoogleGeminiCli2 + }); + registerApiProvider2({ + api: "google-vertex", + stream: streamGoogleVertex2, + streamSimple: streamSimpleGoogleVertex2 + }); + registerApiProvider2({ + api: "bedrock-converse-stream", + stream: streamBedrockLazy2, + streamSimple: streamSimpleBedrockLazy2 + }); +} +var dynamicImport6, BEDROCK_PROVIDER_SPECIFIER2, bedrockProviderModuleOverride2; +var init_register_builtins = __esm({ + "../pi-mono/packages/ai/dist/providers/register-builtins.js"() { + "use strict"; + init_process_shim(); + init_api_registry(); + init_event_stream(); + init_anthropic(); + init_azure_openai_responses(); + init_google(); + init_google_gemini_cli(); + init_google_vertex(); + init_mistral(); + init_openai_codex_responses(); + init_openai_completions(); + init_openai_responses(); + dynamicImport6 = (specifier) => import(specifier); + BEDROCK_PROVIDER_SPECIFIER2 = "./amazon-bedrock.js"; + registerBuiltInApiProviders2(); + } +}); + +// ../pi-mono/packages/ai/dist/stream.js +function resolveApiProvider2(api) { + const provider = getApiProvider2(api); + if (!provider) { + throw new Error(`No API provider registered for api: ${api}`); + } + return provider; +} +function stream(model, context, options) { + const provider = resolveApiProvider2(model.api); + return provider.stream(model, context, options); +} +async function complete(model, context, options) { + const s6 = stream(model, context, options); + return s6.result(); +} +function streamSimple2(model, context, options) { + const provider = resolveApiProvider2(model.api); + return provider.streamSimple(model, context, options); +} +var init_stream = __esm({ + "../pi-mono/packages/ai/dist/stream.js"() { + "use strict"; + init_process_shim(); + init_register_builtins(); + init_api_registry(); + init_env_api_keys(); + } +}); + +// ../pi-mono/packages/ai/dist/types.js +var init_types = __esm({ + "../pi-mono/packages/ai/dist/types.js"() { + "use strict"; + init_process_shim(); + } +}); + +// ../pi-mono/packages/ai/dist/utils/overflow.js +var init_overflow = __esm({ + "../pi-mono/packages/ai/dist/utils/overflow.js"() { + "use strict"; + init_process_shim(); + } +}); + +// ../pi-mono/packages/ai/dist/utils/typebox-helpers.js +function StringEnum(values2, options) { + return Type.Unsafe({ + type: "string", + enum: values2, + ...options?.description && { description: options.description }, + ...options?.default && { default: options.default } + }); +} +var init_typebox_helpers = __esm({ + "../pi-mono/packages/ai/dist/utils/typebox-helpers.js"() { + "use strict"; + init_process_shim(); + init_esm(); + } +}); + +// ../pi-mono/packages/ai/dist/utils/validation.js +var import_ajv2, import_ajv_formats2, Ajv2, addFormats2, isBrowserExtension2, ajv2; +var init_validation = __esm({ + "../pi-mono/packages/ai/dist/utils/validation.js"() { + "use strict"; + init_process_shim(); + import_ajv2 = __toESM(require_ajv(), 1); + import_ajv_formats2 = __toESM(require_dist2(), 1); + Ajv2 = import_ajv2.default.default || import_ajv2.default; + addFormats2 = import_ajv_formats2.default.default || import_ajv_formats2.default; + isBrowserExtension2 = typeof globalThis !== "undefined" && globalThis.chrome?.runtime?.id !== void 0; + ajv2 = null; + if (!isBrowserExtension2) { + try { + ajv2 = new Ajv2({ + allErrors: true, + strict: false, + coerceTypes: true + }); + addFormats2(ajv2); + } catch (_e2) { + console.warn("AJV validation disabled due to CSP restrictions"); + } + } + } +}); + +// ../pi-mono/packages/ai/dist/index.js +var init_dist2 = __esm({ + "../pi-mono/packages/ai/dist/index.js"() { + "use strict"; + init_process_shim(); + init_api_registry(); + init_env_api_keys(); + init_models4(); + init_anthropic(); + init_azure_openai_responses(); + init_google(); + init_google_gemini_cli(); + init_google_vertex(); + init_mistral(); + init_openai_completions(); + init_openai_responses(); + init_register_builtins(); + init_stream(); + init_types(); + init_event_stream(); + init_json_parse(); + init_overflow(); + init_typebox_helpers(); + init_validation(); + } +}); + +// ../mini-lit/dist/Badge.js +function Badge(propsOrChildren, variant = "default", className = "") { + if (typeof propsOrChildren === "object" && propsOrChildren !== null && "children" in propsOrChildren) { + return _Badge(propsOrChildren); + } + return _Badge({ children: propsOrChildren, variant, className }); +} +var _Badge; +var init_Badge = __esm({ + "../mini-lit/dist/Badge.js"() { + "use strict"; + init_process_shim(); + init_mini(); + _Badge = fc(({ variant = "default", className = "", children }) => { + const variantClasses = { + default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80", + secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", + destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", + outline: "border-input text-foreground" + }; + const baseClasses = "inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden"; + return b2` ${children} `; + }); + } +}); + +// ../mini-lit/dist/Dialog.js +var Dialog, DialogHeader, DialogContent, DialogFooter; +var init_Dialog = __esm({ + "../mini-lit/dist/Dialog.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_i18n(); + init_mini(); + Dialog = fc(({ isOpen, onClose, children, width = "min(600px, 90vw)", height = "auto", className = "", backdropClassName = "bg-black/50" }) => { + if (!isOpen) + return b2``; + const handleBackdropClick = (e9) => { + if (e9.target === e9.currentTarget) { + onClose?.(); + } + }; + const handleKeyDown = (e9) => { + if (e9.key === "Escape") { + onClose?.(); + } + }; + if (isOpen) { + document.addEventListener("keydown", handleKeyDown); + setTimeout(() => { + if (!isOpen) { + document.removeEventListener("keydown", handleKeyDown); + } + }, 0); + } + return b2` + +
+ +
e9.stopPropagation()} + > + ${children} + + + +
+
+ `; + }); + DialogHeader = fc(({ title, description, className = "" }) => { + return b2` +
+

${title}

+ ${description ? b2`

${description}

` : ""} +
+ `; + }); + DialogContent = fc(({ children, className = "" }) => { + return b2`
${children}
`; + }); + DialogFooter = fc(({ children, className = "" }) => { + return b2`
${children}
`; + }); + } +}); + +// ../mini-lit/dist/DialogBase.js +var DialogBase; +var init_DialogBase = __esm({ + "../mini-lit/dist/DialogBase.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_Dialog(); + DialogBase = class extends i4 { + constructor() { + super(...arguments); + this.modalWidth = "min(600px, 90vw)"; + this.modalHeight = "min(600px, 80vh)"; + } + createRenderRoot() { + return this; + } + open() { + this.previousFocus = document.activeElement; + document.body.appendChild(this); + this.boundHandleKeyDown = (e9) => { + if (e9.key === "Escape") { + this.close(); + } + }; + window.addEventListener("keydown", this.boundHandleKeyDown); + } + close() { + if (this.boundHandleKeyDown) { + window.removeEventListener("keydown", this.boundHandleKeyDown); + } + this.remove(); + if (this.previousFocus?.focus) { + requestAnimationFrame(() => { + this.previousFocus?.focus(); + }); + } + } + render() { + return Dialog({ + isOpen: true, + onClose: () => this.close(), + width: this.modalWidth, + height: this.modalHeight, + backdropClassName: "bg-black/50 backdrop-blur-sm", + children: this.renderContent() + }); + } + }; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/brain.js +var Brain; +var init_brain = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/brain.js"() { + init_process_shim(); + Brain = [ + ["path", { d: "M12 18V5" }], + ["path", { d: "M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4" }], + ["path", { d: "M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5" }], + ["path", { d: "M17.997 5.125a4 4 0 0 1 2.526 5.77" }], + ["path", { d: "M18 18a4 4 0 0 0 2-7.464" }], + ["path", { d: "M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517" }], + ["path", { d: "M6 18a4 4 0 0 1-2-7.464" }], + ["path", { d: "M6.003 5.125a4 4 0 0 0-2.526 5.77" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/calculator.js +var Calculator; +var init_calculator = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/calculator.js"() { + init_process_shim(); + Calculator = [ + ["rect", { width: "16", height: "20", x: "4", y: "2", rx: "2" }], + ["line", { x1: "8", x2: "16", y1: "6", y2: "6" }], + ["line", { x1: "16", x2: "16", y1: "14", y2: "18" }], + ["path", { d: "M16 10h.01" }], + ["path", { d: "M12 10h.01" }], + ["path", { d: "M8 10h.01" }], + ["path", { d: "M12 14h.01" }], + ["path", { d: "M8 14h.01" }], + ["path", { d: "M12 18h.01" }], + ["path", { d: "M8 18h.01" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/check.js +var Check2; +var init_check2 = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/check.js"() { + init_process_shim(); + Check2 = [["path", { d: "M20 6 9 17l-5-5" }]]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/chevron-down.js +var ChevronDown; +var init_chevron_down = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/chevron-down.js"() { + init_process_shim(); + ChevronDown = [["path", { d: "m6 9 6 6 6-6" }]]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/chevron-right.js +var ChevronRight; +var init_chevron_right = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/chevron-right.js"() { + init_process_shim(); + ChevronRight = [["path", { d: "m9 18 6-6-6-6" }]]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/chevron-up.js +var ChevronUp; +var init_chevron_up = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/chevron-up.js"() { + init_process_shim(); + ChevronUp = [["path", { d: "m18 15-6-6-6 6" }]]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/chevrons-down.js +var ChevronsDown; +var init_chevrons_down = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/chevrons-down.js"() { + init_process_shim(); + ChevronsDown = [ + ["path", { d: "m7 6 5 5 5-5" }], + ["path", { d: "m7 13 5 5 5-5" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/chevrons-up-down.js +var ChevronsUpDown; +var init_chevrons_up_down = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/chevrons-up-down.js"() { + init_process_shim(); + ChevronsUpDown = [ + ["path", { d: "m7 15 5 5 5-5" }], + ["path", { d: "m7 9 5-5 5 5" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/clock.js +var Clock; +var init_clock = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/clock.js"() { + init_process_shim(); + Clock = [ + ["path", { d: "M12 6v6l4 2" }], + ["circle", { cx: "12", cy: "12", r: "10" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/code.js +var Code2; +var init_code2 = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/code.js"() { + init_process_shim(); + Code2 = [ + ["path", { d: "m16 18 6-6-6-6" }], + ["path", { d: "m8 6-6 6 6 6" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/copy.js +var Copy2; +var init_copy2 = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/copy.js"() { + init_process_shim(); + Copy2 = [ + ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" }], + ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/download.js +var Download2; +var init_download2 = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/download.js"() { + init_process_shim(); + Download2 = [ + ["path", { d: "M12 15V3" }], + ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }], + ["path", { d: "m7 10 5 5 5-5" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/file-code-2.js +var FileCode2; +var init_file_code_2 = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/file-code-2.js"() { + init_process_shim(); + FileCode2 = [ + ["path", { d: "M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4" }], + ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }], + ["path", { d: "m5 12-3 3 3 3" }], + ["path", { d: "m9 18 3-3-3-3" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/file-spreadsheet.js +var FileSpreadsheet; +var init_file_spreadsheet = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/file-spreadsheet.js"() { + init_process_shim(); + FileSpreadsheet = [ + ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }], + ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }], + ["path", { d: "M8 13h2" }], + ["path", { d: "M14 13h2" }], + ["path", { d: "M8 17h2" }], + ["path", { d: "M14 17h2" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/file-text.js +var FileText; +var init_file_text = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/file-text.js"() { + init_process_shim(); + FileText = [ + ["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" }], + ["path", { d: "M14 2v4a2 2 0 0 0 2 2h4" }], + ["path", { d: "M10 9H8" }], + ["path", { d: "M16 13H8" }], + ["path", { d: "M16 17H8" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/image.js +var Image2; +var init_image = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/image.js"() { + init_process_shim(); + Image2 = [ + ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2" }], + ["circle", { cx: "9", cy: "9", r: "2" }], + ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/loader-circle.js +var LoaderCircle; +var init_loader_circle = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/loader-circle.js"() { + init_process_shim(); + LoaderCircle = [["path", { d: "M21 12a9 9 0 1 1-6.219-8.56" }]]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/loader.js +var Loader; +var init_loader = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/loader.js"() { + init_process_shim(); + Loader = [ + ["path", { d: "M12 2v4" }], + ["path", { d: "m16.2 7.8 2.9-2.9" }], + ["path", { d: "M18 12h4" }], + ["path", { d: "m16.2 16.2 2.9 2.9" }], + ["path", { d: "M12 18v4" }], + ["path", { d: "m4.9 19.1 2.9-2.9" }], + ["path", { d: "M2 12h4" }], + ["path", { d: "m4.9 4.9 2.9 2.9" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/lock.js +var Lock; +var init_lock = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/lock.js"() { + init_process_shim(); + Lock = [ + ["rect", { width: "18", height: "11", x: "3", y: "11", rx: "2", ry: "2" }], + ["path", { d: "M7 11V7a5 5 0 0 1 10 0v4" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/paperclip.js +var Paperclip; +var init_paperclip = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/paperclip.js"() { + init_process_shim(); + Paperclip = [ + [ + "path", + { + d: "m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551" + } + ] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/refresh-cw.js +var RefreshCw; +var init_refresh_cw = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/refresh-cw.js"() { + init_process_shim(); + RefreshCw = [ + ["path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" }], + ["path", { d: "M21 3v5h-5" }], + ["path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" }], + ["path", { d: "M8 16H3v5" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/send.js +var Send; +var init_send = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/send.js"() { + init_process_shim(); + Send = [ + [ + "path", + { + d: "M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z" + } + ], + ["path", { d: "m21.854 2.147-10.94 10.939" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/sparkles.js +var Sparkles; +var init_sparkles = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/sparkles.js"() { + init_process_shim(); + Sparkles = [ + [ + "path", + { + d: "M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z" + } + ], + ["path", { d: "M20 2v4" }], + ["path", { d: "M22 4h-4" }], + ["circle", { cx: "4", cy: "20", r: "2" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/square-terminal.js +var SquareTerminal; +var init_square_terminal = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/square-terminal.js"() { + init_process_shim(); + SquareTerminal = [ + ["path", { d: "m7 11 2-2-2-2" }], + ["path", { d: "M11 13h4" }], + ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/square.js +var Square; +var init_square = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/square.js"() { + init_process_shim(); + Square = [["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2" }]]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/icons/x.js +var X; +var init_x = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/icons/x.js"() { + init_process_shim(); + X = [ + ["path", { d: "M18 6 6 18" }], + ["path", { d: "m6 6 12 12" }] + ]; + } +}); + +// ../pi-mono/node_modules/lucide/dist/esm/lucide.js +var init_lucide2 = __esm({ + "../pi-mono/node_modules/lucide/dist/esm/lucide.js"() { + init_process_shim(); + init_brain(); + init_calculator(); + init_check2(); + init_chevron_down(); + init_chevron_right(); + init_chevron_up(); + init_chevrons_down(); + init_chevrons_up_down(); + init_clock(); + init_code2(); + init_copy2(); + init_download2(); + init_file_code_2(); + init_file_spreadsheet(); + init_file_text(); + init_image(); + init_loader_circle(); + init_loader(); + init_lock(); + init_paperclip(); + init_refresh_cw(); + init_send(); + init_sparkles(); + init_square_terminal(); + init_square(); + init_x(); + } +}); + +// ../pi-mono/packages/web-ui/dist/utils/i18n.js +var translations2; +var init_i18n2 = __esm({ + "../pi-mono/packages/web-ui/dist/utils/i18n.js"() { + "use strict"; + init_process_shim(); + init_dist(); + init_i18n(); + translations2 = { + en: { + ...defaultEnglish, + Free: "Free", + "Input Required": "Input Required", + Cancel: "Cancel", + Confirm: "Confirm", + "Select Model": "Select Model", + "Search models...": "Search models...", + Format: "Format", + Thinking: "Thinking", + Vision: "Vision", + You: "You", + Assistant: "Assistant", + "Thinking...": "Thinking...", + "Type your message...": "Type your message...", + "API Keys Configuration": "API Keys Configuration", + "Configure API keys for LLM providers. Keys are stored locally in your browser.": "Configure API keys for LLM providers. Keys are stored locally in your browser.", + Configured: "Configured", + "Not configured": "Not configured", + "\u2713 Valid": "\u2713 Valid", + "\u2717 Invalid": "\u2717 Invalid", + "Testing...": "Testing...", + Update: "Update", + Test: "Test", + Remove: "Remove", + Save: "Save", + "Update API key": "Update API key", + "Enter API key": "Enter API key", + "Type a message...": "Type a message...", + "Failed to fetch file": "Failed to fetch file", + "Invalid source type": "Invalid source type", + PDF: "PDF", + Document: "Document", + Presentation: "Presentation", + Spreadsheet: "Spreadsheet", + Text: "Text", + "Error loading file": "Error loading file", + "No text content available": "No text content available", + "Failed to load PDF": "Failed to load PDF", + "Failed to load document": "Failed to load document", + "Failed to load spreadsheet": "Failed to load spreadsheet", + "Error loading PDF": "Error loading PDF", + "Error loading document": "Error loading document", + "Error loading spreadsheet": "Error loading spreadsheet", + "Preview not available for this file type.": "Preview not available for this file type.", + "Click the download button above to view it on your computer.": "Click the download button above to view it on your computer.", + "No content available": "No content available", + "Failed to display text content": "Failed to display text content", + "API keys are required to use AI models. Get your keys from the provider's website.": "API keys are required to use AI models. Get your keys from the provider's website.", + console: "console", + "Copy output": "Copy output", + "Copied!": "Copied!", + "Error:": "Error:", + "Request aborted": "Request aborted", + Call: "Call", + Result: "Result", + "(no result)": "(no result)", + "Waiting for tool result\u2026": "Waiting for tool result\u2026", + "Call was aborted; no result.": "Call was aborted; no result.", + "No session available": "No session available", + "No session set": "No session set", + "Preparing tool parameters...": "Preparing tool parameters...", + "(no output)": "(no output)", + Input: "Input", + Output: "Output", + "Waiting for expression...": "Waiting for expression...", + "Writing expression...": "Writing expression...", + Calculating: "Calculating", + "Getting current time in": "Getting current time in", + "Getting current date and time": "Getting current date and time", + "Waiting for command...": "Waiting for command...", + "Writing command...": "Writing command...", + "Running command...": "Running command...", + "Command failed": "Command failed", + "Enter Auth Token": "Enter Auth Token", + "Please enter your auth token.": "Please enter your auth token.", + "Auth token is required for proxy transport": "Auth token is required for proxy transport", + // JavaScript REPL strings + "Execution aborted": "Execution aborted", + "Code parameter is required": "Code parameter is required", + "Unknown error": "Unknown error", + "Code executed successfully (no output)": "Code executed successfully (no output)", + "Execution failed": "Execution failed", + "JavaScript REPL": "JavaScript REPL", + "JavaScript code to execute": "JavaScript code to execute", + "Writing JavaScript code...": "Writing JavaScript code...", + "Executing JavaScript": "Executing JavaScript", + "Preparing JavaScript...": "Preparing JavaScript...", + "Preparing command...": "Preparing command...", + "Preparing calculation...": "Preparing calculation...", + "Preparing tool...": "Preparing tool...", + "Getting time...": "Getting time...", + // Artifacts strings + "Processing artifact...": "Processing artifact...", + "Preparing artifact...": "Preparing artifact...", + "Processing artifact": "Processing artifact", + "Processed artifact": "Processed artifact", + "Creating artifact": "Creating artifact", + "Created artifact": "Created artifact", + "Updating artifact": "Updating artifact", + "Updated artifact": "Updated artifact", + "Rewriting artifact": "Rewriting artifact", + "Rewrote artifact": "Rewrote artifact", + "Getting artifact": "Getting artifact", + "Got artifact": "Got artifact", + "Deleting artifact": "Deleting artifact", + "Deleted artifact": "Deleted artifact", + "Getting logs": "Getting logs", + "Got logs": "Got logs", + "An error occurred": "An error occurred", + "Copy logs": "Copy logs", + "Autoscroll enabled": "Autoscroll enabled", + "Autoscroll disabled": "Autoscroll disabled", + Processing: "Processing", + Create: "Create", + Rewrite: "Rewrite", + Get: "Get", + "Get logs": "Get logs", + "Show artifacts": "Show artifacts", + "Close artifacts": "Close artifacts", + Artifacts: "Artifacts", + "Copy HTML": "Copy HTML", + "Download HTML": "Download HTML", + "Reload HTML": "Reload HTML", + "Copy SVG": "Copy SVG", + "Download SVG": "Download SVG", + "Copy Markdown": "Copy Markdown", + "Download Markdown": "Download Markdown", + Download: "Download", + "No logs for {filename}": "No logs for {filename}", + "API Keys Settings": "API Keys Settings", + Settings: "Settings", + "API Keys": "API Keys", + Proxy: "Proxy", + "Use CORS Proxy": "Use CORS Proxy", + "Proxy URL": "Proxy URL", + "Format: The proxy must accept requests as /?url=": "Format: The proxy must accept requests as /?url=", + "Settings are stored locally in your browser": "Settings are stored locally in your browser", + Clear: "Clear", + "API Key Required": "API Key Required", + "Enter your API key for {provider}": "Enter your API key for {provider}", + "Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.": "Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.", + Off: "Off", + Minimal: "Minimal", + Low: "Low", + Medium: "Medium", + High: "High", + "Storage Permission Required": "Storage Permission Required", + "This app needs persistent storage to save your conversations": "This app needs persistent storage to save your conversations", + "Why is this needed?": "Why is this needed?", + "Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.": "Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.", + "What this means:": "What this means:", + "Your conversations will be saved locally in your browser": "Your conversations will be saved locally in your browser", + "Data will not be deleted automatically to free up space": "Data will not be deleted automatically to free up space", + "You can still manually clear data at any time": "You can still manually clear data at any time", + "No data is sent to external servers": "No data is sent to external servers", + "Continue Anyway": "Continue Anyway", + "Requesting...": "Requesting...", + "Grant Permission": "Grant Permission", + Sessions: "Sessions", + "Load a previous conversation": "Load a previous conversation", + "No sessions yet": "No sessions yet", + "Delete this session?": "Delete this session?", + Today: "Today", + Yesterday: "Yesterday", + "{days} days ago": "{days} days ago", + messages: "messages", + tokens: "tokens", + Delete: "Delete", + "Drop files here": "Drop files here", + "Command failed:": "Command failed:", + // Providers & Models + "Providers & Models": "Providers & Models", + "Cloud Providers": "Cloud Providers", + "Cloud LLM providers with predefined models. API keys are stored locally in your browser.": "Cloud LLM providers with predefined models. API keys are stored locally in your browser.", + "Custom Providers": "Custom Providers", + "User-configured servers with auto-discovered or manually defined models.": "User-configured servers with auto-discovered or manually defined models.", + "Add Provider": "Add Provider", + "No custom providers configured. Click 'Add Provider' to get started.": "No custom providers configured. Click 'Add Provider' to get started.", + "auto-discovered": "auto-discovered", + Refresh: "Refresh", + Edit: "Edit", + "Are you sure you want to delete this provider?": "Are you sure you want to delete this provider?", + "Edit Provider": "Edit Provider", + "Provider Name": "Provider Name", + "e.g., My Ollama Server": "e.g., My Ollama Server", + "Provider Type": "Provider Type", + "Base URL": "Base URL", + "e.g., http://localhost:11434": "e.g., http://localhost:11434", + "API Key (Optional)": "API Key (Optional)", + "Leave empty if not required": "Leave empty if not required", + "Test Connection": "Test Connection", + Discovered: "Discovered", + Models: "Models", + models: "models", + and: "and", + more: "more", + "For manual provider types, add models after saving the provider.": "For manual provider types, add models after saving the provider.", + "Please fill in all required fields": "Please fill in all required fields", + "Failed to save provider": "Failed to save provider", + "OpenAI Completions Compatible": "OpenAI Completions Compatible", + "OpenAI Responses Compatible": "OpenAI Responses Compatible", + "Anthropic Messages Compatible": "Anthropic Messages Compatible", + "Checking...": "Checking...", + Disconnected: "Disconnected" + }, + de: { + ...defaultGerman, + Free: "Kostenlos", + "Input Required": "Eingabe erforderlich", + Cancel: "Abbrechen", + Confirm: "Best\xE4tigen", + "Select Model": "Modell ausw\xE4hlen", + "Search models...": "Modelle suchen...", + Format: "Formatieren", + Thinking: "Thinking", + Vision: "Vision", + You: "Sie", + Assistant: "Assistent", + "Thinking...": "Denkt nach...", + "Type your message...": "Geben Sie Ihre Nachricht ein...", + "API Keys Configuration": "API-Schl\xFCssel-Konfiguration", + "Configure API keys for LLM providers. Keys are stored locally in your browser.": "Konfigurieren Sie API-Schl\xFCssel f\xFCr LLM-Anbieter. Schl\xFCssel werden lokal in Ihrem Browser gespeichert.", + Configured: "Konfiguriert", + "Not configured": "Nicht konfiguriert", + "\u2713 Valid": "\u2713 G\xFCltig", + "\u2717 Invalid": "\u2717 Ung\xFCltig", + "Testing...": "Teste...", + Update: "Aktualisieren", + Test: "Testen", + Remove: "Entfernen", + Save: "Speichern", + "Update API key": "API-Schl\xFCssel aktualisieren", + "Enter API key": "API-Schl\xFCssel eingeben", + "Type a message...": "Nachricht eingeben...", + "Failed to fetch file": "Datei konnte nicht abgerufen werden", + "Invalid source type": "Ung\xFCltiger Quellentyp", + PDF: "PDF", + Document: "Dokument", + Presentation: "Pr\xE4sentation", + Spreadsheet: "Tabelle", + Text: "Text", + "Error loading file": "Fehler beim Laden der Datei", + "No text content available": "Kein Textinhalt verf\xFCgbar", + "Failed to load PDF": "PDF konnte nicht geladen werden", + "Failed to load document": "Dokument konnte nicht geladen werden", + "Failed to load spreadsheet": "Tabelle konnte nicht geladen werden", + "Error loading PDF": "Fehler beim Laden des PDFs", + "Error loading document": "Fehler beim Laden des Dokuments", + "Error loading spreadsheet": "Fehler beim Laden der Tabelle", + "Preview not available for this file type.": "Vorschau f\xFCr diesen Dateityp nicht verf\xFCgbar.", + "Click the download button above to view it on your computer.": "Klicken Sie oben auf die Download-Schaltfl\xE4che, um die Datei auf Ihrem Computer anzuzeigen.", + "No content available": "Kein Inhalt verf\xFCgbar", + "Failed to display text content": "Textinhalt konnte nicht angezeigt werden", + "API keys are required to use AI models. Get your keys from the provider's website.": "API-Schl\xFCssel sind erforderlich, um KI-Modelle zu verwenden. Holen Sie sich Ihre Schl\xFCssel von der Website des Anbieters.", + console: "Konsole", + "Copy output": "Ausgabe kopieren", + "Copied!": "Kopiert!", + "Error:": "Fehler:", + "Request aborted": "Anfrage abgebrochen", + Call: "Aufruf", + Result: "Ergebnis", + "(no result)": "(kein Ergebnis)", + "Waiting for tool result\u2026": "Warte auf Tool-Ergebnis\u2026", + "Call was aborted; no result.": "Aufruf wurde abgebrochen; kein Ergebnis.", + "No session available": "Keine Sitzung verf\xFCgbar", + "No session set": "Keine Sitzung gesetzt", + "Preparing tool parameters...": "Bereite Tool-Parameter vor...", + "(no output)": "(keine Ausgabe)", + Input: "Eingabe", + Output: "Ausgabe", + "Waiting for expression...": "Warte auf Ausdruck", + "Writing expression...": "Schreibe Ausdruck...", + Calculating: "Berechne", + "Getting current time in": "Hole aktuelle Zeit in", + "Getting current date and time": "Hole aktuelles Datum und Uhrzeit", + "Waiting for command...": "Warte auf Befehl...", + "Writing command...": "Schreibe Befehl...", + "Running command...": "F\xFChre Befehl aus...", + "Command failed": "Befehl fehlgeschlagen", + "Enter Auth Token": "Auth-Token eingeben", + "Please enter your auth token.": "Bitte geben Sie Ihr Auth-Token ein.", + "Auth token is required for proxy transport": "Auth-Token ist f\xFCr Proxy-Transport erforderlich", + // JavaScript REPL strings + "Execution aborted": "Ausf\xFChrung abgebrochen", + "Code parameter is required": "Code-Parameter ist erforderlich", + "Unknown error": "Unbekannter Fehler", + "Code executed successfully (no output)": "Code erfolgreich ausgef\xFChrt (keine Ausgabe)", + "Execution failed": "Ausf\xFChrung fehlgeschlagen", + "JavaScript REPL": "JavaScript REPL", + "JavaScript code to execute": "Auszuf\xFChrender JavaScript-Code", + "Writing JavaScript code...": "Schreibe JavaScript-Code...", + "Executing JavaScript": "F\xFChre JavaScript aus", + "Preparing JavaScript...": "Bereite JavaScript vor...", + "Preparing command...": "Bereite Befehl vor...", + "Preparing calculation...": "Bereite Berechnung vor...", + "Preparing tool...": "Bereite Tool vor...", + "Getting time...": "Hole Zeit...", + // Artifacts strings + "Processing artifact...": "Verarbeite Artefakt...", + "Preparing artifact...": "Bereite Artefakt vor...", + "Processing artifact": "Verarbeite Artefakt", + "Processed artifact": "Artefakt verarbeitet", + "Creating artifact": "Erstelle Artefakt", + "Created artifact": "Artefakt erstellt", + "Updating artifact": "Aktualisiere Artefakt", + "Updated artifact": "Artefakt aktualisiert", + "Rewriting artifact": "\xDCberschreibe Artefakt", + "Rewrote artifact": "Artefakt \xFCberschrieben", + "Getting artifact": "Hole Artefakt", + "Got artifact": "Artefakt geholt", + "Deleting artifact": "L\xF6sche Artefakt", + "Deleted artifact": "Artefakt gel\xF6scht", + "Getting logs": "Hole Logs", + "Got logs": "Logs geholt", + "An error occurred": "Ein Fehler ist aufgetreten", + "Copy logs": "Logs kopieren", + "Autoscroll enabled": "Automatisches Scrollen aktiviert", + "Autoscroll disabled": "Automatisches Scrollen deaktiviert", + Processing: "Verarbeitung", + Create: "Erstellen", + Rewrite: "\xDCberschreiben", + Get: "Abrufen", + "Get logs": "Logs abrufen", + "Show artifacts": "Artefakte anzeigen", + "Close artifacts": "Artefakte schlie\xDFen", + Artifacts: "Artefakte", + "Copy HTML": "HTML kopieren", + "Download HTML": "HTML herunterladen", + "Reload HTML": "HTML neu laden", + "Copy SVG": "SVG kopieren", + "Download SVG": "SVG herunterladen", + "Copy Markdown": "Markdown kopieren", + "Download Markdown": "Markdown herunterladen", + Download: "Herunterladen", + "No logs for {filename}": "Keine Logs f\xFCr {filename}", + "API Keys Settings": "API-Schl\xFCssel Einstellungen", + Settings: "Einstellungen", + "API Keys": "API-Schl\xFCssel", + Proxy: "Proxy", + "Use CORS Proxy": "CORS-Proxy verwenden", + "Proxy URL": "Proxy-URL", + "Format: The proxy must accept requests as /?url=": "Format: Der Proxy muss Anfragen als /?url= akzeptieren", + "Settings are stored locally in your browser": "Einstellungen werden lokal in Ihrem Browser gespeichert", + Clear: "L\xF6schen", + "API Key Required": "API-Schl\xFCssel erforderlich", + "Enter your API key for {provider}": "Geben Sie Ihren API-Schl\xFCssel f\xFCr {provider} ein", + "Allows browser-based apps to bypass CORS restrictions when calling LLM providers. Required for Z-AI and Anthropic with OAuth token.": "Erm\xF6glicht browserbasierten Anwendungen, CORS-Einschr\xE4nkungen beim Aufruf von LLM-Anbietern zu umgehen. Erforderlich f\xFCr Z-AI und Anthropic mit OAuth-Token.", + Off: "Aus", + Minimal: "Minimal", + Low: "Niedrig", + Medium: "Mittel", + High: "Hoch", + "Storage Permission Required": "Speicherberechtigung erforderlich", + "This app needs persistent storage to save your conversations": "Diese App ben\xF6tigt dauerhaften Speicher, um Ihre Konversationen zu speichern", + "Why is this needed?": "Warum wird das ben\xF6tigt?", + "Without persistent storage, your browser may delete saved conversations when it needs disk space. Granting this permission ensures your chat history is preserved.": "Ohne dauerhaften Speicher kann Ihr Browser gespeicherte Konversationen l\xF6schen, wenn Speicherplatz ben\xF6tigt wird. Diese Berechtigung stellt sicher, dass Ihr Chatverlauf erhalten bleibt.", + "What this means:": "Was das bedeutet:", + "Your conversations will be saved locally in your browser": "Ihre Konversationen werden lokal in Ihrem Browser gespeichert", + "Data will not be deleted automatically to free up space": "Daten werden nicht automatisch gel\xF6scht, um Speicherplatz freizugeben", + "You can still manually clear data at any time": "Sie k\xF6nnen Daten jederzeit manuell l\xF6schen", + "No data is sent to external servers": "Keine Daten werden an externe Server gesendet", + "Continue Anyway": "Trotzdem fortfahren", + "Requesting...": "Anfrage l\xE4uft...", + "Grant Permission": "Berechtigung erteilen", + Sessions: "Sitzungen", + "Load a previous conversation": "Fr\xFChere Konversation laden", + "No sessions yet": "Noch keine Sitzungen", + "Delete this session?": "Diese Sitzung l\xF6schen?", + Today: "Heute", + Yesterday: "Gestern", + "{days} days ago": "vor {days} Tagen", + messages: "Nachrichten", + tokens: "Tokens", + Delete: "L\xF6schen", + "Drop files here": "Dateien hier ablegen", + "Command failed:": "Befehl fehlgeschlagen:", + // Providers & Models + "Providers & Models": "Anbieter & Modelle", + "Cloud Providers": "Cloud-Anbieter", + "Cloud LLM providers with predefined models. API keys are stored locally in your browser.": "Cloud-LLM-Anbieter mit vordefinierten Modellen. API-Schl\xFCssel werden lokal in Ihrem Browser gespeichert.", + "Custom Providers": "Benutzerdefinierte Anbieter", + "User-configured servers with auto-discovered or manually defined models.": "Benutzerkonfigurierte Server mit automatisch erkannten oder manuell definierten Modellen.", + "Add Provider": "Anbieter hinzuf\xFCgen", + "No custom providers configured. Click 'Add Provider' to get started.": "Keine benutzerdefinierten Anbieter konfiguriert. Klicken Sie auf 'Anbieter hinzuf\xFCgen', um zu beginnen.", + "auto-discovered": "automatisch erkannt", + Refresh: "Aktualisieren", + Edit: "Bearbeiten", + "Are you sure you want to delete this provider?": "Sind Sie sicher, dass Sie diesen Anbieter l\xF6schen m\xF6chten?", + "Edit Provider": "Anbieter bearbeiten", + "Provider Name": "Anbietername", + "e.g., My Ollama Server": "z.B. Mein Ollama Server", + "Provider Type": "Anbietertyp", + "Base URL": "Basis-URL", + "e.g., http://localhost:11434": "z.B. http://localhost:11434", + "API Key (Optional)": "API-Schl\xFCssel (Optional)", + "Leave empty if not required": "Leer lassen, falls nicht erforderlich", + "Test Connection": "Verbindung testen", + Discovered: "Erkannt", + Models: "Modelle", + models: "Modelle", + and: "und", + more: "mehr", + "For manual provider types, add models after saving the provider.": "F\xFCr manuelle Anbietertypen f\xFCgen Sie Modelle nach dem Speichern des Anbieters hinzu.", + "Please fill in all required fields": "Bitte f\xFCllen Sie alle erforderlichen Felder aus", + "Failed to save provider": "Fehler beim Speichern des Anbieters", + "OpenAI Completions Compatible": "OpenAI Completions Kompatibel", + "OpenAI Responses Compatible": "OpenAI Responses Kompatibel", + "Anthropic Messages Compatible": "Anthropic Messages Kompatibel", + "Checking...": "\xDCberpr\xFCfe...", + Disconnected: "Getrennt" + } + }; + setTranslations(translations2); + } +}); + +// ../pi-mono/packages/web-ui/dist/components/Input.js +var Input2; +var init_Input2 = __esm({ + "../pi-mono/packages/web-ui/dist/components/Input.js"() { + "use strict"; + init_process_shim(); + init_mini(); + init_lit(); + init_ref2(); + init_i18n2(); + Input2 = fc(({ type = "text", size = "md", value = "", placeholder = "", label = "", error = "", disabled = false, required = false, name = "", autocomplete = "", min, max, step, inputRef, onInput, onChange, onKeyDown, onKeyUp, className = "" }) => { + const sizeClasses2 = { + sm: "h-8 px-3 py-1 text-sm", + md: "h-9 px-3 py-1 text-sm md:text-sm", + lg: "h-10 px-4 py-1 text-base" + }; + const baseClasses = "flex w-full min-w-0 rounded-md border bg-transparent text-foreground shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium"; + const interactionClasses = "placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground"; + const focusClasses = "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"; + const darkClasses = "dark:bg-input/30"; + const stateClasses = error ? "border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40" : "border-input"; + const disabledClasses = "disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"; + const handleInput = (e9) => { + onInput?.(e9); + }; + const handleChange = (e9) => { + onChange?.(e9); + }; + return b2` +
+ ${label ? b2` + + ` : ""} + + ${error ? b2`${error}` : ""} +
+ `; + }); + } +}); + +// ../pi-mono/packages/web-ui/dist/storage/app-storage.js +function getAppStorage() { + if (!globalAppStorage) { + throw new Error("AppStorage not initialized. Call setAppStorage() first."); + } + return globalAppStorage; +} +function setAppStorage(storage2) { + globalAppStorage = storage2; +} +var AppStorage, globalAppStorage; +var init_app_storage = __esm({ + "../pi-mono/packages/web-ui/dist/storage/app-storage.js"() { + "use strict"; + init_process_shim(); + AppStorage = class { + constructor(settings, providerKeys, sessions, customProviders, backend) { + this.settings = settings; + this.providerKeys = providerKeys; + this.sessions = sessions; + this.customProviders = customProviders; + this.backend = backend; + } + async getQuotaInfo() { + return this.backend.getQuotaInfo(); + } + async requestPersistence() { + return this.backend.requestPersistence(); + } + }; + globalAppStorage = null; + } +}); + +// ../pi-mono/packages/web-ui/dist/utils/format.js +function formatCost(cost) { + return `$${cost.toFixed(4)}`; +} +function formatModelCost(cost) { + if (!cost) + return i18n("Free"); + const input = cost.input || 0; + const output = cost.output || 0; + if (input === 0 && output === 0) + return i18n("Free"); + const formatNum = (num) => { + if (num >= 100) + return num.toFixed(0); + if (num >= 10) + return num.toFixed(1).replace(/\.0$/, ""); + if (num >= 1) + return num.toFixed(2).replace(/\.?0+$/, ""); + return num.toFixed(3).replace(/\.?0+$/, ""); + }; + return `$${formatNum(input)}/$${formatNum(output)}`; +} +function formatUsage(usage) { + if (!usage) + return ""; + const parts = []; + if (usage.input) + parts.push(`\u2191${formatTokenCount(usage.input)}`); + if (usage.output) + parts.push(`\u2193${formatTokenCount(usage.output)}`); + if (usage.cacheRead) + parts.push(`R${formatTokenCount(usage.cacheRead)}`); + if (usage.cacheWrite) + parts.push(`W${formatTokenCount(usage.cacheWrite)}`); + if (usage.cost?.total) + parts.push(formatCost(usage.cost.total)); + return parts.join(" "); +} +function formatTokenCount(count) { + if (count < 1e3) + return count.toString(); + if (count < 1e4) + return `${(count / 1e3).toFixed(1)}k`; + return `${Math.round(count / 1e3)}k`; +} +var init_format2 = __esm({ + "../pi-mono/packages/web-ui/dist/utils/format.js"() { + "use strict"; + init_process_shim(); + init_dist(); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/util.js +var util, objectUtil, ZodParsedType, getParsedType; +var init_util = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/util.js"() { + init_process_shim(); + (function(util3) { + util3.assertEqual = (_3) => { + }; + function assertIs(_arg) { + } + util3.assertIs = assertIs; + function assertNever3(_x2) { + throw new Error(); + } + util3.assertNever = assertNever3; + util3.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util3.getValidEnumValues = (obj) => { + const validKeys = util3.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); + const filtered = {}; + for (const k2 of validKeys) { + filtered[k2] = obj[k2]; + } + return util3.objectValues(filtered); + }; + util3.objectValues = (obj) => { + return util3.objectKeys(obj).map(function(e9) { + return obj[e9]; + }); + }; + util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys2 = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys2.push(key); + } + } + return keys2; + }; + util3.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util3.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2; + function joinValues(array, separator = " | ") { + return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); + } + util3.joinValues = joinValues; + util3.jsonStringifyReplacer = (_3, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util || (util = {})); + (function(objectUtil3) { + objectUtil3.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; + })(objectUtil || (objectUtil = {})); + ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); + getParsedType = (data) => { + const t6 = typeof data; + switch (t6) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/ZodError.js +var ZodIssueCode, quotelessJson, ZodError; +var init_ZodError = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/ZodError.js"() { + init_process_shim(); + init_util(); + ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + quotelessJson = (obj) => { + const json2 = JSON.stringify(obj, null, 2); + return json2.replace(/"([^"]+)":/g, "$1:"); + }; + ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub2) => { + this.issues = [...this.issues, sub2]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i7 = 0; + while (i7 < issue.path.length) { + const el = issue.path[i7]; + const terminal = i7 === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i7++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub2 of this.issues) { + if (sub2.path.length > 0) { + const firstEl = sub2.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub2)); + } else { + formErrors.push(mapper(sub2)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + }; + ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/locales/en.js +var errorMap, en_default; +var init_en = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/locales/en.js"() { + init_process_shim(); + init_ZodError(); + init_util(); + errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; + }; + en_default = errorMap; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/errors.js +function setErrorMap(map3) { + overrideErrorMap = map3; +} +function getErrorMap() { + return overrideErrorMap; +} +var overrideErrorMap; +var init_errors3 = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/errors.js"() { + init_process_shim(); + init_en(); + overrideErrorMap = en_default; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/parseUtil.js +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x2) => !!x2) + }); + ctx.common.issues.push(issue); +} +var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync; +var init_parseUtil = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/parseUtil.js"() { + init_process_shim(); + init_errors3(); + init_en(); + makeIssue = (params) => { + const { data, path: path6, errorMaps, issueData } = params; + const fullPath = [...path6, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m4) => !!m4).slice().reverse(); + for (const map3 of maps) { + errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; + }; + EMPTY_PATH = []; + ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s6 of results) { + if (s6.status === "aborted") + return INVALID; + if (s6.status === "dirty") + status.dirty(); + arrayValue.push(s6.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + }; + INVALID = Object.freeze({ + status: "aborted" + }); + DIRTY = (value) => ({ status: "dirty", value }); + OK = (value) => ({ status: "valid", value }); + isAborted = (x2) => x2.status === "aborted"; + isDirty = (x2) => x2.status === "dirty"; + isValid = (x2) => x2.status === "valid"; + isAsync = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/typeAliases.js +var init_typeAliases = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/typeAliases.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +var init_errorUtil = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/helpers/errorUtil.js"() { + init_process_shim(); + (function(errorUtil3) { + errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil || (errorUtil = {})); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/types.js +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; + if (errorMap3 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap3) + return { errorMap: errorMap3, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4Regex.test(ip)) { + return true; + } + if ((version6 === "v6" || !version6) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version6 === "v6" || !version6) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +function floatSafeRemainder(val2, step) { + const valDecCount = (val2.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +function mergeValues(a3, b4) { + const aType = getParsedType(a3); + const bType = getParsedType(b4); + if (a3 === b4) { + return { valid: true, data: a3 }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b4); + const sharedKeys = util.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a3, ...b4 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a3[key], b4[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a3.length !== b4.length) { + return { valid: false }; + } + const newArray = []; + for (let index2 = 0; index2 < a3.length; index2++) { + const itemA = a3[index2]; + const itemB = b4[index2]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a3 === +b4) { + return { valid: true, data: a3 }; + } else { + return { valid: false }; + } +} +function createZodEnum(values2, params) { + return new ZodEnum({ + values: values2, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +function cleanParams(params, data) { + const p4 = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p22 = typeof p4 === "string" ? { message: p4 } : p4; + return p22; +} +function custom(check, _params = {}, fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r8 = check(data); + if (r8 instanceof Promise) { + return r8.then((r9) => { + if (!r9) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r8) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER; +var init_types2 = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/types.js"() { + init_process_shim(); + init_ZodError(); + init_errors3(); + init_errorUtil(); + init_parseUtil(); + init_util(); + ParseInputLazyPath = class { + constructor(parent, value, path6, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path6; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + }; + handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } + }; + ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val2) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val2); + } else { + return message; + } + }; + return this._refinement((val2, ctx) => { + const result = check(val2); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val2) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val2, ctx) => { + if (!check(val2)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } + }; + cuidRegex = /^c[^\s-]{8,}$/i; + cuid2Regex = /^[0-9a-z]+$/; + ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + nanoidRegex = /^[a-z0-9_-]{21}$/i; + jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; + dateRegex = new RegExp(`^${dateRegexSource}$`); + ZodString = class _ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + }; + ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + }; + ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + }; + ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); + }; + ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); + }; + ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + }; + ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); + }; + ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); + }; + ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); + }; + ZodNull = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); + }; + ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } + }; + ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); + }; + ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } + }; + ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); + }; + ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } + }; + ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); + }; + ZodVoid = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } + }; + ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); + }; + ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i7) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i7)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i7) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i7)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); + }; + ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys2 = util.objectKeys(shape); + this._cached = { shape, keys: keys2 }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index2) { + return new _ZodObject({ + ...this._def, + catchall: index2 + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } + }; + ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + }; + ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + }; + ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); + }; + ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } + }; + ZodUnion.create = (types2, params) => { + return new ZodUnion({ + options: types2, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); + }; + getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } + }; + ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } + }; + ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } + }; + ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); + }; + ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x2) => !!x2); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } + }; + ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); + }; + ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } + }; + ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + }; + ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); + }; + ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements3) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements3) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements2 = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i7))); + if (ctx.common.async) { + return Promise.all(elements2).then((elements3) => finalizeSet(elements3)); + } else { + return finalizeSet(elements2); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); + }; + ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x2) => !!x2), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e9) => { + error.addIssue(makeArgsIssue(args, e9)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => { + error.addIssue(makeReturnsIssue(result, e9)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } + }; + ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); + }; + ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + }; + ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); + }; + ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + extract(values2, newDef = this._def) { + return _ZodEnum.create(values2, { + ...this._def, + ...newDef + }); + } + exclude(values2, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), { + ...this._def, + ...newDef + }); + } + }; + ZodEnum.create = createZodEnum; + ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } + }; + ZodNativeEnum.create = (values2, params) => { + return new ZodNativeEnum({ + values: values2, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); + }; + ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } + }; + ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); + }; + ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner2 = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner2.status === "aborted") + return INVALID; + if (inner2.status === "dirty") + status.dirty(); + executeRefinement(inner2.value); + return { status: status.value, value: inner2.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => { + if (inner2.status === "aborted") + return INVALID; + if (inner2.status === "dirty") + status.dirty(); + return executeRefinement(inner2.value).then(() => { + return { status: status.value, value: inner2.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); + } + }; + ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); + }; + ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); + }; + ZodOptional = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); + }; + ZodNullable = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); + }; + ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } + }; + ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); + }; + ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } + }; + ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); + }; + ZodNaN = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + }; + ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); + }; + BRAND = Symbol("zod_brand"); + ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } + }; + ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a3, b4) { + return new _ZodPipeline({ + in: a3, + out: b4, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } + }; + ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze2 = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze2(data)) : freeze2(result); + } + unwrap() { + return this._def.innerType; + } + }; + ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); + }; + late = { + object: ZodObject.lazycreate + }; + (function(ZodFirstPartyTypeKind3) { + ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); + instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` + }) => custom((data) => data instanceof cls, params); + stringType = ZodString.create; + numberType = ZodNumber.create; + nanType = ZodNaN.create; + bigIntType = ZodBigInt.create; + booleanType = ZodBoolean.create; + dateType = ZodDate.create; + symbolType = ZodSymbol.create; + undefinedType = ZodUndefined.create; + nullType = ZodNull.create; + anyType = ZodAny.create; + unknownType = ZodUnknown.create; + neverType = ZodNever.create; + voidType = ZodVoid.create; + arrayType = ZodArray.create; + objectType = ZodObject.create; + strictObjectType = ZodObject.strictCreate; + unionType = ZodUnion.create; + discriminatedUnionType = ZodDiscriminatedUnion.create; + intersectionType = ZodIntersection.create; + tupleType = ZodTuple.create; + recordType = ZodRecord.create; + mapType = ZodMap.create; + setType = ZodSet.create; + functionType = ZodFunction.create; + lazyType = ZodLazy.create; + literalType = ZodLiteral.create; + enumType = ZodEnum.create; + nativeEnumType = ZodNativeEnum.create; + promiseType = ZodPromise.create; + effectsType = ZodEffects.create; + optionalType = ZodOptional.create; + nullableType = ZodNullable.create; + preprocessType = ZodEffects.createWithPreprocess; + pipelineType = ZodPipeline.create; + ostring = () => stringType().optional(); + onumber = () => numberType().optional(); + oboolean = () => booleanType().optional(); + coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })) + }; + NEVER = INVALID; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); +var init_external = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/v3/external.js"() { + init_process_shim(); + init_errors3(); + init_parseUtil(); + init_typeAliases(); + init_util(); + init_types2(); + init_ZodError(); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/index.js +var init_zod = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/zod/index.js"() { + init_process_shim(); + init_external(); + init_external(); + } +}); + +// ../pi-mono/node_modules/color-name/index.js +var require_color_name = __commonJS({ + "../pi-mono/node_modules/color-name/index.js"(exports, module) { + "use strict"; + init_process_shim(); + module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + } +}); + +// ../pi-mono/node_modules/color-convert/conversions.js +var require_conversions = __commonJS({ + "../pi-mono/node_modules/color-convert/conversions.js"(exports, module) { + init_process_shim(); + var cssKeywords = require_color_name(); + var reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + var convert = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + lch: { channels: 3, labels: "lch" }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } + }; + module.exports = convert; + for (const model of Object.keys(convert)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + const { channels, labels } = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); + } + convert.rgb.hsl = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const min = Math.min(r8, g3, b4); + const max = Math.max(r8, g3, b4); + const delta = max - min; + let h7; + let s6; + if (max === min) { + h7 = 0; + } else if (r8 === max) { + h7 = (g3 - b4) / delta; + } else if (g3 === max) { + h7 = 2 + (b4 - r8) / delta; + } else if (b4 === max) { + h7 = 4 + (r8 - g3) / delta; + } + h7 = Math.min(h7 * 60, 360); + if (h7 < 0) { + h7 += 360; + } + const l5 = (min + max) / 2; + if (max === min) { + s6 = 0; + } else if (l5 <= 0.5) { + s6 = delta / (max + min); + } else { + s6 = delta / (2 - max - min); + } + return [h7, s6 * 100, l5 * 100]; + }; + convert.rgb.hsv = function(rgb) { + let rdif; + let gdif; + let bdif; + let h7; + let s6; + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const v4 = Math.max(r8, g3, b4); + const diff = v4 - Math.min(r8, g3, b4); + const diffc = function(c6) { + return (v4 - c6) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h7 = 0; + s6 = 0; + } else { + s6 = diff / v4; + rdif = diffc(r8); + gdif = diffc(g3); + bdif = diffc(b4); + if (r8 === v4) { + h7 = bdif - gdif; + } else if (g3 === v4) { + h7 = 1 / 3 + rdif - bdif; + } else if (b4 === v4) { + h7 = 2 / 3 + gdif - rdif; + } + if (h7 < 0) { + h7 += 1; + } else if (h7 > 1) { + h7 -= 1; + } + } + return [ + h7 * 360, + s6 * 100, + v4 * 100 + ]; + }; + convert.rgb.hwb = function(rgb) { + const r8 = rgb[0]; + const g3 = rgb[1]; + let b4 = rgb[2]; + const h7 = convert.rgb.hsl(rgb)[0]; + const w3 = 1 / 255 * Math.min(r8, Math.min(g3, b4)); + b4 = 1 - 1 / 255 * Math.max(r8, Math.max(g3, b4)); + return [h7, w3 * 100, b4 * 100]; + }; + convert.rgb.cmyk = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const k2 = Math.min(1 - r8, 1 - g3, 1 - b4); + const c6 = (1 - r8 - k2) / (1 - k2) || 0; + const m4 = (1 - g3 - k2) / (1 - k2) || 0; + const y4 = (1 - b4 - k2) / (1 - k2) || 0; + return [c6 * 100, m4 * 100, y4 * 100, k2 * 100]; + }; + function comparativeDistance(x2, y4) { + return (x2[0] - y4[0]) ** 2 + (x2[1] - y4[1]) ** 2 + (x2[2] - y4[2]) ** 2; + } + convert.rgb.keyword = function(rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + let currentClosestDistance = Infinity; + let currentClosestKeyword; + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + const distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + return currentClosestKeyword; + }; + convert.keyword.rgb = function(keyword) { + return cssKeywords[keyword]; + }; + convert.rgb.xyz = function(rgb) { + let r8 = rgb[0] / 255; + let g3 = rgb[1] / 255; + let b4 = rgb[2] / 255; + r8 = r8 > 0.04045 ? ((r8 + 0.055) / 1.055) ** 2.4 : r8 / 12.92; + g3 = g3 > 0.04045 ? ((g3 + 0.055) / 1.055) ** 2.4 : g3 / 12.92; + b4 = b4 > 0.04045 ? ((b4 + 0.055) / 1.055) ** 2.4 : b4 / 12.92; + const x2 = r8 * 0.4124 + g3 * 0.3576 + b4 * 0.1805; + const y4 = r8 * 0.2126 + g3 * 0.7152 + b4 * 0.0722; + const z3 = r8 * 0.0193 + g3 * 0.1192 + b4 * 0.9505; + return [x2 * 100, y4 * 100, z3 * 100]; + }; + convert.rgb.lab = function(rgb) { + const xyz = convert.rgb.xyz(rgb); + let x2 = xyz[0]; + let y4 = xyz[1]; + let z3 = xyz[2]; + x2 /= 95.047; + y4 /= 100; + z3 /= 108.883; + x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116; + y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116; + z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116; + const l5 = 116 * y4 - 16; + const a3 = 500 * (x2 - y4); + const b4 = 200 * (y4 - z3); + return [l5, a3, b4]; + }; + convert.hsl.rgb = function(hsl) { + const h7 = hsl[0] / 360; + const s6 = hsl[1] / 100; + const l5 = hsl[2] / 100; + let t22; + let t32; + let val2; + if (s6 === 0) { + val2 = l5 * 255; + return [val2, val2, val2]; + } + if (l5 < 0.5) { + t22 = l5 * (1 + s6); + } else { + t22 = l5 + s6 - l5 * s6; + } + const t1 = 2 * l5 - t22; + const rgb = [0, 0, 0]; + for (let i7 = 0; i7 < 3; i7++) { + t32 = h7 + 1 / 3 * -(i7 - 1); + if (t32 < 0) { + t32++; + } + if (t32 > 1) { + t32--; + } + if (6 * t32 < 1) { + val2 = t1 + (t22 - t1) * 6 * t32; + } else if (2 * t32 < 1) { + val2 = t22; + } else if (3 * t32 < 2) { + val2 = t1 + (t22 - t1) * (2 / 3 - t32) * 6; + } else { + val2 = t1; + } + rgb[i7] = val2 * 255; + } + return rgb; + }; + convert.hsl.hsv = function(hsl) { + const h7 = hsl[0]; + let s6 = hsl[1] / 100; + let l5 = hsl[2] / 100; + let smin = s6; + const lmin = Math.max(l5, 0.01); + l5 *= 2; + s6 *= l5 <= 1 ? l5 : 2 - l5; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v4 = (l5 + s6) / 2; + const sv = l5 === 0 ? 2 * smin / (lmin + smin) : 2 * s6 / (l5 + s6); + return [h7, sv * 100, v4 * 100]; + }; + convert.hsv.rgb = function(hsv) { + const h7 = hsv[0] / 60; + const s6 = hsv[1] / 100; + let v4 = hsv[2] / 100; + const hi = Math.floor(h7) % 6; + const f4 = h7 - Math.floor(h7); + const p4 = 255 * v4 * (1 - s6); + const q2 = 255 * v4 * (1 - s6 * f4); + const t6 = 255 * v4 * (1 - s6 * (1 - f4)); + v4 *= 255; + switch (hi) { + case 0: + return [v4, t6, p4]; + case 1: + return [q2, v4, p4]; + case 2: + return [p4, v4, t6]; + case 3: + return [p4, q2, v4]; + case 4: + return [t6, p4, v4]; + case 5: + return [v4, p4, q2]; + } + }; + convert.hsv.hsl = function(hsv) { + const h7 = hsv[0]; + const s6 = hsv[1] / 100; + const v4 = hsv[2] / 100; + const vmin = Math.max(v4, 0.01); + let sl; + let l5; + l5 = (2 - s6) * v4; + const lmin = (2 - s6) * vmin; + sl = s6 * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l5 /= 2; + return [h7, sl * 100, l5 * 100]; + }; + convert.hwb.rgb = function(hwb) { + const h7 = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f4; + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + const i7 = Math.floor(6 * h7); + const v4 = 1 - bl; + f4 = 6 * h7 - i7; + if ((i7 & 1) !== 0) { + f4 = 1 - f4; + } + const n7 = wh + f4 * (v4 - wh); + let r8; + let g3; + let b4; + switch (i7) { + default: + case 6: + case 0: + r8 = v4; + g3 = n7; + b4 = wh; + break; + case 1: + r8 = n7; + g3 = v4; + b4 = wh; + break; + case 2: + r8 = wh; + g3 = v4; + b4 = n7; + break; + case 3: + r8 = wh; + g3 = n7; + b4 = v4; + break; + case 4: + r8 = n7; + g3 = wh; + b4 = v4; + break; + case 5: + r8 = v4; + g3 = wh; + b4 = n7; + break; + } + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.cmyk.rgb = function(cmyk) { + const c6 = cmyk[0] / 100; + const m4 = cmyk[1] / 100; + const y4 = cmyk[2] / 100; + const k2 = cmyk[3] / 100; + const r8 = 1 - Math.min(1, c6 * (1 - k2) + k2); + const g3 = 1 - Math.min(1, m4 * (1 - k2) + k2); + const b4 = 1 - Math.min(1, y4 * (1 - k2) + k2); + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.xyz.rgb = function(xyz) { + const x2 = xyz[0] / 100; + const y4 = xyz[1] / 100; + const z3 = xyz[2] / 100; + let r8; + let g3; + let b4; + r8 = x2 * 3.2406 + y4 * -1.5372 + z3 * -0.4986; + g3 = x2 * -0.9689 + y4 * 1.8758 + z3 * 0.0415; + b4 = x2 * 0.0557 + y4 * -0.204 + z3 * 1.057; + r8 = r8 > 31308e-7 ? 1.055 * r8 ** (1 / 2.4) - 0.055 : r8 * 12.92; + g3 = g3 > 31308e-7 ? 1.055 * g3 ** (1 / 2.4) - 0.055 : g3 * 12.92; + b4 = b4 > 31308e-7 ? 1.055 * b4 ** (1 / 2.4) - 0.055 : b4 * 12.92; + r8 = Math.min(Math.max(0, r8), 1); + g3 = Math.min(Math.max(0, g3), 1); + b4 = Math.min(Math.max(0, b4), 1); + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.xyz.lab = function(xyz) { + let x2 = xyz[0]; + let y4 = xyz[1]; + let z3 = xyz[2]; + x2 /= 95.047; + y4 /= 100; + z3 /= 108.883; + x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116; + y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116; + z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116; + const l5 = 116 * y4 - 16; + const a3 = 500 * (x2 - y4); + const b4 = 200 * (y4 - z3); + return [l5, a3, b4]; + }; + convert.lab.xyz = function(lab) { + const l5 = lab[0]; + const a3 = lab[1]; + const b4 = lab[2]; + let x2; + let y4; + let z3; + y4 = (l5 + 16) / 116; + x2 = a3 / 500 + y4; + z3 = y4 - b4 / 200; + const y22 = y4 ** 3; + const x22 = x2 ** 3; + const z22 = z3 ** 3; + y4 = y22 > 8856e-6 ? y22 : (y4 - 16 / 116) / 7.787; + x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787; + z3 = z22 > 8856e-6 ? z22 : (z3 - 16 / 116) / 7.787; + x2 *= 95.047; + y4 *= 100; + z3 *= 108.883; + return [x2, y4, z3]; + }; + convert.lab.lch = function(lab) { + const l5 = lab[0]; + const a3 = lab[1]; + const b4 = lab[2]; + let h7; + const hr = Math.atan2(b4, a3); + h7 = hr * 360 / 2 / Math.PI; + if (h7 < 0) { + h7 += 360; + } + const c6 = Math.sqrt(a3 * a3 + b4 * b4); + return [l5, c6, h7]; + }; + convert.lch.lab = function(lch) { + const l5 = lch[0]; + const c6 = lch[1]; + const h7 = lch[2]; + const hr = h7 / 360 * 2 * Math.PI; + const a3 = c6 * Math.cos(hr); + const b4 = c6 * Math.sin(hr); + return [l5, a3, b4]; + }; + convert.rgb.ansi16 = function(args, saturation = null) { + const [r8, g3, b4] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + let ansi = 30 + (Math.round(b4 / 255) << 2 | Math.round(g3 / 255) << 1 | Math.round(r8 / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; + }; + convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + convert.rgb.ansi256 = function(args) { + const r8 = args[0]; + const g3 = args[1]; + const b4 = args[2]; + if (r8 === g3 && g3 === b4) { + if (r8 < 8) { + return 16; + } + if (r8 > 248) { + return 231; + } + return Math.round((r8 - 8) / 247 * 24) + 232; + } + const ansi = 16 + 36 * Math.round(r8 / 255 * 5) + 6 * Math.round(g3 / 255 * 5) + Math.round(b4 / 255 * 5); + return ansi; + }; + convert.ansi16.rgb = function(args) { + let color2 = args % 10; + if (color2 === 0 || color2 === 7) { + if (args > 50) { + color2 += 3.5; + } + color2 = color2 / 10.5 * 255; + return [color2, color2, color2]; + } + const mult = (~~(args > 50) + 1) * 0.5; + const r8 = (color2 & 1) * mult * 255; + const g3 = (color2 >> 1 & 1) * mult * 255; + const b4 = (color2 >> 2 & 1) * mult * 255; + return [r8, g3, b4]; + }; + convert.ansi256.rgb = function(args) { + if (args >= 232) { + const c6 = (args - 232) * 10 + 8; + return [c6, c6, c6]; + } + args -= 16; + let rem; + const r8 = Math.floor(args / 36) / 5 * 255; + const g3 = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b4 = rem % 6 / 5 * 255; + return [r8, g3, b4]; + }; + convert.rgb.hex = function(args) { + const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + const string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.hex.rgb = function(args) { + const match2 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match2) { + return [0, 0, 0]; + } + let colorString = match2[0]; + if (match2[0].length === 3) { + colorString = colorString.split("").map((char) => { + return char + char; + }).join(""); + } + const integer = parseInt(colorString, 16); + const r8 = integer >> 16 & 255; + const g3 = integer >> 8 & 255; + const b4 = integer & 255; + return [r8, g3, b4]; + }; + convert.rgb.hcg = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const max = Math.max(Math.max(r8, g3), b4); + const min = Math.min(Math.min(r8, g3), b4); + const chroma = max - min; + let grayscale; + let hue2; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + if (chroma <= 0) { + hue2 = 0; + } else if (max === r8) { + hue2 = (g3 - b4) / chroma % 6; + } else if (max === g3) { + hue2 = 2 + (b4 - r8) / chroma; + } else { + hue2 = 4 + (r8 - g3) / chroma; + } + hue2 /= 6; + hue2 %= 1; + return [hue2 * 360, chroma * 100, grayscale * 100]; + }; + convert.hsl.hcg = function(hsl) { + const s6 = hsl[1] / 100; + const l5 = hsl[2] / 100; + const c6 = l5 < 0.5 ? 2 * s6 * l5 : 2 * s6 * (1 - l5); + let f4 = 0; + if (c6 < 1) { + f4 = (l5 - 0.5 * c6) / (1 - c6); + } + return [hsl[0], c6 * 100, f4 * 100]; + }; + convert.hsv.hcg = function(hsv) { + const s6 = hsv[1] / 100; + const v4 = hsv[2] / 100; + const c6 = s6 * v4; + let f4 = 0; + if (c6 < 1) { + f4 = (v4 - c6) / (1 - c6); + } + return [hsv[0], c6 * 100, f4 * 100]; + }; + convert.hcg.rgb = function(hcg) { + const h7 = hcg[0] / 360; + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + if (c6 === 0) { + return [g3 * 255, g3 * 255, g3 * 255]; + } + const pure = [0, 0, 0]; + const hi = h7 % 1 * 6; + const v4 = hi % 1; + const w3 = 1 - v4; + let mg = 0; + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v4; + pure[2] = 0; + break; + case 1: + pure[0] = w3; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v4; + break; + case 3: + pure[0] = 0; + pure[1] = w3; + pure[2] = 1; + break; + case 4: + pure[0] = v4; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w3; + } + mg = (1 - c6) * g3; + return [ + (c6 * pure[0] + mg) * 255, + (c6 * pure[1] + mg) * 255, + (c6 * pure[2] + mg) * 255 + ]; + }; + convert.hcg.hsv = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const v4 = c6 + g3 * (1 - c6); + let f4 = 0; + if (v4 > 0) { + f4 = c6 / v4; + } + return [hcg[0], f4 * 100, v4 * 100]; + }; + convert.hcg.hsl = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const l5 = g3 * (1 - c6) + 0.5 * c6; + let s6 = 0; + if (l5 > 0 && l5 < 0.5) { + s6 = c6 / (2 * l5); + } else if (l5 >= 0.5 && l5 < 1) { + s6 = c6 / (2 * (1 - l5)); + } + return [hcg[0], s6 * 100, l5 * 100]; + }; + convert.hcg.hwb = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const v4 = c6 + g3 * (1 - c6); + return [hcg[0], (v4 - c6) * 100, (1 - v4) * 100]; + }; + convert.hwb.hcg = function(hwb) { + const w3 = hwb[1] / 100; + const b4 = hwb[2] / 100; + const v4 = 1 - b4; + const c6 = v4 - w3; + let g3 = 0; + if (c6 < 1) { + g3 = (v4 - c6) / (1 - c6); + } + return [hwb[0], c6 * 100, g3 * 100]; + }; + convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + convert.gray.hsl = function(args) { + return [0, 0, args[0]]; + }; + convert.gray.hsv = convert.gray.hsl; + convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; + }; + convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; + }; + convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; + }; + convert.gray.hex = function(gray) { + const val2 = Math.round(gray[0] / 100 * 255) & 255; + const integer = (val2 << 16) + (val2 << 8) + val2; + const string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.rgb.gray = function(rgb) { + const val2 = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val2 / 255 * 100]; + }; + } +}); + +// ../pi-mono/node_modules/color-convert/route.js +var require_route = __commonJS({ + "../pi-mono/node_modules/color-convert/route.js"(exports, module) { + init_process_shim(); + var conversions2 = require_conversions(); + function buildGraph() { + const graph = {}; + const models = Object.keys(conversions2); + for (let len = models.length, i7 = 0; i7 < len; i7++) { + graph[models[i7]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; + } + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length) { + const current2 = queue.pop(); + const adjacents = Object.keys(conversions2[current2]); + for (let len = adjacents.length, i7 = 0; i7 < len; i7++) { + const adjacent = adjacents[i7]; + const node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current2].distance + 1; + node.parent = current2; + queue.unshift(adjacent); + } + } + } + return graph; + } + function link(from2, to2) { + return function(args) { + return to2(from2(args)); + }; + } + function wrapConversion(toModel, graph) { + const path6 = [graph[toModel].parent, toModel]; + let fn = conversions2[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path6.unshift(graph[cur].parent); + fn = link(conversions2[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path6; + return fn; + } + module.exports = function(fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + const models = Object.keys(graph); + for (let len = models.length, i7 = 0; i7 < len; i7++) { + const toModel = models[i7]; + const node = graph[toModel]; + if (node.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; + }; + } +}); + +// ../pi-mono/node_modules/color-convert/index.js +var require_color_convert = __commonJS({ + "../pi-mono/node_modules/color-convert/index.js"(exports, module) { + init_process_shim(); + var conversions2 = require_conversions(); + var route2 = require_route(); + var convert = {}; + var models = Object.keys(conversions2); + function wrapRaw(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + return fn(args); + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; + } + function wrapRounded(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + const result = fn(args); + if (typeof result === "object") { + for (let len = result.length, i7 = 0; i7 < len; i7++) { + result[i7] = Math.round(result[i7]); + } + } + return result; + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; + } + models.forEach((fromModel) => { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels }); + Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels }); + const routes = route2(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach((toModel) => { + const fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + module.exports = convert; + } +}); + +// ../pi-mono/node_modules/ansi-styles/index.js +var require_ansi_styles = __commonJS({ + "../pi-mono/node_modules/ansi-styles/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\x1B[${code + offset}m`; + }; + var wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\x1B[${38 + offset};5;${code}m`; + }; + var wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + var ansi2ansi = (n7) => n7; + var rgb2rgb = (r8, g3, b4) => [r8, g3, b4]; + var setLazyProperty = (object, property, get4) => { + Object.defineProperty(object, property, { + get: () => { + const value = get4(); + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + return value; + }, + enumerable: true, + configurable: true + }); + }; + var colorConvert2; + var makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert2 === void 0) { + colorConvert2 = require_color_convert(); + } + const offset = isBackground ? 10 : 0; + const styles2 = {}; + for (const [sourceSpace, suite] of Object.entries(colorConvert2)) { + const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace; + if (sourceSpace === targetSpace) { + styles2[name] = wrap(identity, offset); + } else if (typeof suite === "object") { + styles2[name] = wrap(suite[targetSpace], offset); + } + } + return styles2; + }; + function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + const styles2 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + styles2.color.gray = styles2.color.blackBright; + styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; + styles2.color.grey = styles2.color.blackBright; + styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; + for (const [groupName, group] of Object.entries(styles2)) { + for (const [styleName, style] of Object.entries(group)) { + styles2[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m` + }; + group[styleName] = styles2[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles2, groupName, { + value: group, + enumerable: false + }); + } + Object.defineProperty(styles2, "codes", { + value: codes, + enumerable: false + }); + styles2.color.close = "\x1B[39m"; + styles2.bgColor.close = "\x1B[49m"; + setLazyProperty(styles2.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false)); + setLazyProperty(styles2.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false)); + setLazyProperty(styles2.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false)); + setLazyProperty(styles2.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true)); + setLazyProperty(styles2.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true)); + setLazyProperty(styles2.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true)); + return styles2; + } + Object.defineProperty(module, "exports", { + enumerable: true, + get: assembleStyles + }); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/supports-color/browser.js +var require_browser = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/supports-color/browser.js"(exports, module) { + "use strict"; + init_process_shim(); + module.exports = { + stdout: false, + stderr: false + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/util.js +var require_util3 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/util.js"(exports, module) { + "use strict"; + init_process_shim(); + var stringReplaceAll = (string, substring, replacer) => { + let index2 = string.indexOf(substring); + if (index2 === -1) { + return string; + } + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ""; + do { + returnValue += string.substr(endIndex, index2 - endIndex) + substring + replacer; + endIndex = index2 + substringLength; + index2 = string.indexOf(substring, endIndex); + } while (index2 !== -1); + returnValue += string.substr(endIndex); + return returnValue; + }; + var stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index2) => { + let endIndex = 0; + let returnValue = ""; + do { + const gotCR = string[index2 - 1] === "\r"; + returnValue += string.substr(endIndex, (gotCR ? index2 - 1 : index2) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix; + endIndex = index2 + 1; + index2 = string.indexOf("\n", endIndex); + } while (index2 !== -1); + returnValue += string.substr(endIndex); + return returnValue; + }; + module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/templates.js +var require_templates = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/templates.js"(exports, module) { + "use strict"; + init_process_shim(); + var TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; + var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; + var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; + var ESCAPE_REGEX2 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + var ESCAPES = /* @__PURE__ */ new Map([ + ["n", "\n"], + ["r", "\r"], + ["t", " "], + ["b", "\b"], + ["f", "\f"], + ["v", "\v"], + ["0", "\0"], + ["\\", "\\"], + ["e", "\x1B"], + ["a", "\x07"] + ]); + function unescape3(c6) { + const u5 = c6[0] === "u"; + const bracket = c6[1] === "{"; + if (u5 && !bracket && c6.length === 5 || c6[0] === "x" && c6.length === 3) { + return String.fromCharCode(parseInt(c6.slice(1), 16)); + } + if (u5 && bracket) { + return String.fromCodePoint(parseInt(c6.slice(2, -1), 16)); + } + return ESCAPES.get(c6) || c6; + } + function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX2, (m4, escape4, character) => escape4 ? unescape3(escape4) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + return results; + } + function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + const results = []; + let matches; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + return results; + } + function buildStyle(chalk2, styles2) { + const enabled = {}; + for (const layer of styles2) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + let current2 = chalk2; + for (const [styleName, styles3] of Object.entries(enabled)) { + if (!Array.isArray(styles3)) { + continue; + } + if (!(styleName in current2)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + current2 = styles3.length > 0 ? current2[styleName](...styles3) : current2[styleName]; + } + return current2; + } + module.exports = (chalk2, temporary) => { + const styles2 = []; + const chunks = []; + let chunk = []; + temporary.replace(TEMPLATE_REGEX, (m4, escapeCharacter, inverse, style, close2, character) => { + if (escapeCharacter) { + chunk.push(unescape3(escapeCharacter)); + } else if (style) { + const string = chunk.join(""); + chunk = []; + chunks.push(styles2.length === 0 ? string : buildStyle(chalk2, styles2)(string)); + styles2.push({ inverse, styles: parseStyle(style) }); + } else if (close2) { + if (styles2.length === 0) { + throw new Error("Found extraneous } in Chalk template literal"); + } + chunks.push(buildStyle(chalk2, styles2)(chunk.join(""))); + chunk = []; + styles2.pop(); + } else { + chunk.push(character); + } + }); + chunks.push(chunk.join("")); + if (styles2.length > 0) { + const errMessage = `Chalk template literal is missing ${styles2.length} closing bracket${styles2.length === 1 ? "" : "s"} (\`}\`)`; + throw new Error(errMessage); + } + return chunks.join(""); + }; + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/index.js +var require_source2 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/sdk/node_modules/chalk/source/index.js"(exports, module) { + "use strict"; + init_process_shim(); + var ansiStyles2 = require_ansi_styles(); + var { stdout: stdoutColor, stderr: stderrColor } = require_browser(); + var { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex + } = require_util3(); + var { isArray: isArray7 } = Array; + var levelMapping = [ + "ansi", + "ansi", + "ansi256", + "ansi16m" + ]; + var styles2 = /* @__PURE__ */ Object.create(null); + var applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error("The `level` option should be an integer from 0 to 3"); + } + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === void 0 ? colorLevel : options.level; + }; + var ChalkClass = class { + constructor(options) { + return chalkFactory(options); + } + }; + var chalkFactory = (options) => { + const chalk3 = {}; + applyOptions(chalk3, options); + chalk3.template = (...arguments_) => chalkTag(chalk3.template, ...arguments_); + Object.setPrototypeOf(chalk3, Chalk.prototype); + Object.setPrototypeOf(chalk3.template, chalk3); + chalk3.template.constructor = () => { + throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead."); + }; + chalk3.template.Instance = ChalkClass; + return chalk3.template; + }; + function Chalk(options) { + return chalkFactory(options); + } + for (const [styleName, style] of Object.entries(ansiStyles2)) { + styles2[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, { value: builder }); + return builder; + } + }; + } + styles2.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, "visible", { value: builder }); + return builder; + } + }; + var usedModels = ["rgb", "hex", "keyword", "hsl", "hsv", "hwb", "ansi", "ansi256"]; + for (const model of usedModels) { + styles2[model] = { + get() { + const { level } = this; + return function(...arguments_) { + const styler = createStyler(ansiStyles2.color[levelMapping[level]][model](...arguments_), ansiStyles2.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; + } + for (const model of usedModels) { + const bgModel = "bg" + model[0].toUpperCase() + model.slice(1); + styles2[bgModel] = { + get() { + const { level } = this; + return function(...arguments_) { + const styler = createStyler(ansiStyles2.bgColor[levelMapping[level]][model](...arguments_), ansiStyles2.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; + } + var proto = Object.defineProperties(() => { + }, { + ...styles2, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } + }); + var createStyler = (open2, close2, parent) => { + let openAll; + let closeAll; + if (parent === void 0) { + openAll = open2; + closeAll = close2; + } else { + openAll = parent.openAll + open2; + closeAll = close2 + parent.closeAll; + } + return { + open: open2, + close: close2, + openAll, + closeAll, + parent + }; + }; + var createBuilder = (self2, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray7(arguments_[0]) && isArray7(arguments_[0].raw)) { + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + return applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" ")); + }; + Object.setPrototypeOf(builder, proto); + builder._generator = self2; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + return builder; + }; + var applyStyle = (self2, string) => { + if (self2.level <= 0 || !string) { + return self2._isEmpty ? "" : string; + } + let styler = self2._styler; + if (styler === void 0) { + return string; + } + const { openAll, closeAll } = styler; + if (string.indexOf("\x1B") !== -1) { + while (styler !== void 0) { + string = stringReplaceAll(string, styler.close, styler.open); + styler = styler.parent; + } + } + const lfIndex = string.indexOf("\n"); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + return openAll + string + closeAll; + }; + var template; + var chalkTag = (chalk3, ...strings) => { + const [firstString] = strings; + if (!isArray7(firstString) || !isArray7(firstString.raw)) { + return strings.join(" "); + } + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + for (let i7 = 1; i7 < firstString.length; i7++) { + parts.push( + String(arguments_[i7 - 1]).replace(/[{}\\]/g, "\\$&"), + String(firstString.raw[i7]) + ); + } + if (template === void 0) { + template = require_templates(); + } + return template(chalk3, parts.join("")); + }; + Object.defineProperties(Chalk.prototype, styles2); + var chalk2 = Chalk(); + chalk2.supportsColor = stdoutColor; + chalk2.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 }); + chalk2.stderr.supportsColor = stderrColor; + module.exports = chalk2; + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/generateRandomBase64.js +var require_generateRandomBase64 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/generateRandomBase64.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.generateRandomBase64 = generateRandomBase642; + function generateRandomBase642(bytesOfRandomness = 18) { + const randomBytes = new Uint8Array(bytesOfRandomness); + globalThis.crypto.getRandomValues(randomBytes); + return btoa(String.fromCharCode(...randomBytes)); + } + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/readFileAsBase64.js +var require_readFileAsBase64 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/readFileAsBase64.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.readFileAsBase64 = readFileAsBase642; + async function readFileAsBase642(_path) { + return { success: false }; + } + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/terminalSize.js +var require_terminalSize = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/terminalSize.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.terminalSize = terminalSize2; + function terminalSize2() { + return { columns: 80, rows: 24 }; + } + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/WebSocket.js +var require_WebSocket = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser/WebSocket.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocket = void 0; + exports.WebSocket = globalThis.WebSocket; + } +}); + +// ../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser.js +var require_browser2 = __commonJS({ + "../pi-mono/node_modules/@lmstudio/lms-isomorphic/dist/cjs/browser.js"(exports) { + "use strict"; + init_process_shim(); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.WebSocket = exports.terminalSize = exports.readFileAsBase64 = exports.generateRandomBase64 = void 0; + var generateRandomBase64_js_1 = require_generateRandomBase64(); + Object.defineProperty(exports, "generateRandomBase64", { enumerable: true, get: function() { + return generateRandomBase64_js_1.generateRandomBase64; + } }); + var readFileAsBase64_js_1 = require_readFileAsBase64(); + Object.defineProperty(exports, "readFileAsBase64", { enumerable: true, get: function() { + return readFileAsBase64_js_1.readFileAsBase64; + } }); + var terminalSize_js_1 = require_terminalSize(); + Object.defineProperty(exports, "terminalSize", { enumerable: true, get: function() { + return terminalSize_js_1.terminalSize; + } }); + var WebSocket_js_1 = require_WebSocket(); + Object.defineProperty(exports, "WebSocket", { enumerable: true, get: function() { + return WebSocket_js_1.WebSocket; + } }); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/Options.js +var ignoreOverride, defaultOptions, getDefaultOptions; +var init_Options = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/Options.js"() { + init_process_shim(); + ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + defaultOptions = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" + }; + getDefaultOptions = (options) => typeof options === "string" ? { + ...defaultOptions, + name: options + } : { + ...defaultOptions, + ...options + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/Refs.js +var getRefs; +var init_Refs = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/Refs.js"() { + init_process_shim(); + init_Options(); + getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + def._def, + { + def: def._def, + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: void 0 + } + ])) + }; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/errorMessages.js +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; + } +} +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} +var init_errorMessages = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/errorMessages.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js +var getRelativePath; +var init_getRelativePath = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js"() { + init_process_shim(); + getRelativePath = (pathA, pathB) => { + let i7 = 0; + for (; i7 < pathA.length && i7 < pathB.length; i7++) { + if (pathA[i7] !== pathB[i7]) + break; + } + return [(pathA.length - i7).toString(), ...pathB.slice(i7)].join("/"); + }; + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/util.js +var util2, objectUtil2, ZodParsedType2, getParsedType2; +var init_util2 = __esm({ + "../pi-mono/node_modules/zod/v3/helpers/util.js"() { + init_process_shim(); + (function(util3) { + util3.assertEqual = (_3) => { + }; + function assertIs(_arg) { + } + util3.assertIs = assertIs; + function assertNever3(_x2) { + throw new Error(); + } + util3.assertNever = assertNever3; + util3.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util3.getValidEnumValues = (obj) => { + const validKeys = util3.objectKeys(obj).filter((k2) => typeof obj[obj[k2]] !== "number"); + const filtered = {}; + for (const k2 of validKeys) { + filtered[k2] = obj[k2]; + } + return util3.objectValues(filtered); + }; + util3.objectValues = (obj) => { + return util3.objectKeys(obj).map(function(e9) { + return obj[e9]; + }); + }; + util3.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys2 = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys2.push(key); + } + } + return keys2; + }; + util3.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util3.isInteger = typeof Number.isInteger === "function" ? (val2) => Number.isInteger(val2) : (val2) => typeof val2 === "number" && Number.isFinite(val2) && Math.floor(val2) === val2; + function joinValues(array, separator = " | ") { + return array.map((val2) => typeof val2 === "string" ? `'${val2}'` : val2).join(separator); + } + util3.joinValues = joinValues; + util3.jsonStringifyReplacer = (_3, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; + })(util2 || (util2 = {})); + (function(objectUtil3) { + objectUtil3.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; + })(objectUtil2 || (objectUtil2 = {})); + ZodParsedType2 = util2.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" + ]); + getParsedType2 = (data) => { + const t6 = typeof data; + switch (t6) { + case "undefined": + return ZodParsedType2.undefined; + case "string": + return ZodParsedType2.string; + case "number": + return Number.isNaN(data) ? ZodParsedType2.nan : ZodParsedType2.number; + case "boolean": + return ZodParsedType2.boolean; + case "function": + return ZodParsedType2.function; + case "bigint": + return ZodParsedType2.bigint; + case "symbol": + return ZodParsedType2.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType2.array; + } + if (data === null) { + return ZodParsedType2.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType2.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType2.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType2.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType2.date; + } + return ZodParsedType2.object; + default: + return ZodParsedType2.unknown; + } + }; + } +}); + +// ../pi-mono/node_modules/zod/v3/ZodError.js +var ZodIssueCode2, ZodError2; +var init_ZodError2 = __esm({ + "../pi-mono/node_modules/zod/v3/ZodError.js"() { + init_process_shim(); + init_util2(); + ZodIssueCode2 = util2.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" + ]); + ZodError2 = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub2) => { + this.issues = [...this.issues, sub2]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i7 = 0; + while (i7 < issue.path.length) { + const el = issue.path[i7]; + const terminal = i7 === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i7++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util2.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = /* @__PURE__ */ Object.create(null); + const formErrors = []; + for (const sub2 of this.issues) { + if (sub2.path.length > 0) { + const firstEl = sub2.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub2)); + } else { + formErrors.push(mapper(sub2)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } + }; + ZodError2.create = (issues) => { + const error = new ZodError2(issues); + return error; + }; + } +}); + +// ../pi-mono/node_modules/zod/v3/locales/en.js +var errorMap2, en_default2; +var init_en2 = __esm({ + "../pi-mono/node_modules/zod/v3/locales/en.js"() { + init_process_shim(); + init_ZodError2(); + init_util2(); + errorMap2 = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode2.invalid_type: + if (issue.received === ZodParsedType2.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode2.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util2.jsonStringifyReplacer)}`; + break; + case ZodIssueCode2.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util2.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode2.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode2.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util2.joinValues(issue.options)}`; + break; + case ZodIssueCode2.invalid_enum_value: + message = `Invalid enum value. Expected ${util2.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode2.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode2.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode2.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode2.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util2.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode2.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode2.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode2.custom: + message = `Invalid input`; + break; + case ZodIssueCode2.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode2.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode2.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util2.assertNever(issue); + } + return { message }; + }; + en_default2 = errorMap2; + } +}); + +// ../pi-mono/node_modules/zod/v3/errors.js +function getErrorMap2() { + return overrideErrorMap2; +} +var overrideErrorMap2; +var init_errors4 = __esm({ + "../pi-mono/node_modules/zod/v3/errors.js"() { + init_process_shim(); + init_en2(); + overrideErrorMap2 = en_default2; + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/parseUtil.js +function addIssueToContext2(ctx, issueData) { + const overrideMap = getErrorMap2(); + const issue = makeIssue2({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default2 ? void 0 : en_default2 + // then global default map + ].filter((x2) => !!x2) + }); + ctx.common.issues.push(issue); +} +var makeIssue2, ParseStatus2, INVALID2, DIRTY2, OK2, isAborted2, isDirty2, isValid2, isAsync2; +var init_parseUtil2 = __esm({ + "../pi-mono/node_modules/zod/v3/helpers/parseUtil.js"() { + init_process_shim(); + init_errors4(); + init_en2(); + makeIssue2 = (params) => { + const { data, path: path6, errorMaps, issueData } = params; + const fullPath = [...path6, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m4) => !!m4).slice().reverse(); + for (const map3 of maps) { + errorMessage = map3(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; + }; + ParseStatus2 = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s6 of results) { + if (s6.status === "aborted") + return INVALID2; + if (s6.status === "dirty") + status.dirty(); + arrayValue.push(s6.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID2; + if (value.status === "aborted") + return INVALID2; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } + }; + INVALID2 = Object.freeze({ + status: "aborted" + }); + DIRTY2 = (value) => ({ status: "dirty", value }); + OK2 = (value) => ({ status: "valid", value }); + isAborted2 = (x2) => x2.status === "aborted"; + isDirty2 = (x2) => x2.status === "dirty"; + isValid2 = (x2) => x2.status === "valid"; + isAsync2 = (x2) => typeof Promise !== "undefined" && x2 instanceof Promise; + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/typeAliases.js +var init_typeAliases2 = __esm({ + "../pi-mono/node_modules/zod/v3/helpers/typeAliases.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod/v3/helpers/errorUtil.js +var errorUtil2; +var init_errorUtil2 = __esm({ + "../pi-mono/node_modules/zod/v3/helpers/errorUtil.js"() { + init_process_shim(); + (function(errorUtil3) { + errorUtil3.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil3.toString = (message) => typeof message === "string" ? message : message?.message; + })(errorUtil2 || (errorUtil2 = {})); + } +}); + +// ../pi-mono/node_modules/zod/v3/types.js +function processCreateParams2(params) { + if (!params) + return {}; + const { errorMap: errorMap3, invalid_type_error, required_error, description } = params; + if (errorMap3 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap3) + return { errorMap: errorMap3, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +function timeRegexSource2(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex2(args) { + return new RegExp(`^${timeRegexSource2(args)}$`); +} +function datetimeRegex2(args) { + let regex = `${dateRegexSource2}T${timeRegexSource2(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP2(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4Regex2.test(ip)) { + return true; + } + if ((version6 === "v6" || !version6) && ipv6Regex2.test(ip)) { + return true; + } + return false; +} +function isValidJWT2(jwt, alg) { + if (!jwtRegex2.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr2(ip, version6) { + if ((version6 === "v4" || !version6) && ipv4CidrRegex2.test(ip)) { + return true; + } + if ((version6 === "v6" || !version6) && ipv6CidrRegex2.test(ip)) { + return true; + } + return false; +} +function floatSafeRemainder2(val2, step) { + const valDecCount = (val2.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val2.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function deepPartialify2(schema) { + if (schema instanceof ZodObject2) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional2.create(deepPartialify2(fieldSchema)); + } + return new ZodObject2({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray2) { + return new ZodArray2({ + ...schema._def, + type: deepPartialify2(schema.element) + }); + } else if (schema instanceof ZodOptional2) { + return ZodOptional2.create(deepPartialify2(schema.unwrap())); + } else if (schema instanceof ZodNullable2) { + return ZodNullable2.create(deepPartialify2(schema.unwrap())); + } else if (schema instanceof ZodTuple2) { + return ZodTuple2.create(schema.items.map((item) => deepPartialify2(item))); + } else { + return schema; + } +} +function mergeValues2(a3, b4) { + const aType = getParsedType2(a3); + const bType = getParsedType2(b4); + if (a3 === b4) { + return { valid: true, data: a3 }; + } else if (aType === ZodParsedType2.object && bType === ZodParsedType2.object) { + const bKeys = util2.objectKeys(b4); + const sharedKeys = util2.objectKeys(a3).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a3, ...b4 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues2(a3[key], b4[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType2.array && bType === ZodParsedType2.array) { + if (a3.length !== b4.length) { + return { valid: false }; + } + const newArray = []; + for (let index2 = 0; index2 < a3.length; index2++) { + const itemA = a3[index2]; + const itemB = b4[index2]; + const sharedValue = mergeValues2(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType2.date && bType === ZodParsedType2.date && +a3 === +b4) { + return { valid: true, data: a3 }; + } else { + return { valid: false }; + } +} +function createZodEnum2(values2, params) { + return new ZodEnum2({ + values: values2, + typeName: ZodFirstPartyTypeKind2.ZodEnum, + ...processCreateParams2(params) + }); +} +var ParseInputLazyPath2, handleResult2, ZodType2, cuidRegex2, cuid2Regex2, ulidRegex2, uuidRegex2, nanoidRegex2, jwtRegex2, durationRegex2, emailRegex2, _emojiRegex2, emojiRegex2, ipv4Regex2, ipv4CidrRegex2, ipv6Regex2, ipv6CidrRegex2, base64Regex2, base64urlRegex2, dateRegexSource2, dateRegex2, ZodString2, ZodNumber2, ZodBigInt2, ZodBoolean2, ZodDate2, ZodSymbol2, ZodUndefined2, ZodNull2, ZodAny2, ZodUnknown2, ZodNever2, ZodVoid2, ZodArray2, ZodObject2, ZodUnion2, getDiscriminator2, ZodDiscriminatedUnion2, ZodIntersection2, ZodTuple2, ZodRecord2, ZodMap2, ZodSet2, ZodFunction2, ZodLazy2, ZodLiteral2, ZodEnum2, ZodNativeEnum2, ZodPromise2, ZodEffects2, ZodOptional2, ZodNullable2, ZodDefault2, ZodCatch2, ZodNaN2, BRAND2, ZodBranded2, ZodPipeline2, ZodReadonly2, late2, ZodFirstPartyTypeKind2, stringType2, numberType2, nanType2, bigIntType2, booleanType2, dateType2, symbolType2, undefinedType2, nullType2, anyType2, unknownType2, neverType2, voidType2, arrayType2, objectType2, strictObjectType2, unionType2, discriminatedUnionType2, intersectionType2, tupleType2, recordType2, mapType2, setType2, functionType2, lazyType2, literalType2, enumType2, nativeEnumType2, promiseType2, effectsType2, optionalType2, nullableType2, preprocessType2, pipelineType2; +var init_types3 = __esm({ + "../pi-mono/node_modules/zod/v3/types.js"() { + init_process_shim(); + init_ZodError2(); + init_errors4(); + init_errorUtil2(); + init_parseUtil2(); + init_util2(); + ParseInputLazyPath2 = class { + constructor(parent, value, path6, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path6; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } + }; + handleResult2 = (ctx, result) => { + if (isValid2(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError2(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } + }; + ZodType2 = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType2(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType2(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus2(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType2(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync2(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType2(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult2(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType2(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid2(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid2(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType2(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync2(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult2(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val2) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val2); + } else { + return message; + } + }; + return this._refinement((val2, ctx) => { + const result = check(val2); + const setError = () => ctx.addIssue({ + code: ZodIssueCode2.custom, + ...getIssueProperties(val2) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val2, ctx) => { + if (!check(val2)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val2, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects2({ + schema: this, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional2.create(this, this._def); + } + nullable() { + return ZodNullable2.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray2.create(this); + } + promise() { + return ZodPromise2.create(this, this._def); + } + or(option) { + return ZodUnion2.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection2.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects2({ + ...processCreateParams2(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault2({ + ...processCreateParams2(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind2.ZodDefault + }); + } + brand() { + return new ZodBranded2({ + typeName: ZodFirstPartyTypeKind2.ZodBranded, + type: this, + ...processCreateParams2(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch2({ + ...processCreateParams2(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind2.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline2.create(this, target); + } + readonly() { + return ZodReadonly2.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } + }; + cuidRegex2 = /^c[^\s-]{8,}$/i; + cuid2Regex2 = /^[0-9a-z]+$/; + ulidRegex2 = /^[0-9A-HJKMNP-TV-Z]{26}$/i; + uuidRegex2 = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; + nanoidRegex2 = /^[a-z0-9_-]{21}$/i; + jwtRegex2 = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; + durationRegex2 = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + emailRegex2 = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; + _emojiRegex2 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + ipv4Regex2 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; + ipv4CidrRegex2 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; + ipv6Regex2 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; + ipv6CidrRegex2 = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; + base64urlRegex2 = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; + dateRegexSource2 = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; + dateRegex2 = new RegExp(`^${dateRegexSource2}$`); + ZodString2 = class _ZodString extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.string, + received: ctx2.parsedType + }); + return INVALID2; + } + const status = new ParseStatus2(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "email", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex2) { + emojiRegex2 = new RegExp(_emojiRegex2, "u"); + } + if (!emojiRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "emoji", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "uuid", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "nanoid", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "cuid", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "cuid2", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "ulid", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "url", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "regex", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex2(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex2; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex2(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "duration", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP2(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "ip", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT2(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "jwt", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr2(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "cidr", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "base64", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex2.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + validation: "base64url", + code: ZodIssueCode2.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util2.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode2.invalid_string, + ...errorUtil2.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil2.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil2.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil2.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil2.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil2.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil2.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil2.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil2.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil2.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil2.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil2.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil2.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil2.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil2.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil2.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil2.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil2.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil2.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil2.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil2.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil2.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil2.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil2.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil2.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + ZodString2.create = (params) => { + return new ZodString2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams2(params) + }); + }; + ZodNumber2 = class _ZodNumber extends ZodType2 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.number, + received: ctx2.parsedType + }); + return INVALID2; + } + let ctx = void 0; + const status = new ParseStatus2(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util2.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder2(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util2.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil2.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil2.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil2.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil2.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil2.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil2.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil2.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil2.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil2.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil2.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil2.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil2.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil2.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil2.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util2.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } + }; + ZodNumber2.create = (params) => { + return new ZodNumber2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams2(params) + }); + }; + ZodBigInt2 = class _ZodBigInt extends ZodType2 { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus2(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util2.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.bigint, + received: ctx.parsedType + }); + return INVALID2; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil2.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil2.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil2.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil2.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil2.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil2.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil2.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil2.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil2.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil2.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + }; + ZodBigInt2.create = (params) => { + return new ZodBigInt2({ + checks: [], + typeName: ZodFirstPartyTypeKind2.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams2(params) + }); + }; + ZodBoolean2 = class extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.boolean, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); + } + }; + ZodBoolean2.create = (params) => { + return new ZodBoolean2({ + typeName: ZodFirstPartyTypeKind2.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams2(params) + }); + }; + ZodDate2 = class _ZodDate extends ZodType2 { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.date, + received: ctx2.parsedType + }); + return INVALID2; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode2.invalid_date + }); + return INVALID2; + } + const status = new ParseStatus2(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util2.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil2.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil2.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } + }; + ZodDate2.create = (params) => { + return new ZodDate2({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind2.ZodDate, + ...processCreateParams2(params) + }); + }; + ZodSymbol2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.symbol, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); + } + }; + ZodSymbol2.create = (params) => { + return new ZodSymbol2({ + typeName: ZodFirstPartyTypeKind2.ZodSymbol, + ...processCreateParams2(params) + }); + }; + ZodUndefined2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.undefined, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); + } + }; + ZodUndefined2.create = (params) => { + return new ZodUndefined2({ + typeName: ZodFirstPartyTypeKind2.ZodUndefined, + ...processCreateParams2(params) + }); + }; + ZodNull2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.null, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); + } + }; + ZodNull2.create = (params) => { + return new ZodNull2({ + typeName: ZodFirstPartyTypeKind2.ZodNull, + ...processCreateParams2(params) + }); + }; + ZodAny2 = class extends ZodType2 { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK2(input.data); + } + }; + ZodAny2.create = (params) => { + return new ZodAny2({ + typeName: ZodFirstPartyTypeKind2.ZodAny, + ...processCreateParams2(params) + }); + }; + ZodUnknown2 = class extends ZodType2 { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK2(input.data); + } + }; + ZodUnknown2.create = (params) => { + return new ZodUnknown2({ + typeName: ZodFirstPartyTypeKind2.ZodUnknown, + ...processCreateParams2(params) + }); + }; + ZodNever2 = class extends ZodType2 { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.never, + received: ctx.parsedType + }); + return INVALID2; + } + }; + ZodNever2.create = (params) => { + return new ZodNever2({ + typeName: ZodFirstPartyTypeKind2.ZodNever, + ...processCreateParams2(params) + }); + }; + ZodVoid2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.void, + received: ctx.parsedType + }); + return INVALID2; + } + return OK2(input.data); + } + }; + ZodVoid2.create = (params) => { + return new ZodVoid2({ + typeName: ZodFirstPartyTypeKind2.ZodVoid, + ...processCreateParams2(params) + }); + }; + ZodArray2 = class _ZodArray extends ZodType2 { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType2.array) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.array, + received: ctx.parsedType + }); + return INVALID2; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext2(ctx, { + code: tooBig ? ZodIssueCode2.too_big : ZodIssueCode2.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i7) => { + return def.type._parseAsync(new ParseInputLazyPath2(ctx, item, ctx.path, i7)); + })).then((result2) => { + return ParseStatus2.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i7) => { + return def.type._parseSync(new ParseInputLazyPath2(ctx, item, ctx.path, i7)); + }); + return ParseStatus2.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil2.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil2.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil2.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodArray2.create = (schema, params) => { + return new ZodArray2({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind2.ZodArray, + ...processCreateParams2(params) + }); + }; + ZodObject2 = class _ZodObject extends ZodType2 { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys2 = util2.objectKeys(shape); + this._cached = { shape, keys: keys2 }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext2(ctx2, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.object, + received: ctx2.parsedType + }); + return INVALID2; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever2 && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath2(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever2) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath2(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus2.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus2.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil2.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil2.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind2.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index2) { + return new _ZodObject({ + ...this._def, + catchall: index2 + }); + } + pick(mask) { + const shape = {}; + for (const key of util2.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util2.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify2(this); + } + partial(mask) { + const newShape = {}; + for (const key of util2.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util2.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional2) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum2(util2.objectKeys(this.shape)); + } + }; + ZodObject2.create = (shape, params) => { + return new ZodObject2({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams2(params) + }); + }; + ZodObject2.strictCreate = (shape, params) => { + return new ZodObject2({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams2(params) + }); + }; + ZodObject2.lazycreate = (shape, params) => { + return new ZodObject2({ + shape, + unknownKeys: "strip", + catchall: ZodNever2.create(), + typeName: ZodFirstPartyTypeKind2.ZodObject, + ...processCreateParams2(params) + }); + }; + ZodUnion2 = class extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError2(result.ctx.common.issues)); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_union, + unionErrors + }); + return INVALID2; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError2(issues2)); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_union, + unionErrors + }); + return INVALID2; + } + } + get options() { + return this._def.options; + } + }; + ZodUnion2.create = (types2, params) => { + return new ZodUnion2({ + options: types2, + typeName: ZodFirstPartyTypeKind2.ZodUnion, + ...processCreateParams2(params) + }); + }; + getDiscriminator2 = (type) => { + if (type instanceof ZodLazy2) { + return getDiscriminator2(type.schema); + } else if (type instanceof ZodEffects2) { + return getDiscriminator2(type.innerType()); + } else if (type instanceof ZodLiteral2) { + return [type.value]; + } else if (type instanceof ZodEnum2) { + return type.options; + } else if (type instanceof ZodNativeEnum2) { + return util2.objectValues(type.enum); + } else if (type instanceof ZodDefault2) { + return getDiscriminator2(type._def.innerType); + } else if (type instanceof ZodUndefined2) { + return [void 0]; + } else if (type instanceof ZodNull2) { + return [null]; + } else if (type instanceof ZodOptional2) { + return [void 0, ...getDiscriminator2(type.unwrap())]; + } else if (type instanceof ZodNullable2) { + return [null, ...getDiscriminator2(type.unwrap())]; + } else if (type instanceof ZodBranded2) { + return getDiscriminator2(type.unwrap()); + } else if (type instanceof ZodReadonly2) { + return getDiscriminator2(type.unwrap()); + } else if (type instanceof ZodCatch2) { + return getDiscriminator2(type._def.innerType); + } else { + return []; + } + }; + ZodDiscriminatedUnion2 = class _ZodDiscriminatedUnion extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.object) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.object, + received: ctx.parsedType + }); + return INVALID2; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID2; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator2(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind2.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams2(params) + }); + } + }; + ZodIntersection2 = class extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted2(parsedLeft) || isAborted2(parsedRight)) { + return INVALID2; + } + const merged = mergeValues2(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_intersection_types + }); + return INVALID2; + } + if (isDirty2(parsedLeft) || isDirty2(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } + }; + ZodIntersection2.create = (left, right, params) => { + return new ZodIntersection2({ + left, + right, + typeName: ZodFirstPartyTypeKind2.ZodIntersection, + ...processCreateParams2(params) + }); + }; + ZodTuple2 = class _ZodTuple extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.array) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.array, + received: ctx.parsedType + }); + return INVALID2; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID2; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath2(ctx, item, ctx.path, itemIndex)); + }).filter((x2) => !!x2); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus2.mergeArray(status, results); + }); + } else { + return ParseStatus2.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } + }; + ZodTuple2.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple2({ + items: schemas, + typeName: ZodFirstPartyTypeKind2.ZodTuple, + rest: null, + ...processCreateParams2(params) + }); + }; + ZodRecord2 = class _ZodRecord extends ZodType2 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.object) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.object, + received: ctx.parsedType + }); + return INVALID2; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath2(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus2.mergeObjectAsync(status, pairs); + } else { + return ParseStatus2.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType2) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind2.ZodRecord, + ...processCreateParams2(third) + }); + } + return new _ZodRecord({ + keyType: ZodString2.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind2.ZodRecord, + ...processCreateParams2(second) + }); + } + }; + ZodMap2 = class extends ZodType2 { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.map) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.map, + received: ctx.parsedType + }); + return INVALID2; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index2) => { + return { + key: keyType._parse(new ParseInputLazyPath2(ctx, key, ctx.path, [index2, "key"])), + value: valueType._parse(new ParseInputLazyPath2(ctx, value, ctx.path, [index2, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID2; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID2; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } + }; + ZodMap2.create = (keyType, valueType, params) => { + return new ZodMap2({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind2.ZodMap, + ...processCreateParams2(params) + }); + }; + ZodSet2 = class _ZodSet extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.set) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.set, + received: ctx.parsedType + }); + return INVALID2; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements3) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements3) { + if (element.status === "aborted") + return INVALID2; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements2 = [...ctx.data.values()].map((item, i7) => valueType._parse(new ParseInputLazyPath2(ctx, item, ctx.path, i7))); + if (ctx.common.async) { + return Promise.all(elements2).then((elements3) => finalizeSet(elements3)); + } else { + return finalizeSet(elements2); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil2.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil2.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } + }; + ZodSet2.create = (valueType, params) => { + return new ZodSet2({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind2.ZodSet, + ...processCreateParams2(params) + }); + }; + ZodFunction2 = class _ZodFunction extends ZodType2 { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.function) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.function, + received: ctx.parsedType + }); + return INVALID2; + } + function makeArgsIssue(args, error) { + return makeIssue2({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x2) => !!x2), + issueData: { + code: ZodIssueCode2.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue2({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap2(), en_default2].filter((x2) => !!x2), + issueData: { + code: ZodIssueCode2.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise2) { + const me = this; + return OK2(async function(...args) { + const error = new ZodError2([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e9) => { + error.addIssue(makeArgsIssue(args, e9)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e9) => { + error.addIssue(makeReturnsIssue(result, e9)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK2(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError2([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError2([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple2.create(items).rest(ZodUnknown2.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple2.create([]).rest(ZodUnknown2.create()), + returns: returns || ZodUnknown2.create(), + typeName: ZodFirstPartyTypeKind2.ZodFunction, + ...processCreateParams2(params) + }); + } + }; + ZodLazy2 = class extends ZodType2 { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } + }; + ZodLazy2.create = (getter, params) => { + return new ZodLazy2({ + getter, + typeName: ZodFirstPartyTypeKind2.ZodLazy, + ...processCreateParams2(params) + }); + }; + ZodLiteral2 = class extends ZodType2 { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_literal, + expected: this._def.value + }); + return INVALID2; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } + }; + ZodLiteral2.create = (value, params) => { + return new ZodLiteral2({ + value, + typeName: ZodFirstPartyTypeKind2.ZodLiteral, + ...processCreateParams2(params) + }); + }; + ZodEnum2 = class _ZodEnum extends ZodType2 { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext2(ctx, { + expected: util2.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode2.invalid_type + }); + return INVALID2; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext2(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_enum_value, + options: expectedValues + }); + return INVALID2; + } + return OK2(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val2 of this._def.values) { + enumValues[val2] = val2; + } + return enumValues; + } + extract(values2, newDef = this._def) { + return _ZodEnum.create(values2, { + ...this._def, + ...newDef + }); + } + exclude(values2, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values2.includes(opt)), { + ...this._def, + ...newDef + }); + } + }; + ZodEnum2.create = createZodEnum2; + ZodNativeEnum2 = class extends ZodType2 { + _parse(input) { + const nativeEnumValues = util2.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType2.string && ctx.parsedType !== ZodParsedType2.number) { + const expectedValues = util2.objectValues(nativeEnumValues); + addIssueToContext2(ctx, { + expected: util2.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode2.invalid_type + }); + return INVALID2; + } + if (!this._cache) { + this._cache = new Set(util2.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util2.objectValues(nativeEnumValues); + addIssueToContext2(ctx, { + received: ctx.data, + code: ZodIssueCode2.invalid_enum_value, + options: expectedValues + }); + return INVALID2; + } + return OK2(input.data); + } + get enum() { + return this._def.values; + } + }; + ZodNativeEnum2.create = (values2, params) => { + return new ZodNativeEnum2({ + values: values2, + typeName: ZodFirstPartyTypeKind2.ZodNativeEnum, + ...processCreateParams2(params) + }); + }; + ZodPromise2 = class extends ZodType2 { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType2.promise && ctx.common.async === false) { + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.promise, + received: ctx.parsedType + }); + return INVALID2; + } + const promisified = ctx.parsedType === ZodParsedType2.promise ? ctx.data : Promise.resolve(ctx.data); + return OK2(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } + }; + ZodPromise2.create = (schema, params) => { + return new ZodPromise2({ + type: schema, + typeName: ZodFirstPartyTypeKind2.ZodPromise, + ...processCreateParams2(params) + }); + }; + ZodEffects2 = class extends ZodType2 { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind2.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext2(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID2; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID2; + if (result.status === "dirty") + return DIRTY2(result.value); + if (status.value === "dirty") + return DIRTY2(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID2; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID2; + if (result.status === "dirty") + return DIRTY2(result.value); + if (status.value === "dirty") + return DIRTY2(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner2 = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner2.status === "aborted") + return INVALID2; + if (inner2.status === "dirty") + status.dirty(); + executeRefinement(inner2.value); + return { status: status.value, value: inner2.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner2) => { + if (inner2.status === "aborted") + return INVALID2; + if (inner2.status === "dirty") + status.dirty(); + return executeRefinement(inner2.value).then(() => { + return { status: status.value, value: inner2.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid2(base)) + return INVALID2; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid2(base)) + return INVALID2; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util2.assertNever(effect); + } + }; + ZodEffects2.create = (schema, effect, params) => { + return new ZodEffects2({ + schema, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + effect, + ...processCreateParams2(params) + }); + }; + ZodEffects2.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects2({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind2.ZodEffects, + ...processCreateParams2(params) + }); + }; + ZodOptional2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType2.undefined) { + return OK2(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + ZodOptional2.create = (type, params) => { + return new ZodOptional2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodOptional, + ...processCreateParams2(params) + }); + }; + ZodNullable2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType2.null) { + return OK2(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } + }; + ZodNullable2.create = (type, params) => { + return new ZodNullable2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodNullable, + ...processCreateParams2(params) + }); + }; + ZodDefault2 = class extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType2.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } + }; + ZodDefault2.create = (type, params) => { + return new ZodDefault2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams2(params) + }); + }; + ZodCatch2 = class extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync2(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError2(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError2(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } + }; + ZodCatch2.create = (type, params) => { + return new ZodCatch2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams2(params) + }); + }; + ZodNaN2 = class extends ZodType2 { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType2.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext2(ctx, { + code: ZodIssueCode2.invalid_type, + expected: ZodParsedType2.nan, + received: ctx.parsedType + }); + return INVALID2; + } + return { status: "valid", value: input.data }; + } + }; + ZodNaN2.create = (params) => { + return new ZodNaN2({ + typeName: ZodFirstPartyTypeKind2.ZodNaN, + ...processCreateParams2(params) + }); + }; + BRAND2 = Symbol("zod_brand"); + ZodBranded2 = class extends ZodType2 { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } + }; + ZodPipeline2 = class _ZodPipeline extends ZodType2 { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID2; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY2(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID2; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a3, b4) { + return new _ZodPipeline({ + in: a3, + out: b4, + typeName: ZodFirstPartyTypeKind2.ZodPipeline + }); + } + }; + ZodReadonly2 = class extends ZodType2 { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze2 = (data) => { + if (isValid2(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync2(result) ? result.then((data) => freeze2(data)) : freeze2(result); + } + unwrap() { + return this._def.innerType; + } + }; + ZodReadonly2.create = (type, params) => { + return new ZodReadonly2({ + innerType: type, + typeName: ZodFirstPartyTypeKind2.ZodReadonly, + ...processCreateParams2(params) + }); + }; + late2 = { + object: ZodObject2.lazycreate + }; + (function(ZodFirstPartyTypeKind3) { + ZodFirstPartyTypeKind3["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly"; + })(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {})); + stringType2 = ZodString2.create; + numberType2 = ZodNumber2.create; + nanType2 = ZodNaN2.create; + bigIntType2 = ZodBigInt2.create; + booleanType2 = ZodBoolean2.create; + dateType2 = ZodDate2.create; + symbolType2 = ZodSymbol2.create; + undefinedType2 = ZodUndefined2.create; + nullType2 = ZodNull2.create; + anyType2 = ZodAny2.create; + unknownType2 = ZodUnknown2.create; + neverType2 = ZodNever2.create; + voidType2 = ZodVoid2.create; + arrayType2 = ZodArray2.create; + objectType2 = ZodObject2.create; + strictObjectType2 = ZodObject2.strictCreate; + unionType2 = ZodUnion2.create; + discriminatedUnionType2 = ZodDiscriminatedUnion2.create; + intersectionType2 = ZodIntersection2.create; + tupleType2 = ZodTuple2.create; + recordType2 = ZodRecord2.create; + mapType2 = ZodMap2.create; + setType2 = ZodSet2.create; + functionType2 = ZodFunction2.create; + lazyType2 = ZodLazy2.create; + literalType2 = ZodLiteral2.create; + enumType2 = ZodEnum2.create; + nativeEnumType2 = ZodNativeEnum2.create; + promiseType2 = ZodPromise2.create; + effectsType2 = ZodEffects2.create; + optionalType2 = ZodOptional2.create; + nullableType2 = ZodNullable2.create; + preprocessType2 = ZodEffects2.createWithPreprocess; + pipelineType2 = ZodPipeline2.create; + } +}); + +// ../pi-mono/node_modules/zod/v3/external.js +var init_external2 = __esm({ + "../pi-mono/node_modules/zod/v3/external.js"() { + init_process_shim(); + init_errors4(); + init_parseUtil2(); + init_typeAliases2(); + init_util2(); + init_types3(); + init_ZodError2(); + } +}); + +// ../pi-mono/node_modules/zod/v3/index.js +var init_v3 = __esm({ + "../pi-mono/node_modules/zod/v3/index.js"() { + init_process_shim(); + init_external2(); + init_external2(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/any.js +function parseAnyDef(refs) { + if (refs.target !== "openAi") { + return {}; + } + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { + $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") + }; +} +var init_any3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/any.js"() { + init_process_shim(); + init_getRelativePath(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/array.js +function parseArrayDef(def, refs) { + const res = { + type: "array" + }; + if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind2.ZodAny) { + res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + } + if (def.minLength) { + setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +var init_array3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/array.js"() { + init_process_shim(); + init_v3(); + init_errorMessages(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} +var init_bigint3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js"() { + init_process_shim(); + init_errorMessages(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js +function parseBooleanDef() { + return { + type: "boolean" + }; +} +var init_boolean3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} +var init_branded = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js"() { + init_process_shim(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js +var parseCatchDef; +var init_catch = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js"() { + init_process_shim(); + init_parseDef(); + parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/date.js +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i7) => parseDateDef(def, refs, item)) + }; + } + switch (strategy) { + case "string": + case "format:date-time": + return { + type: "string", + format: "date-time" + }; + case "format:date": + return { + type: "string", + format: "date" + }; + case "integer": + return integerDateParser(def, refs); + } +} +var integerDateParser; +var init_date3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/date.js"() { + init_process_shim(); + init_errorMessages(); + integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors( + res, + "minimum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + case "max": + setResponseValueAndErrors( + res, + "maximum", + check.value, + // This is in milliseconds + check.message, + refs + ); + break; + } + } + return res; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/default.js +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue() + }; +} +var init_default = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/default.js"() { + init_process_shim(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); +} +var init_effects = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js"() { + init_process_shim(); + init_parseDef(); + init_any3(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) + }; +} +var init_enum3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js +function parseIntersectionDef(def, refs) { + const allOf = [ + parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }), + parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "1"] + }) + ].filter((x2) => !!x2); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) { + unevaluatedProperties = void 0; + } + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } else { + unevaluatedProperties = void 0; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; +} +var isJsonSchema7AllOfType; +var init_intersection = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js"() { + init_process_shim(); + init_parseDef(); + isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") + return false; + return "allOf" in type; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { + return { + type: Array.isArray(def.value) ? "array" : "object" + }; + } + if (refs.target === "openApi3") { + return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value] + }; + } + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value + }; +} +var init_literal3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/string.js +function parseStringDef(def, refs) { + const res = { + type: "string" + }; + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": { + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + } + case "ip": { + if (check.version !== "v6") { + addFormat(res, "ipv4", check.message, refs); + } + if (check.version !== "v4") { + addFormat(res, "ipv6", check.message, refs); + } + break; + } + case "base64url": + addPattern(res, zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check.message, refs); + break; + case "cidr": { + if (check.version !== "v6") { + addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + } + if (check.version !== "v4") { + addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + } + break; + } + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": { + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + } + case "base64": { + switch (refs.base64Strategy) { + case "format:binary": { + addFormat(res, "binary", check.message, refs); + break; + } + case "contentEncoding:base64": { + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + } + case "pattern:zod": { + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case "nanoid": { + addPattern(res, zodPatterns.nanoid, check.message, refs); + } + case "toLowerCase": + case "toUpperCase": + case "trim": + break; + default: + /* @__PURE__ */ ((_3) => { + })(check); + } + } + } + return res; +} +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; +} +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i7 = 0; i7 < source.length; i7++) { + if (!ALPHA_NUMERIC.has(source[i7])) { + result += "\\"; + } + result += source[i7]; + } + return result; +} +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x2) => x2.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format } + } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else { + setResponseValueAndErrors(schema, "format", value, message, refs); + } +} +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x2) => x2.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern } + } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else { + setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); + } +} +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) { + return regex.source; + } + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + // `.` matches newlines + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i7 = 0; i7 < source.length; i7++) { + if (isEscaped) { + pattern += source[i7]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i7].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i7]; + pattern += `${source[i7 - 2]}-${source[i7]}`.toUpperCase(); + inCharRange = false; + } else if (source[i7 + 1] === "-" && source[i7 + 2]?.match(/[a-z]/)) { + pattern += source[i7]; + inCharRange = true; + } else { + pattern += `${source[i7]}${source[i7].toUpperCase()}`; + } + continue; + } + } else if (source[i7].match(/[a-z]/)) { + pattern += `[${source[i7]}${source[i7].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i7] === "^") { + pattern += `(^|(?<=[\r +]))`; + continue; + } else if (source[i7] === "$") { + pattern += `($|(?=[\r +]))`; + continue; + } + } + if (flags.s && source[i7] === ".") { + pattern += inCharGroup ? `${source[i7]}\r +` : `[${source[i7]}\r +]`; + continue; + } + pattern += source[i7]; + if (source[i7] === "\\") { + isEscaped = true; + } else if (inCharGroup && source[i7] === "]") { + inCharGroup = false; + } else if (!inCharGroup && source[i7] === "[") { + inCharGroup = true; + } + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +} +var emojiRegex3, zodPatterns, ALPHA_NUMERIC; +var init_string3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/string.js"() { + init_process_shim(); + init_errorMessages(); + emojiRegex3 = void 0; + zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (emojiRegex3 === void 0) { + emojiRegex3 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + } + return emojiRegex3; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ + }; + ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/record.js +function parseRecordDef(def, refs) { + if (refs.target === "openAi") { + console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + } + if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) { + return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", key] + }) ?? parseAnyDef(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + } + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") { + return schema; + } + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) { + const { type, ...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values + } + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) { + const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; +} +var init_record3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/record.js"() { + init_process_shim(); + init_v3(); + init_parseDef(); + init_string3(); + init_branded(); + init_any3(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/map.js +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") { + return parseRecordDef(def, refs); + } + const keys2 = parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "0"] + }) || parseAnyDef(refs); + const values2 = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items", "items", "1"] + }) || parseAnyDef(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys2, values2], + minItems: 2, + maxItems: 2 + } + }; +} +var init_map = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/map.js"() { + init_process_shim(); + init_parseDef(); + init_record3(); + init_any3(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values2) => typeof values2))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; +} +var init_nativeEnum = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/never.js +function parseNeverDef(refs) { + return refs.target === "openAi" ? void 0 : { + not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) + }; +} +var init_never3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/never.js"() { + init_process_shim(); + init_any3(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/null.js +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { + type: "null" + }; +} +var init_null3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/null.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/union.js +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") + return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x2) => x2._def.typeName in primitiveMappings && (!x2._def.checks || !x2._def.checks.length))) { + const types2 = options.reduce((types3, x2) => { + const type = primitiveMappings[x2._def.typeName]; + return type && !types3.includes(type) ? [...types3, type] : types3; + }, []); + return { + type: types2.length > 1 ? types2 : types2[0] + }; + } else if (options.every((x2) => x2._def.typeName === "ZodLiteral" && !x2.description)) { + const types2 = options.reduce((acc, x2) => { + const type = typeof x2._def.value; + switch (type) { + case "string": + case "number": + case "boolean": + return [...acc, type]; + case "bigint": + return [...acc, "integer"]; + case "object": + if (x2._def.value === null) + return [...acc, "null"]; + case "symbol": + case "undefined": + case "function": + default: + return acc; + } + }, []); + if (types2.length === options.length) { + const uniqueTypes = types2.filter((x2, i7, a3) => a3.indexOf(x2) === i7); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x2) => { + return acc.includes(x2._def.value) ? acc : [...acc, x2._def.value]; + }, []) + }; + } + } else if (options.every((x2) => x2._def.typeName === "ZodEnum")) { + return { + type: "string", + enum: options.reduce((acc, x2) => [ + ...acc, + ...x2._def.values.filter((x3) => !acc.includes(x3)) + ], []) + }; + } + return asAnyOf(def, refs); +} +var primitiveMappings, asAnyOf; +var init_union4 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/union.js"() { + init_process_shim(); + init_parseDef(); + primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" + }; + asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x2, i7) => parseDef(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", `${i7}`] + })).filter((x2) => !!x2 && (!refs.strictUnions || typeof x2 === "object" && Object.keys(x2).length > 0)); + return anyOf.length ? { anyOf } : void 0; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js +function parseNullableDef(def, refs) { + if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") { + return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + } + return { + type: [ + primitiveMappings[def.innerType._def.typeName], + "null" + ] + }; + } + if (refs.target === "openApi3") { + const base2 = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }); + if (base2 && "$ref" in base2) + return { allOf: [base2], nullable: true }; + return base2 && { ...base2, nullable: true }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "0"] + }); + return base && { anyOf: [base, { type: "null" }] }; +} +var init_nullable = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js"() { + init_process_shim(); + init_parseDef(); + init_union4(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/number.js +function parseNumberDef(def, refs) { + const res = { + type: "number" + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") { + if (check.inclusive) { + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } else { + setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + } + } else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + } + return res; +} +var init_number3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/number.js"() { + init_process_shim(); + init_errorMessages(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/object.js +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) { + continue; + } + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") { + propDef = propDef._def.innerType; + } + if (!propDef.isNullable()) { + propDef = propDef.nullable(); + } + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [...refs.currentPath, "properties", propName], + propertyPath: [...refs.currentPath, "properties", propName] + }); + if (parsedDef === void 0) { + continue; + } + result.properties[propName] = parsedDef; + if (!propOptional) { + required.push(propName); + } + } + if (required.length) { + result.required = required; + } + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== void 0) { + result.additionalProperties = additionalProperties; + } + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") { + return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + } + switch (def.unknownKeys) { + case "passthrough": + return refs.allowedAdditionalProperties; + case "strict": + return refs.rejectedAdditionalProperties; + case "strip": + return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } catch { + return true; + } +} +var init_object3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/object.js"() { + init_process_shim(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js +var parseOptionalDef; +var init_optional3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js"() { + init_process_shim(); + init_parseDef(); + init_any3(); + parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) { + return parseDef(def.innerType._def, refs); + } + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, "anyOf", "1"] + }); + return innerSchema ? { + anyOf: [ + { + not: parseAnyDef(refs) + }, + innerSchema + ] + } : parseAnyDef(refs); + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js +var parsePipelineDef; +var init_pipeline = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js"() { + init_process_shim(); + init_parseDef(); + parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") { + return parseDef(def.in._def, refs); + } else if (refs.pipeStrategy === "output") { + return parseDef(def.out._def, refs); + } + const a3 = parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", "0"] + }); + const b4 = parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, "allOf", a3 ? "1" : "0"] + }); + return { + allOf: [a3, b4].filter((x2) => x2 !== void 0) + }; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} +var init_promise3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js"() { + init_process_shim(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/set.js +function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + const schema = { + type: "array", + uniqueItems: true, + items + }; + if (def.minSize) { + setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} +var init_set2 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/set.js"() { + init_process_shim(); + init_errorMessages(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js +function parseTupleDef(def, refs) { + if (def.rest) { + return { + type: "array", + minItems: def.items.length, + items: def.items.map((x2, i7) => parseDef(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i7}`] + })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + } else { + return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x2, i7) => parseDef(x2._def, { + ...refs, + currentPath: [...refs.currentPath, "items", `${i7}`] + })).reduce((acc, x2) => x2 === void 0 ? acc : [...acc, x2], []) + }; + } +} +var init_tuple3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js"() { + init_process_shim(); + init_parseDef(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js +function parseUndefinedDef(refs) { + return { + not: parseAnyDef(refs) + }; +} +var init_undefined3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js"() { + init_process_shim(); + init_any3(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js +function parseUnknownDef(refs) { + return parseAnyDef(refs); +} +var init_unknown3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js"() { + init_process_shim(); + init_any3(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js +var parseReadonlyDef; +var init_readonly3 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js"() { + init_process_shim(); + init_parseDef(); + parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/selectParser.js +var selectParser; +var init_selectParser = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/selectParser.js"() { + init_process_shim(); + init_v3(); + init_any3(); + init_array3(); + init_bigint3(); + init_boolean3(); + init_branded(); + init_catch(); + init_date3(); + init_default(); + init_effects(); + init_enum3(); + init_intersection(); + init_literal3(); + init_map(); + init_nativeEnum(); + init_never3(); + init_null3(); + init_nullable(); + init_number3(); + init_object3(); + init_optional3(); + init_pipeline(); + init_promise3(); + init_record3(); + init_set2(); + init_string3(); + init_tuple3(); + init_undefined3(); + init_union4(); + init_unknown3(); + init_readonly3(); + selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind2.ZodString: + return parseStringDef(def, refs); + case ZodFirstPartyTypeKind2.ZodNumber: + return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind2.ZodObject: + return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind2.ZodBigInt: + return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind2.ZodBoolean: + return parseBooleanDef(); + case ZodFirstPartyTypeKind2.ZodDate: + return parseDateDef(def, refs); + case ZodFirstPartyTypeKind2.ZodUndefined: + return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind2.ZodNull: + return parseNullDef(refs); + case ZodFirstPartyTypeKind2.ZodArray: + return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind2.ZodUnion: + case ZodFirstPartyTypeKind2.ZodDiscriminatedUnion: + return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind2.ZodIntersection: + return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind2.ZodTuple: + return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind2.ZodRecord: + return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind2.ZodLiteral: + return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind2.ZodEnum: + return parseEnumDef(def); + case ZodFirstPartyTypeKind2.ZodNativeEnum: + return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind2.ZodNullable: + return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind2.ZodOptional: + return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind2.ZodMap: + return parseMapDef(def, refs); + case ZodFirstPartyTypeKind2.ZodSet: + return parseSetDef(def, refs); + case ZodFirstPartyTypeKind2.ZodLazy: + return () => def.getter()._def; + case ZodFirstPartyTypeKind2.ZodPromise: + return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind2.ZodNaN: + case ZodFirstPartyTypeKind2.ZodNever: + return parseNeverDef(refs); + case ZodFirstPartyTypeKind2.ZodEffects: + return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind2.ZodAny: + return parseAnyDef(refs); + case ZodFirstPartyTypeKind2.ZodUnknown: + return parseUnknownDef(refs); + case ZodFirstPartyTypeKind2.ZodDefault: + return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind2.ZodBranded: + return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind2.ZodReadonly: + return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind2.ZodCatch: + return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind2.ZodPipeline: + return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind2.ZodFunction: + case ZodFirstPartyTypeKind2.ZodVoid: + case ZodFirstPartyTypeKind2.ZodSymbol: + return void 0; + default: + return /* @__PURE__ */ ((_3) => void 0)(typeName); + } + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parseDef.js +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== void 0) { + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) { + addMeta(def, refs, jsonSchema); + } + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +var get$ref, addMeta; +var init_parseDef = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parseDef.js"() { + init_process_shim(); + init_Options(); + init_selectParser(); + init_getRelativePath(); + init_any3(); + get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": + return { $ref: item.path.join("/") }; + case "relative": + return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": { + if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; + } + } + }; + addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/parseTypes.js +var init_parseTypes = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/parseTypes.js"() { + init_process_shim(); + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js +var zodToJsonSchema; +var init_zodToJsonSchema = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js"() { + init_process_shim(); + init_parseDef(); + init_Refs(); + init_any3(); + zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({ + ...acc, + [name2]: parseDef(schema2._def, { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name2] + }, true) ?? parseAnyDef(refs) + }), {}) : void 0; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main2 = parseDef(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name] + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) { + main2.title = title; + } + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) { + definitions = {}; + } + if (!definitions[refs.openAiAnyTypeName]) { + definitions[refs.openAiAnyTypeName] = { + // Skipping "object" as no properties can be defined and additionalProperties must be "false" + type: ["string", "number", "integer", "boolean", "array", "null"], + items: { + $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") + } + }; + } + } + const combined = name === void 0 ? definitions ? { + ...main2, + [refs.definitionPath]: definitions + } : main2 : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main2 + } + }; + if (refs.target === "jsonSchema7") { + combined.$schema = "http://json-schema.org/draft-07/schema#"; + } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") { + combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + } + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) { + console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + } + return combined; + }; + } +}); + +// ../pi-mono/node_modules/zod-to-json-schema/dist/esm/index.js +var init_esm2 = __esm({ + "../pi-mono/node_modules/zod-to-json-schema/dist/esm/index.js"() { + init_process_shim(); + init_Options(); + init_Refs(); + init_errorMessages(); + init_getRelativePath(); + init_parseDef(); + init_parseTypes(); + init_any3(); + init_array3(); + init_bigint3(); + init_boolean3(); + init_branded(); + init_catch(); + init_date3(); + init_default(); + init_effects(); + init_enum3(); + init_intersection(); + init_literal3(); + init_map(); + init_nativeEnum(); + init_never3(); + init_null3(); + init_nullable(); + init_number3(); + init_object3(); + init_optional3(); + init_pipeline(); + init_promise3(); + init_readonly3(); + init_record3(); + init_set2(); + init_string3(); + init_tuple3(); + init_undefined3(); + init_union4(); + init_unknown3(); + init_selectParser(); + init_zodToJsonSchema(); + init_zodToJsonSchema(); + } +}); + +// ../pi-mono/node_modules/@lmstudio/sdk/dist/index.mjs +function isSignalLike(value) { + return typeof value === "object" && value !== null && typeof value.get === "function" && typeof value.subscribe === "function"; +} +function makePromise() { + let resolve2; + let reject; + const promise = new Promise((_resolve2, _reject) => { + resolve2 = _resolve2; + reject = _reject; + }); + return { promise, resolve: resolve2, reject }; +} +function die(error, ...args) { + if (false) { + const e9 = errors[error]; + const msg = typeof e9 === "function" ? e9.apply(null, args) : e9; + throw new Error(`[Immer] ${msg}`); + } + throw new Error( + `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf` + ); +} +function isDraft(value) { + return !!value && !!value[DRAFT_STATE]; +} +function isDraftable(value) { + if (!value) + return false; + return isPlainObject$2(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap$1(value) || isSet$1(value); +} +function isPlainObject$2(value) { + if (!value || typeof value !== "object") + return false; + const proto = getPrototypeOf(value); + if (proto === null) { + return true; + } + const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor; + if (Ctor === Object) + return true; + return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString; +} +function each(obj, iter) { + if (getArchtype(obj) === 0) { + Reflect.ownKeys(obj).forEach((key) => { + iter(key, obj[key], obj); + }); + } else { + obj.forEach((entry, index2) => iter(index2, entry, obj)); + } +} +function getArchtype(thing) { + const state = thing[DRAFT_STATE]; + return state ? state.type_ : Array.isArray(thing) ? 1 : isMap$1(thing) ? 2 : isSet$1(thing) ? 3 : 0; +} +function has2(thing, prop) { + return getArchtype(thing) === 2 ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop); +} +function get(thing, prop) { + return getArchtype(thing) === 2 ? thing.get(prop) : thing[prop]; +} +function set(thing, propOrOldValue, value) { + const t6 = getArchtype(thing); + if (t6 === 2) + thing.set(propOrOldValue, value); + else if (t6 === 3) { + thing.add(value); + } else + thing[propOrOldValue] = value; +} +function is(x2, y4) { + if (x2 === y4) { + return x2 !== 0 || 1 / x2 === 1 / y4; + } else { + return x2 !== x2 && y4 !== y4; + } +} +function isMap$1(target) { + return target instanceof Map; +} +function isSet$1(target) { + return target instanceof Set; +} +function latest(state) { + return state.copy_ || state.base_; +} +function shallowCopy(base, strict) { + if (isMap$1(base)) { + return new Map(base); + } + if (isSet$1(base)) { + return new Set(base); + } + if (Array.isArray(base)) + return Array.prototype.slice.call(base); + const isPlain = isPlainObject$2(base); + if (strict === true || strict === "class_only" && !isPlain) { + const descriptors2 = Object.getOwnPropertyDescriptors(base); + delete descriptors2[DRAFT_STATE]; + let keys2 = Reflect.ownKeys(descriptors2); + for (let i7 = 0; i7 < keys2.length; i7++) { + const key = keys2[i7]; + const desc = descriptors2[key]; + if (desc.writable === false) { + desc.writable = true; + desc.configurable = true; + } + if (desc.get || desc.set) + descriptors2[key] = { + configurable: true, + writable: true, + // could live with !!desc.set as well here... + enumerable: desc.enumerable, + value: base[key] + }; + } + return Object.create(getPrototypeOf(base), descriptors2); + } else { + const proto = getPrototypeOf(base); + if (proto !== null && isPlain) { + return { ...base }; + } + const obj = Object.create(proto); + return Object.assign(obj, base); + } +} +function freeze(obj, deep = false) { + if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) + return obj; + if (getArchtype(obj) > 1) { + obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections; + } + Object.freeze(obj); + if (deep) + Object.values(obj).forEach((value) => freeze(value, true)); + return obj; +} +function dontMutateFrozenCollections() { + die(2); +} +function isFrozen(obj) { + return Object.isFrozen(obj); +} +function getPlugin(pluginKey) { + const plugin = plugins[pluginKey]; + if (!plugin) { + die(0, pluginKey); + } + return plugin; +} +function loadPlugin(pluginKey, implementation) { + if (!plugins[pluginKey]) + plugins[pluginKey] = implementation; +} +function getCurrentScope() { + return currentScope; +} +function createScope(parent_, immer_) { + return { + drafts_: [], + parent_, + immer_, + // Whenever the modified draft contains a draft from another scope, we + // need to prevent auto-freezing so the unowned draft can be finalized. + canAutoFreeze_: true, + unfinalizedDrafts_: 0 + }; +} +function usePatchesInScope(scope, patchListener) { + if (patchListener) { + getPlugin("Patches"); + scope.patches_ = []; + scope.inversePatches_ = []; + scope.patchListener_ = patchListener; + } +} +function revokeScope(scope) { + leaveScope(scope); + scope.drafts_.forEach(revokeDraft); + scope.drafts_ = null; +} +function leaveScope(scope) { + if (scope === currentScope) { + currentScope = scope.parent_; + } +} +function enterScope(immer2) { + return currentScope = createScope(currentScope, immer2); +} +function revokeDraft(draft) { + const state = draft[DRAFT_STATE]; + if (state.type_ === 0 || state.type_ === 1) + state.revoke_(); + else + state.revoked_ = true; +} +function processResult(result, scope) { + scope.unfinalizedDrafts_ = scope.drafts_.length; + const baseDraft = scope.drafts_[0]; + const isReplaced = result !== void 0 && result !== baseDraft; + if (isReplaced) { + if (baseDraft[DRAFT_STATE].modified_) { + revokeScope(scope); + die(4); + } + if (isDraftable(result)) { + result = finalize(scope, result); + if (!scope.parent_) + maybeFreeze(scope, result); + } + if (scope.patches_) { + getPlugin("Patches").generateReplacementPatches_( + baseDraft[DRAFT_STATE].base_, + result, + scope.patches_, + scope.inversePatches_ + ); + } + } else { + result = finalize(scope, baseDraft, []); + } + revokeScope(scope); + if (scope.patches_) { + scope.patchListener_(scope.patches_, scope.inversePatches_); + } + return result !== NOTHING ? result : void 0; +} +function finalize(rootScope, value, path6) { + if (isFrozen(value)) + return value; + const state = value[DRAFT_STATE]; + if (!state) { + each( + value, + (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path6) + ); + return value; + } + if (state.scope_ !== rootScope) + return value; + if (!state.modified_) { + maybeFreeze(rootScope, state.base_, true); + return state.base_; + } + if (!state.finalized_) { + state.finalized_ = true; + state.scope_.unfinalizedDrafts_--; + const result = state.copy_; + let resultEach = result; + let isSet2 = false; + if (state.type_ === 3) { + resultEach = new Set(result); + result.clear(); + isSet2 = true; + } + each( + resultEach, + (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path6, isSet2) + ); + maybeFreeze(rootScope, result, false); + if (path6 && rootScope.patches_) { + getPlugin("Patches").generatePatches_( + state, + path6, + rootScope.patches_, + rootScope.inversePatches_ + ); + } + } + return state.copy_; +} +function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) { + if (false) + die(5); + if (isDraft(childValue)) { + const path6 = rootPath && parentState && parentState.type_ !== 3 && // Set objects are atomic since they have no keys. + !has2(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0; + const res = finalize(rootScope, childValue, path6); + set(targetObject, prop, res); + if (isDraft(res)) { + rootScope.canAutoFreeze_ = false; + } else + return; + } else if (targetIsSet) { + targetObject.add(childValue); + } + if (isDraftable(childValue) && !isFrozen(childValue)) { + if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) { + return; + } + finalize(rootScope, childValue); + if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop)) + maybeFreeze(rootScope, childValue); + } +} +function maybeFreeze(scope, value, deep = false) { + if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) { + freeze(value, deep); + } +} +function createProxyProxy(base, parent) { + const isArray7 = Array.isArray(base); + const state = { + type_: isArray7 ? 1 : 0, + // Track which produce call this is associated with. + scope_: parent ? parent.scope_ : getCurrentScope(), + // True for both shallow and deep changes. + modified_: false, + // Used during finalization. + finalized_: false, + // Track which properties have been assigned (true) or deleted (false). + assigned_: {}, + // The parent draft state. + parent_: parent, + // The base state. + base_: base, + // The base proxy. + draft_: null, + // set below + // The base copy with any updated values. + copy_: null, + // Called by the `produce` function. + revoke_: null, + isManual_: false + }; + let target = state; + let traps = objectTraps; + if (isArray7) { + target = [state]; + traps = arrayTraps; + } + const { revoke, proxy } = Proxy.revocable(target, traps); + state.draft_ = proxy; + state.revoke_ = revoke; + return proxy; +} +function peek(draft, prop) { + const state = draft[DRAFT_STATE]; + const source = state ? latest(state) : draft; + return source[prop]; +} +function readPropFromProto(state, source, prop) { + const desc = getDescriptorFromProto(source, prop); + return desc ? `value` in desc ? desc.value : ( + // This is a very special case, if the prop is a getter defined by the + // prototype, we should invoke it with the draft as context! + desc.get?.call(state.draft_) + ) : void 0; +} +function getDescriptorFromProto(source, prop) { + if (!(prop in source)) + return void 0; + let proto = getPrototypeOf(source); + while (proto) { + const desc = Object.getOwnPropertyDescriptor(proto, prop); + if (desc) + return desc; + proto = getPrototypeOf(proto); + } + return void 0; +} +function markChanged(state) { + if (!state.modified_) { + state.modified_ = true; + if (state.parent_) { + markChanged(state.parent_); + } + } +} +function prepareCopy(state) { + if (!state.copy_) { + state.copy_ = shallowCopy( + state.base_, + state.scope_.immer_.useStrictShallowCopy_ + ); + } +} +function createProxy(value, parent) { + const draft = isMap$1(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet$1(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent); + const scope = parent ? parent.scope_ : getCurrentScope(); + scope.drafts_.push(draft); + return draft; +} +function current(value) { + if (!isDraft(value)) + die(10, value); + return currentImpl(value); +} +function currentImpl(value) { + if (!isDraftable(value) || isFrozen(value)) + return value; + const state = value[DRAFT_STATE]; + let copy2; + if (state) { + if (!state.modified_) + return state.base_; + state.finalized_ = true; + copy2 = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_); + } else { + copy2 = shallowCopy(value, true); + } + each(copy2, (key, childValue) => { + set(copy2, key, currentImpl(childValue)); + }); + if (state) { + state.finalized_ = false; + } + return copy2; +} +function enableMapSet() { + class DraftMap extends Map { + constructor(target, parent) { + super(); + this[DRAFT_STATE] = { + type_: 2, + parent_: parent, + scope_: parent ? parent.scope_ : getCurrentScope(), + modified_: false, + finalized_: false, + copy_: void 0, + assigned_: void 0, + base_: target, + draft_: this, + isManual_: false, + revoked_: false + }; + } + get size() { + return latest(this[DRAFT_STATE]).size; + } + has(key) { + return latest(this[DRAFT_STATE]).has(key); + } + set(key, value) { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + if (!latest(state).has(key) || latest(state).get(key) !== value) { + prepareMapCopy(state); + markChanged(state); + state.assigned_.set(key, true); + state.copy_.set(key, value); + state.assigned_.set(key, true); + } + return this; + } + delete(key) { + if (!this.has(key)) { + return false; + } + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + prepareMapCopy(state); + markChanged(state); + if (state.base_.has(key)) { + state.assigned_.set(key, false); + } else { + state.assigned_.delete(key); + } + state.copy_.delete(key); + return true; + } + clear() { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + if (latest(state).size) { + prepareMapCopy(state); + markChanged(state); + state.assigned_ = /* @__PURE__ */ new Map(); + each(state.base_, (key) => { + state.assigned_.set(key, false); + }); + state.copy_.clear(); + } + } + forEach(cb, thisArg) { + const state = this[DRAFT_STATE]; + latest(state).forEach((_value, key, _map) => { + cb.call(thisArg, this.get(key), key, this); + }); + } + get(key) { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + const value = latest(state).get(key); + if (state.finalized_ || !isDraftable(value)) { + return value; + } + if (value !== state.base_.get(key)) { + return value; + } + const draft = createProxy(value, state); + prepareMapCopy(state); + state.copy_.set(key, draft); + return draft; + } + keys() { + return latest(this[DRAFT_STATE]).keys(); + } + values() { + const iterator = this.keys(); + return { + [Symbol.iterator]: () => this.values(), + next: () => { + const r8 = iterator.next(); + if (r8.done) + return r8; + const value = this.get(r8.value); + return { + done: false, + value + }; + } + }; + } + entries() { + const iterator = this.keys(); + return { + [Symbol.iterator]: () => this.entries(), + next: () => { + const r8 = iterator.next(); + if (r8.done) + return r8; + const value = this.get(r8.value); + return { + done: false, + value: [r8.value, value] + }; + } + }; + } + [Symbol.iterator]() { + return this.entries(); + } + } + function proxyMap_(target, parent) { + return new DraftMap(target, parent); + } + function prepareMapCopy(state) { + if (!state.copy_) { + state.assigned_ = /* @__PURE__ */ new Map(); + state.copy_ = new Map(state.base_); + } + } + class DraftSet extends Set { + constructor(target, parent) { + super(); + this[DRAFT_STATE] = { + type_: 3, + parent_: parent, + scope_: parent ? parent.scope_ : getCurrentScope(), + modified_: false, + finalized_: false, + copy_: void 0, + base_: target, + draft_: this, + drafts_: /* @__PURE__ */ new Map(), + revoked_: false, + isManual_: false + }; + } + get size() { + return latest(this[DRAFT_STATE]).size; + } + has(value) { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + if (!state.copy_) { + return state.base_.has(value); + } + if (state.copy_.has(value)) + return true; + if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value))) + return true; + return false; + } + add(value) { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + if (!this.has(value)) { + prepareSetCopy(state); + markChanged(state); + state.copy_.add(value); + } + return this; + } + delete(value) { + if (!this.has(value)) { + return false; + } + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + prepareSetCopy(state); + markChanged(state); + return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : ( + /* istanbul ignore next */ + false + )); + } + clear() { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + if (latest(state).size) { + prepareSetCopy(state); + markChanged(state); + state.copy_.clear(); + } + } + values() { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + prepareSetCopy(state); + return state.copy_.values(); + } + entries() { + const state = this[DRAFT_STATE]; + assertUnrevoked(state); + prepareSetCopy(state); + return state.copy_.entries(); + } + keys() { + return this.values(); + } + [Symbol.iterator]() { + return this.values(); + } + forEach(cb, thisArg) { + const iterator = this.values(); + let result = iterator.next(); + while (!result.done) { + cb.call(thisArg, result.value, result.value, this); + result = iterator.next(); + } + } + } + function proxySet_(target, parent) { + return new DraftSet(target, parent); + } + function prepareSetCopy(state) { + if (!state.copy_) { + state.copy_ = /* @__PURE__ */ new Set(); + state.base_.forEach((value) => { + if (isDraftable(value)) { + const draft = createProxy(value, state); + state.drafts_.set(value, draft); + state.copy_.add(draft); + } else { + state.copy_.add(value); + } + }); + } + } + function assertUnrevoked(state) { + if (state.revoked_) + die(3, JSON.stringify(latest(state))); + } + loadPlugin("MapSet", { proxyMap_, proxySet_ }); +} +function enablePatches() { + const errorOffset = 16; + if (false) { + errors.push( + 'Sets cannot have "replace" patches.', + function(op2) { + return "Unsupported patch operation: " + op2; + }, + function(path6) { + return "Cannot apply patch, path doesn't resolve: " + path6; + }, + "Patching reserved attributes like __proto__, prototype and constructor is not allowed" + ); + } + const REPLACE = "replace"; + const ADD = "add"; + const REMOVE = "remove"; + function generatePatches_(state, basePath, patches, inversePatches) { + switch (state.type_) { + case 0: + case 2: + return generatePatchesFromAssigned( + state, + basePath, + patches, + inversePatches + ); + case 1: + return generateArrayPatches(state, basePath, patches, inversePatches); + case 3: + return generateSetPatches( + state, + basePath, + patches, + inversePatches + ); + } + } + function generateArrayPatches(state, basePath, patches, inversePatches) { + let { base_, assigned_ } = state; + let copy_ = state.copy_; + if (copy_.length < base_.length) { + [base_, copy_] = [copy_, base_]; + [patches, inversePatches] = [inversePatches, patches]; + } + for (let i7 = 0; i7 < base_.length; i7++) { + if (assigned_[i7] && copy_[i7] !== base_[i7]) { + const path6 = basePath.concat([i7]); + patches.push({ + op: REPLACE, + path: path6, + // Need to maybe clone it, as it can in fact be the original value + // due to the base/copy inversion at the start of this function + value: clonePatchValueIfNeeded(copy_[i7]) + }); + inversePatches.push({ + op: REPLACE, + path: path6, + value: clonePatchValueIfNeeded(base_[i7]) + }); + } + } + for (let i7 = base_.length; i7 < copy_.length; i7++) { + const path6 = basePath.concat([i7]); + patches.push({ + op: ADD, + path: path6, + // Need to maybe clone it, as it can in fact be the original value + // due to the base/copy inversion at the start of this function + value: clonePatchValueIfNeeded(copy_[i7]) + }); + } + for (let i7 = copy_.length - 1; base_.length <= i7; --i7) { + const path6 = basePath.concat([i7]); + inversePatches.push({ + op: REMOVE, + path: path6 + }); + } + } + function generatePatchesFromAssigned(state, basePath, patches, inversePatches) { + const { base_, copy_ } = state; + each(state.assigned_, (key, assignedValue) => { + const origValue = get(base_, key); + const value = get(copy_, key); + const op2 = !assignedValue ? REMOVE : has2(base_, key) ? REPLACE : ADD; + if (origValue === value && op2 === REPLACE) + return; + const path6 = basePath.concat(key); + patches.push(op2 === REMOVE ? { op: op2, path: path6 } : { op: op2, path: path6, value }); + inversePatches.push( + op2 === ADD ? { op: REMOVE, path: path6 } : op2 === REMOVE ? { op: ADD, path: path6, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path: path6, value: clonePatchValueIfNeeded(origValue) } + ); + }); + } + function generateSetPatches(state, basePath, patches, inversePatches) { + let { base_, copy_ } = state; + let i7 = 0; + base_.forEach((value) => { + if (!copy_.has(value)) { + const path6 = basePath.concat([i7]); + patches.push({ + op: REMOVE, + path: path6, + value + }); + inversePatches.unshift({ + op: ADD, + path: path6, + value + }); + } + i7++; + }); + i7 = 0; + copy_.forEach((value) => { + if (!base_.has(value)) { + const path6 = basePath.concat([i7]); + patches.push({ + op: ADD, + path: path6, + value + }); + inversePatches.unshift({ + op: REMOVE, + path: path6, + value + }); + } + i7++; + }); + } + function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) { + patches.push({ + op: REPLACE, + path: [], + value: replacement === NOTHING ? void 0 : replacement + }); + inversePatches.push({ + op: REPLACE, + path: [], + value: baseValue + }); + } + function applyPatches_(draft, patches) { + patches.forEach((patch) => { + const { path: path6, op: op2 } = patch; + let base = draft; + for (let i7 = 0; i7 < path6.length - 1; i7++) { + const parentType = getArchtype(base); + let p4 = path6[i7]; + if (typeof p4 !== "string" && typeof p4 !== "number") { + p4 = "" + p4; + } + if ((parentType === 0 || parentType === 1) && (p4 === "__proto__" || p4 === "constructor")) + die(errorOffset + 3); + if (typeof base === "function" && p4 === "prototype") + die(errorOffset + 3); + base = get(base, p4); + if (typeof base !== "object") + die(errorOffset + 2, path6.join("/")); + } + const type = getArchtype(base); + const value = deepClonePatchValue(patch.value); + const key = path6[path6.length - 1]; + switch (op2) { + case REPLACE: + switch (type) { + case 2: + return base.set(key, value); + case 3: + die(errorOffset); + default: + return base[key] = value; + } + case ADD: + switch (type) { + case 1: + return key === "-" ? base.push(value) : base.splice(key, 0, value); + case 2: + return base.set(key, value); + case 3: + return base.add(value); + default: + return base[key] = value; + } + case REMOVE: + switch (type) { + case 1: + return base.splice(key, 1); + case 2: + return base.delete(key); + case 3: + return base.delete(patch.value); + default: + return delete base[key]; + } + default: + die(errorOffset + 1, op2); + } + }); + return draft; + } + function deepClonePatchValue(obj) { + if (!isDraftable(obj)) + return obj; + if (Array.isArray(obj)) + return obj.map(deepClonePatchValue); + if (isMap$1(obj)) + return new Map( + Array.from(obj.entries()).map(([k2, v4]) => [k2, deepClonePatchValue(v4)]) + ); + if (isSet$1(obj)) + return new Set(Array.from(obj).map(deepClonePatchValue)); + const cloned = Object.create(getPrototypeOf(obj)); + for (const key in obj) + cloned[key] = deepClonePatchValue(obj[key]); + if (has2(obj, DRAFTABLE)) + cloned[DRAFTABLE] = obj[DRAFTABLE]; + return cloned; + } + function clonePatchValueIfNeeded(obj) { + if (isDraft(obj)) { + return deepClonePatchValue(obj); + } else + return obj; + } + loadPlugin("Patches", { + applyPatches_, + generatePatches_, + generateReplacementPatches_ + }); +} +function cwt(...allTags) { + return allTags.filter((tags) => tags !== void 0).reduce((acc, tags) => acc.concat(tags), []); +} +function makeRootReplacingPatches(value) { + return [ + { + op: "replace", + path: [], + value + } + ]; +} +function makeSetterWithPatches(update, prependTagsFn) { + const setter = (value, tags) => { + update(() => [value, makeRootReplacingPatches(value)], cwt(prependTagsFn?.(), tags)); + }; + setter.withProducer = (producer, tags) => { + update((oldData) => { + const [newData, patches] = produceWithPatches(oldData, producer); + if (isAvailable(newData)) { + return [newData, patches]; + } + throw new Error("Cannot update value to NOT_AVAILABLE"); + }, cwt(prependTagsFn?.(), tags)); + }; + setter.withUpdater = (updater, tags) => { + update((oldData) => { + const newData = updater(oldData); + return [newData, makeRootReplacingPatches(newData)]; + }, cwt(prependTagsFn?.(), tags)); + }; + setter.withPatchUpdater = (updater, tags) => { + update(updater, cwt(prependTagsFn?.(), tags)); + }; + setter.withPatches = (patches, tags) => { + update((oldData) => { + return [applyPatches(oldData, patches), patches]; + }, cwt(prependTagsFn?.(), tags)); + }; + setter.withValueAndPatches = (newValue, patches, tags) => { + update(() => [newValue, patches], cwt(prependTagsFn?.(), tags)); + }; + return setter; +} +function isAvailable(data) { + return data !== LazySignal.NOT_AVAILABLE; +} +function getCurrentStack(goAbove = 0) { + const stack = new Error().stack; + if (!stack) { + return ""; + } + const lines = stack.split("\n"); + return lines.slice(2 + goAbove).join("\n"); +} +function changeErrorStackInPlace(error, newStack) { + if (process_shim_default.env.LMS_KEEP_INTERNAL_STACK) { + return; + } + const stackContent = error.stack ?? ""; + error.stack = (stackContent.substring(0, stackContent.indexOf("\n at ")).trimEnd() + "\n" + newStack).trimEnd(); +} +function getDefaultExportFromCjs(x2) { + return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2; +} +function requireAnsiRegex() { + if (hasRequiredAnsiRegex) return ansiRegex; + hasRequiredAnsiRegex = 1; + ansiRegex = ({ onlyFirst = false } = {}) => { + const pattern = [ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))" + ].join("|"); + return new RegExp(pattern, onlyFirst ? void 0 : "g"); + }; + return ansiRegex; +} +function requireStripAnsi() { + if (hasRequiredStripAnsi) return stripAnsi; + hasRequiredStripAnsi = 1; + const ansiRegex2 = requireAnsiRegex(); + stripAnsi = (string) => typeof string === "string" ? string.replace(ansiRegex2(), "") : string; + return stripAnsi; +} +function requireIsFullwidthCodePoint() { + if (hasRequiredIsFullwidthCodePoint) return isFullwidthCodePoint.exports; + hasRequiredIsFullwidthCodePoint = 1; + const isFullwidthCodePoint$1 = (codePoint) => { + if (Number.isNaN(codePoint)) { + return false; + } + if (codePoint >= 4352 && (codePoint <= 4447 || // Hangul Jamo + codePoint === 9001 || // LEFT-POINTING ANGLE BRACKET + codePoint === 9002 || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + 11904 <= codePoint && codePoint <= 12871 && codePoint !== 12351 || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + 12880 <= codePoint && codePoint <= 19903 || // CJK Unified Ideographs .. Yi Radicals + 19968 <= codePoint && codePoint <= 42182 || // Hangul Jamo Extended-A + 43360 <= codePoint && codePoint <= 43388 || // Hangul Syllables + 44032 <= codePoint && codePoint <= 55203 || // CJK Compatibility Ideographs + 63744 <= codePoint && codePoint <= 64255 || // Vertical Forms + 65040 <= codePoint && codePoint <= 65049 || // CJK Compatibility Forms .. Small Form Variants + 65072 <= codePoint && codePoint <= 65131 || // Halfwidth and Fullwidth Forms + 65281 <= codePoint && codePoint <= 65376 || 65504 <= codePoint && codePoint <= 65510 || // Kana Supplement + 110592 <= codePoint && codePoint <= 110593 || // Enclosed Ideographic Supplement + 127488 <= codePoint && codePoint <= 127569 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + 131072 <= codePoint && codePoint <= 262141)) { + return true; + } + return false; + }; + isFullwidthCodePoint.exports = isFullwidthCodePoint$1; + isFullwidthCodePoint.exports.default = isFullwidthCodePoint$1; + return isFullwidthCodePoint.exports; +} +function requireEmojiRegex() { + if (hasRequiredEmojiRegex) return emojiRegex4; + hasRequiredEmojiRegex = 1; + emojiRegex4 = function() { + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; + }; + return emojiRegex4; +} +function requireStringWidth() { + if (hasRequiredStringWidth) return stringWidth.exports; + hasRequiredStringWidth = 1; + const stripAnsi2 = requireStripAnsi(); + const isFullwidthCodePoint2 = requireIsFullwidthCodePoint(); + const emojiRegex5 = requireEmojiRegex(); + const stringWidth$1 = (string) => { + if (typeof string !== "string" || string.length === 0) { + return 0; + } + string = stripAnsi2(string); + if (string.length === 0) { + return 0; + } + string = string.replace(emojiRegex5(), " "); + let width = 0; + for (let i7 = 0; i7 < string.length; i7++) { + const code = string.codePointAt(i7); + if (code <= 31 || code >= 127 && code <= 159) { + continue; + } + if (code >= 768 && code <= 879) { + continue; + } + if (code > 65535) { + i7++; + } + width += isFullwidthCodePoint2(code) ? 2 : 1; + } + return width; + }; + stringWidth.exports = stringWidth$1; + stringWidth.exports.default = stringWidth$1; + return stringWidth.exports; +} +function requireWidestLine() { + if (hasRequiredWidestLine) return widestLine.exports; + hasRequiredWidestLine = 1; + const stringWidth2 = requireStringWidth(); + const widestLine$1 = (input) => { + let max = 0; + for (const line of input.split("\n")) { + max = Math.max(max, stringWidth2(line)); + } + return max; + }; + widestLine.exports = widestLine$1; + widestLine.exports.default = widestLine$1; + return widestLine.exports; +} +function requireCliBoxes() { + if (hasRequiredCliBoxes) return cliBoxes.exports; + hasRequiredCliBoxes = 1; + const cliBoxes$1 = require$$0; + cliBoxes.exports = cliBoxes$1; + cliBoxes.exports.default = cliBoxes$1; + return cliBoxes.exports; +} +function requireCamelcase() { + if (hasRequiredCamelcase) return camelcase.exports; + hasRequiredCamelcase = 1; + const UPPERCASE = /[\p{Lu}]/u; + const LOWERCASE = /[\p{Ll}]/u; + const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; + const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; + const SEPARATORS = /[_.\- ]+/; + const LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source); + const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu"); + const NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu"); + const preserveCamelCase = (string, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + for (let i7 = 0; i7 < string.length; i7++) { + const character = string[i7]; + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, i7) + "-" + string.slice(i7); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i7++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string = string.slice(0, i7 - 1) + "-" + string.slice(i7 - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + return string; + }; + const preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1)); + }; + const postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + return input.replace(SEPARATORS_AND_IDENTIFIER, (_3, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m4) => toUpperCase(m4)); + }; + const camelCase = (input, options) => { + if (!(typeof input === "string" || Array.isArray(input))) { + throw new TypeError("Expected the input to be `string | string[]`"); + } + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + if (Array.isArray(input)) { + input = input.map((x2) => x2.trim()).filter((x2) => x2.length).join("-"); + } else { + input = input.trim(); + } + if (input.length === 0) { + return ""; + } + const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale); + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + const hasUpperCase = input !== toLowerCase(input); + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } + input = input.replace(LEADING_SEPARATORS, ""); + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + return postProcess(input, toUpperCase); + }; + camelcase.exports = camelCase; + camelcase.exports.default = camelCase; + return camelcase.exports; +} +function requireAnsiAlign() { + if (hasRequiredAnsiAlign) return ansiAlign_1; + hasRequiredAnsiAlign = 1; + const stringWidth2 = requireStringWidth(); + function ansiAlign(text3, opts) { + if (!text3) return text3; + opts = opts || {}; + const align = opts.align || "center"; + if (align === "left") return text3; + const split = opts.split || "\n"; + const pad2 = opts.pad || " "; + const widthDiffFn = align !== "right" ? halfDiff : fullDiff; + let returnString = false; + if (!Array.isArray(text3)) { + returnString = true; + text3 = String(text3).split(split); + } + let width; + let maxWidth = 0; + text3 = text3.map(function(str2) { + str2 = String(str2); + width = stringWidth2(str2); + maxWidth = Math.max(width, maxWidth); + return { + str: str2, + width + }; + }).map(function(obj) { + return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad2) + obj.str; + }); + return returnString ? text3.join(split) : text3; + } + ansiAlign.left = function left(text3) { + return ansiAlign(text3, { align: "left" }); + }; + ansiAlign.center = function center(text3) { + return ansiAlign(text3, { align: "center" }); + }; + ansiAlign.right = function right(text3) { + return ansiAlign(text3, { align: "right" }); + }; + ansiAlign_1 = ansiAlign; + function halfDiff(maxWidth, curWidth) { + return Math.floor((maxWidth - curWidth) / 2); + } + function fullDiff(maxWidth, curWidth) { + return maxWidth - curWidth; + } + return ansiAlign_1; +} +function requireColorName() { + if (hasRequiredColorName) return colorName; + hasRequiredColorName = 1; + colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] + }; + return colorName; +} +function requireConversions() { + if (hasRequiredConversions) return conversions; + hasRequiredConversions = 1; + const cssKeywords = requireColorName(); + const reverseKeywords = {}; + for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; + } + const convert = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + lch: { channels: 3, labels: "lch" }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } + }; + conversions = convert; + for (const model of Object.keys(convert)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + const { channels, labels } = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); + } + convert.rgb.hsl = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const min = Math.min(r8, g3, b4); + const max = Math.max(r8, g3, b4); + const delta = max - min; + let h7; + let s6; + if (max === min) { + h7 = 0; + } else if (r8 === max) { + h7 = (g3 - b4) / delta; + } else if (g3 === max) { + h7 = 2 + (b4 - r8) / delta; + } else if (b4 === max) { + h7 = 4 + (r8 - g3) / delta; + } + h7 = Math.min(h7 * 60, 360); + if (h7 < 0) { + h7 += 360; + } + const l5 = (min + max) / 2; + if (max === min) { + s6 = 0; + } else if (l5 <= 0.5) { + s6 = delta / (max + min); + } else { + s6 = delta / (2 - max - min); + } + return [h7, s6 * 100, l5 * 100]; + }; + convert.rgb.hsv = function(rgb) { + let rdif; + let gdif; + let bdif; + let h7; + let s6; + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const v4 = Math.max(r8, g3, b4); + const diff = v4 - Math.min(r8, g3, b4); + const diffc = function(c6) { + return (v4 - c6) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h7 = 0; + s6 = 0; + } else { + s6 = diff / v4; + rdif = diffc(r8); + gdif = diffc(g3); + bdif = diffc(b4); + if (r8 === v4) { + h7 = bdif - gdif; + } else if (g3 === v4) { + h7 = 1 / 3 + rdif - bdif; + } else if (b4 === v4) { + h7 = 2 / 3 + gdif - rdif; + } + if (h7 < 0) { + h7 += 1; + } else if (h7 > 1) { + h7 -= 1; + } + } + return [ + h7 * 360, + s6 * 100, + v4 * 100 + ]; + }; + convert.rgb.hwb = function(rgb) { + const r8 = rgb[0]; + const g3 = rgb[1]; + let b4 = rgb[2]; + const h7 = convert.rgb.hsl(rgb)[0]; + const w3 = 1 / 255 * Math.min(r8, Math.min(g3, b4)); + b4 = 1 - 1 / 255 * Math.max(r8, Math.max(g3, b4)); + return [h7, w3 * 100, b4 * 100]; + }; + convert.rgb.cmyk = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const k2 = Math.min(1 - r8, 1 - g3, 1 - b4); + const c6 = (1 - r8 - k2) / (1 - k2) || 0; + const m4 = (1 - g3 - k2) / (1 - k2) || 0; + const y4 = (1 - b4 - k2) / (1 - k2) || 0; + return [c6 * 100, m4 * 100, y4 * 100, k2 * 100]; + }; + function comparativeDistance(x2, y4) { + return (x2[0] - y4[0]) ** 2 + (x2[1] - y4[1]) ** 2 + (x2[2] - y4[2]) ** 2; + } + convert.rgb.keyword = function(rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + let currentClosestDistance = Infinity; + let currentClosestKeyword; + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + const distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + return currentClosestKeyword; + }; + convert.keyword.rgb = function(keyword) { + return cssKeywords[keyword]; + }; + convert.rgb.xyz = function(rgb) { + let r8 = rgb[0] / 255; + let g3 = rgb[1] / 255; + let b4 = rgb[2] / 255; + r8 = r8 > 0.04045 ? ((r8 + 0.055) / 1.055) ** 2.4 : r8 / 12.92; + g3 = g3 > 0.04045 ? ((g3 + 0.055) / 1.055) ** 2.4 : g3 / 12.92; + b4 = b4 > 0.04045 ? ((b4 + 0.055) / 1.055) ** 2.4 : b4 / 12.92; + const x2 = r8 * 0.4124 + g3 * 0.3576 + b4 * 0.1805; + const y4 = r8 * 0.2126 + g3 * 0.7152 + b4 * 0.0722; + const z3 = r8 * 0.0193 + g3 * 0.1192 + b4 * 0.9505; + return [x2 * 100, y4 * 100, z3 * 100]; + }; + convert.rgb.lab = function(rgb) { + const xyz = convert.rgb.xyz(rgb); + let x2 = xyz[0]; + let y4 = xyz[1]; + let z3 = xyz[2]; + x2 /= 95.047; + y4 /= 100; + z3 /= 108.883; + x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116; + y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116; + z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116; + const l5 = 116 * y4 - 16; + const a3 = 500 * (x2 - y4); + const b4 = 200 * (y4 - z3); + return [l5, a3, b4]; + }; + convert.hsl.rgb = function(hsl) { + const h7 = hsl[0] / 360; + const s6 = hsl[1] / 100; + const l5 = hsl[2] / 100; + let t22; + let t32; + let val2; + if (s6 === 0) { + val2 = l5 * 255; + return [val2, val2, val2]; + } + if (l5 < 0.5) { + t22 = l5 * (1 + s6); + } else { + t22 = l5 + s6 - l5 * s6; + } + const t1 = 2 * l5 - t22; + const rgb = [0, 0, 0]; + for (let i7 = 0; i7 < 3; i7++) { + t32 = h7 + 1 / 3 * -(i7 - 1); + if (t32 < 0) { + t32++; + } + if (t32 > 1) { + t32--; + } + if (6 * t32 < 1) { + val2 = t1 + (t22 - t1) * 6 * t32; + } else if (2 * t32 < 1) { + val2 = t22; + } else if (3 * t32 < 2) { + val2 = t1 + (t22 - t1) * (2 / 3 - t32) * 6; + } else { + val2 = t1; + } + rgb[i7] = val2 * 255; + } + return rgb; + }; + convert.hsl.hsv = function(hsl) { + const h7 = hsl[0]; + let s6 = hsl[1] / 100; + let l5 = hsl[2] / 100; + let smin = s6; + const lmin = Math.max(l5, 0.01); + l5 *= 2; + s6 *= l5 <= 1 ? l5 : 2 - l5; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v4 = (l5 + s6) / 2; + const sv = l5 === 0 ? 2 * smin / (lmin + smin) : 2 * s6 / (l5 + s6); + return [h7, sv * 100, v4 * 100]; + }; + convert.hsv.rgb = function(hsv) { + const h7 = hsv[0] / 60; + const s6 = hsv[1] / 100; + let v4 = hsv[2] / 100; + const hi = Math.floor(h7) % 6; + const f4 = h7 - Math.floor(h7); + const p4 = 255 * v4 * (1 - s6); + const q2 = 255 * v4 * (1 - s6 * f4); + const t6 = 255 * v4 * (1 - s6 * (1 - f4)); + v4 *= 255; + switch (hi) { + case 0: + return [v4, t6, p4]; + case 1: + return [q2, v4, p4]; + case 2: + return [p4, v4, t6]; + case 3: + return [p4, q2, v4]; + case 4: + return [t6, p4, v4]; + case 5: + return [v4, p4, q2]; + } + }; + convert.hsv.hsl = function(hsv) { + const h7 = hsv[0]; + const s6 = hsv[1] / 100; + const v4 = hsv[2] / 100; + const vmin = Math.max(v4, 0.01); + let sl; + let l5; + l5 = (2 - s6) * v4; + const lmin = (2 - s6) * vmin; + sl = s6 * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l5 /= 2; + return [h7, sl * 100, l5 * 100]; + }; + convert.hwb.rgb = function(hwb) { + const h7 = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f4; + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + const i7 = Math.floor(6 * h7); + const v4 = 1 - bl; + f4 = 6 * h7 - i7; + if ((i7 & 1) !== 0) { + f4 = 1 - f4; + } + const n7 = wh + f4 * (v4 - wh); + let r8; + let g3; + let b4; + switch (i7) { + default: + case 6: + case 0: + r8 = v4; + g3 = n7; + b4 = wh; + break; + case 1: + r8 = n7; + g3 = v4; + b4 = wh; + break; + case 2: + r8 = wh; + g3 = v4; + b4 = n7; + break; + case 3: + r8 = wh; + g3 = n7; + b4 = v4; + break; + case 4: + r8 = n7; + g3 = wh; + b4 = v4; + break; + case 5: + r8 = v4; + g3 = wh; + b4 = n7; + break; + } + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.cmyk.rgb = function(cmyk) { + const c6 = cmyk[0] / 100; + const m4 = cmyk[1] / 100; + const y4 = cmyk[2] / 100; + const k2 = cmyk[3] / 100; + const r8 = 1 - Math.min(1, c6 * (1 - k2) + k2); + const g3 = 1 - Math.min(1, m4 * (1 - k2) + k2); + const b4 = 1 - Math.min(1, y4 * (1 - k2) + k2); + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.xyz.rgb = function(xyz) { + const x2 = xyz[0] / 100; + const y4 = xyz[1] / 100; + const z3 = xyz[2] / 100; + let r8; + let g3; + let b4; + r8 = x2 * 3.2406 + y4 * -1.5372 + z3 * -0.4986; + g3 = x2 * -0.9689 + y4 * 1.8758 + z3 * 0.0415; + b4 = x2 * 0.0557 + y4 * -0.204 + z3 * 1.057; + r8 = r8 > 31308e-7 ? 1.055 * r8 ** (1 / 2.4) - 0.055 : r8 * 12.92; + g3 = g3 > 31308e-7 ? 1.055 * g3 ** (1 / 2.4) - 0.055 : g3 * 12.92; + b4 = b4 > 31308e-7 ? 1.055 * b4 ** (1 / 2.4) - 0.055 : b4 * 12.92; + r8 = Math.min(Math.max(0, r8), 1); + g3 = Math.min(Math.max(0, g3), 1); + b4 = Math.min(Math.max(0, b4), 1); + return [r8 * 255, g3 * 255, b4 * 255]; + }; + convert.xyz.lab = function(xyz) { + let x2 = xyz[0]; + let y4 = xyz[1]; + let z3 = xyz[2]; + x2 /= 95.047; + y4 /= 100; + z3 /= 108.883; + x2 = x2 > 8856e-6 ? x2 ** (1 / 3) : 7.787 * x2 + 16 / 116; + y4 = y4 > 8856e-6 ? y4 ** (1 / 3) : 7.787 * y4 + 16 / 116; + z3 = z3 > 8856e-6 ? z3 ** (1 / 3) : 7.787 * z3 + 16 / 116; + const l5 = 116 * y4 - 16; + const a3 = 500 * (x2 - y4); + const b4 = 200 * (y4 - z3); + return [l5, a3, b4]; + }; + convert.lab.xyz = function(lab) { + const l5 = lab[0]; + const a3 = lab[1]; + const b4 = lab[2]; + let x2; + let y4; + let z3; + y4 = (l5 + 16) / 116; + x2 = a3 / 500 + y4; + z3 = y4 - b4 / 200; + const y22 = y4 ** 3; + const x22 = x2 ** 3; + const z22 = z3 ** 3; + y4 = y22 > 8856e-6 ? y22 : (y4 - 16 / 116) / 7.787; + x2 = x22 > 8856e-6 ? x22 : (x2 - 16 / 116) / 7.787; + z3 = z22 > 8856e-6 ? z22 : (z3 - 16 / 116) / 7.787; + x2 *= 95.047; + y4 *= 100; + z3 *= 108.883; + return [x2, y4, z3]; + }; + convert.lab.lch = function(lab) { + const l5 = lab[0]; + const a3 = lab[1]; + const b4 = lab[2]; + let h7; + const hr = Math.atan2(b4, a3); + h7 = hr * 360 / 2 / Math.PI; + if (h7 < 0) { + h7 += 360; + } + const c6 = Math.sqrt(a3 * a3 + b4 * b4); + return [l5, c6, h7]; + }; + convert.lch.lab = function(lch) { + const l5 = lch[0]; + const c6 = lch[1]; + const h7 = lch[2]; + const hr = h7 / 360 * 2 * Math.PI; + const a3 = c6 * Math.cos(hr); + const b4 = c6 * Math.sin(hr); + return [l5, a3, b4]; + }; + convert.rgb.ansi16 = function(args, saturation = null) { + const [r8, g3, b4] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + let ansi = 30 + (Math.round(b4 / 255) << 2 | Math.round(g3 / 255) << 1 | Math.round(r8 / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; + }; + convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + }; + convert.rgb.ansi256 = function(args) { + const r8 = args[0]; + const g3 = args[1]; + const b4 = args[2]; + if (r8 === g3 && g3 === b4) { + if (r8 < 8) { + return 16; + } + if (r8 > 248) { + return 231; + } + return Math.round((r8 - 8) / 247 * 24) + 232; + } + const ansi = 16 + 36 * Math.round(r8 / 255 * 5) + 6 * Math.round(g3 / 255 * 5) + Math.round(b4 / 255 * 5); + return ansi; + }; + convert.ansi16.rgb = function(args) { + let color2 = args % 10; + if (color2 === 0 || color2 === 7) { + if (args > 50) { + color2 += 3.5; + } + color2 = color2 / 10.5 * 255; + return [color2, color2, color2]; + } + const mult = (~~(args > 50) + 1) * 0.5; + const r8 = (color2 & 1) * mult * 255; + const g3 = (color2 >> 1 & 1) * mult * 255; + const b4 = (color2 >> 2 & 1) * mult * 255; + return [r8, g3, b4]; + }; + convert.ansi256.rgb = function(args) { + if (args >= 232) { + const c6 = (args - 232) * 10 + 8; + return [c6, c6, c6]; + } + args -= 16; + let rem; + const r8 = Math.floor(args / 36) / 5 * 255; + const g3 = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b4 = rem % 6 / 5 * 255; + return [r8, g3, b4]; + }; + convert.rgb.hex = function(args) { + const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + const string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.hex.rgb = function(args) { + const match2 = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match2) { + return [0, 0, 0]; + } + let colorString = match2[0]; + if (match2[0].length === 3) { + colorString = colorString.split("").map((char) => { + return char + char; + }).join(""); + } + const integer = parseInt(colorString, 16); + const r8 = integer >> 16 & 255; + const g3 = integer >> 8 & 255; + const b4 = integer & 255; + return [r8, g3, b4]; + }; + convert.rgb.hcg = function(rgb) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const max = Math.max(Math.max(r8, g3), b4); + const min = Math.min(Math.min(r8, g3), b4); + const chroma = max - min; + let grayscale; + let hue2; + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + if (chroma <= 0) { + hue2 = 0; + } else if (max === r8) { + hue2 = (g3 - b4) / chroma % 6; + } else if (max === g3) { + hue2 = 2 + (b4 - r8) / chroma; + } else { + hue2 = 4 + (r8 - g3) / chroma; + } + hue2 /= 6; + hue2 %= 1; + return [hue2 * 360, chroma * 100, grayscale * 100]; + }; + convert.hsl.hcg = function(hsl) { + const s6 = hsl[1] / 100; + const l5 = hsl[2] / 100; + const c6 = l5 < 0.5 ? 2 * s6 * l5 : 2 * s6 * (1 - l5); + let f4 = 0; + if (c6 < 1) { + f4 = (l5 - 0.5 * c6) / (1 - c6); + } + return [hsl[0], c6 * 100, f4 * 100]; + }; + convert.hsv.hcg = function(hsv) { + const s6 = hsv[1] / 100; + const v4 = hsv[2] / 100; + const c6 = s6 * v4; + let f4 = 0; + if (c6 < 1) { + f4 = (v4 - c6) / (1 - c6); + } + return [hsv[0], c6 * 100, f4 * 100]; + }; + convert.hcg.rgb = function(hcg) { + const h7 = hcg[0] / 360; + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + if (c6 === 0) { + return [g3 * 255, g3 * 255, g3 * 255]; + } + const pure = [0, 0, 0]; + const hi = h7 % 1 * 6; + const v4 = hi % 1; + const w3 = 1 - v4; + let mg = 0; + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; + pure[1] = v4; + pure[2] = 0; + break; + case 1: + pure[0] = w3; + pure[1] = 1; + pure[2] = 0; + break; + case 2: + pure[0] = 0; + pure[1] = 1; + pure[2] = v4; + break; + case 3: + pure[0] = 0; + pure[1] = w3; + pure[2] = 1; + break; + case 4: + pure[0] = v4; + pure[1] = 0; + pure[2] = 1; + break; + default: + pure[0] = 1; + pure[1] = 0; + pure[2] = w3; + } + mg = (1 - c6) * g3; + return [ + (c6 * pure[0] + mg) * 255, + (c6 * pure[1] + mg) * 255, + (c6 * pure[2] + mg) * 255 + ]; + }; + convert.hcg.hsv = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const v4 = c6 + g3 * (1 - c6); + let f4 = 0; + if (v4 > 0) { + f4 = c6 / v4; + } + return [hcg[0], f4 * 100, v4 * 100]; + }; + convert.hcg.hsl = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const l5 = g3 * (1 - c6) + 0.5 * c6; + let s6 = 0; + if (l5 > 0 && l5 < 0.5) { + s6 = c6 / (2 * l5); + } else if (l5 >= 0.5 && l5 < 1) { + s6 = c6 / (2 * (1 - l5)); + } + return [hcg[0], s6 * 100, l5 * 100]; + }; + convert.hcg.hwb = function(hcg) { + const c6 = hcg[1] / 100; + const g3 = hcg[2] / 100; + const v4 = c6 + g3 * (1 - c6); + return [hcg[0], (v4 - c6) * 100, (1 - v4) * 100]; + }; + convert.hwb.hcg = function(hwb) { + const w3 = hwb[1] / 100; + const b4 = hwb[2] / 100; + const v4 = 1 - b4; + const c6 = v4 - w3; + let g3 = 0; + if (c6 < 1) { + g3 = (v4 - c6) / (1 - c6); + } + return [hwb[0], c6 * 100, g3 * 100]; + }; + convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; + }; + convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; + }; + convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; + }; + convert.gray.hsl = function(args) { + return [0, 0, args[0]]; + }; + convert.gray.hsv = convert.gray.hsl; + convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; + }; + convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; + }; + convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; + }; + convert.gray.hex = function(gray) { + const val2 = Math.round(gray[0] / 100 * 255) & 255; + const integer = (val2 << 16) + (val2 << 8) + val2; + const string = integer.toString(16).toUpperCase(); + return "000000".substring(string.length) + string; + }; + convert.rgb.gray = function(rgb) { + const val2 = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val2 / 255 * 100]; + }; + return conversions; +} +function requireRoute() { + if (hasRequiredRoute) return route; + hasRequiredRoute = 1; + const conversions2 = requireConversions(); + function buildGraph() { + const graph = {}; + const models = Object.keys(conversions2); + for (let len = models.length, i7 = 0; i7 < len; i7++) { + graph[models[i7]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; + } + function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length) { + const current2 = queue.pop(); + const adjacents = Object.keys(conversions2[current2]); + for (let len = adjacents.length, i7 = 0; i7 < len; i7++) { + const adjacent = adjacents[i7]; + const node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current2].distance + 1; + node.parent = current2; + queue.unshift(adjacent); + } + } + } + return graph; + } + function link(from2, to2) { + return function(args) { + return to2(from2(args)); + }; + } + function wrapConversion(toModel, graph) { + const path6 = [graph[toModel].parent, toModel]; + let fn = conversions2[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path6.unshift(graph[cur].parent); + fn = link(conversions2[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path6; + return fn; + } + route = function(fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + const models = Object.keys(graph); + for (let len = models.length, i7 = 0; i7 < len; i7++) { + const toModel = models[i7]; + const node = graph[toModel]; + if (node.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; + }; + return route; +} +function requireColorConvert() { + if (hasRequiredColorConvert) return colorConvert; + hasRequiredColorConvert = 1; + const conversions2 = requireConversions(); + const route2 = requireRoute(); + const convert = {}; + const models = Object.keys(conversions2); + function wrapRaw(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + return fn(args); + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; + } + function wrapRounded(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + const result = fn(args); + if (typeof result === "object") { + for (let len = result.length, i7 = 0; i7 < len; i7++) { + result[i7] = Math.round(result[i7]); + } + } + return result; + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; + } + models.forEach((fromModel) => { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], "channels", { value: conversions2[fromModel].channels }); + Object.defineProperty(convert[fromModel], "labels", { value: conversions2[fromModel].labels }); + const routes = route2(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach((toModel) => { + const fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); + }); + colorConvert = convert; + return colorConvert; +} +function requireAnsiStyles() { + if (hasRequiredAnsiStyles) return ansiStyles.exports; + hasRequiredAnsiStyles = 1; + (function(module) { + const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\x1B[${code + offset}m`; + }; + const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\x1B[${38 + offset};5;${code}m`; + }; + const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\x1B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + const ansi2ansi = (n7) => n7; + const rgb2rgb = (r8, g3, b4) => [r8, g3, b4]; + const setLazyProperty = (object, property, get4) => { + Object.defineProperty(object, property, { + get: () => { + const value = get4(); + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + return value; + }, + enumerable: true, + configurable: true + }); + }; + let colorConvert2; + const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert2 === void 0) { + colorConvert2 = requireColorConvert(); + } + const offset = isBackground ? 10 : 0; + const styles2 = {}; + for (const [sourceSpace, suite] of Object.entries(colorConvert2)) { + const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace; + if (sourceSpace === targetSpace) { + styles2[name] = wrap(identity, offset); + } else if (typeof suite === "object") { + styles2[name] = wrap(suite[targetSpace], offset); + } + } + return styles2; + }; + function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + const styles2 = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + styles2.color.gray = styles2.color.blackBright; + styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; + styles2.color.grey = styles2.color.blackBright; + styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; + for (const [groupName, group] of Object.entries(styles2)) { + for (const [styleName, style] of Object.entries(group)) { + styles2[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m` + }; + group[styleName] = styles2[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles2, groupName, { + value: group, + enumerable: false + }); + } + Object.defineProperty(styles2, "codes", { + value: codes, + enumerable: false + }); + styles2.color.close = "\x1B[39m"; + styles2.bgColor.close = "\x1B[49m"; + setLazyProperty(styles2.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false)); + setLazyProperty(styles2.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false)); + setLazyProperty(styles2.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false)); + setLazyProperty(styles2.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true)); + setLazyProperty(styles2.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true)); + setLazyProperty(styles2.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true)); + return styles2; + } + Object.defineProperty(module, "exports", { + enumerable: true, + get: assembleStyles + }); + })(ansiStyles); + return ansiStyles.exports; +} +function requireWrapAnsi() { + if (hasRequiredWrapAnsi) return wrapAnsi_1; + hasRequiredWrapAnsi = 1; + const stringWidth2 = requireStringWidth(); + const stripAnsi2 = requireStripAnsi(); + const ansiStyles2 = requireAnsiStyles(); + const ESCAPES = /* @__PURE__ */ new Set([ + "\x1B", + "\x9B" + ]); + const END_CODE = 39; + const ANSI_ESCAPE_BELL = "\x07"; + const ANSI_CSI = "["; + const ANSI_OSC = "]"; + const ANSI_SGR_TERMINATOR = "m"; + const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + const wrapAnsi = (code) => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; + const wrapAnsiHyperlink = (uri) => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + const wordLengths = (string) => string.split(" ").map((character) => stringWidth2(character)); + const wrapWord = (rows, word, columns) => { + const characters = [...word]; + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth2(stripAnsi2(rows[rows.length - 1])); + for (const [index2, character] of characters.entries()) { + const characterLength = stringWidth2(character); + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + if (ESCAPES.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index2 + 1).join("").startsWith(ANSI_ESCAPE_LINK); + } + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + continue; + } + visible += characterLength; + if (visible === columns && index2 < characters.length - 1) { + rows.push(""); + visible = 0; + } + } + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } + }; + const stringVisibleTrimSpacesRight = (string) => { + const words = string.split(" "); + let last = words.length; + while (last > 0) { + if (stringWidth2(words[last - 1]) > 0) { + break; + } + last--; + } + if (last === words.length) { + return string; + } + return words.slice(0, last).join(" ") + words.slice(last).join(""); + }; + const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === "") { + return ""; + } + let returnValue = ""; + let escapeCode; + let escapeUrl; + const lengths = wordLengths(string); + let rows = [""]; + for (const [index2, word] of string.split(" ").entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + let rowLength = stringWidth2(rows[rows.length - 1]); + if (index2 !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + rows.push(""); + rowLength = 0; + } + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += " "; + rowLength++; + } + } + if (options.hard && lengths[index2] > columns) { + const remainingColumns = columns - rowLength; + const breaksStartingThisLine = 1 + Math.floor((lengths[index2] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index2] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(""); + } + wrapWord(rows, word, columns); + continue; + } + if (rowLength + lengths[index2] > columns && rowLength > 0 && lengths[index2] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + rows.push(""); + } + if (rowLength + lengths[index2] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + rows[rows.length - 1] += word; + } + if (options.trim !== false) { + rows = rows.map(stringVisibleTrimSpacesRight); + } + const pre = [...rows.join("\n")]; + for (const [index2, character] of pre.entries()) { + returnValue += character; + if (ESCAPES.has(character)) { + const { groups } = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index2).join("")) || { groups: {} }; + if (groups.code !== void 0) { + const code2 = Number.parseFloat(groups.code); + escapeCode = code2 === END_CODE ? void 0 : code2; + } else if (groups.uri !== void 0) { + escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri; + } + } + const code = ansiStyles2.codes.get(Number(escapeCode)); + if (pre[index2 + 1] === "\n") { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(""); + } + if (escapeCode && code) { + returnValue += wrapAnsi(code); + } + } else if (character === "\n") { + if (escapeCode && code) { + returnValue += wrapAnsi(escapeCode); + } + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + return returnValue; + }; + wrapAnsi_1 = (string, columns, options) => { + return String(string).normalize().replace(/\r\n/g, "\n").split("\n").map((line) => exec(line, columns, options)).join("\n"); + }; + return wrapAnsi_1; +} +function requireBoxen() { + if (hasRequiredBoxen) return boxen$1.exports; + hasRequiredBoxen = 1; + const stringWidth2 = requireStringWidth(); + const chalk$1 = import_chalk.default; + const widestLine2 = requireWidestLine(); + const cliBoxes2 = requireCliBoxes(); + const camelCase = requireCamelcase(); + const ansiAlign = requireAnsiAlign(); + const wrapAnsi = requireWrapAnsi(); + const NL = "\n"; + const PAD = " "; + const terminalColumns = () => { + const { env, stdout, stderr } = process; + if (stdout && stdout.columns) { + return stdout.columns; + } + if (stderr && stderr.columns) { + return stderr.columns; + } + if (env.COLUMNS) { + return Number.parseInt(env.COLUMNS, 10); + } + return 80; + }; + const getObject = (detail) => { + return typeof detail === "number" ? { + top: detail, + right: detail * 3, + bottom: detail, + left: detail * 3 + } : { + top: 0, + right: 0, + bottom: 0, + left: 0, + ...detail + }; + }; + const getBorderChars = (borderStyle) => { + const sides = [ + "topLeft", + "topRight", + "bottomRight", + "bottomLeft", + "vertical", + "horizontal" + ]; + let chararacters; + if (typeof borderStyle === "string") { + chararacters = cliBoxes2[borderStyle]; + if (!chararacters) { + throw new TypeError(`Invalid border style: ${borderStyle}`); + } + } else { + for (const side of sides) { + if (!borderStyle[side] || typeof borderStyle[side] !== "string") { + throw new TypeError(`Invalid border style: ${side}`); + } + } + chararacters = borderStyle; + } + return chararacters; + }; + const makeTitle = (text3, horizontal, alignement) => { + let title = ""; + const textWidth = stringWidth2(text3); + switch (alignement) { + case "left": + title = text3 + horizontal.slice(textWidth); + break; + case "right": + title = horizontal.slice(textWidth) + text3; + break; + default: + horizontal = horizontal.slice(textWidth); + if (horizontal.length % 2 === 1) { + horizontal = horizontal.slice(Math.floor(horizontal.length / 2)); + title = horizontal.slice(1) + text3 + horizontal; + } else { + horizontal = horizontal.slice(horizontal.length / 2); + title = horizontal + text3 + horizontal; + } + break; + } + return title; + }; + const makeContentText = (text3, padding, columns, align) => { + text3 = ansiAlign(text3, { align }); + let lines = text3.split(NL); + const textWidth = widestLine2(text3); + const max = columns - padding.left - padding.right; + if (textWidth > max) { + const newLines = []; + for (const line of lines) { + const createdLines = wrapAnsi(line, max, { hard: true }); + const alignedLines = ansiAlign(createdLines, { align }); + const alignedLinesArray = alignedLines.split("\n"); + const longestLength = Math.max(...alignedLinesArray.map((s6) => stringWidth2(s6))); + for (const alignedLine of alignedLinesArray) { + let paddedLine; + switch (align) { + case "center": + paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine; + break; + case "right": + paddedLine = PAD.repeat(max - longestLength) + alignedLine; + break; + default: + paddedLine = alignedLine; + break; + } + newLines.push(paddedLine); + } + } + lines = newLines; + } + if (align === "center" && textWidth < max) { + lines = lines.map((line) => PAD.repeat((max - textWidth) / 2) + line); + } else if (align === "right" && textWidth < max) { + lines = lines.map((line) => PAD.repeat(max - textWidth) + line); + } + const paddingLeft = PAD.repeat(padding.left); + const paddingRight = PAD.repeat(padding.right); + lines = lines.map((line) => paddingLeft + line + paddingRight); + lines = lines.map((line) => { + if (columns - stringWidth2(line) > 0) { + switch (align) { + case "center": + return line + PAD.repeat(columns - stringWidth2(line)); + case "right": + return line + PAD.repeat(columns - stringWidth2(line)); + default: + return line + PAD.repeat(columns - stringWidth2(line)); + } + } + return line; + }); + if (padding.top > 0) { + lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines); + } + if (padding.bottom > 0) { + lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns))); + } + return lines.join(NL); + }; + const isHex = (color2) => color2.match(/^#(?:[0-f]{3}){1,2}$/i); + const isColorValid = (color2) => typeof color2 === "string" && (chalk$1[color2] || isHex(color2)); + const getColorFn = (color2) => isHex(color2) ? chalk$1.hex(color2) : chalk$1[color2]; + const getBGColorFn = (color2) => isHex(color2) ? chalk$1.bgHex(color2) : chalk$1[camelCase(["bg", color2])]; + boxen$1.exports = (text3, options) => { + options = { + padding: 0, + borderStyle: "single", + dimBorder: false, + textAlignment: "left", + float: "left", + titleAlignment: "left", + ...options + }; + if (options.align) { + options.textAlignment = options.align; + } + const BORDERS_WIDTH = 2; + if (options.borderColor && !isColorValid(options.borderColor)) { + throw new Error(`${options.borderColor} is not a valid borderColor`); + } + if (options.backgroundColor && !isColorValid(options.backgroundColor)) { + throw new Error(`${options.backgroundColor} is not a valid backgroundColor`); + } + const chars = getBorderChars(options.borderStyle); + const padding = getObject(options.padding); + const margin = getObject(options.margin); + const colorizeBorder = (border) => { + const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border; + return options.dimBorder ? chalk$1.dim(newBorder) : newBorder; + }; + const colorizeContent = (content) => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content; + const columns = terminalColumns() - 1; + let contentWidth = widestLine2(wrapAnsi(text3, columns - BORDERS_WIDTH, { hard: true, trim: false })) + padding.left + padding.right; + let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right); + if (title) { + title = ` ${title} `; + if (stringWidth2(title) > contentWidth) { + contentWidth = stringWidth2(title); + } + } + if (margin.left && margin.right && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) { + const spaceForMargins = columns - contentWidth - BORDERS_WIDTH; + const multiplier = spaceForMargins / (margin.left + margin.right); + margin.left = Math.max(0, Math.floor(margin.left * multiplier)); + margin.right = Math.max(0, Math.floor(margin.right * multiplier)); + } + contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right); + text3 = makeContentText(text3, padding, contentWidth, options.textAlignment); + let marginLeft = PAD.repeat(margin.left); + if (options.float === "center") { + const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0); + marginLeft = PAD.repeat(marginWidth); + } else if (options.float === "right") { + const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0); + marginLeft = PAD.repeat(marginWidth); + } + const horizontal = chars.horizontal.repeat(contentWidth); + const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight); + const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom)); + const side = colorizeBorder(chars.vertical); + const LINE_SEPARATOR = NL; + const lines = text3.split(NL); + const middle = lines.map((line) => { + return marginLeft + side + colorizeContent(line) + side; + }).join(LINE_SEPARATOR); + return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom; + }; + boxen$1.exports._borderStyles = cliBoxes2; + return boxen$1.exports; +} +function makeTitledPrettyError(title, content, stack) { + return makePrettyError(import_chalk.default.redBright(title) + "\n\n" + content, stack); +} +function makePrettyError(content, stack) { + if (process_shim_default.browser || process_shim_default.env.LMS_NO_FANCY_ERRORS || (0, import_lms_isomorphic.terminalSize)().columns < 80) { + const error = new Error(content); + if (stack === void 0) { + changeErrorStackInPlace(error, ""); + } else { + changeErrorStackInPlace(error, stack); + } + return error; + } else { + if (stack !== void 0) { + content += "\n\n\n " + import_chalk.default.bgWhite.black(" STACK TRACE ") + "\n\n" + import_chalk.default.gray(stack); + } + const error = new Error("\n" + boxen(content, { padding: 1, margin: 1, borderColor: "redBright", title: "Error" })); + Object.defineProperty(error, "lmstudioRawError", { value: content, enumerable: false }); + changeErrorStackInPlace(error, ""); + return error; + } +} +function text(strings, ...values2) { + if (values2.length + 1 !== strings.length) { + throw new Error("text called with the wrong number of arguments."); + } + let compiled = compiledTemplatesCache.get(strings); + if (compiled === void 0) { + compiled = compile(strings); + compiledTemplatesCache.set(strings, compiled); + } + for (let i7 = 0; i7 < values2.length; i7++) { + if (typeof values2[i7] === "object") { + if (typeof values2[i7].stack === "string") { + compiled[i7 * 2 + 1] = values2[i7].stack; + } else { + try { + compiled[i7 * 2 + 1] = JSON.stringify(values2[i7]); + } catch (error) { + compiled[i7 * 2 + 1] = "[Object failed to stringify]"; + } + } + } else { + compiled[i7 * 2 + 1] = String(values2[i7]); + } + } + return compiled.join(""); +} +function removeLeadingNewlines(input) { + return input.replace(/^\n+/, ""); +} +function removeTrailingNewlinesAndWhitespace(input) { + return input.replace(/[\n ]+$/, ""); +} +function removeLeadingWhitespace(input) { + return input.replace(/^ +/, ""); +} +function removeTrailingWhitespace(input) { + return input.replace(/ +$/, ""); +} +function breakIntoLines(strings) { + const lines = []; + let currentLine = []; + for (const string of strings) { + let prevNewlineIndex = -1; + let nextNewlineIndex; + while ((nextNewlineIndex = string.indexOf("\n", prevNewlineIndex + 1)) !== -1) { + currentLine.push(string.substring(prevNewlineIndex + 1, nextNewlineIndex)); + lines.push(currentLine); + currentLine = []; + prevNewlineIndex = nextNewlineIndex; + } + currentLine.push(string.substring(prevNewlineIndex + 1)); + } + lines.push(currentLine); + return lines; +} +function countStringIndentations(string) { + let count = 0; + for (const char of string) { + if (char === " ") { + count++; + } else { + return count; + } + } + return Infinity; +} +function countLineIndentations(line) { + const firstPart = line[0]; + const firstPartIndentation = countStringIndentations(firstPart); + if (firstPartIndentation === Infinity) { + if (line.length === 1) { + return Infinity; + } else { + return firstPart.length; + } + } + return firstPartIndentation; +} +function findMaxCommonIndentation(lines) { + let minIndentation = Infinity; + for (const line of lines) { + minIndentation = Math.min(minIndentation, countLineIndentations(line)); + } + return minIndentation; +} +function removeIndentation(line, indentation) { + if (line.length < indentation) { + return ""; + } + return line.slice(indentation); +} +function removeAllIndentation(lines, indentation) { + for (const line of lines) { + line[0] = removeIndentation(line[0], indentation); + } +} +function isEmptyLine(line) { + if (line.length !== 1) { + return false; + } + for (const char of line[0]) { + if (char !== " ") { + return false; + } + } + return true; +} +function mergeLines(lines) { + const linesAreEmpty = lines.map(isEmptyLine); + const paragraphs = []; + let currentParagraph = []; + for (let i7 = 0; i7 < lines.length; i7++) { + if (linesAreEmpty[i7]) { + if (currentParagraph.length !== 0) { + paragraphs.push(currentParagraph); + currentParagraph = []; + } + continue; + } + if (currentParagraph.length !== 0) { + const last = removeTrailingWhitespace(currentParagraph[currentParagraph.length - 1]); + const next = removeLeadingWhitespace(lines[i7][0]); + currentParagraph[currentParagraph.length - 1] = last + " " + next; + currentParagraph.push(...lines[i7].slice(1)); + } else { + currentParagraph.push(...lines[i7]); + } + } + if (currentParagraph.length !== 0) { + paragraphs.push(currentParagraph); + } + return paragraphs; +} +function mergeParagraphs(paragraphs) { + const result = []; + if (paragraphs.length === 0) { + return [""]; + } + result.push(...paragraphs[0]); + for (let i7 = 1; i7 < paragraphs.length; i7++) { + result[result.length - 1] += "\n\n" + paragraphs[i7][0]; + result.push(...paragraphs[i7].slice(1)); + } + return result; +} +function addHolesForVariables(strings) { + const result = []; + for (let i7 = 0; i7 < strings.length; i7++) { + result.push(strings[i7]); + if (i7 < strings.length - 1) { + result.push(""); + } + } + return result; +} +function compile(readonlyStrings) { + const strings = [...readonlyStrings]; + strings[0] = removeLeadingNewlines(strings[0]); + strings[strings.length - 1] = removeTrailingNewlinesAndWhitespace(strings[strings.length - 1]); + const lines = breakIntoLines(strings); + const commonIndentation = findMaxCommonIndentation(lines); + removeAllIndentation(lines, commonIndentation); + const paragraphs = mergeLines(lines); + return addHolesForVariables(mergeParagraphs(paragraphs)); +} +function accessMaybeMutableInternals(maybeMutable) { + return maybeMutable; +} +function parseFileIdentifier(fileIdentifier) { + if (!fileIdentifier.includes(":")) { + fileIdentifier = `local:${fileIdentifier}`; + } + const colonIndex = fileIdentifier.indexOf(":"); + const namespace = fileIdentifier.slice(0, colonIndex); + const content = fileIdentifier.slice(colonIndex + 1); + switch (namespace) { + case "local": { + if (content.includes("/") || content.includes("\\") || content.length === 0) { + throw new Error(`Invalid local file name: ${content}.`); + } + return { + type: "local", + fileName: content + }; + } + case "base64": { + return { + type: "base64", + base64Data: content + }; + } + default: { + throw new Error(`Unknown file identifier namespace: ${namespace}.`); + } + } +} +function promisifyAbortSignal(abortSignal) { + return new Promise((_resolve2, reject) => { + if (abortSignal.aborted) { + reject(abortSignal.reason); + return; + } + abortSignal.addEventListener("abort", () => { + reject(abortSignal.reason); + }, { once: true }); + }); +} +function raceWithAbortSignal(promise, abortSignal) { + return Promise.race([promise, promisifyAbortSignal(abortSignal)]); +} +function failOk(schema) { + return external_exports.any().transform((val2) => schema.safeParse(val2).success ? val2 : void 0); +} +function serializeError(error) { + if (typeof error === "object") { + const title = error.title ?? error.lmstudioRawError ?? error.message ?? "Unknown error"; + return serializedLMSExtendedErrorSchema.parse({ + title, + cause: error.cause, + suggestion: error.suggestion, + errorData: error.errorData, + displayData: error.displayData, + stack: error.stack, + rootTitle: title + }); + } else { + const title = String(error); + return { + title, + rootTitle: title + }; + } +} +function attachSerializedErrorData(error, serialized) { + const untypedError = error; + untypedError.title = serialized.title; + if (serialized.cause !== void 0) { + untypedError.cause = serialized.cause; + } + if (serialized.suggestion !== void 0) { + untypedError.suggestion = serialized.suggestion; + } + if (serialized.errorData !== void 0) { + untypedError.errorData = serialized.errorData; + } +} +function fromSerializedError(error, message = "Rehydrated error", replacementStack) { + const result = new Error(error.rootTitle); + attachSerializedErrorData(result, error); + if (error.displayData !== void 0) { + result.displayData = error.displayData; + } + if (replacementStack !== void 0) { + if (error.stack !== void 0) { + result.stack = `Error: ${message} +${replacementStack} +- Caused By: ${error.stack}`; + } else { + result.stack = `Error: ${message} +${replacementStack}`; + } + } else { + if (error.stack !== void 0) { + result.stack = `Error: ${message} +${result.stack.substring(error.stack.indexOf("\n") + 1)} +- Caused By: ` + error.stack; + } else { + result.message += ` - caused by error without stack (${error.title})`; + } + } + return result; +} +function convertGPUSettingToGPUSplitConfig(gpuSetting) { + return { + strategy: gpuSetting?.splitStrategy == "favorMainGpu" ? "priorityOrder" : gpuSetting?.splitStrategy ?? "evenly", + disabledGpus: gpuSetting?.disabledGpus ?? [], + priority: gpuSetting?.mainGpu ? [gpuSetting.mainGpu] : [], + customRatio: [] + }; +} +function safeCallCallback(logger2, name, callback2, args) { + if (callback2 === void 0) { + return; + } + try { + const maybePromise = callback2(...args); + if (typeof maybePromise === "object" && typeof maybePromise.catch === "function") { + maybePromise.catch((error) => { + logger2.error(`Error in the ${name} callback (triggered asynchronously):`, error); + }); + } + } catch (error) { + logger2.error(`Error in the ${name} callback:`, error); + } +} +function isSimpleLogger(logger2) { + return logger2?.isSimpleLogger === true; +} +function isChatMessageInputAsOpposeToChatMessageData(chatMessageInput) { + return !Array.isArray(chatMessageInput.content); +} +function isChatMessageInputAsOpposeToChatHistoryData(chatMessageInput) { + return !("messages" in chatMessageInput); +} +function chatMessageInputToChatMessageData(chatMessageInput) { + const { role, content, images } = chatMessageInput; + const parts = []; + if (images === void 0 || images.length === 0) { + if (content === void 0) { + parts.push({ + type: "text", + text: "" + }); + } + } else { + for (const file of images) { + parts.push({ + type: "file", + identifier: file.identifier, + name: file.name, + fileType: file.type, + sizeBytes: file.sizeBytes + }); + } + } + if (content !== void 0) { + parts.push({ + type: "text", + text: content + }); + } + return { + role: role ?? "user", + content: parts + }; +} +function kvConfigToMap(config) { + return new Map(config.fields.map((f4) => [f4.key, f4.value])); +} +function mapToKVConfig(map3) { + return { + fields: Array.from(map3.entries()).map(([key, value]) => ({ key, value })) + }; +} +function collapseKVStackRaw(configs) { + const map3 = /* @__PURE__ */ new Map(); + for (const config of configs) { + for (const { key, value } of config.fields) { + map3.set(key, value); + } + } + return mapToKVConfig(map3); +} +function singleLayerKVConfigStackOf(name, config) { + return { + layers: [ + { + layerName: name, + config + } + ] + }; +} +function addKVConfigToStack(stack, newLayerName, newLayerConfig) { + return { + layers: [ + ...stack.layers, + { + layerName: newLayerName, + config: newLayerConfig + } + ] + }; +} +function deepEquals(a3, b4) { + if (a3 === b4) { + return true; + } + if (typeof a3 !== "object" || typeof b4 !== "object") { + return false; + } + if (a3 === null || b4 === null) { + return false; + } + if (Array.isArray(a3) !== Array.isArray(b4)) { + return false; + } + if (Array.isArray(a3)) { + if (a3.length !== b4?.length) { + return false; + } + for (let i7 = 0; i7 < a3.length; i7++) { + if (!deepEquals(a3[i7], b4[i7])) { + return false; + } + } + return true; + } + const aKeys = new Set(Object.keys(a3)); + const bKeys = new Set(Object.keys(b4)); + if (aKeys.size !== bKeys.size) { + return false; + } + for (const key of aKeys) { + if (!bKeys.has(key)) { + return false; + } + if (!deepEquals(a3[key], b4[key])) { + return false; + } + } + return true; +} +function quoteString(str2, empty) { + if (str2 === void 0 || str2 === "") { + return empty ?? '""'; + } + return JSON.stringify(str2); +} +function quoteStringWithManualEscape(str2, empty) { + return quoteString(str2?.replace(/\\n/g, "\n"), empty); +} +function maybeFalseNumberToCheckboxNumeric(maybeFalseNumber, valueWhenUnchecked) { + if (maybeFalseNumber === void 0) { + return void 0; + } + if (maybeFalseNumber === false) { + return { checked: false, value: valueWhenUnchecked }; + } + return { checked: true, value: maybeFalseNumber }; +} +function llmPredictionConfigToKVConfig(config) { + const top = llmPredictionConfigSchematics.buildPartialConfig({ + "temperature": config.temperature, + "contextOverflowPolicy": config.contextOverflowPolicy, + "maxPredictedTokens": maybeFalseNumberToCheckboxNumeric(config.maxTokens, 1), + "stopStrings": config.stopStrings, + "toolCallStopStrings": config.toolCallStopStrings, + "structured": config.structured, + "tools": config.rawTools, + "toolNaming": config.toolNaming, + "topKSampling": config.topKSampling, + "repeatPenalty": maybeFalseNumberToCheckboxNumeric(config.repeatPenalty, 1.1), + "minPSampling": maybeFalseNumberToCheckboxNumeric(config.minPSampling, 0.05), + "topPSampling": maybeFalseNumberToCheckboxNumeric(config.topPSampling, 0.95), + "llama.xtcProbability": maybeFalseNumberToCheckboxNumeric(config.xtcProbability, 0), + "llama.xtcThreshold": maybeFalseNumberToCheckboxNumeric(config.xtcThreshold, 0), + "logProbs": maybeFalseNumberToCheckboxNumeric(config.logProbs, 0), + "llama.cpuThreads": config.cpuThreads, + "promptTemplate": config.promptTemplate, + "speculativeDecoding.draftModel": config.draftModel, + "speculativeDecoding.numDraftTokensExact": config.speculativeDecodingNumDraftTokensExact, + "speculativeDecoding.minDraftLengthToConsider": config.speculativeDecodingMinDraftLengthToConsider, + "speculativeDecoding.minContinueDraftingProbability": config.speculativeDecodingMinContinueDraftingProbability, + "reasoning.parsing": config.reasoningParsing + }); + if (config.raw !== void 0) { + return collapseKVStackRaw([config.raw, top]); + } + return top; +} +function requireHelpers() { + if (hasRequiredHelpers) return helpers; + hasRequiredHelpers = 1; + var ValidationError = helpers.ValidationError = function ValidationError2(message, instance, schema, path6, name, argument) { + if (Array.isArray(path6)) { + this.path = path6; + this.property = path6.reduce(function(sum, item) { + return sum + makeSuffix(item); + }, "instance"); + } else if (path6 !== void 0) { + this.property = path6; + } + if (message) { + this.message = message; + } + if (schema) { + var id = schema.$id || schema.id; + this.schema = id || schema; + } + if (instance !== void 0) { + this.instance = instance; + } + this.name = name; + this.argument = argument; + this.stack = this.toString(); + }; + ValidationError.prototype.toString = function toString2() { + return this.property + " " + this.message; + }; + var ValidatorResult = helpers.ValidatorResult = function ValidatorResult2(instance, schema, options, ctx) { + this.instance = instance; + this.schema = schema; + this.options = options; + this.path = ctx.path; + this.propertyPath = ctx.propertyPath; + this.errors = []; + this.throwError = options && options.throwError; + this.throwFirst = options && options.throwFirst; + this.throwAll = options && options.throwAll; + this.disableFormat = options && options.disableFormat === true; + }; + ValidatorResult.prototype.addError = function addError(detail) { + var err; + if (typeof detail == "string") { + err = new ValidationError(detail, this.instance, this.schema, this.path); + } else { + if (!detail) throw new Error("Missing error detail"); + if (!detail.message) throw new Error("Missing error message"); + if (!detail.name) throw new Error("Missing validator type"); + err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument); + } + this.errors.push(err); + if (this.throwFirst) { + throw new ValidatorResultError(this); + } else if (this.throwError) { + throw err; + } + return err; + }; + ValidatorResult.prototype.importErrors = function importErrors(res) { + if (typeof res == "string" || res && res.validatorType) { + this.addError(res); + } else if (res && res.errors) { + this.errors = this.errors.concat(res.errors); + } + }; + function stringizer(v4, i7) { + return i7 + ": " + v4.toString() + "\n"; + } + ValidatorResult.prototype.toString = function toString2(res) { + return this.errors.map(stringizer).join(""); + }; + Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() { + return !this.errors.length; + } }); + helpers.ValidatorResultError = ValidatorResultError; + function ValidatorResultError(result) { + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, ValidatorResultError); + } + this.instance = result.instance; + this.schema = result.schema; + this.options = result.options; + this.errors = result.errors; + } + ValidatorResultError.prototype = new Error(); + ValidatorResultError.prototype.constructor = ValidatorResultError; + ValidatorResultError.prototype.name = "Validation Error"; + var SchemaError = helpers.SchemaError = function SchemaError2(msg, schema) { + this.message = msg; + this.schema = schema; + Error.call(this, msg); + if (typeof Error.captureStackTrace === "function") { + Error.captureStackTrace(this, SchemaError2); + } + }; + SchemaError.prototype = Object.create( + Error.prototype, + { + constructor: { value: SchemaError, enumerable: false }, + name: { value: "SchemaError", enumerable: false } + } + ); + var SchemaContext = helpers.SchemaContext = function SchemaContext2(schema, options, path6, base, schemas) { + this.schema = schema; + this.options = options; + if (Array.isArray(path6)) { + this.path = path6; + this.propertyPath = path6.reduce(function(sum, item) { + return sum + makeSuffix(item); + }, "instance"); + } else { + this.propertyPath = path6; + } + this.base = base; + this.schemas = schemas; + }; + SchemaContext.prototype.resolve = function resolve2(target) { + return (() => resolveUrl(this.base, target))(); + }; + SchemaContext.prototype.makeChild = function makeChild(schema, propertyName) { + var path6 = propertyName === void 0 ? this.path : this.path.concat([propertyName]); + var id = schema.$id || schema.id; + let base = (() => resolveUrl(this.base, id || ""))(); + var ctx = new SchemaContext(schema, this.options, path6, base, Object.create(this.schemas)); + if (id && !ctx.schemas[base]) { + ctx.schemas[base] = schema; + } + return ctx; + }; + var FORMAT_REGEXPS = helpers.FORMAT_REGEXPS = { + // 7.3.1. Dates, Times, and Duration + "date-time": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/, + "date": /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/, + "time": /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/, + "duration": /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i, + // 7.3.2. Email Addresses + // TODO: fix the email production + "email": /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/, + "idn-email": /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u, + // 7.3.3. Hostnames + // 7.3.4. IP Addresses + "ip-address": /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, + // FIXME whitespace is invalid + "ipv6": /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/, + // 7.3.5. Resource Identifiers + // TODO: A more accurate regular expression for "uri" goes: + // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)? + "uri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, + "uri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/, + "iri": /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, + "iri-reference": /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u, + "uuid": /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + // 7.3.6. uri-template + "uri-template": /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu, + // 7.3.7. JSON Pointers + "json-pointer": /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu, + "relative-json-pointer": /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu, + // hostname regex from: http://stackoverflow.com/a/1420225/5628 + "hostname": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, + "host-name": /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, + "utc-millisec": function(input) { + return typeof input === "string" && parseFloat(input) === parseInt(input, 10) && !isNaN(input); + }, + // 7.3.8. regex + "regex": function(input) { + var result = true; + try { + new RegExp(input); + } catch (e9) { + result = false; + } + return result; + }, + // Other definitions + // "style" was removed from JSON Schema in draft-4 and is deprecated + "style": /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/, + // "color" was removed from JSON Schema in draft-4 and is deprecated + "color": /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/, + "phone": /^\+(?:[0-9] ?){6,14}[0-9]$/, + "alpha": /^[a-zA-Z]+$/, + "alphanumeric": /^[a-zA-Z0-9]+$/ + }; + FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex; + FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex; + FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS["ip-address"]; + helpers.isFormat = function isFormat(input, format2, validator2) { + if (typeof input === "string" && FORMAT_REGEXPS[format2] !== void 0) { + if (FORMAT_REGEXPS[format2] instanceof RegExp) { + return FORMAT_REGEXPS[format2].test(input); + } + if (typeof FORMAT_REGEXPS[format2] === "function") { + return FORMAT_REGEXPS[format2](input); + } + } else if (validator2 && validator2.customFormats && typeof validator2.customFormats[format2] === "function") { + return validator2.customFormats[format2](input); + } + return true; + }; + var makeSuffix = helpers.makeSuffix = function makeSuffix2(key) { + key = key.toString(); + if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) { + return "." + key; + } + if (key.match(/^\d+$/)) { + return "[" + key + "]"; + } + return "[" + JSON.stringify(key) + "]"; + }; + helpers.deepCompareStrict = function deepCompareStrict(a3, b4) { + if (typeof a3 !== typeof b4) { + return false; + } + if (Array.isArray(a3)) { + if (!Array.isArray(b4)) { + return false; + } + if (a3.length !== b4.length) { + return false; + } + return a3.every(function(v4, i7) { + return deepCompareStrict(a3[i7], b4[i7]); + }); + } + if (typeof a3 === "object") { + if (!a3 || !b4) { + return a3 === b4; + } + var aKeys = Object.keys(a3); + var bKeys = Object.keys(b4); + if (aKeys.length !== bKeys.length) { + return false; + } + return aKeys.every(function(v4) { + return deepCompareStrict(a3[v4], b4[v4]); + }); + } + return a3 === b4; + }; + function deepMerger(target, dst, e9, i7) { + if (typeof e9 === "object") { + dst[i7] = deepMerge(target[i7], e9); + } else { + if (target.indexOf(e9) === -1) { + dst.push(e9); + } + } + } + function copyist(src, dst, key) { + dst[key] = src[key]; + } + function copyistWithDeepMerge(target, src, dst, key) { + if (typeof src[key] !== "object" || !src[key]) { + dst[key] = src[key]; + } else { + if (!target[key]) { + dst[key] = src[key]; + } else { + dst[key] = deepMerge(target[key], src[key]); + } + } + } + function deepMerge(target, src) { + var array = Array.isArray(src); + var dst = array && [] || {}; + if (array) { + target = target || []; + dst = dst.concat(target); + src.forEach(deepMerger.bind(null, target, dst)); + } else { + if (target && typeof target === "object") { + Object.keys(target).forEach(copyist.bind(null, target, dst)); + } + Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst)); + } + return dst; + } + helpers.deepMerge = deepMerge; + helpers.objectGetPath = function objectGetPath(o9, s6) { + var parts = s6.split("/").slice(1); + var k2; + while (typeof (k2 = parts.shift()) == "string") { + var n7 = decodeURIComponent(k2.replace(/~0/, "~").replace(/~1/g, "/")); + if (!(n7 in o9)) return; + o9 = o9[n7]; + } + return o9; + }; + function pathEncoder(v4) { + return "/" + encodeURIComponent(v4).replace(/~/g, "%7E"); + } + helpers.encodePath = function encodePointer(a3) { + return a3.map(pathEncoder).join(""); + }; + helpers.getDecimalPlaces = function getDecimalPlaces(number) { + var decimalPlaces = 0; + if (isNaN(number)) return decimalPlaces; + if (typeof number !== "number") { + number = Number(number); + } + var parts = number.toString().split("e"); + if (parts.length === 2) { + if (parts[1][0] !== "-") { + return decimalPlaces; + } else { + decimalPlaces = Number(parts[1].slice(1)); + } + } + var decimalParts = parts[0].split("."); + if (decimalParts.length === 2) { + decimalPlaces += decimalParts[1].length; + } + return decimalPlaces; + }; + helpers.isSchema = function isSchema(val2) { + return typeof val2 === "object" && val2 || typeof val2 === "boolean"; + }; + var resolveUrl = helpers.resolveUrl = function resolveUrl2(from2, to2) { + const resolvedUrl = new URL(to2, new URL(from2, "resolve://")); + if (resolvedUrl.protocol === "resolve:") { + const { pathname, search: search2, hash } = resolvedUrl; + return pathname + search2 + hash; + } + return resolvedUrl.toString(); + }; + return helpers; +} +function requireAttribute() { + if (hasRequiredAttribute) return attribute_1; + hasRequiredAttribute = 1; + var helpers2 = requireHelpers(); + var ValidatorResult = helpers2.ValidatorResult; + var SchemaError = helpers2.SchemaError; + var attribute = {}; + attribute.ignoreProperties = { + // informative properties + "id": true, + "default": true, + "description": true, + "title": true, + // arguments to other properties + "additionalItems": true, + "then": true, + "else": true, + // special-handled properties + "$schema": true, + "$ref": true, + "extends": true + }; + var validators = attribute.validators = {}; + validators.type = function validateType(instance, schema, options, ctx) { + if (instance === void 0) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + var types2 = Array.isArray(schema.type) ? schema.type : [schema.type]; + if (!types2.some(this.testType.bind(this, instance, schema, options, ctx))) { + var list = types2.map(function(v4) { + if (!v4) return; + var id = v4.$id || v4.id; + return id ? "<" + id + ">" : v4 + ""; + }); + result.addError({ + name: "type", + argument: list, + message: "is not of a type(s) " + list + }); + } + return result; + }; + function testSchemaNoThrow(instance, options, ctx, callback2, schema) { + var throwError = options.throwError; + var throwAll = options.throwAll; + options.throwError = false; + options.throwAll = false; + var res = this.validateSchema(instance, schema, options, ctx); + options.throwError = throwError; + options.throwAll = throwAll; + if (!res.valid && callback2 instanceof Function) { + callback2(res); + } + return res.valid; + } + validators.anyOf = function validateAnyOf(instance, schema, options, ctx) { + if (instance === void 0) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + var inner2 = new ValidatorResult(instance, schema, options, ctx); + if (!Array.isArray(schema.anyOf)) { + throw new SchemaError("anyOf must be an array"); + } + if (!schema.anyOf.some( + testSchemaNoThrow.bind( + this, + instance, + options, + ctx, + function(res) { + inner2.importErrors(res); + } + ) + )) { + var list = schema.anyOf.map(function(v4, i7) { + var id = v4.$id || v4.id; + if (id) return "<" + id + ">"; + return v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]"; + }); + if (options.nestedErrors) { + result.importErrors(inner2); + } + result.addError({ + name: "anyOf", + argument: list, + message: "is not any of " + list.join(",") + }); + } + return result; + }; + validators.allOf = function validateAllOf(instance, schema, options, ctx) { + if (instance === void 0) { + return null; + } + if (!Array.isArray(schema.allOf)) { + throw new SchemaError("allOf must be an array"); + } + var result = new ValidatorResult(instance, schema, options, ctx); + var self2 = this; + schema.allOf.forEach(function(v4, i7) { + var valid = self2.validateSchema(instance, v4, options, ctx); + if (!valid.valid) { + var id = v4.$id || v4.id; + var msg = id || v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]"; + result.addError({ + name: "allOf", + argument: { id: msg, length: valid.errors.length, valid }, + message: "does not match allOf schema " + msg + " with " + valid.errors.length + " error[s]:" + }); + result.importErrors(valid); + } + }); + return result; + }; + validators.oneOf = function validateOneOf(instance, schema, options, ctx) { + if (instance === void 0) { + return null; + } + if (!Array.isArray(schema.oneOf)) { + throw new SchemaError("oneOf must be an array"); + } + var result = new ValidatorResult(instance, schema, options, ctx); + var inner2 = new ValidatorResult(instance, schema, options, ctx); + var count = schema.oneOf.filter( + testSchemaNoThrow.bind( + this, + instance, + options, + ctx, + function(res) { + inner2.importErrors(res); + } + ) + ).length; + var list = schema.oneOf.map(function(v4, i7) { + var id = v4.$id || v4.id; + return id || v4.title && JSON.stringify(v4.title) || v4["$ref"] && "<" + v4["$ref"] + ">" || "[subschema " + i7 + "]"; + }); + if (count !== 1) { + if (options.nestedErrors) { + result.importErrors(inner2); + } + result.addError({ + name: "oneOf", + argument: list, + message: "is not exactly one from " + list.join(",") + }); + } + return result; + }; + validators.if = function validateIf(instance, schema, options, ctx) { + if (instance === void 0) return null; + if (!helpers2.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema'); + var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if); + var result = new ValidatorResult(instance, schema, options, ctx); + var res; + if (ifValid) { + if (schema.then === void 0) return; + if (!helpers2.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema'); + res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then)); + result.importErrors(res); + } else { + if (schema.else === void 0) return; + if (!helpers2.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema'); + res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else)); + result.importErrors(res); + } + return result; + }; + function getEnumerableProperty(object, key) { + if (Object.hasOwnProperty.call(object, key)) return object[key]; + if (!(key in object)) return; + while (object = Object.getPrototypeOf(object)) { + if (Object.propertyIsEnumerable.call(object, key)) return object[key]; + } + } + validators.propertyNames = function validatePropertyNames(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var subschema = schema.propertyNames !== void 0 ? schema.propertyNames : {}; + if (!helpers2.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); + for (var property in instance) { + if (getEnumerableProperty(instance, property) !== void 0) { + var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); + result.importErrors(res); + } + } + return result; + }; + validators.properties = function validateProperties(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var properties = schema.properties || {}; + for (var property in properties) { + var subschema = properties[property]; + if (subschema === void 0) { + continue; + } else if (subschema === null) { + throw new SchemaError('Unexpected null, expected schema in "properties"'); + } + if (typeof options.preValidateProperty == "function") { + options.preValidateProperty(instance, property, subschema, options, ctx); + } + var prop = getEnumerableProperty(instance, property); + var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); + if (res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } + return result; + }; + function testAdditionalProperty(instance, schema, options, ctx, property, result) { + if (!this.types.object(instance)) return; + if (schema.properties && schema.properties[property] !== void 0) { + return; + } + if (schema.additionalProperties === false) { + result.addError({ + name: "additionalProperties", + argument: property, + message: "is not allowed to have the additional property " + JSON.stringify(property) + }); + } else { + var additionalProperties = schema.additionalProperties || {}; + if (typeof options.preValidateProperty == "function") { + options.preValidateProperty(instance, property, additionalProperties, options, ctx); + } + var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); + if (res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } + } + validators.patternProperties = function validatePatternProperties(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var patternProperties = schema.patternProperties || {}; + for (var property in instance) { + var test = true; + for (var pattern in patternProperties) { + var subschema = patternProperties[pattern]; + if (subschema === void 0) { + continue; + } else if (subschema === null) { + throw new SchemaError('Unexpected null, expected schema in "patternProperties"'); + } + try { + var regexp = new RegExp(pattern, "u"); + } catch (_e2) { + regexp = new RegExp(pattern); + } + if (!regexp.test(property)) { + continue; + } + test = false; + if (typeof options.preValidateProperty == "function") { + options.preValidateProperty(instance, property, subschema, options, ctx); + } + var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); + if (res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } + if (test) { + testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); + } + } + return result; + }; + validators.additionalProperties = function validateAdditionalProperties(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + if (schema.patternProperties) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + for (var property in instance) { + testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); + } + return result; + }; + validators.minProperties = function validateMinProperties(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var keys2 = Object.keys(instance); + if (!(keys2.length >= schema.minProperties)) { + result.addError({ + name: "minProperties", + argument: schema.minProperties, + message: "does not meet minimum property length of " + schema.minProperties + }); + } + return result; + }; + validators.maxProperties = function validateMaxProperties(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var keys2 = Object.keys(instance); + if (!(keys2.length <= schema.maxProperties)) { + result.addError({ + name: "maxProperties", + argument: schema.maxProperties, + message: "does not meet maximum property length of " + schema.maxProperties + }); + } + return result; + }; + validators.items = function validateItems(instance, schema, options, ctx) { + var self2 = this; + if (!this.types.array(instance)) return; + if (schema.items === void 0) return; + var result = new ValidatorResult(instance, schema, options, ctx); + instance.every(function(value, i7) { + if (Array.isArray(schema.items)) { + var items = schema.items[i7] === void 0 ? schema.additionalItems : schema.items[i7]; + } else { + var items = schema.items; + } + if (items === void 0) { + return true; + } + if (items === false) { + result.addError({ + name: "items", + message: "additionalItems not permitted" + }); + return false; + } + var res = self2.validateSchema(value, items, options, ctx.makeChild(items, i7)); + if (res.instance !== result.instance[i7]) result.instance[i7] = res.instance; + result.importErrors(res); + return true; + }); + return result; + }; + validators.contains = function validateContains(instance, schema, options, ctx) { + var self2 = this; + if (!this.types.array(instance)) return; + if (schema.contains === void 0) return; + if (!helpers2.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema'); + var result = new ValidatorResult(instance, schema, options, ctx); + var count = instance.some(function(value, i7) { + var res = self2.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i7)); + return res.errors.length === 0; + }); + if (count === false) { + result.addError({ + name: "contains", + argument: schema.contains, + message: "must contain an item matching given schema" + }); + } + return result; + }; + validators.minimum = function validateMinimum(instance, schema, options, ctx) { + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) { + if (!(instance > schema.minimum)) { + result.addError({ + name: "minimum", + argument: schema.minimum, + message: "must be greater than " + schema.minimum + }); + } + } else { + if (!(instance >= schema.minimum)) { + result.addError({ + name: "minimum", + argument: schema.minimum, + message: "must be greater than or equal to " + schema.minimum + }); + } + } + return result; + }; + validators.maximum = function validateMaximum(instance, schema, options, ctx) { + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) { + if (!(instance < schema.maximum)) { + result.addError({ + name: "maximum", + argument: schema.maximum, + message: "must be less than " + schema.maximum + }); + } + } else { + if (!(instance <= schema.maximum)) { + result.addError({ + name: "maximum", + argument: schema.maximum, + message: "must be less than or equal to " + schema.maximum + }); + } + } + return result; + }; + validators.exclusiveMinimum = function validateExclusiveMinimum(instance, schema, options, ctx) { + if (typeof schema.exclusiveMinimum === "boolean") return; + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var valid = instance > schema.exclusiveMinimum; + if (!valid) { + result.addError({ + name: "exclusiveMinimum", + argument: schema.exclusiveMinimum, + message: "must be strictly greater than " + schema.exclusiveMinimum + }); + } + return result; + }; + validators.exclusiveMaximum = function validateExclusiveMaximum(instance, schema, options, ctx) { + if (typeof schema.exclusiveMaximum === "boolean") return; + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var valid = instance < schema.exclusiveMaximum; + if (!valid) { + result.addError({ + name: "exclusiveMaximum", + argument: schema.exclusiveMaximum, + message: "must be strictly less than " + schema.exclusiveMaximum + }); + } + return result; + }; + var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy2(instance, schema, options, ctx, validationType, errorMessage) { + if (!this.types.number(instance)) return; + var validationArgument = schema[validationType]; + if (validationArgument == 0) { + throw new SchemaError(validationType + " cannot be zero"); + } + var result = new ValidatorResult(instance, schema, options, ctx); + var instanceDecimals = helpers2.getDecimalPlaces(instance); + var divisorDecimals = helpers2.getDecimalPlaces(validationArgument); + var maxDecimals = Math.max(instanceDecimals, divisorDecimals); + var multiplier = Math.pow(10, maxDecimals); + if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { + result.addError({ + name: validationType, + argument: validationArgument, + message: errorMessage + JSON.stringify(validationArgument) + }); + } + return result; + }; + validators.multipleOf = function validateMultipleOf(instance, schema, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); + }; + validators.divisibleBy = function validateDivisibleBy(instance, schema, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); + }; + validators.required = function validateRequired(instance, schema, options, ctx) { + var result = new ValidatorResult(instance, schema, options, ctx); + if (instance === void 0 && schema.required === true) { + result.addError({ + name: "required", + message: "is required" + }); + } else if (this.types.object(instance) && Array.isArray(schema.required)) { + schema.required.forEach(function(n7) { + if (getEnumerableProperty(instance, n7) === void 0) { + result.addError({ + name: "required", + argument: n7, + message: "requires property " + JSON.stringify(n7) + }); + } + }); + } + return result; + }; + validators.pattern = function validatePattern(instance, schema, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var pattern = schema.pattern; + try { + var regexp = new RegExp(pattern, "u"); + } catch (_e2) { + regexp = new RegExp(pattern); + } + if (!instance.match(regexp)) { + result.addError({ + name: "pattern", + argument: schema.pattern, + message: "does not match pattern " + JSON.stringify(schema.pattern.toString()) + }); + } + return result; + }; + validators.format = function validateFormat(instance, schema, options, ctx) { + if (instance === void 0) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!result.disableFormat && !helpers2.isFormat(instance, schema.format, this)) { + result.addError({ + name: "format", + argument: schema.format, + message: "does not conform to the " + JSON.stringify(schema.format) + " format" + }); + } + return result; + }; + validators.minLength = function validateMinLength(instance, schema, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var hsp = instance.match(/[\uDC00-\uDFFF]/g); + var length = instance.length - (hsp ? hsp.length : 0); + if (!(length >= schema.minLength)) { + result.addError({ + name: "minLength", + argument: schema.minLength, + message: "does not meet minimum length of " + schema.minLength + }); + } + return result; + }; + validators.maxLength = function validateMaxLength(instance, schema, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var hsp = instance.match(/[\uDC00-\uDFFF]/g); + var length = instance.length - (hsp ? hsp.length : 0); + if (!(length <= schema.maxLength)) { + result.addError({ + name: "maxLength", + argument: schema.maxLength, + message: "does not meet maximum length of " + schema.maxLength + }); + } + return result; + }; + validators.minItems = function validateMinItems(instance, schema, options, ctx) { + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!(instance.length >= schema.minItems)) { + result.addError({ + name: "minItems", + argument: schema.minItems, + message: "does not meet minimum length of " + schema.minItems + }); + } + return result; + }; + validators.maxItems = function validateMaxItems(instance, schema, options, ctx) { + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!(instance.length <= schema.maxItems)) { + result.addError({ + name: "maxItems", + argument: schema.maxItems, + message: "does not meet maximum length of " + schema.maxItems + }); + } + return result; + }; + function testArrays(v4, i7, a3) { + var j3, len = a3.length; + for (j3 = i7 + 1, len; j3 < len; j3++) { + if (helpers2.deepCompareStrict(v4, a3[j3])) { + return false; + } + } + return true; + } + validators.uniqueItems = function validateUniqueItems(instance, schema, options, ctx) { + if (schema.uniqueItems !== true) return; + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!instance.every(testArrays)) { + result.addError({ + name: "uniqueItems", + message: "contains duplicate item" + }); + } + return result; + }; + validators.dependencies = function validateDependencies(instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + for (var property in schema.dependencies) { + if (instance[property] === void 0) { + continue; + } + var dep = schema.dependencies[property]; + var childContext = ctx.makeChild(dep, property); + if (typeof dep == "string") { + dep = [dep]; + } + if (Array.isArray(dep)) { + dep.forEach(function(prop) { + if (instance[prop] === void 0) { + result.addError({ + // FIXME there's two different "dependencies" errors here with slightly different outputs + // Can we make these the same? Or should we create different error types? + name: "dependencies", + argument: childContext.propertyPath, + message: "property " + prop + " not found, required by " + childContext.propertyPath + }); + } + }); + } else { + var res = this.validateSchema(instance, dep, options, childContext); + if (result.instance !== res.instance) result.instance = res.instance; + if (res && res.errors.length) { + result.addError({ + name: "dependencies", + argument: childContext.propertyPath, + message: "does not meet dependency required by " + childContext.propertyPath + }); + result.importErrors(res); + } + } + } + return result; + }; + validators["enum"] = function validateEnum(instance, schema, options, ctx) { + if (instance === void 0) { + return null; + } + if (!Array.isArray(schema["enum"])) { + throw new SchemaError("enum expects an array", schema); + } + var result = new ValidatorResult(instance, schema, options, ctx); + if (!schema["enum"].some(helpers2.deepCompareStrict.bind(null, instance))) { + result.addError({ + name: "enum", + argument: schema["enum"], + message: "is not one of enum values: " + schema["enum"].map(String).join(",") + }); + } + return result; + }; + validators["const"] = function validateEnum(instance, schema, options, ctx) { + if (instance === void 0) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + if (!helpers2.deepCompareStrict(schema["const"], instance)) { + result.addError({ + name: "const", + argument: schema["const"], + message: "does not exactly match expected constant: " + schema["const"] + }); + } + return result; + }; + validators.not = validators.disallow = function validateNot(instance, schema, options, ctx) { + var self2 = this; + if (instance === void 0) return null; + var result = new ValidatorResult(instance, schema, options, ctx); + var notTypes = schema.not || schema.disallow; + if (!notTypes) return null; + if (!Array.isArray(notTypes)) notTypes = [notTypes]; + notTypes.forEach(function(type) { + if (self2.testType(instance, schema, options, ctx, type)) { + var id = type && (type.$id || type.id); + var schemaId = id || type; + result.addError({ + name: "not", + argument: schemaId, + message: "is of prohibited type " + schemaId + }); + } + }); + return result; + }; + attribute_1 = attribute; + return attribute_1; +} +function requireScan() { + if (hasRequiredScan) return scan; + hasRequiredScan = 1; + var helpers2 = requireHelpers(); + scan.SchemaScanResult = SchemaScanResult; + function SchemaScanResult(found, ref) { + this.id = found; + this.ref = ref; + } + scan.scan = function scan2(base, schema) { + function scanSchema(baseuri, schema2) { + if (!schema2 || typeof schema2 != "object") return; + if (schema2.$ref) { + let resolvedUri = helpers2.resolveUrl(baseuri, schema2.$ref); + ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri] + 1 : 0; + return; + } + var id = schema2.$id || schema2.id; + let resolvedBase = helpers2.resolveUrl(baseuri, id); + var ourBase = id ? resolvedBase : baseuri; + if (ourBase) { + if (ourBase.indexOf("#") < 0) ourBase += "#"; + if (found[ourBase]) { + if (!helpers2.deepCompareStrict(found[ourBase], schema2)) { + throw new Error("Schema <" + ourBase + "> already exists with different definition"); + } + return found[ourBase]; + } + found[ourBase] = schema2; + if (ourBase[ourBase.length - 1] == "#") { + found[ourBase.substring(0, ourBase.length - 1)] = schema2; + } + } + scanArray(ourBase + "/items", Array.isArray(schema2.items) ? schema2.items : [schema2.items]); + scanArray(ourBase + "/extends", Array.isArray(schema2.extends) ? schema2.extends : [schema2.extends]); + scanSchema(ourBase + "/additionalItems", schema2.additionalItems); + scanObject(ourBase + "/properties", schema2.properties); + scanSchema(ourBase + "/additionalProperties", schema2.additionalProperties); + scanObject(ourBase + "/definitions", schema2.definitions); + scanObject(ourBase + "/patternProperties", schema2.patternProperties); + scanObject(ourBase + "/dependencies", schema2.dependencies); + scanArray(ourBase + "/disallow", schema2.disallow); + scanArray(ourBase + "/allOf", schema2.allOf); + scanArray(ourBase + "/anyOf", schema2.anyOf); + scanArray(ourBase + "/oneOf", schema2.oneOf); + scanSchema(ourBase + "/not", schema2.not); + } + function scanArray(baseuri, schemas) { + if (!Array.isArray(schemas)) return; + for (var i7 = 0; i7 < schemas.length; i7++) { + scanSchema(baseuri + "/" + i7, schemas[i7]); + } + } + function scanObject(baseuri, schemas) { + if (!schemas || typeof schemas != "object") return; + for (var p4 in schemas) { + scanSchema(baseuri + "/" + p4, schemas[p4]); + } + } + var found = {}; + var ref = {}; + scanSchema(base, schema); + return new SchemaScanResult(found, ref); + }; + return scan; +} +function requireValidator() { + if (hasRequiredValidator) return validator; + hasRequiredValidator = 1; + var attribute = requireAttribute(); + var helpers2 = requireHelpers(); + var scanSchema = requireScan().scan; + var ValidatorResult = helpers2.ValidatorResult; + var ValidatorResultError = helpers2.ValidatorResultError; + var SchemaError = helpers2.SchemaError; + var SchemaContext = helpers2.SchemaContext; + var anonymousBase = "/"; + var Validator2 = function Validator3() { + this.customFormats = Object.create(Validator3.prototype.customFormats); + this.schemas = {}; + this.unresolvedRefs = []; + this.types = Object.create(types2); + this.attributes = Object.create(attribute.validators); + }; + Validator2.prototype.customFormats = {}; + Validator2.prototype.schemas = null; + Validator2.prototype.types = null; + Validator2.prototype.attributes = null; + Validator2.prototype.unresolvedRefs = null; + Validator2.prototype.addSchema = function addSchema(schema, base) { + var self2 = this; + if (!schema) { + return null; + } + var scan2 = scanSchema(base || anonymousBase, schema); + var ourUri = base || schema.$id || schema.id; + for (var uri in scan2.id) { + this.schemas[uri] = scan2.id[uri]; + } + for (var uri in scan2.ref) { + this.unresolvedRefs.push(uri); + } + this.unresolvedRefs = this.unresolvedRefs.filter(function(uri2) { + return typeof self2.schemas[uri2] === "undefined"; + }); + return this.schemas[ourUri]; + }; + Validator2.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) { + if (!Array.isArray(schemas)) return; + for (var i7 = 0; i7 < schemas.length; i7++) { + this.addSubSchema(baseuri, schemas[i7]); + } + }; + Validator2.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) { + if (!schemas || typeof schemas != "object") return; + for (var p4 in schemas) { + this.addSubSchema(baseuri, schemas[p4]); + } + }; + Validator2.prototype.setSchemas = function setSchemas(schemas) { + this.schemas = schemas; + }; + Validator2.prototype.getSchema = function getSchema(urn) { + return this.schemas[urn]; + }; + Validator2.prototype.validate = function validate(instance, schema, options, ctx) { + if (typeof schema !== "boolean" && typeof schema !== "object" || schema === null) { + throw new SchemaError("Expected `schema` to be an object or boolean"); + } + if (!options) { + options = {}; + } + var id = schema.$id || schema.id; + let base = helpers2.resolveUrl(options.base, id || ""); + if (!ctx) { + ctx = new SchemaContext(schema, options, [], base, Object.create(this.schemas)); + if (!ctx.schemas[base]) { + ctx.schemas[base] = schema; + } + var found = scanSchema(base, schema); + for (var n7 in found.id) { + var sch = found.id[n7]; + ctx.schemas[n7] = sch; + } + } + if (options.required && instance === void 0) { + var result = new ValidatorResult(instance, schema, options, ctx); + result.addError("is required, but is undefined"); + return result; + } + var result = this.validateSchema(instance, schema, options, ctx); + if (!result) { + throw new Error("Result undefined"); + } else if (options.throwAll && result.errors.length) { + throw new ValidatorResultError(result); + } + return result; + }; + function shouldResolve(schema) { + var ref = typeof schema === "string" ? schema : schema.$ref; + if (typeof ref == "string") return ref; + return false; + } + Validator2.prototype.validateSchema = function validateSchema(instance, schema, options, ctx) { + var result = new ValidatorResult(instance, schema, options, ctx); + if (typeof schema === "boolean") { + if (schema === true) { + schema = {}; + } else if (schema === false) { + schema = { type: [] }; + } + } else if (!schema) { + throw new Error("schema is undefined"); + } + if (schema["extends"]) { + if (Array.isArray(schema["extends"])) { + var schemaobj = { schema, ctx }; + schema["extends"].forEach(this.schemaTraverser.bind(this, schemaobj)); + schema = schemaobj.schema; + schemaobj.schema = null; + schemaobj.ctx = null; + schemaobj = null; + } else { + schema = helpers2.deepMerge(schema, this.superResolve(schema["extends"], ctx)); + } + } + var switchSchema = shouldResolve(schema); + if (switchSchema) { + var resolved = this.resolve(schema, switchSchema, ctx); + var subctx = new SchemaContext(resolved.subschema, options, ctx.path, resolved.switchSchema, ctx.schemas); + return this.validateSchema(instance, resolved.subschema, options, subctx); + } + var skipAttributes = options && options.skipAttributes || []; + for (var key in schema) { + if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) { + var validatorErr = null; + var validator2 = this.attributes[key]; + if (validator2) { + validatorErr = validator2.call(this, instance, schema, options, ctx); + } else if (options.allowUnknownAttributes === false) { + throw new SchemaError("Unsupported attribute: " + key, schema); + } + if (validatorErr) { + result.importErrors(validatorErr); + } + } + } + if (typeof options.rewrite == "function") { + var value = options.rewrite.call(this, instance, schema, options, ctx); + result.instance = value; + } + return result; + }; + Validator2.prototype.schemaTraverser = function schemaTraverser(schemaobj, s6) { + schemaobj.schema = helpers2.deepMerge(schemaobj.schema, this.superResolve(s6, schemaobj.ctx)); + }; + Validator2.prototype.superResolve = function superResolve(schema, ctx) { + var ref = shouldResolve(schema); + if (ref) { + return this.resolve(schema, ref, ctx).subschema; + } + return schema; + }; + Validator2.prototype.resolve = function resolve2(schema, switchSchema, ctx) { + switchSchema = ctx.resolve(switchSchema); + if (ctx.schemas[switchSchema]) { + return { subschema: ctx.schemas[switchSchema], switchSchema }; + } + let parsed = new URL(switchSchema, "thismessage::/"); + let fragment2 = parsed.hash; + var document2 = fragment2 && fragment2.length && switchSchema.substr(0, switchSchema.length - fragment2.length); + if (!document2 || !ctx.schemas[document2]) { + throw new SchemaError("no such schema <" + switchSchema + ">", schema); + } + var subschema = helpers2.objectGetPath(ctx.schemas[document2], fragment2.substr(1)); + if (subschema === void 0) { + throw new SchemaError("no such schema " + fragment2 + " located in <" + document2 + ">", schema); + } + return { subschema, switchSchema }; + }; + Validator2.prototype.testType = function validateType(instance, schema, options, ctx, type) { + if (type === void 0) { + return; + } else if (type === null) { + throw new SchemaError('Unexpected null in "type" keyword'); + } + if (typeof this.types[type] == "function") { + return this.types[type].call(this, instance); + } + if (type && typeof type == "object") { + var res = this.validateSchema(instance, type, options, ctx); + return res === void 0 || !(res && res.errors.length); + } + return true; + }; + var types2 = Validator2.prototype.types = {}; + types2.string = function testString(instance) { + return typeof instance == "string"; + }; + types2.number = function testNumber(instance) { + return typeof instance == "number" && isFinite(instance); + }; + types2.integer = function testInteger(instance) { + return typeof instance == "number" && instance % 1 === 0; + }; + types2.boolean = function testBoolean(instance) { + return typeof instance == "boolean"; + }; + types2.array = function testArray(instance) { + return Array.isArray(instance); + }; + types2["null"] = function testNull(instance) { + return instance === null; + }; + types2.date = function testDate(instance) { + return instance instanceof Date; + }; + types2.any = function testAny(instance) { + return true; + }; + types2.object = function testObject(instance) { + return instance && typeof instance === "object" && !Array.isArray(instance) && !(instance instanceof Date); + }; + validator = Validator2; + return validator; +} +function requireLib() { + if (hasRequiredLib) return lib; + hasRequiredLib = 1; + var Validator2 = lib.Validator = requireValidator(); + lib.ValidatorResult = requireHelpers().ValidatorResult; + lib.ValidatorResultError = requireHelpers().ValidatorResultError; + lib.ValidationError = requireHelpers().ValidationError; + lib.SchemaError = requireHelpers().SchemaError; + lib.SchemaScanResult = requireScan().SchemaScanResult; + lib.scan = requireScan().scan; + lib.validate = function(instance, schema, options) { + var v4 = new Validator2(); + return v4.validate(instance, schema, options); + }; + return lib; +} +function jsonSchemaValidationErrorToAIReadableText(root, validationErrors) { + return validationErrors.map((validatioNError) => { + const fullPath = [root, ...validatioNError.path].join("."); + return `${fullPath} ${validatioNError.message}`; + }).join("\n"); +} +function internalCreateRemoteTool({ name, description, pluginIdentifier, parametersJsonSchema, implementation }) { + return { + name, + description, + type: "remoteTool", + pluginIdentifier, + parametersJsonSchema, + checkParameters: (params) => { + const jsonSchemaValidator = new libExports.Validator(); + const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); + if (validationResult.errors.length > 0) { + throw new Error(text` + Failed to parse arguments for tool "${name}": + ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} + `); + } + }, + implementation + }; +} +function functionToolToLLMTool(tool) { + return { + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: zodToJsonSchema(tool.parametersSchema) + } + }; +} +function rawFunctionToolToLLMTool(tool) { + return { + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parametersJsonSchema + } + }; +} +function remoteToolToLLMTool(tool) { + return { + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parametersJsonSchema + } + }; +} +function toolToLLMTool(tool) { + const type = tool.type; + switch (type) { + case "function": + return functionToolToLLMTool(tool); + case "rawFunction": + case "unimplementedRawFunction": + return rawFunctionToolToLLMTool(tool); + case "remoteTool": + return remoteToolToLLMTool(tool); + default: { + const exhaustiveCheck = type; + throw new Error(`Unhandled type: ${exhaustiveCheck}`); + } + } +} +function valuesOfObj(record) { + if ("values" in Object) { + return Object.values(record); + } + var values2 = []; + for (var key in record) { + if (record.hasOwnProperty(key)) { + values2.push(record[key]); + } + } + return values2; +} +function find(record, predicate) { + var values2 = valuesOfObj(record); + if ("find" in values2) { + return values2.find(predicate); + } + var valuesNotNever = values2; + for (var i7 = 0; i7 < valuesNotNever.length; i7++) { + var value = valuesNotNever[i7]; + if (predicate(value)) { + return value; + } + } + return void 0; +} +function forEach(record, run) { + Object.entries(record).forEach(function(_a7) { + var _b = __read$3(_a7, 2), key = _b[0], value = _b[1]; + return run(value, key); + }); +} +function includes(arr, value) { + return arr.indexOf(value) !== -1; +} +function findArr(record, predicate) { + for (var i7 = 0; i7 < record.length; i7++) { + var value = record[i7]; + if (predicate(value)) { + return value; + } + } + return void 0; +} +function simpleTransformation(isApplicable, annotation, transform, untransform) { + return { + isApplicable, + annotation, + transform, + untransform + }; +} +function compositeTransformation(isApplicable, annotation, transform, untransform) { + return { + isApplicable, + annotation, + transform, + untransform + }; +} +function isInstanceOfRegisteredClass(potentialClass, superJson) { + if (potentialClass === null || potentialClass === void 0 ? void 0 : potentialClass.constructor) { + var isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor); + return isRegistered; + } + return false; +} +function validatePath(path6) { + if (includes(path6, "__proto__")) { + throw new Error("__proto__ is not allowed as a property"); + } + if (includes(path6, "prototype")) { + throw new Error("prototype is not allowed as a property"); + } + if (includes(path6, "constructor")) { + throw new Error("constructor is not allowed as a property"); + } +} +function traverse(tree, walker2, origin) { + if (origin === void 0) { + origin = []; + } + if (!tree) { + return; + } + if (!isArray$1(tree)) { + forEach(tree, function(subtree, key) { + return traverse(subtree, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key)))); + }); + return; + } + var _a7 = __read$1(tree, 2), nodeValue = _a7[0], children = _a7[1]; + if (children) { + forEach(children, function(child, key) { + traverse(child, walker2, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key)))); + }); + } + walker2(nodeValue, origin); +} +function applyValueAnnotations(plain, annotations, superJson) { + traverse(annotations, function(type, path6) { + plain = setDeep(plain, path6, function(v4) { + return untransformValue(v4, type, superJson); + }); + }); + return plain; +} +function applyReferentialEqualityAnnotations(plain, annotations) { + function apply(identicalPaths, path6) { + var object = getDeep(plain, parsePath(path6)); + identicalPaths.map(parsePath).forEach(function(identicalObjectPath) { + plain = setDeep(plain, identicalObjectPath, function() { + return object; + }); + }); + } + if (isArray$1(annotations)) { + var _a7 = __read$1(annotations, 2), root = _a7[0], other = _a7[1]; + root.forEach(function(identicalPath) { + plain = setDeep(plain, parsePath(identicalPath), function() { + return plain; + }); + }); + if (other) { + forEach(other, apply); + } + } else { + forEach(annotations, apply); + } + return plain; +} +function addIdentity(object, path6, identities) { + var existingSet = identities.get(object); + if (existingSet) { + existingSet.push(path6); + } else { + identities.set(object, [path6]); + } +} +function generateReferentialEqualityAnnotations(identitites, dedupe) { + var result = {}; + var rootEqualityPaths = void 0; + identitites.forEach(function(paths) { + if (paths.length <= 1) { + return; + } + if (!dedupe) { + paths = paths.map(function(path6) { + return path6.map(String); + }).sort(function(a3, b4) { + return a3.length - b4.length; + }); + } + var _a7 = __read$1(paths), representativePath = _a7[0], identicalPaths = _a7.slice(1); + if (representativePath.length === 0) { + rootEqualityPaths = identicalPaths.map(stringifyPath); + } else { + result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath); + } + }); + if (rootEqualityPaths) { + if (isEmptyObject(result)) { + return [rootEqualityPaths]; + } else { + return [rootEqualityPaths, result]; + } + } else { + return isEmptyObject(result) ? void 0 : result; + } +} +function getType(payload) { + return Object.prototype.toString.call(payload).slice(8, -1); +} +function isArray4(payload) { + return getType(payload) === "Array"; +} +function isPlainObject(payload) { + if (getType(payload) !== "Object") + return false; + const prototype = Object.getPrototypeOf(payload); + return !!prototype && prototype.constructor === Object && prototype === Object.prototype; +} +function assignProp(carry2, key, newVal, originalObject, includeNonenumerable) { + const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable"; + if (propType === "enumerable") + carry2[key] = newVal; + if (includeNonenumerable && propType === "nonenumerable") { + Object.defineProperty(carry2, key, { + value: newVal, + enumerable: false, + writable: true, + configurable: true + }); + } +} +function copy(target, options = {}) { + if (isArray4(target)) { + return target.map((item) => copy(item, options)); + } + if (!isPlainObject(target)) { + return target; + } + const props = Object.getOwnPropertyNames(target); + const symbols2 = Object.getOwnPropertySymbols(target); + return [...props, ...symbols2].reduce((carry2, key) => { + if (isArray4(options.props) && !options.props.includes(key)) { + return carry2; + } + const val2 = target[key]; + const newVal = copy(val2, options); + assignProp(carry2, key, newVal, target, options.nonenumerable); + return carry2; + }, {}); +} +function serialize(type, value) { + switch (type) { + case "raw": + return value; + case "superjson": + return serialize$1(value); + } +} +function deserialize(type, value) { + switch (type) { + case "raw": + return value; + case "superjson": + return deserialize$1(value); + } +} +function defaultErrorDeserializer(serialized, directCause, stack) { + return fromSerializedError(serialized, directCause, stack); +} +function getHostedEnv() { + let anyWindow; + try { + anyWindow = window; + } catch (error) { + anyWindow = void 0; + } + if (anyWindow !== void 0 && anyWindow.lmsHostedEnv !== void 0) { + return anyWindow.lmsHostedEnv; + } + return null; +} +function createBaseModelBackendInterface(specificModelInstanceInfoSchemaInput, specificModelInfoSchemaInput) { + const specificModelInstanceInfoSchema = specificModelInstanceInfoSchemaInput; + const specificModelInfoSchema = specificModelInfoSchemaInput; + return new BackendInterface().addChannelEndpoint("loadModel", { + creationParameter: external_exports.object({ + modelKey: external_exports.string(), + identifier: external_exports.string().optional(), + /** + * If provided, when the model is not used for this amount of time, it will be unloaded. + */ + ttlMs: external_exports.number().int().min(1).optional(), + loadConfigStack: kvConfigStackSchema + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("resolved"), + info: specificModelInfoSchema, + ambiguous: external_exports.array(external_exports.string()).optional() + }), + external_exports.object({ + type: external_exports.literal("progress"), + progress: external_exports.number() + }), + external_exports.object({ + type: external_exports.literal("success"), + info: specificModelInstanceInfoSchema + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }).addRpcEndpoint("unloadModel", { + parameter: external_exports.object({ + identifier: external_exports.string() + }), + returns: external_exports.void() + }).addRpcEndpoint("listLoaded", { + parameter: external_exports.undefined(), + returns: external_exports.array(specificModelInstanceInfoSchema) + }).addRpcEndpoint("getModelInfo", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + throwIfNotFound: external_exports.boolean() + }), + returns: specificModelInstanceInfoSchema.optional() + }).addRpcEndpoint("getLoadConfig", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema + }), + returns: kvConfigSchema + }).addChannelEndpoint("getOrLoad", { + creationParameter: external_exports.object({ + identifier: external_exports.string(), + /** + * If provided and a new instance is loaded as a result of this call, it will be unloaded + * after idling for this amount of time. + */ + loadTtlMs: external_exports.number().int().min(1).optional(), + loadConfigStack: kvConfigStackSchema + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("alreadyLoaded"), + info: specificModelInstanceInfoSchema + }), + external_exports.object({ + type: external_exports.literal("startLoading"), + identifier: external_exports.string(), + info: specificModelInfoSchema + }), + external_exports.object({ + // We are unloading other JIT model + type: external_exports.literal("unloadingOtherJITModel"), + info: modelInstanceInfoSchema + }), + external_exports.object({ + type: external_exports.literal("loadProgress"), + progress: external_exports.number() + }), + external_exports.object({ + type: external_exports.literal("loadSuccess"), + info: specificModelInstanceInfoSchema + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }); +} +function createDiagnosticsBackendInterface() { + return new BackendInterface().addChannelEndpoint("streamLogs", { + creationParameter: external_exports.void(), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("stop") + }) + ]), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("log"), + log: diagnosticsLogEventSchema + }) + ]) + }); +} +function createEmbeddingBackendInterface() { + const baseModelBackendInterface = createBaseModelBackendInterface(embeddingModelInstanceInfoSchema, embeddingModelInfoSchema); + return baseModelBackendInterface.addRpcEndpoint("embedString", { + parameter: external_exports.object({ + modelSpecifier: modelSpecifierSchema, + inputString: external_exports.string() + }), + returns: external_exports.object({ + embedding: external_exports.array(external_exports.number()) + }) + }).addRpcEndpoint("tokenize", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + inputString: external_exports.string() + }), + returns: external_exports.object({ + tokens: external_exports.array(external_exports.number()) + }) + }).addRpcEndpoint("countTokens", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + inputString: external_exports.string() + }), + returns: external_exports.object({ + tokenCount: external_exports.number().int() + }) + }); +} +function createFilesBackendInterface() { + return new BackendInterface().addRpcEndpoint("getLocalFileAbsolutePath", { + parameter: external_exports.object({ + fileName: external_exports.string() + }), + returns: external_exports.object({ + path: external_exports.string() + }) + }).addRpcEndpoint("uploadFileBase64", { + parameter: external_exports.object({ + name: external_exports.string(), + contentBase64: external_exports.string() + }), + returns: external_exports.object({ + identifier: external_exports.string(), + fileType: fileTypeSchema, + sizeBytes: external_exports.number().int() + }) + }).addChannelEndpoint("retrieve", { + creationParameter: external_exports.object({ + query: external_exports.string(), + fileIdentifiers: external_exports.array(external_exports.string()), + config: kvConfigSchema + }), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("stop") + }) + ]), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("onFileProcessList"), + indices: external_exports.array(external_exports.number().int()) + }), + external_exports.object({ + type: external_exports.literal("onFileProcessingStart"), + index: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("onFileProcessingEnd"), + index: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("onFileProcessingStepStart"), + index: external_exports.number().int(), + step: retrievalFileProcessingStepSchema + }), + external_exports.object({ + type: external_exports.literal("onFileProcessingStepProgress"), + index: external_exports.number().int(), + step: retrievalFileProcessingStepSchema, + progress: external_exports.number() + }), + external_exports.object({ + type: external_exports.literal("onFileProcessingStepEnd"), + index: external_exports.number().int(), + step: retrievalFileProcessingStepSchema + }), + external_exports.object({ + type: external_exports.literal("onSearchingStart") + }), + external_exports.object({ + type: external_exports.literal("onSearchingEnd") + }), + external_exports.object({ + type: external_exports.literal("result"), + result: internalRetrievalResultSchema + }) + ]) + }).addChannelEndpoint("parseDocument", { + creationParameter: external_exports.object({ + fileIdentifier: external_exports.string(), + parseOpts: documentParsingOptsSchema + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("parserLoaded"), + parser: documentParsingLibraryIdentifierSchema + }), + external_exports.object({ + type: external_exports.literal("progress"), + progress: external_exports.number() + }), + external_exports.object({ + type: external_exports.literal("result"), + content: external_exports.string(), + parser: documentParsingLibraryIdentifierSchema + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }).addRpcEndpoint("getDocumentParsingLibrary", { + parameter: external_exports.object({ + fileIdentifier: external_exports.string() + }), + returns: external_exports.object({ + library: external_exports.string(), + version: external_exports.string() + }) + }); +} +function createLlmBackendInterface() { + const baseModelBackendInterface = createBaseModelBackendInterface(llmInstanceInfoSchema, llmInfoSchema); + return baseModelBackendInterface.addChannelEndpoint("predict", { + creationParameter: external_exports.object({ + modelSpecifier: modelSpecifierSchema, + history: chatHistoryDataSchema, + predictionConfigStack: kvConfigStackSchema, + /** + * Which preset to use. Supports limited fuzzy matching. + */ + fuzzyPresetIdentifier: external_exports.string().optional(), + ignoreServerSessionConfig: external_exports.boolean().optional() + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("fragment"), + fragment: llmPredictionFragmentSchema, + logprobs: external_exports.array(external_exports.array(external_exports.object({ text: external_exports.string(), logprob: external_exports.number() }))).optional() + }), + external_exports.object({ + type: external_exports.literal("promptProcessingProgress"), + progress: external_exports.number() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationStart"), + /** + * The LLM specific call id of the tool call. + */ + toolCallId: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationNameReceived"), + name: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"), + content: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationEnd"), + toolCallRequest: toolCallRequestSchema, + /** + * The raw output that represents this tool call. It is recommended to present this to + * the user as is, if desired. + * + * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use + * JSON to represent tool calls. + */ + rawContent: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationFailed"), + error: serializedLMSExtendedErrorSchema, + /** + * The raw output that was generated by the model before the tool call. The exact nature + * of this fields depends on the error. It sometimes include the entire tool calls + * section, or sometimes just the single tool call that failed. + * + * It is recommended to present this to the user as is, if desired. + */ + rawContent: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("success"), + stats: llmPredictionStatsSchema, + modelInfo: llmInstanceInfoSchema, + loadModelConfig: kvConfigSchema, + predictionConfig: kvConfigSchema + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }).addRpcEndpoint("applyPromptTemplate", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + history: chatHistoryDataSchema, + predictionConfigStack: kvConfigStackSchema, + opts: llmApplyPromptTemplateOptsSchema + }), + returns: external_exports.object({ + formatted: external_exports.string() + }) + }).addRpcEndpoint("tokenize", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + inputString: external_exports.string() + }), + returns: external_exports.object({ + tokens: external_exports.array(external_exports.number()) + }) + }).addRpcEndpoint("countTokens", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + inputString: external_exports.string() + }), + returns: external_exports.object({ + tokenCount: external_exports.number().int() + }) + }).addRpcEndpoint("preloadDraftModel", { + parameter: external_exports.object({ + specifier: modelSpecifierSchema, + draftModelKey: external_exports.string() + }), + returns: external_exports.void() + }); +} +function createPluginsBackendInterface() { + return new BackendInterface().addChannelEndpoint("startToolUseSession", { + creationParameter: external_exports.object({ + pluginIdentifier: external_exports.string(), + pluginConfigSpecifier: pluginConfigSpecifierSchema + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + /** + * The session has been started successfully. The client can now use the session. Note, + * there are no sessionError message because if a session fails to start, the channel + * will error instead. + */ + external_exports.object({ + type: external_exports.literal("sessionReady"), + toolDefinitions: external_exports.array(llmToolSchema) + }), + /** + * A tool call has been completed. + */ + external_exports.object({ + type: external_exports.literal("toolCallComplete"), + callId: external_exports.number(), + result: jsonSerializableSchema + }), + /** + * A tool call has failed. + */ + external_exports.object({ + type: external_exports.literal("toolCallError"), + callId: external_exports.number(), + error: serializedLMSExtendedErrorSchema + }), + /** + * Status update for a tool call. + */ + external_exports.object({ + type: external_exports.literal("toolCallStatus"), + callId: external_exports.number(), + statusText: external_exports.string() + }), + /** + * Warning message for a tool call. + */ + external_exports.object({ + type: external_exports.literal("toolCallWarn"), + callId: external_exports.number(), + warnText: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + /** + * Request to start a tool call. This call can be aborted using the `abortToolCall` + * packet. When the tool call is completed, either the `toolCallResult` or `toolCallError` + * packet will be sent. + */ + external_exports.object({ + type: external_exports.literal("callTool"), + callId: external_exports.number(), + name: external_exports.string(), + arguments: jsonSerializableSchema + }), + /** + * Request to abort a tool call. Upon calling this, no toolCallComplete or toolCallError + * packets will be sent for the call. We assume abort is done immediately. + */ + external_exports.object({ + type: external_exports.literal("abortToolCall"), + callId: external_exports.number() + }), + /** + * Client requests to discard the session. Upon calling this, the channel will be closed. + */ + external_exports.object({ + type: external_exports.literal("discardSession") + }) + ]) + }).addChannelEndpoint("generateWithGenerator", { + creationParameter: external_exports.object({ + pluginIdentifier: external_exports.string(), + pluginConfigSpecifier: pluginConfigSpecifierSchema, + tools: external_exports.array(llmToolSchema), + history: chatHistoryDataSchema + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("fragment"), + fragment: llmPredictionFragmentSchema + }), + external_exports.object({ + type: external_exports.literal("promptProcessingProgress"), + progress: external_exports.number() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationStart"), + /** + * The LLM specific call id of the tool call. + */ + toolCallId: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationNameReceived"), + name: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"), + content: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationEnd"), + toolCallRequest: toolCallRequestSchema + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationFailed") + }), + external_exports.object({ + type: external_exports.literal("success") + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }).addChannelEndpoint("registerDevelopmentPlugin", { + creationParameter: external_exports.object({ + manifest: pluginManifestSchema + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("ready"), + clientIdentifier: external_exports.string(), + clientPasskey: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("end") + }) + ]) + }).addRpcEndpoint("reindexPlugins", { + parameter: external_exports.void(), + returns: external_exports.void() + }).addChannelEndpoint("setPromptPreprocessor", { + creationParameter: external_exports.void(), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("preprocess"), + taskId: external_exports.string(), + input: chatMessageDataSchema, + config: kvConfigSchema, + pluginConfig: kvConfigSchema, + globalPluginConfig: kvConfigSchema, + workingDirectoryPath: external_exports.string().nullable(), + /** + * An array of all the plugins that are enabled for this prediction. + */ + enabledPluginInfos: external_exports.array(remotePluginInfoSchema), + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("abort"), + taskId: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("complete"), + taskId: external_exports.string(), + processed: chatMessageDataSchema + }), + external_exports.object({ + type: external_exports.literal("aborted"), + taskId: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("error"), + taskId: external_exports.string(), + error: serializedLMSExtendedErrorSchema + }) + ]) + }).addChannelEndpoint("setPredictionLoopHandler", { + creationParameter: external_exports.void(), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("handlePredictionLoop"), + taskId: external_exports.string(), + config: kvConfigSchema, + pluginConfig: kvConfigSchema, + globalPluginConfig: kvConfigSchema, + workingDirectoryPath: external_exports.string().nullable(), + /** + * An array of all the plugins that are enabled for this prediction. + */ + enabledPluginInfos: external_exports.array(remotePluginInfoSchema), + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("abort"), + taskId: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("complete"), + taskId: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("aborted"), + taskId: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("error"), + taskId: external_exports.string(), + error: serializedLMSExtendedErrorSchema + }) + ]) + }).addChannelEndpoint("setToolsProvider", { + creationParameter: external_exports.void(), + toClientPacket: external_exports.discriminatedUnion("type", [ + /** + * Starts a "tool providing session". Once this is received, the plugin should call the + * tools provider and pass the tools to the server using the `sessionInitialized` packet. + * + * If the initialization failed, the plugin should send the `sessionInitializationFailed` + * packet. + */ + external_exports.object({ + type: external_exports.literal("initSession"), + pluginConfig: kvConfigSchema, + globalPluginConfig: kvConfigSchema, + workingDirectoryPath: external_exports.string().nullable(), + sessionId: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("discardSession"), + sessionId: external_exports.string() + }), + /** + * Call a tool within a session. The plugin should call the tool and return the result + * using the `toolCallComplete` packet. + * + * If the tool call fails in an unrecoverable way the plugin can send the `toolCallError` + * packet. + */ + external_exports.object({ + type: external_exports.literal("callTool"), + sessionId: external_exports.string(), + callId: external_exports.string(), + toolName: external_exports.string(), + parameters: jsonSerializableSchema + }), + /** + * Abort a tool call. The plugin should abort the tool call and confirm the abort using + * the `toolCallAborted` packet. + */ + external_exports.object({ + type: external_exports.literal("abortToolCall"), + sessionId: external_exports.string(), + callId: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + /** + * The plugin has provided a list of tools in a new session. + */ + external_exports.object({ + type: external_exports.literal("sessionInitialized"), + sessionId: external_exports.string(), + toolDefinitions: external_exports.array(llmToolSchema) + }), + external_exports.object({ + type: external_exports.literal("sessionInitializationFailed"), + sessionId: external_exports.string(), + error: serializedLMSExtendedErrorSchema + }), + external_exports.object({ + type: external_exports.literal("toolCallComplete"), + sessionId: external_exports.string(), + callId: external_exports.string(), + result: jsonSerializableSchema + }), + external_exports.object({ + type: external_exports.literal("toolCallError"), + sessionId: external_exports.string(), + callId: external_exports.string(), + error: serializedLMSExtendedErrorSchema + }), + external_exports.object({ + type: external_exports.literal("toolCallStatus"), + sessionId: external_exports.string(), + callId: external_exports.string(), + statusText: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallWarn"), + sessionId: external_exports.string(), + callId: external_exports.string(), + warnText: external_exports.string() + }) + ]) + }).addChannelEndpoint("setGenerator", { + creationParameter: external_exports.void(), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("generate"), + taskId: external_exports.string(), + input: chatHistoryDataSchema, + pluginConfig: kvConfigSchema, + globalPluginConfig: kvConfigSchema, + toolDefinitions: external_exports.array(llmToolSchema), + workingDirectoryPath: external_exports.string().nullable() + }), + external_exports.object({ + type: external_exports.literal("abort"), + taskId: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("complete"), + taskId: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("aborted"), + taskId: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("error"), + taskId: external_exports.string(), + error: serializedLMSExtendedErrorSchema + }), + external_exports.object({ + type: external_exports.literal("fragmentGenerated"), + taskId: external_exports.string(), + content: external_exports.string(), + opts: llmPredictionFragmentInputOptsSchema + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationStarted"), + taskId: external_exports.string(), + toolCallId: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationNameReceived"), + taskId: external_exports.string(), + toolName: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationArgumentFragmentGenerated"), + taskId: external_exports.string(), + content: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationEnded"), + taskId: external_exports.string(), + toolCallRequest: toolCallRequestSchema + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationFailed"), + taskId: external_exports.string(), + error: serializedLMSExtendedErrorSchema + }) + ]) + }).addRpcEndpoint("processingHandleUpdate", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string(), + update: processingUpdateSchema + }), + returns: external_exports.void() + }).addRpcEndpoint("processingHandleRequest", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string(), + request: processingRequestSchema + }), + returns: external_exports.object({ + response: processingRequestResponseSchema + }) + }).addRpcEndpoint("processingPullHistory", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string(), + includeCurrent: external_exports.boolean() + }), + returns: chatHistoryDataSchema + }).addRpcEndpoint("processingGetOrLoadTokenSource", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string() + }), + returns: external_exports.object({ + tokenSourceIdentifier: tokenSourceIdentifierSchema + }) + }).addRpcEndpoint("processingHasStatus", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string() + }), + returns: external_exports.boolean() + }).addRpcEndpoint("processingNeedsNaming", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string() + }), + returns: external_exports.boolean() + }).addRpcEndpoint("processingSuggestName", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string(), + name: external_exports.string() + }), + returns: external_exports.void() + }).addRpcEndpoint("processingSetSenderName", { + parameter: external_exports.object({ + /** Processing Context Identifier */ + pci: external_exports.string(), + token: external_exports.string(), + name: external_exports.string() + }), + returns: external_exports.void() + }).addRpcEndpoint("setConfigSchematics", { + parameter: external_exports.object({ + schematics: serializedKVConfigSchematicsSchema + }), + returns: external_exports.void() + }).addRpcEndpoint("setGlobalConfigSchematics", { + parameter: external_exports.object({ + schematics: serializedKVConfigSchematicsSchema + }), + returns: external_exports.void() + }).addRpcEndpoint("pluginInitCompleted", { + parameter: external_exports.void(), + returns: external_exports.void() + }); +} +function createRepositoryBackendInterface() { + return new BackendInterface().addRpcEndpoint("searchModels", { + parameter: external_exports.object({ + opts: modelSearchOptsSchema + }), + returns: external_exports.object({ + results: external_exports.array(modelSearchResultEntryDataSchema) + }) + }).addRpcEndpoint("getModelDownloadOptions", { + parameter: external_exports.object({ + modelSearchResultIdentifier: modelSearchResultIdentifierSchema + }), + returns: external_exports.object({ + results: external_exports.array(modelSearchResultDownloadOptionDataSchema) + }) + }).addChannelEndpoint("downloadModel", { + creationParameter: external_exports.object({ + downloadIdentifier: external_exports.string() + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("downloadProgress"), + update: downloadProgressUpdateSchema + }), + external_exports.object({ + type: external_exports.literal("startFinalizing") + }), + external_exports.object({ + type: external_exports.literal("success"), + defaultIdentifier: external_exports.string() + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }).addChannelEndpoint("downloadArtifact", { + creationParameter: external_exports.object({ + artifactOwner: kebabCaseSchema, + artifactName: kebabCaseWithDotsSchema, + revisionNumber: external_exports.number().int().nullable(), + path: external_exports.string() + }), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("downloadProgress"), + update: downloadProgressUpdateSchema + }), + external_exports.object({ + type: external_exports.literal("startFinalizing") + }), + external_exports.object({ + type: external_exports.literal("success") + }) + ]), + toServerPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("cancel") + }) + ]) + }).addRpcEndpoint("installPluginDependencies", { + parameter: external_exports.object({ + pluginFolder: external_exports.string() + }), + returns: external_exports.void() + }).addRpcEndpoint("getLocalArtifactFiles", { + parameter: external_exports.object({ + path: external_exports.string() + }), + returns: external_exports.object({ + fileList: localArtifactFileListSchema + }) + }).addChannelEndpoint("pushArtifact", { + creationParameter: external_exports.object({ + path: external_exports.string(), + description: external_exports.string().max(1e3).optional(), + /** + * Request to make the artifact private. Only effective if the artifact did not exist + * before. Will not change the visibility of an existing artifact. + */ + makePrivate: external_exports.boolean().optional(), + /** + * If true, will write the revision number of the artifact after the push back to the + * artifact manifest.json. + */ + writeRevision: external_exports.boolean().optional(), + overrides: jsonSerializableSchema.optional() + }), + toServerPacket: external_exports.void(), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("message"), + message: external_exports.string() + }) + ]) + }).addChannelEndpoint("ensureAuthenticated", { + creationParameter: external_exports.void(), + toServerPacket: external_exports.void(), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("authenticationUrl"), + url: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("authenticated") + }) + ]) + }).addRpcEndpoint("loginWithPreAuthenticatedKeys", { + parameter: external_exports.object({ + keyId: external_exports.string(), + publicKey: external_exports.string(), + privateKey: external_exports.string() + }), + returns: external_exports.object({ + userName: external_exports.string() + }) + }).addChannelEndpoint("createArtifactDownloadPlan", { + creationParameter: external_exports.object({ + owner: kebabCaseSchema, + name: kebabCaseWithDotsSchema + }), + toServerPacket: external_exports.discriminatedUnion("type", [ + /** + * If called before committing the plan, the plan is aborted. If called after committing + * the plan, the download is canceled. + */ + external_exports.object({ + type: external_exports.literal("cancel") + }), + /** + * Can only be called after plan ready. Once called, starts the plan. + */ + external_exports.object({ + type: external_exports.literal("commit") + }) + ]), + toClientPacket: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("planUpdated"), + plan: artifactDownloadPlanSchema + }), + external_exports.object({ + type: external_exports.literal("planReady"), + plan: artifactDownloadPlanSchema + }), + external_exports.object({ + type: external_exports.literal("downloadProgress"), + update: downloadProgressUpdateSchema + }), + external_exports.object({ + type: external_exports.literal("startFinalizing") + }), + external_exports.object({ + type: external_exports.literal("success") + }) + ]) + }); +} +function createSystemBackendInterface() { + return new BackendInterface().addRpcEndpoint("listDownloadedModels", { + parameter: external_exports.void(), + returns: external_exports.array(modelInfoSchema) + }).addChannelEndpoint("alive", { + creationParameter: external_exports.void(), + toServerPacket: external_exports.void(), + toClientPacket: external_exports.void() + }).addRpcEndpoint("notify", { + parameter: backendNotificationSchema, + returns: external_exports.void() + }).addRpcEndpoint("version", { + parameter: external_exports.void(), + returns: external_exports.object({ + /** + * `major.minor.patch` + */ + version: external_exports.string(), + /** + * LM Studio build number + */ + build: external_exports.number() + }) + }).addRpcEndpoint("setExperimentFlag", { + parameter: external_exports.object({ + code: external_exports.string(), + value: external_exports.boolean() + }), + returns: external_exports.void() + }).addRpcEndpoint("getExperimentFlags", { + parameter: external_exports.void(), + returns: external_exports.array(external_exports.string()) + }).addRpcEndpoint("startHttpServer", { + parameter: external_exports.object({ + port: external_exports.number().int().min(1).max(65535).optional(), + cors: external_exports.boolean().optional() + }), + returns: external_exports.void() + }).addRpcEndpoint("stopHttpServer", { + parameter: external_exports.void(), + returns: external_exports.void() + }); +} +function createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey) { + const [onMessage, emitOnMessage] = BufferedEvent.create(); + const [onClose, emitOnClose] = BufferedEvent.create(); + const sendToServer = hostedEnv.getApiIpcTunnel(apiNamespace, { + authVersion: 1, + clientIdentifier, + clientPasskey + }, emitOnMessage, emitOnClose); + return GenericClientTransport.createFactory(onMessage, onClose, sendToServer); +} +function createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey) { + return AuthenticatedWsClientTransport.createAuthenticatedWsClientTransportFactory({ + url: Promise.resolve(wsAddress).then((wsAddress2) => `${wsAddress2}/${apiNamespace}`), + clientIdentifier, + clientPasskey + }); +} +function createAuthenticatedClientPort(backendInterface, wsAddress, apiNamespace, clientIdentifier, clientPasskey, logger2, { errorDeserializer, verboseErrorMessage } = {}) { + const hostedEnv = getHostedEnv(); + if (hostedEnv !== null) { + if (wsAddress !== void 0) { + logger2.debug("Ignoring wsAddress parameter when constructing the client because the client is running in a hosted environment. This is not an error."); + } + return new ClientPort(backendInterface, createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey), { parentLogger: logger2, errorDeserializer, verboseErrorMessage }); + } else { + return new ClientPort(backendInterface, createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey), { parentLogger: logger2, errorDeserializer, verboseErrorMessage }); + } +} +function makeLoadModelOptsSchema(loadModelConfigSchema) { + return external_exports.object({ + identifier: external_exports.string().optional(), + config: loadModelConfigSchema.optional(), + signal: external_exports.instanceof(AbortSignal).optional(), + ttl: external_exports.number().optional(), + verbose: external_exports.union([external_exports.boolean(), logLevelSchema]).optional(), + onProgress: external_exports.function().optional() + }); +} +function numberToCheckboxNumeric(value, uncheckedValue, valueWhenUnchecked) { + if (value === void 0) { + return void 0; + } + if (value === uncheckedValue) { + return { checked: false, value: valueWhenUnchecked }; + } + return { checked: true, value }; +} +function getProcessingStepName(processingStep) { + switch (processingStep) { + case "loading": + return "Loading"; + case "chunking": + return "Chunking"; + case "embedding": + return "Embedding"; + default: { + const exhaustiveCheck = processingStep; + throw new Error(`Unexpected processing step: ${exhaustiveCheck}`); + } + } +} +function deserializeOtherError(serialized, stack) { + let content = import_chalk.default.redBright(` ${serialized.title} `); + if (serialized.suggestion !== void 0) { + content += "\n\n\n " + import_chalk.default.bgWhite.black(" (!) SUGGESTION ") + "\n\n" + import_chalk.default.white(serialized.suggestion); + } + if (serialized.cause !== void 0) { + content += "\n\n\n " + import_chalk.default.bgWhite.black(" (X) CAUSE ") + "\n\n" + import_chalk.default.gray(serialized.cause); + } + return makePrettyError(content, stack); +} +function registerErrorDeserializer(code, deserializer) { + errorDeserializersMap.set(code, deserializer); +} +function formatAvailableLLMs(availablePathsSample, totalModels) { + if (availablePathsSample.length === 0) { + return import_chalk.default.gray(" You don't have any LLMs downloaded."); + } + let text3 = availablePathsSample.map((path6) => import_chalk.default.cyanBright(" \u2022 " + path6)).join("\n"); + if (availablePathsSample.length < totalModels) { + text3 += import_chalk.default.gray(` + ... (and ${totalModels - availablePathsSample.length} more)`); + } + return text3; +} +function formatLoadedModels(loadedModelsSample, totalLoadedModels) { + if (loadedModelsSample.length === 0) { + return import_chalk.default.gray(" You don't have any models loaded."); + } + let text3 = loadedModelsSample.map((path6) => import_chalk.default.cyanBright(" \u2022 " + path6)).join("\n"); + if (loadedModelsSample.length < totalLoadedModels) { + text3 += import_chalk.default.gray(` + ... (and ${totalLoadedModels - loadedModelsSample.length} more)`); + } + return text3; +} +function getModelDomainTypeDisplayNameSingular(domain) { + switch (domain) { + case "llm": + return "an LLM"; + case "embedding": + return "an embedding model"; + case "imageGen": + return "an image generation model"; + case "transcription": + return "a transcription model"; + case "tts": + return "a text-to-speech model"; + default: { + const exhaustiveCheck = domain; + console.error(`Unexpected domain type: ${exhaustiveCheck}`); + return "Unknown Model Domain"; + } + } +} +function formatQuery(query) { + const requirements = []; + if (query.domain !== void 0) { + requirements.push(text` + The model must be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(query.domain))} + `); + } + if (query.identifier !== void 0) { + requirements.push(`The identifier must be exactly "${import_chalk.default.yellowBright(query.identifier)}"`); + } + if (query.path !== void 0) { + requirements.push(`The path must match "${import_chalk.default.yellowBright(query.path)}"`); + } + if (requirements.length === 0) { + return import_chalk.default.gray(" \u2022 Any Model"); + } + return requirements.map((req) => import_chalk.default.white(" \u2022 " + req)).join("\n"); +} +function formatAvailablePresets(presets, totalAvailablePresets) { + if (presets.length === 0) { + return import_chalk.default.gray(" You don't have any presets available."); + } + let text3 = presets.map(({ identifier, name }) => import_chalk.default.cyanBright(` \u2022 ${name} (${import_chalk.default.cyan(identifier)})`)).join("\n"); + if (presets.length < totalAvailablePresets) { + text3 += import_chalk.default.gray(` + ... (and ${totalAvailablePresets - presets.length} more)`); + } + return text3; +} +function friendlyErrorDeserializer(serialized, _directCause, stack) { + if (serialized.displayData === void 0) { + return deserializeOtherError(serialized, stack); + } + let error; + const specificDeserializer = errorDeserializersMap.get(serialized.displayData.code); + if (specificDeserializer !== void 0) { + error = specificDeserializer(serialized.displayData, stack); + attachSerializedErrorData(error, serialized); + return error; + } else { + return deserializeOtherError(serialized, stack); + } +} +function cacheQuantizationTypeToCheckbox({ value, falseDefault }) { + return value === void 0 ? void 0 : value === false ? { checked: false, value: falseDefault } : { checked: true, value }; +} +async function internalAct(chat, tools, baseOpts, stack, logger2, startTime, predictImpl, makePredictionResult) { + const abortController = new AbortController(); + const mutableChat = Chat3.from(chat); + let currentCallId = -1; + let hasCalledUnimplementedTool = false; + if (baseOpts.signal !== void 0) { + if (baseOpts.signal.aborted) { + abortController.abort(baseOpts.signal.reason); + } else { + baseOpts.signal.addEventListener("abort", () => { + abortController.abort(baseOpts.signal?.reason); + }, { once: true }); + } + } + let shouldContinue = false; + let predictionsPerformed = 0; + const toolsMap = /* @__PURE__ */ new Map(); + for (const tool of tools) { + if (toolsMap.has(tool.name)) { + logger2.warnText` + Duplicate tool (${tool.name}) found in the tools array. The last tool with the same name + will be used. + `; + } + toolsMap.set(tool.name, tool); + } + do { + let allowTools = true; + if ( + // If there is a defined number of max predictions, + baseOpts.maxPredictionRounds !== void 0 && // ... and this is the last chance to perform predictions, don't allow the model to use + // tools. + predictionsPerformed + 1 >= baseOpts.maxPredictionRounds + ) { + allowTools = false; + } + let finished2 = false; + let firstTokenTriggered = false; + const contentArray = []; + const reasoningContentArray = []; + const nonReasoningContentArray = []; + const toolCallRequests = []; + let nextToolCallIndex = 0; + const toolCallResults = []; + const toolCallPromises = []; + const { promise: predictionPromise, resolve: predictionResolve, reject: predictionReject } = makePromise(); + const { promise: finalPromise, resolve: finalResolve, reject: finalReject } = makePromise(); + const internalHandleInvalidToolCallRequest = async (error, request, toolCallIndex) => { + let result; + try { + result = await (baseOpts.handleInvalidToolRequest ?? defaultHandleInvalidToolRequest)(error, request); + } catch (error2) { + if (abortController.signal.aborted) { + throw abortController.signal.reason; + } + abortController.abort(); + throw error2; + } + if (result === void 0) { + return; + } + let resultString; + try { + resultString = JSON.stringify(result); + } catch (error2) { + abortController.abort(); + throw makePrettyError("handleInvalidToolRequest returned a value that cannot be converted to JSON.", stack); + } + if (request === void 0) { + logger2.warnText` + The "handleInvalidToolRequest" callback has returned a result, but the tool request has + completely failed to parse, thus LM Studio cannot provide the result to the tool call. + Please avoid returning a result when the second parameter of the callback is undefined. + See the documentation for "handleInvalidToolRequest" for more information. + `; + } else { + toolCallResults.push({ + index: toolCallIndex, + data: { + type: "toolCallResult", + toolCallId: request.id, + content: resultString + } + }); + nextToolCallIndex++; + } + }; + abortController.signal.throwIfAborted(); + safeCallCallback(logger2, "onRoundStart", baseOpts.onRoundStart, [predictionsPerformed]); + let isGeneratingToolCall = false; + const roundAbortController = new AbortController(); + const queue = baseOpts.allowParallelToolExecution ? new NoQueueQueue() : new FIFOQueue(); + let receivedEagerToolNameReporting = false; + let receivedToolArgumentsStreaming = false; + predictImpl({ + allowTools, + history: accessMaybeMutableInternals(mutableChat)._internalGetData(), + signal: roundAbortController.signal, + handleFragment: (fragment2) => { + if (!firstTokenTriggered) { + firstTokenTriggered = true; + safeCallCallback(logger2, "onFirstToken", baseOpts.onFirstToken, [predictionsPerformed]); + } + safeCallCallback(logger2, "onFragment", baseOpts.onPredictionFragment, [ + { roundIndex: predictionsPerformed, ...fragment2 } + ]); + contentArray.push(fragment2.content); + if (!fragment2.isStructural) { + if (fragment2.reasoningType === "reasoning") { + reasoningContentArray.push(fragment2.content); + } else { + nonReasoningContentArray.push(fragment2.content); + } + } + }, + handlePromptProcessingProgress: (progress) => { + safeCallCallback(logger2, "onPromptProcessingProgress", baseOpts.onPromptProcessingProgress, [predictionsPerformed, progress]); + }, + handleToolCallGenerationStart: (toolCallId) => { + currentCallId = callIdGiver.next(); + receivedEagerToolNameReporting = false; + receivedToolArgumentsStreaming = false; + isGeneratingToolCall = true; + safeCallCallback(logger2, "onToolCallRequestStart", baseOpts.onToolCallRequestStart, [ + predictionsPerformed, + currentCallId, + { toolCallId } + ]); + }, + handleToolCallGenerationNameReceived: (name) => { + receivedEagerToolNameReporting = true; + safeCallCallback(logger2, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, currentCallId, name]); + }, + handleToolCallGenerationArgumentFragmentGenerated: (content) => { + receivedToolArgumentsStreaming = true; + safeCallCallback(logger2, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, currentCallId, content]); + }, + handleToolCallGenerationEnd: (request, rawContent) => { + const callId = currentCallId; + isGeneratingToolCall = false; + const toolCallIndex = nextToolCallIndex; + nextToolCallIndex++; + if (!receivedEagerToolNameReporting) { + safeCallCallback(logger2, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, callId, request.name]); + } + if (!receivedToolArgumentsStreaming) { + safeCallCallback(logger2, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, callId, JSON.stringify(request.arguments ?? {}, null, 2)]); + } + const pushedRequest = { ...request }; + toolCallRequests.push(pushedRequest); + const tool = toolsMap.get(request.name); + if (tool === void 0) { + const toolCallRequestError = new ToolCallRequestError(`Cannot find tool with name ${request.name}.`, rawContent); + toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject)); + safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ + predictionsPerformed, + callId, + toolCallRequestError + ]); + return; + } + try { + tool.checkParameters(pushedRequest.arguments); + } catch (error) { + const toolCallRequestError = new ToolCallRequestError(error.message, rawContent); + toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject)); + safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ + predictionsPerformed, + callId, + toolCallRequestError + ]); + return; + } + const toolCallContext = new SimpleToolCallContext(new SimpleLogger(`Tool(${request.name})`, logger2), abortController.signal, callId); + const isQueued = queue.needsQueueing(); + safeCallCallback(logger2, "onToolCallRequestEnd", baseOpts.onToolCallRequestEnd, [ + predictionsPerformed, + callId, + { + isQueued, + toolCallRequest: request, + rawContent + } + ]); + toolCallPromises.push(queue.runInQueue(async () => { + if (isQueued) { + safeCallCallback(logger2, "onToolCallRequestDequeued", baseOpts.onToolCallRequestDequeued, [predictionsPerformed, callId]); + } + if (baseOpts.guardToolCall !== void 0) { + const resultContainer = [null]; + await baseOpts.guardToolCall(predictionsPerformed, callId, new GuardToolCallController(request, tool, resultContainer)); + if (resultContainer[0] === null) { + throw makeTitledPrettyError("Tool call guard did not allow or deny the tool call.", text` + The \`guardToolCall\` handler must call one of the methods on the controller + to allow or deny the tool call. + `, stack); + } + const guardResult = resultContainer[0]; + const guardResultType = guardResult.type; + switch (guardResultType) { + case "allow": { + break; + } + case "allowAndOverrideParameters": { + pushedRequest.arguments = guardResult.parameters; + break; + } + case "deny": { + toolCallResults.push({ + index: toolCallIndex, + data: { + type: "toolCallResult", + toolCallId: request.id, + content: JSON.stringify({ + error: guardResult.reason + }) + } + }); + return; + } + } + } + safeCallCallback(logger2, "onToolCallRequestFinalized", baseOpts.onToolCallRequestFinalized, [ + predictionsPerformed, + callId, + { + toolCallRequest: request, + rawContent + } + ]); + let result; + try { + result = await tool.implementation(pushedRequest.arguments ?? {}, toolCallContext); + } catch (error) { + if (!(error instanceof UnimplementedToolError)) { + throw error; + } + hasCalledUnimplementedTool = true; + } + let resultString; + if (result === void 0) { + resultString = "undefined"; + } else { + try { + resultString = JSON.stringify(result); + } catch (error) { + throw makePrettyError(`Return value of tool ${tool.name} cannot be converted to JSON.`, stack); + } + } + toolCallResults.push({ + index: toolCallIndex, + data: { + type: "toolCallResult", + toolCallId: request.id, + content: resultString + } + }); + }, abortController.signal).catch(finalReject)); + }, + handleToolCallGenerationFailed: (error, rawContent) => { + isGeneratingToolCall = false; + const toolCallRequestError = new ToolCallRequestError(error.message, rawContent); + toolCallPromises.push(internalHandleInvalidToolCallRequest( + toolCallRequestError, + // We don't have a request in this because the model has failed miserably. + void 0, + // Tool call index. Doesn't matter because if there is no request, there cannot be + // a replacement. + 0 + ).catch(finalReject)); + safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ + predictionsPerformed, + currentCallId, + toolCallRequestError + ]); + }, + handlePredictionEnd: (endPacket) => { + const predictionResult = makePredictionResult({ + endPacket, + content: contentArray.join(""), + reasoningContent: reasoningContentArray.join(""), + nonReasoningContent: nonReasoningContentArray.join(""), + predictionsPerformed + }); + safeCallCallback(logger2, "onPredictionCompleted", baseOpts.onPredictionCompleted, [ + predictionResult + ]); + predictionResolve(); + }, + handleError: (error) => { + if (isGeneratingToolCall) { + const toolCallRequestError = new ToolCallRequestError(`Generation failed: ${error.message}`, void 0); + isGeneratingToolCall = false; + safeCallCallback(logger2, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ + predictionsPerformed, + currentCallId, + toolCallRequestError + ]); + } + finished2 = true; + predictionReject(error); + } + }); + const abortListener = () => { + if (finished2) { + return; + } + finished2 = true; + roundAbortController.abort(abortController.signal.reason); + }; + abortController.signal.addEventListener("abort", abortListener); + predictionPromise.then(() => { + const assistantMessage = ChatMessage.from({ + role: "assistant", + content: [ + { + type: "text", + text: contentArray.join("") + }, + ...toolCallRequests.map((toolCallRequest) => ({ + type: "toolCallRequest", + toolCallRequest + })) + ] + }); + mutableChat.append(assistantMessage.asMutableCopy()); + safeCallCallback(logger2, "onMessage", baseOpts.onMessage, [assistantMessage]); + }).then(() => Promise.all(toolCallPromises)).then(() => finalResolve(), finalReject); + await finalPromise; + shouldContinue = false; + if (toolCallResults.length > 0) { + toolCallResults.sort((a3, b4) => a3.index - b4.index); + const toolMessage = ChatMessage.from({ + role: "tool", + content: toolCallResults.map((r8) => r8.data) + }); + mutableChat.append(toolMessage.asMutableCopy()); + safeCallCallback(logger2, "onMessage", baseOpts.onMessage, [toolMessage]); + shouldContinue = true; + } + safeCallCallback(logger2, "onRoundEnd", baseOpts.onRoundEnd, [predictionsPerformed]); + predictionsPerformed++; + if (baseOpts.maxPredictionRounds !== void 0 && predictionsPerformed >= baseOpts.maxPredictionRounds) { + shouldContinue = false; + } + shouldContinue &&= !hasCalledUnimplementedTool; + } while (shouldContinue); + return new ActResult(predictionsPerformed, (performance.now() - startTime) / 1e3); +} +function splitPredictionOpts(opts) { + const { onPromptProcessingProgress, onFirstToken, onPredictionFragment, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFailure, signal, preset, ...config } = opts; + return [ + config, + { + onPromptProcessingProgress, + onFirstToken, + onPredictionFragment, + onToolCallRequestStart, + onToolCallRequestNameReceived, + onToolCallRequestArgumentFragmentGenerated, + onToolCallRequestEnd, + onToolCallRequestFailure, + signal, + preset + } + ]; +} +function splitRespondOpts(opts) { + const { onMessage, ...remaining } = opts; + const [config, llmPredictionOpts] = splitPredictionOpts(remaining); + return [ + config, + llmPredictionOpts, + { + onMessage + } + ]; +} +function splitActOpts(opts) { + const { onFirstToken, onPredictionFragment, onMessage, onRoundStart, onRoundEnd, onPredictionCompleted, onPromptProcessingProgress, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFinalized, onToolCallRequestFailure, onToolCallRequestDequeued, guardToolCall, handleInvalidToolRequest, maxPredictionRounds, signal, preset, allowParallelToolExecution, ...config } = opts; + return [ + config, + { + onFirstToken, + onPredictionFragment, + onMessage, + onRoundStart, + onRoundEnd, + onPredictionCompleted, + onPromptProcessingProgress, + onToolCallRequestStart, + onToolCallRequestNameReceived, + onToolCallRequestArgumentFragmentGenerated, + onToolCallRequestEnd, + onToolCallRequestFinalized, + onToolCallRequestFailure, + onToolCallRequestDequeued, + guardToolCall, + handleInvalidToolRequest, + maxPredictionRounds, + signal, + preset, + allowParallelToolExecution + } + ]; +} +function stringifyAny(message) { + switch (typeof message) { + case "string": + return message; + case "number": + return message.toString(); + case "boolean": + return message ? "true" : "false"; + case "undefined": + return "undefined"; + case "object": + if (message === null) { + return "null"; + } + if (message instanceof Error) { + return message.stack; + } + return JSON.stringify(message, null, 2); + case "bigint": + return message.toString(); + case "symbol": + return message.toString(); + case "function": + return message.toString(); + default: + return "unknown"; + } +} +function concatenateDebugMessages(...messages) { + return messages.map(stringifyAny).join(" "); +} +function createId() { + return `${Date.now()}-${Math.random()}`; +} +var import_chalk, import_lms_isomorphic, Subscribable, Event2, NOTHING, DRAFTABLE, DRAFT_STATE, getPrototypeOf, objectCtorString, plugins, currentScope, objectTraps, arrayTraps, Immer2, immer, produceWithPatches, applyPatches, equals, Signal, LazySignal, apiServerPorts, waitForNextMicroTask, BufferedEvent, CancelEvent, Cleaner, IdGiver, boxen$1, stringWidth, ansiRegex, hasRequiredAnsiRegex, stripAnsi, hasRequiredStripAnsi, isFullwidthCodePoint, hasRequiredIsFullwidthCodePoint, emojiRegex4, hasRequiredEmojiRegex, hasRequiredStringWidth, widestLine, hasRequiredWidestLine, cliBoxes, single, double, round, bold, singleDouble, doubleSingle, classic, require$$0, hasRequiredCliBoxes, camelcase, hasRequiredCamelcase, ansiAlign_1, hasRequiredAnsiAlign, ansiStyles, colorName, hasRequiredColorName, conversions, hasRequiredConversions, route, hasRequiredRoute, colorConvert, hasRequiredColorConvert, hasRequiredAnsiStyles, wrapAnsi_1, hasRequiredWrapAnsi, hasRequiredBoxen, boxenExports, boxen, compiledTemplatesCache, MaybeMutable, OWLSignal, allowableEnvVarKeys, allowableEnvVarKeysSchema, allowableEnvVarsSchema, kebabCaseRegex, kebabCaseSchema, kebabCaseWithDotsRegex, kebabCaseWithDotsSchema, fileNameRegex, fileNameSchema, relativePathNoLeadingDotSlashRegex, huggingFaceModelDownloadSourceSchema, modelDownloadSourceSchema, artifactDependencyPurposeSchema, artifactDependencyBaseSchema, artifactModelDependencySchema, artifactArtifactDependencySchema, artifactDependencySchema, artifactManifestBaseSchema, artifactIdentifierRegex, artifactIdentifierSchema, modelManifestSchema, pluginRunnerTypeSchema, pluginManifestSchema, presetManifestSchema, artifactTypeSchema, backendNotificationSchema, fileTypeSchema, jsonSerializableSchema, chatMessagePartTextDataSchema, chatMessagePartFileDataSchema, functionToolCallRequestSchema, toolCallRequestSchema, chatMessagePartToolCallRequestDataSchema, chatMessagePartToolCallResultDataSchema, chatMessageDataSchema, chatHistoryDataSchema, citationSourceSchema, colorPalette, colorPaletteSchema, diagnosticsLogEventDataSchema, diagnosticsLogEventSchema, llmLlamaAccelerationOffloadRatioSchema, llmSplitStrategySchema, gpuSettingSchema, llmLlamaCacheQuantizationTypes, llmLlamaCacheQuantizationTypeSchema, llmMlxKvCacheBitsTypeSchema, llmMlxKvCacheGroupSizeTypesSchema, llmMlxKvCacheQuantizationSchema, llmLoadModelConfigSchema, embeddingLoadModelConfigSchema, modelCompatibilityTypeSchema, quantizationSchema, modelInfoBaseSchema, modelInstanceInfoBaseSchema, embeddingModelAdditionalInfoSchema, embeddingModelInstanceAdditionalInfoSchema, embeddingModelInfoSchema, embeddingModelInstanceInfoSchema, modelDomainTypeSchema, reasonableKeyStringSchema, modelQuerySchema, modelSpecifierSchema, genericErrorDisplayDataSchema, llmErrorDisplayDataSchema, errorDisplayDataSchema, serializedLMSExtendedErrorSchema, documentParsingLibraryIdentifierSchema, documentParsingOptsSchema, gpuSplitStrategies, gpuSplitStrategySchema, defaultGPUSplitConfig, gpuSplitConfigSchema, kvConfigFieldSchema, kvConfigSchema, kvConfigLayerNameSchema, kvConfigStackLayerSchema, kvConfigStackSchema, kvConfigFieldDependencySchema, contentBlockStyleSchema, llmToolParametersSchema, llmToolSchema, llmToolUseSettingSchema, llmApplyPromptTemplateOptsSchema, llmContextReferenceSchema, llmAdditionalInfoSchema, llmInstanceAdditionalInfoSchema, llmInfoSchema, llmInstanceInfoSchema, toolNamingSchema, zodSchemaSchema, llmManualPromptTemplateSchema, llmJinjaPromptTemplateSchema, llmPromptTemplateTypeSchema, llmPromptTemplateSchema, llmStructuredPredictionTypeSchema, llmStructuredPredictionSettingSchema, llmContextOverflowPolicySchema, llmReasoningParsingSchema, llmPredictionConfigInputSchema, llmLlamaMirostatSamplingConfigSchema, llmLlamaSingleLogitBiasModificationSchema, llmLlamaLogitBiasConfigSchema, llmPredictionFragmentReasoningTypeSchema, llmPredictionFragmentSchema, llmPredictionFragmentInputOptsSchema, llmPredictionStopReasonSchema, llmPredictionStatsSchema, llmGenInfoSchema, blockLocationSchema, statusStepStatusSchema, statusStepStateSchema, processingUpdateStatusCreateSchema, processingUpdateStatusUpdateSchema, processingUpdateStatusRemoveSchema, processingUpdateCitationBlockCreateSchema, processingUpdateDebugInfoBlockCreateSchema, processingUpdateContentBlockCreateSchema, processingUpdateContentBlockAppendTextSchema, processingUpdateContentBlockAppendToolResultSchema, processingUpdateContentBlockAppendToolRequestSchema, processingUpdateContentBlockReplaceToolRequestSchema, processingUpdateContentBlockReplaceTextSchema, processingUpdateContentBlockSetPrefixSchema, processingUpdateContentBlockSetSuffixSchema, processingUpdateContentBlockAttachGenInfoSchema, processingUpdateContentBlockSetStyleSchema, toolStatusStepStateStatusSchema, toolStatusStepStateSchema, processingUpdateToolStatusCreateSchema, processingUpdateToolStatusUpdateSchema, processingUpdateToolStatusArgumentFragmentSchema, processingUpdateSetSenderNameSchema, processingUpdateSchema, processingRequestConfirmToolCallSchema, processingRequestTextInputSchema, processingRequestSchema, processingRequestResponseConfirmToolCallSchema, processingRequestResponseTextInputSchema, processingRequestResponseSchema, tokenSourceIdentifierSchema, modelInfoSchema, modelInstanceInfoSchema, pluginConfigSpecifierSchema, remotePluginInfoSchema, artifactDownloadPlanModelInfoSchema, artifactDownloadPlanNodeStateSchema, artifactDownloadPlanNodeSchema, artifactDownloadPlanSchema, localArtifactFileEntrySchema, localArtifactFileListSchema, downloadProgressUpdateSchema, modelSearchResultDownloadOptionFitEstimationSchema, modelSearchResultDownloadOptionDataSchema, modelSearchResultIdentifierSchema, modelSearchResultEntryDataSchema, modelSearchOptsSchema, internalRetrievalResultEntrySchema, internalRetrievalResultSchema, retrievalChunkingMethodSchema, retrievalFileProcessingStepSchema, acceleratorTypeSchema, acceleratorSchema, serializedKVConfigSchematicsFieldSchema, serializedKVConfigSchematicsSchema, booleanOrMixedSchema, virtualModelDefinitionMetadataOverridesSchema, virtualModelDefinitionConcreteModelBaseSchema, virtualModelCustomFieldSetJinjaVariableEffectSchema, virtualModelCustomFieldPrependSystemPromptEffectSchema, virtualModelCustomFieldAppendSystemPromptEffectSchema, virtualModelCustomFieldDefinitionBaseSchema, virtualModelBooleanCustomFieldDefinitionSchema, virtualModelStringCustomFieldDefinitionSchema, virtualModelSelectCustomFieldDefinitionSchema, virtualModelCustomFieldDefinitionSchema, virtualModelConditionEqualsSchema, virtualModelConditionSchema, virtualModelSuggestionSchema, logLevelSchema, defaultInfoPrefix, defaultWarnPrefix, defaultErrorPrefix, defaultDebugPrefix, SimpleLogger, _a5, finished, StreamablePromise, Validator, sharedValidator, FileHandle, chatMessageInputSchema, chatHistoryInputSchema, Chat3, chatHistoryLikeSchema, ChatMessage, chatMessageLikeSchema, KVFieldValueTypesLibraryBuilder, KVFieldValueTypeLibrary, KVConfigSchematicsBuilder, createParsedKVConfig, KVConfigSchematics, KVConfigBuilder, ParsedKVConfig, PartialParsedKVConfig, emptyKVConfig, baseKVValueTypesLibraryBuilder, kvValueTypesLibrary, globalConfigSchematics, llmPredictionConfigSchematics, llmSharedPredictionConfigSchematics, llmLoadSchematics, llmSharedLoadConfigSchematics, llamaLoadConfigSchematics, llmLlamaLoadConfigSchematics, llmLlamaMoeAdditionalLoadConfigSchematics, llmLlamaMoeLoadConfigSchematics, embeddingLoadSchematics, embeddingSharedLoadConfigSchematics, retrievalSchematics, embeddingLlamaLoadConfigSchematics, lib, helpers, hasRequiredHelpers, attribute_1, hasRequiredAttribute, scan, hasRequiredScan, validator, hasRequiredValidator, hasRequiredLib, libExports, toolBaseSchema, SimpleToolCallContext, functionToolSchema, rawFunctionToolSchema, unimplementedRawFunctionToolSchema, remoteToolSchema, UnimplementedToolError, ToolCallRequestError, BackendInterface, ConnectionStatus, logger, Channel, DoubleIndexedKV, Registry, __extends, ClassRegistry, __read$3, CustomTransformerRegistry, getType$1, isUndefined, isNull, isPlainObject$1, isEmptyObject, isArray$1, isString, isNumber, isBoolean, isRegExp, isMap, isSet, isSymbol, isDate, isError, isNaNValue, isPrimitive, isBigint, isInfinite, isTypedArray, isURL, escapeKey, stringifyPath, parsePath, __assign$1, __read$2, __spreadArray$2, simpleRules, symbolRule, constructorToName, typedArrayRule, classRule, customRule, compositeRules, transformValue, simpleRulesByAnnotation, untransformValue, getNthKey, getDeep, setDeep, __read$1, __spreadArray$1, isDeep, walker, __assign, __read, __spreadArray, SuperJSON, serialize$1, deserialize$1, serializedOpaqueSchema, clientToServerMessageSchema, serverToClientMessageSchema, Transport, ClientTransport, wsAuthenticationResultSchema, WsClientTransportStatus, WsClientTransport, AuthenticatedWsClientTransport, ClientPort, GenericClientTransport, DiagnosticsNamespace, ModelNamespace, DynamicHandle, EmbeddingDynamicHandle, EmbeddingModel, EmbeddingNamespace, parseDocumentOptsSchema, retrievalCallbacksSchema, retrievalOptsSchema, FilesNamespace, errorDeserializersMap, ActResult, callIdGiver, NoQueueQueue, FIFOQueue, GuardToolCallController, llmActBaseOptsSchema, defaultHandleInvalidToolRequest, PredictionResult, StructuredPredictionResult, OngoingPrediction, llmPredictionOptsSchema, llmRespondOptsSchema, llmActionOptsSchema, noFormattingTemplate, LLMDynamicHandle, LLM, LLMNamespace, GeneratorPredictionResult, OngoingGeneratorPrediction, llmGeneratorPredictionOptsSchema, llmGeneratorActOptsSchema, LLMGeneratorHandle, generatorSchema, BaseController, GeneratorController, __addDisposableResource$1, __disposeResources$1, ProcessingConnector, ProcessingController, PredictionProcessStatusController, PredictionProcessCitationBlockController, PredictionProcessDebugInfoBlockController, PredictionProcessContentBlockController, PredictionProcessToolStatusController, ToolsProviderController, GeneratorConnectorImpl, PluginSelfRegistrationHost, __addDisposableResource, __disposeResources, SingleRemoteToolUseSession, MultiRemoteToolUseSession, pluginToolsOptsSchema, registerDevelopmentPluginOptsSchema, PluginsNamespace, artifactDownloadPlannerDownloadOptsSchema, ArtifactDownloadPlanner, downloadOptsSchema, ModelSearchResultDownloadOption, ModelSearchResultEntry, downloadArtifactOptsSchema, pushArtifactOptsSchema, ensureAuthenticatedOptsSchema, loginWithPreAuthenticatedKeysOptsSchema, createArtifactDownloadPlannerOptsSchema, RepositoryNamespace, startHttpServerOptsSchema, SystemNamespace, constructorOptsSchema, LMStudioClient; +var init_dist3 = __esm({ + "../pi-mono/node_modules/@lmstudio/sdk/dist/index.mjs"() { + init_process_shim(); + init_zod(); + init_process_shim(); + import_chalk = __toESM(require_source2(), 1); + import_lms_isomorphic = __toESM(require_browser2(), 1); + init_esm2(); + Subscribable = class { + subscribeWithCleaner(cleaner, listener) { + const unsubscribe = this.subscribe(listener); + cleaner.register(unsubscribe); + } + subscribeOnce(listener) { + const unsubscribe = this.subscribe((data) => { + unsubscribe(); + listener(data); + }); + return unsubscribe; + } + subscribeOnceWithCleaner(cleaner, listener) { + const unsubscribe = this.subscribeOnce(listener); + cleaner.register(unsubscribe); + } + derive(deriver, outputEqualsPredicate = (a3, b4) => a3 === b4) { + if (isSignalLike(this)) { + return LazySignal.deriveFrom([this], deriver); + } + const thisWithGetter = this; + if (thisWithGetter.get !== void 0) { + const initialValue = thisWithGetter.get(); + if (initialValue === LazySignal.NOT_AVAILABLE) { + return LazySignal.createWithoutInitialValue((setDownstream) => { + return thisWithGetter.subscribe((data) => { + if (isAvailable(data)) { + setDownstream(deriver(data)); + } + }); + }); + } + const thisNarrowed = thisWithGetter; + return LazySignal.create(deriver(thisNarrowed.get()), (setDownstream) => { + return thisNarrowed.subscribe((data) => { + setDownstream(deriver(data)); + }); + }, outputEqualsPredicate); + } + return LazySignal.createWithoutInitialValue((setDownstream) => { + return this.subscribe((data) => { + if (isAvailable(data)) { + setDownstream(deriver(data)); + } + }); + }, outputEqualsPredicate); + } + }; + Event2 = class _Event extends Subscribable { + /** + * Internal state that tracks whether the event has any subscribers. + */ + constructor() { + super(); + this.subscribers = /* @__PURE__ */ new Set(); + this.onSubscribed = null; + this.onUnsubscribed = null; + } + emit(data) { + queueMicrotask(() => { + for (const subscriber of this.subscribers) { + subscriber(data); + } + }); + } + static create() { + const event = new _Event(); + const emitter = (data) => { + event.emit(data); + }; + return [event, emitter]; + } + subscribe(listener) { + const previousSize = this.subscribers.size; + this.subscribers.add(listener); + if (previousSize === 0 && this.subscribers.size === 1) { + this.onSubscribed?.(); + } + return () => { + const previousSize2 = this.subscribers.size; + this.subscribers.delete(listener); + if (previousSize2 === 1 && this.subscribers.size === 0) { + this.onUnsubscribed?.(); + } + }; + } + batch({ minIdleTimeMs = 200, maxBatchTimeMs = 1e3 }) { + const [batchedEvent, emitBatchedEvent] = _Event.create(); + batchedEvent.onSubscribed = () => { + let batch = []; + let emitBatchTimeout = null; + let firstEventTime = 0; + const emitBatch = () => { + emitBatchTimeout = null; + emitBatchedEvent(batch); + batch = []; + }; + batchedEvent.onUnsubscribed = this.subscribe((data) => { + batch.push(data); + if (emitBatchTimeout === null) { + firstEventTime = Date.now(); + emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, maxBatchTimeMs)); + } else { + clearTimeout(emitBatchTimeout); + const timeSinceFirstEvent = Date.now() - firstEventTime; + emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, Math.max(0, maxBatchTimeMs - timeSinceFirstEvent))); + } + }); + }; + return batchedEvent; + } + }; + NOTHING = Symbol.for("immer-nothing"); + DRAFTABLE = Symbol.for("immer-draftable"); + DRAFT_STATE = Symbol.for("immer-state"); + getPrototypeOf = Object.getPrototypeOf; + objectCtorString = Object.prototype.constructor.toString(); + plugins = {}; + objectTraps = { + get(state, prop) { + if (prop === DRAFT_STATE) + return state; + const source = latest(state); + if (!has2(source, prop)) { + return readPropFromProto(state, source, prop); + } + const value = source[prop]; + if (state.finalized_ || !isDraftable(value)) { + return value; + } + if (value === peek(state.base_, prop)) { + prepareCopy(state); + return state.copy_[prop] = createProxy(value, state); + } + return value; + }, + has(state, prop) { + return prop in latest(state); + }, + ownKeys(state) { + return Reflect.ownKeys(latest(state)); + }, + set(state, prop, value) { + const desc = getDescriptorFromProto(latest(state), prop); + if (desc?.set) { + desc.set.call(state.draft_, value); + return true; + } + if (!state.modified_) { + const current2 = peek(latest(state), prop); + const currentState = current2?.[DRAFT_STATE]; + if (currentState && currentState.base_ === value) { + state.copy_[prop] = value; + state.assigned_[prop] = false; + return true; + } + if (is(value, current2) && (value !== void 0 || has2(state.base_, prop))) + return true; + prepareCopy(state); + markChanged(state); + } + if (state.copy_[prop] === value && // special case: handle new props with value 'undefined' + (value !== void 0 || prop in state.copy_) || // special case: NaN + Number.isNaN(value) && Number.isNaN(state.copy_[prop])) + return true; + state.copy_[prop] = value; + state.assigned_[prop] = true; + return true; + }, + deleteProperty(state, prop) { + if (peek(state.base_, prop) !== void 0 || prop in state.base_) { + state.assigned_[prop] = false; + prepareCopy(state); + markChanged(state); + } else { + delete state.assigned_[prop]; + } + if (state.copy_) { + delete state.copy_[prop]; + } + return true; + }, + // Note: We never coerce `desc.value` into an Immer draft, because we can't make + // the same guarantee in ES5 mode. + getOwnPropertyDescriptor(state, prop) { + const owner = latest(state); + const desc = Reflect.getOwnPropertyDescriptor(owner, prop); + if (!desc) + return desc; + return { + writable: true, + configurable: state.type_ !== 1 || prop !== "length", + enumerable: desc.enumerable, + value: owner[prop] + }; + }, + defineProperty() { + die(11); + }, + getPrototypeOf(state) { + return getPrototypeOf(state.base_); + }, + setPrototypeOf() { + die(12); + } + }; + arrayTraps = {}; + each(objectTraps, (key, fn) => { + arrayTraps[key] = function() { + arguments[0] = arguments[0][0]; + return fn.apply(this, arguments); + }; + }); + arrayTraps.deleteProperty = function(state, prop) { + if (false) + die(13); + return arrayTraps.set.call(this, state, prop, void 0); + }; + arrayTraps.set = function(state, prop, value) { + if (false) + die(14); + return objectTraps.set.call(this, state[0], prop, value, state[0]); + }; + Immer2 = class { + constructor(config) { + this.autoFreeze_ = true; + this.useStrictShallowCopy_ = false; + this.produce = (base, recipe, patchListener) => { + if (typeof base === "function" && typeof recipe !== "function") { + const defaultBase = recipe; + recipe = base; + const self2 = this; + return function curriedProduce(base2 = defaultBase, ...args) { + return self2.produce(base2, (draft) => recipe.call(this, draft, ...args)); + }; + } + if (typeof recipe !== "function") + die(6); + if (patchListener !== void 0 && typeof patchListener !== "function") + die(7); + let result; + if (isDraftable(base)) { + const scope = enterScope(this); + const proxy = createProxy(base, void 0); + let hasError = true; + try { + result = recipe(proxy); + hasError = false; + } finally { + if (hasError) + revokeScope(scope); + else + leaveScope(scope); + } + usePatchesInScope(scope, patchListener); + return processResult(result, scope); + } else if (!base || typeof base !== "object") { + result = recipe(base); + if (result === void 0) + result = base; + if (result === NOTHING) + result = void 0; + if (this.autoFreeze_) + freeze(result, true); + if (patchListener) { + const p4 = []; + const ip = []; + getPlugin("Patches").generateReplacementPatches_(base, result, p4, ip); + patchListener(p4, ip); + } + return result; + } else + die(1, base); + }; + this.produceWithPatches = (base, recipe) => { + if (typeof base === "function") { + return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args)); + } + let patches, inversePatches; + const result = this.produce(base, recipe, (p4, ip) => { + patches = p4; + inversePatches = ip; + }); + return [result, patches, inversePatches]; + }; + if (typeof config?.autoFreeze === "boolean") + this.setAutoFreeze(config.autoFreeze); + if (typeof config?.useStrictShallowCopy === "boolean") + this.setUseStrictShallowCopy(config.useStrictShallowCopy); + } + createDraft(base) { + if (!isDraftable(base)) + die(8); + if (isDraft(base)) + base = current(base); + const scope = enterScope(this); + const proxy = createProxy(base, void 0); + proxy[DRAFT_STATE].isManual_ = true; + leaveScope(scope); + return proxy; + } + finishDraft(draft, patchListener) { + const state = draft && draft[DRAFT_STATE]; + if (!state || !state.isManual_) + die(9); + const { scope_: scope } = state; + usePatchesInScope(scope, patchListener); + return processResult(void 0, scope); + } + /** + * Pass true to automatically freeze all copies created by Immer. + * + * By default, auto-freezing is enabled. + */ + setAutoFreeze(value) { + this.autoFreeze_ = value; + } + /** + * Pass true to enable strict shallow copy. + * + * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties. + */ + setUseStrictShallowCopy(value) { + this.useStrictShallowCopy_ = value; + } + applyPatches(base, patches) { + let i7; + for (i7 = patches.length - 1; i7 >= 0; i7--) { + const patch = patches[i7]; + if (patch.path.length === 0 && patch.op === "replace") { + base = patch.value; + break; + } + } + if (i7 > -1) { + patches = patches.slice(i7 + 1); + } + const applyPatchesImpl = getPlugin("Patches").applyPatches_; + if (isDraft(base)) { + return applyPatchesImpl(base, patches); + } + return this.produce( + base, + (draft) => applyPatchesImpl(draft, patches) + ); + } + }; + immer = new Immer2(); + immer.produce; + produceWithPatches = immer.produceWithPatches.bind( + immer + ); + immer.setAutoFreeze.bind(immer); + immer.setUseStrictShallowCopy.bind(immer); + applyPatches = immer.applyPatches.bind(immer); + immer.createDraft.bind(immer); + immer.finishDraft.bind(immer); + enableMapSet(); + enablePatches(); + equals = (a3, b4) => a3 === b4; + Signal = class _Signal extends Subscribable { + /** + * Creates a signal. + * + * @param value - The initial value of the signal. + * @param equalsPredicate - A function to compare two values. The subscribers will only be called + * if the value changes according to the `equalsPredicate`. By default, it uses the `===` + * operator. + * @returns This method returns a tuple with two elements: + * - The signal + * - A function to update the value + **/ + static create(value, equalsPredicate = equals) { + const signal = new _Signal(value, equalsPredicate); + const update = (updater, tags) => { + signal.update(updater, tags); + }; + const setter = makeSetterWithPatches(update); + return [signal, setter]; + } + static createReadonly(value) { + return _Signal.create(value)[0]; + } + constructor(value, equalsPredicate) { + super(); + this.value = value; + this.equalsPredicate = equalsPredicate; + this.subscribers = /* @__PURE__ */ new Set(); + this.queuedUpdaters = []; + this.isEmitting = false; + } + /** + * Returns the current value of the signal. + */ + get() { + return this.value; + } + pull() { + return this.value; + } + notifyFull(value, patches, tags) { + for (const { type, callback: callback2 } of this.subscribers) { + if (type === "full") { + callback2(value, patches, tags); + } + } + } + notifyAll(value, patches, tags) { + for (const { type, callback: callback2 } of this.subscribers) { + if (type === "regular") { + callback2(value); + } else { + callback2(value, patches, tags); + } + } + } + notifyAndUpdateIfChanged(value, patches, tags) { + if (!this.equalsPredicate(this.value, value)) { + this.value = value; + this.notifyAll(value, patches, tags); + } else if (tags.length > 0) { + this.notifyFull(value, patches, tags); + } + } + isReplaceRoot(patch) { + return patch.path.length === 0 && patch.op === "replace"; + } + update(updater, tags) { + this.queuedUpdaters.push([updater, tags]); + if (this.isEmitting) { + return; + } + this.isEmitting = true; + try { + while (this.queuedUpdaters.length > 0) { + let value = this.value; + let patches = []; + const tags2 = []; + while (this.queuedUpdaters.length > 0) { + const [updater2, newTags] = this.queuedUpdaters.shift(); + const [newValue, newPatches] = updater2(value); + value = newValue; + const rootReplacerIndex = newPatches.findIndex(this.isReplaceRoot); + if (rootReplacerIndex !== -1) { + patches = newPatches.slice(rootReplacerIndex); + } else { + patches.push(...newPatches); + } + if (newTags !== void 0) { + tags2.push(...newTags); + } + } + this.notifyAndUpdateIfChanged(value, patches, tags2); + } + } finally { + this.isEmitting = false; + } + } + /** + * Subscribes to the signal. The callback will be called whenever the value changes. All callbacks + * are called synchronously upon updating. It will NOT be immediately called with the current + * value. (Use `get()` to get the current value.) Returns a function to unsubscribe. + * + * Edge cases involving manipulating the signal in the callback: + * + * - If the callback adds new subscribers, they will also be called within the same update. + * - If the callback causes removal of subscribers that have not been called yet, they will no + * longer be called. + * - If the callback causes an update of the value, the update will be queued. If multiple updates + * are queued, only the last one will be executed. + * + * Edge cases involving adding the same callback multiple times. + * + * - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called + * multiple times. + */ + subscribe(callback2) { + const subscriber = { + type: "regular", + callback: callback2 + }; + this.subscribers.add(subscriber); + return () => { + this.subscribers.delete(subscriber); + }; + } + /** + * Subscribes to the signal with the callback and trigger the callback immediately with the + * current value. + */ + subscribeAndNow(callback2) { + const unsubscribe = this.subscribe(callback2); + callback2(this.value); + return unsubscribe; + } + subscribeFull(callback2) { + const subscriber = { + type: "full", + callback: callback2 + }; + this.subscribers.add(subscriber); + return () => { + this.subscribers.delete(subscriber); + }; + } + /** + * Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will + * return immediately. Otherwise, it will wait until the signal satisfies the predicate. + */ + async until(predicate) { + const current2 = this.get(); + if (predicate(current2)) { + return current2; + } + const { promise, resolve: resolve2 } = makePromise(); + const unsubscribe = this.subscribe((data) => { + if (predicate(data)) { + resolve2(data); + unsubscribe(); + } + }); + return await promise; + } + }; + LazySignal = class _LazySignal extends Subscribable { + static { + this.NOT_AVAILABLE = Symbol("notAvailable"); + } + static create(initialValue, subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) { + return new _LazySignal(initialValue, subscribeUpstream, equalsPredicate); + } + static createWithoutInitialValue(subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) { + const fullEqualsPredicate = (a3, b4) => { + if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) { + return a3 === b4; + } + return equalsPredicate(a3, b4); + }; + return new _LazySignal(_LazySignal.NOT_AVAILABLE, subscribeUpstream, fullEqualsPredicate); + } + static deriveFrom(sourceSignals, deriver, outputEqualsPredicate) { + let fullEqualsPredicate = void 0; + if (outputEqualsPredicate !== void 0) { + fullEqualsPredicate = (a3, b4) => { + if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) { + return a3 === b4; + } + return outputEqualsPredicate(a3, b4); + }; + } + const derive = () => { + const sourceValues = sourceSignals.map((signal) => signal.get()); + if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) { + return _LazySignal.NOT_AVAILABLE; + } + return deriver(...sourceValues); + }; + return new _LazySignal(derive(), (setDownstream) => { + const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => { + const value = derive(); + if (isAvailable(value)) { + setDownstream(value); + } + })); + const newValue = derive(); + if (isAvailable(newValue)) { + setDownstream(newValue); + } + return () => { + unsubscriber.forEach((unsub) => unsub()); + }; + }, fullEqualsPredicate); + } + static asyncDeriveFrom(strategy, sourceSignals, deriver, outputEqualsPredicate) { + let fullEqualsPredicate = void 0; + if (outputEqualsPredicate !== void 0) { + fullEqualsPredicate = (a3, b4) => { + if (a3 === _LazySignal.NOT_AVAILABLE || b4 === _LazySignal.NOT_AVAILABLE) { + return a3 === b4; + } + return outputEqualsPredicate(a3, b4); + }; + } + let lastAppliedUpdateId = -1; + let lastIssuedUpdateId = -1; + return new _LazySignal(_LazySignal.NOT_AVAILABLE, (setDownstream) => { + const deriveAndUpdate = () => { + lastIssuedUpdateId++; + const updateId = lastIssuedUpdateId; + const sourceValues = sourceSignals.map((signal) => signal.get()); + if (sourceValues.some((value) => value === _LazySignal.NOT_AVAILABLE)) { + return; + } + deriver(...sourceValues).then((result) => { + if (!isAvailable(result)) { + return; + } + switch (strategy) { + case "eager": { + if (updateId > lastAppliedUpdateId) { + lastAppliedUpdateId = updateId; + setDownstream(result); + } + break; + } + default: { + const exhaustiveCheck = strategy; + throw new Error(`Unknown strategy: ${exhaustiveCheck}`); + } + } + }); + }; + const unsubscriber = sourceSignals.map((signal) => signal.subscribe(() => { + deriveAndUpdate(); + })); + deriveAndUpdate(); + return () => { + unsubscriber.forEach((unsub) => unsub()); + }; + }, fullEqualsPredicate); + } + constructor(initialValue, subscribeUpstream, equalsPredicate = (a3, b4) => a3 === b4) { + super(); + this.subscribeUpstream = subscribeUpstream; + this.dataIsStale = true; + this.upstreamUnsubscribe = null; + this.subscribersCount = 0; + this.isSubscribedToUpstream = false; + this.updateReceivedSynchronousCallbacks = /* @__PURE__ */ new Set(); + [this.signal, this.setValue] = Signal.create(initialValue, equalsPredicate); + [this.updateReceivedEvent, this.emitUpdateReceivedEvent] = Event2.create(); + } + /** + * Returns whether the value is currently stale. + * + * A value is stale whenever the upstream subscription is not active. This can happen in three + * cases: + * + * 1. When no subscriber is attached to this signal, the signal will not subscribe to the + * upstream. In this case, the value is always stale. + * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the + * value is also stale. + * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is + * terminated and the value is stale. + * + * If you wish to get the current value and ensure that it is not stale, use the method + * {@link LazySignal#pull}. + */ + isStale() { + return this.dataIsStale; + } + subscribeToUpstream() { + this.isSubscribedToUpstream = true; + let subscribed = true; + let becameStale = false; + const unsubscribeFromUpstream = this.subscribeUpstream(makeSetterWithPatches((updater, tags) => { + if (!subscribed) { + return; + } + this.setValue.withPatchUpdater(updater, tags); + this.dataIsStale = becameStale; + this.emitUpdateReceivedEvent(); + for (const callback2 of this.updateReceivedSynchronousCallbacks) { + callback2(); + } + }), (error) => { + if (!subscribed) { + return; + } + Promise.reject(error); + this.dataIsStale = true; + this.isSubscribedToUpstream = false; + this.upstreamUnsubscribe = null; + subscribed = false; + }); + this.upstreamUnsubscribe = () => { + if (subscribed) { + subscribed = false; + becameStale = true; + unsubscribeFromUpstream(); + } + }; + } + unsubscribeFromUpstream() { + this.isSubscribedToUpstream = false; + if (this.upstreamUnsubscribe !== null) { + this.upstreamUnsubscribe(); + this.upstreamUnsubscribe = null; + this.dataIsStale = true; + } + } + /** + * Gets the current value of the signal. If the value is not available, it will return + * {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created + * without an initial value and the upstream has not emitted a value yet.) + * + * In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to + * check if the value is stale. + * + * If you wish to get the current value and ensure that it is not stale, use the method + * {@link LazySignal#pull}. + */ + get() { + return this.signal.get(); + } + /** + * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for + * the next value from the upstream and return it. + */ + async pull() { + const { promise, resolve: resolve2 } = makePromise(); + if (!this.isStale()) { + resolve2(this.get()); + } else { + const unsubscribe = this.subscribe(() => { + }); + this.updateReceivedEvent.subscribeOnce(() => { + resolve2(this.get()); + }); + promise.then(unsubscribe); + } + return promise; + } + /** + * If the data is not stale, the callback will be called synchronously with the current value. + * + * If the data is stale, it will pull the current value and call the callback with the value. + */ + runOnNextFreshData(callback2) { + if (!this.isStale()) { + callback2(this.get()); + } else { + let unsubscribe = null; + const updateCallback = () => { + this.updateReceivedSynchronousCallbacks.delete(updateCallback); + callback2(this.get()); + unsubscribe?.(); + }; + this.updateReceivedSynchronousCallbacks.add(updateCallback); + unsubscribe = this.subscribe(() => { + }); + } + } + async ensureAvailable() { + await this.pull(); + return this; + } + subscribe(subscriber) { + if (!this.isSubscribedToUpstream) { + this.subscribeToUpstream(); + } + this.subscribersCount++; + const unsubscribe = this.signal.subscribe(subscriber); + let unsubscribeCalled = false; + return () => { + if (unsubscribeCalled) { + return; + } + unsubscribe(); + unsubscribeCalled = true; + this.subscribersCount--; + if (this.subscribersCount === 0 && this.isSubscribedToUpstream) { + this.unsubscribeFromUpstream(); + } + }; + } + subscribeFull(subscriber) { + if (!this.isSubscribedToUpstream) { + this.subscribeToUpstream(); + } + this.subscribersCount++; + const unsubscribe = this.signal.subscribeFull(subscriber); + let unsubscribeCalled = false; + return () => { + if (unsubscribeCalled) { + return; + } + unsubscribe(); + unsubscribeCalled = true; + this.subscribersCount--; + if (this.subscribersCount === 0 && this.isSubscribedToUpstream) { + this.unsubscribeFromUpstream(); + } + }; + } + /** + * Subscribes to the signal. Will not cause the signal to subscribe to the upstream. + */ + passiveSubscribe(subscriber) { + return this.signal.subscribe(subscriber); + } + passiveSubscribeFull(subscriber) { + return this.signal.subscribeFull(subscriber); + } + async until(predicate) { + const current2 = this.get(); + if (isAvailable(current2) && predicate(current2)) { + return current2; + } + const { promise, resolve: resolve2 } = makePromise(); + const unsubscribe = this.subscribe((data) => { + if (isAvailable(data) && predicate(data)) { + resolve2(data); + unsubscribe(); + } + }); + return await promise; + } + }; + apiServerPorts = [41343, 52993, 16141, 39414, 22931]; + waitForNextMicroTask = Symbol(); + BufferedEvent = class _BufferedEvent extends Subscribable { + static create() { + const event = new _BufferedEvent(); + const emitter = (data) => { + event.emit(data); + }; + return [event, emitter]; + } + constructor() { + super(); + this.subscriber = null; + this.queued = []; + this.isNotifying = false; + } + emit(data) { + if (this.queued.length === 0 && this.queued.at(-1) !== waitForNextMicroTask) { + this.queued.push(waitForNextMicroTask); + } + this.queued.push(data); + if (!this.isNotifying) { + this.notifier(); + } + } + async notifier() { + this.isNotifying = true; + while (this.subscriber !== null && this.queued.length > 0) { + const data = this.queued.shift(); + if (data === waitForNextMicroTask) { + await Promise.resolve(); + } else { + this.subscriber(data); + } + } + this.isNotifying = false; + } + subscribe(listener) { + if (this.subscriber !== null) { + throw new Error("Cannot have more than one subscriber"); + } + this.subscriber = listener; + if (!this.isNotifying && this.queued.length > 0) { + this.queued = [ + waitForNextMicroTask, + ...this.queued.filter((data) => data !== waitForNextMicroTask) + ]; + this.notifier(); + } + return () => { + this.subscriber = null; + }; + } + /** + * Convert this buffered event to an event by stop buffering and triggering events on the new + * returned event. + */ + flow() { + const [event, emit] = Event2.create(); + this.subscribe(emit); + return event; + } + }; + CancelEvent = class extends Subscribable { + constructor() { + super(...arguments); + this.canceled = false; + this.listeners = /* @__PURE__ */ new Set(); + } + subscribe(listener) { + if (this.canceled) { + let callbackCanceled = false; + Promise.resolve().then(() => { + if (!callbackCanceled) { + listener(); + } + }); + return () => { + callbackCanceled = true; + }; + } + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + } + cancel() { + if (this.canceled) { + throw new Error("Already canceled"); + } + this.canceled = true; + for (const listener of this.listeners) { + listener(); + } + } + isCanceled() { + return this.canceled; + } + }; + Cleaner = class { + constructor() { + this.eagerCleaned = false; + this.disposed = false; + this.cleanups = []; + } + register(fn) { + if (this.eagerCleaned) { + throw new Error("Cannot register a cleanup after eagerClean() was called."); + } + if (this.disposed) { + throw new Error("Cannot register a cleanup after the Cleaner was disposed."); + } + this.cleanups.push(fn); + } + runCleanersInternal() { + for (const cleanup of this.cleanups) { + cleanup(); + } + this.cleanups.length = 0; + } + [Symbol.dispose]() { + if (this.eagerCleaned) { + return; + } + if (this.disposed) { + throw new Error("Cannot dispose a Cleaner that was already disposed."); + } + this.runCleanersInternal(); + } + eagerClean() { + if (this.eagerCleaned) { + throw new Error("Cannot call eagerClean() twice."); + } + if (this.disposed) { + throw new Error("Cannot call eagerClean() after the Cleaner was disposed."); + } + this.eagerCleaned = true; + this.runCleanersInternal(); + } + }; + IdGiver = class { + constructor(firstId = 0) { + this.nextId = firstId; + } + next() { + const id = this.nextId; + this.nextId++; + return id; + } + }; + boxen$1 = { exports: {} }; + stringWidth = { exports: {} }; + isFullwidthCodePoint = { exports: {} }; + widestLine = { exports: {} }; + cliBoxes = { exports: {} }; + single = { + topLeft: "\u250C", + topRight: "\u2510", + bottomRight: "\u2518", + bottomLeft: "\u2514", + vertical: "\u2502", + horizontal: "\u2500" + }; + double = { + topLeft: "\u2554", + topRight: "\u2557", + bottomRight: "\u255D", + bottomLeft: "\u255A", + vertical: "\u2551", + horizontal: "\u2550" + }; + round = { + topLeft: "\u256D", + topRight: "\u256E", + bottomRight: "\u256F", + bottomLeft: "\u2570", + vertical: "\u2502", + horizontal: "\u2500" + }; + bold = { + topLeft: "\u250F", + topRight: "\u2513", + bottomRight: "\u251B", + bottomLeft: "\u2517", + vertical: "\u2503", + horizontal: "\u2501" + }; + singleDouble = { + topLeft: "\u2553", + topRight: "\u2556", + bottomRight: "\u255C", + bottomLeft: "\u2559", + vertical: "\u2551", + horizontal: "\u2500" + }; + doubleSingle = { + topLeft: "\u2552", + topRight: "\u2555", + bottomRight: "\u255B", + bottomLeft: "\u2558", + vertical: "\u2502", + horizontal: "\u2550" + }; + classic = { + topLeft: "+", + topRight: "+", + bottomRight: "+", + bottomLeft: "+", + vertical: "|", + horizontal: "-" + }; + require$$0 = { + single, + double, + round, + bold, + singleDouble, + doubleSingle, + classic + }; + camelcase = { exports: {} }; + ansiStyles = { exports: {} }; + ansiStyles.exports; + boxenExports = requireBoxen(); + boxen = /* @__PURE__ */ getDefaultExportFromCjs(boxenExports); + compiledTemplatesCache = /* @__PURE__ */ new WeakMap(); + MaybeMutable = class { + constructor(data, mutable) { + this.data = data; + this.mutable = mutable; + } + /** + * Gets the underlying data without any access control. Only used internally. + * + * @internal + */ + _internalGetData() { + return this.data; + } + /** + * If this instance is mutable, return as is. + * + * If this instance is immutable, return a mutable copy. + * + * Very easy to misuse, thus internal only for now. + * + * @internal + */ + _internalToMutable() { + if (this.mutable) { + return this; + } + return this.asMutableCopy(); + } + asMutableCopy() { + return this.create(this.cloneData(this.data), true); + } + asImmutableCopy() { + if (this.mutable) { + return this.create(this.cloneData(this.data), false); + } + return this; + } + guardMutable() { + if (!this.mutable) { + throw new Error(text` + Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a + mutable copy. + `); + } + } + }; + OWLSignal = class _OWLSignal extends Subscribable { + static { + this.NOT_AVAILABLE = LazySignal.NOT_AVAILABLE; + } + applyOptimisticUpdates(data) { + for (const update of this.queuedUpdates) { + [data] = update.updater(data); + } + return data; + } + updateOptimisticValue(tags) { + const innerValue = this.innerSignal.get(); + if (!isAvailable(innerValue)) { + return; + } + this.setOuterSignal(this.applyOptimisticUpdates(innerValue), tags); + } + constructor(initialValue, subscribeUpstream, writeUpstream, equalsPredicate) { + super(); + this.writeUpstream = writeUpstream; + this.isWriteLoopRunning = false; + this.isSubscriptionHandledByWriteLoop = false; + this.queuedUpdates = []; + this.currentEnsureAvailablePromise = null; + [this.writeErrorEvent, this.emitWriteErrorEvent] = Event2.create(); + [this.outerSignal, this.setOuterSignal] = Signal.create(initialValue, equalsPredicate); + this.innerSignal = LazySignal.create(initialValue, subscribeUpstream, equalsPredicate); + this.innerSignal.passiveSubscribeFull((_data, _patches, tags) => { + if (this.isSubscriptionHandledByWriteLoop) { + return; + } + this.updateOptimisticValue(tags); + }); + } + static create(initialValue, subscribeUpstream, writeUpstream, equalsPredicate = (a3, b4) => a3 === b4) { + const signal = new _OWLSignal(initialValue, subscribeUpstream, writeUpstream, equalsPredicate); + const setSignal = makeSetterWithPatches(signal.update.bind(signal)); + const emitError = (tags, error) => signal.emitWriteErrorEvent({ tags, error }); + return [signal, setSignal, emitError]; + } + static createWithoutInitialValue(subscribeUpstream, writeUpstream, equalsPredicate = (a3, b4) => a3 === b4) { + const fullEqualsPredicate = (a3, b4) => { + if (a3 === _OWLSignal.NOT_AVAILABLE || b4 === _OWLSignal.NOT_AVAILABLE) { + return a3 === b4; + } + return equalsPredicate(a3, b4); + }; + return _OWLSignal.create(_OWLSignal.NOT_AVAILABLE, subscribeUpstream, writeUpstream, fullEqualsPredicate); + } + async update(updater, tags) { + const { promise, reject, resolve: resolve2 } = makePromise(); + this.queuedUpdates.push({ + updater, + tags: tags ?? [], + resolve: resolve2, + reject + }); + this.updateOptimisticValue(); + this.ensureWriteLoop(); + return promise; + } + /** + * Starts the write loop if it is not already running. + */ + ensureWriteLoop() { + if (!this.isWriteLoopRunning) { + this.writeLoop(); + } + } + /** + * The main write loop, it will keep running until there are no more updates to process. + */ + async writeLoop() { + const unsubscribe = this.innerSignal.subscribe(() => { + }); + this.isWriteLoopRunning = true; + if (this.isStale()) { + await this.innerSignal.pull(); + } + while (this.queuedUpdates.length > 0) { + const numQueuedUpdatesToHandle = this.queuedUpdates.length; + const updater = (data) => { + const patches = []; + for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) { + const [newData, newPatches] = this.queuedUpdates[i7].updater(data); + data = newData; + patches.push(...newPatches); + } + return [data, patches]; + }; + const resolve2 = () => { + for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) { + this.queuedUpdates[i7].resolve(); + } + }; + const reject = (error) => { + for (let i7 = 0; i7 < numQueuedUpdatesToHandle; i7++) { + this.queuedUpdates[i7].reject(error); + } + }; + const queuedUpdateTags = this.queuedUpdates.flatMap((update) => update.tags); + const tag = Date.now() + "-" + Math.random(); + await new Promise((nextStep) => { + this.isSubscriptionHandledByWriteLoop = true; + const unsubscribeArray = []; + const settle = () => { + this.isSubscriptionHandledByWriteLoop = false; + unsubscribeArray.forEach((unsubscribe2) => unsubscribe2()); + nextStep(); + }; + unsubscribeArray.push(this.innerSignal.subscribeFull((_data, _patches, tags) => { + if (!this.isSubscriptionHandledByWriteLoop) { + return; + } + if (tags?.includes(tag)) { + settle(); + resolve2(); + this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); + this.updateOptimisticValue(tags.filter((t6) => t6 !== tag)); + } else { + this.updateOptimisticValue(tags); + } + })); + unsubscribeArray.push(this.writeErrorEvent.subscribe(({ tags, error }) => { + if (!this.isSubscriptionHandledByWriteLoop) { + return; + } + if (tags.includes(tag)) { + settle(); + reject(error); + this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); + } + })); + const sent = this.writeUpstream(...updater(this.innerSignal.get()), [tag, ...queuedUpdateTags]); + if (!sent) { + settle(); + resolve2(); + this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); + this.updateOptimisticValue(queuedUpdateTags.filter((t6) => t6 !== tag)); + } + }); + } + this.isWriteLoopRunning = false; + unsubscribe(); + } + /** + * Returns whether the value is currently stale. + * + * A value is stale whenever the upstream subscription is not active. This can happen in three + * cases: + * + * 1. When no subscriber is attached to this signal, the signal will not subscribe to the + * upstream. In this case, the value is always stale. + * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the + * value is also stale. + * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is + * terminated and the value is stale. + * + * If you wish to get the current value and ensure that it is not stale, use the method + * {@link OWLSignal#pull}. + */ + isStale() { + return this.innerSignal.isStale(); + } + /** + * Gets the current value of the signal. If the value is not available, it will return + * {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created + * without an initial value and the upstream has not emitted a value yet.) + * + * In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to + * check if the value is stale. + * + * If you wish to get the current value and ensure that it is not stale, use the method + * {@link OWLSignal#pull}. + */ + get() { + return this.outerSignal.get(); + } + /** + * Gets the current value of the signal pessimistically. If the value is not available, it will + * return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is + * created without an initial value and the upstream has not emitted a value yet.) + */ + getPessimistic() { + return this.innerSignal.get(); + } + /** + * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for + * the next value from the upstream and return it. + * + * You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic + * updates will be applied to the value before returning it. + */ + async pull({ optimistic = true } = {}) { + if (optimistic) { + return this.applyOptimisticUpdates(await this.innerSignal.pull()); + } else { + return this.innerSignal.pull(); + } + } + async ensureAvailable() { + if (this.currentEnsureAvailablePromise === null) { + this.currentEnsureAvailablePromise = (async () => { + await this.innerSignal.pull(); + return this; + })(); + } + return this.currentEnsureAvailablePromise; + } + subscribe(subscriber) { + const unsubscribeOuter = this.outerSignal.subscribe(subscriber); + const unsubscribeInner = this.innerSignal.subscribe(() => { + }); + return () => { + unsubscribeOuter(); + unsubscribeInner(); + }; + } + subscribeFull(subscriber) { + const unsubscribeOuter = this.outerSignal.subscribeFull(subscriber); + const unsubscribeInner = this.innerSignal.subscribeFull(() => { + }); + return () => { + unsubscribeOuter(); + unsubscribeInner(); + }; + } + }; + allowableEnvVarKeys = ["HSA_OVERRIDE_GFX_VERSION"]; + allowableEnvVarKeysSchema = external_exports.enum(allowableEnvVarKeys); + allowableEnvVarsSchema = external_exports.record(allowableEnvVarKeysSchema, external_exports.string()); + kebabCaseRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; + kebabCaseSchema = external_exports.string().regex(kebabCaseRegex); + kebabCaseWithDotsRegex = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/; + kebabCaseWithDotsSchema = external_exports.string().regex(kebabCaseWithDotsRegex); + fileNameRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(? { + try { + return JSON.parse(JSON.stringify(val2)); + } catch (e9) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + message: "Not JSON serializable: " + e9.message + }); + return val2; + } + }); + chatMessagePartTextDataSchema = external_exports.object({ + type: external_exports.literal("text"), + text: external_exports.string() + }); + chatMessagePartFileDataSchema = external_exports.object({ + type: external_exports.literal("file"), + name: external_exports.string(), + identifier: external_exports.string(), + sizeBytes: external_exports.number().int(), + fileType: fileTypeSchema + }); + functionToolCallRequestSchema = external_exports.object({ + id: external_exports.string().optional(), + type: external_exports.literal("function"), + arguments: external_exports.record(jsonSerializableSchema).optional(), + name: external_exports.string() + }); + toolCallRequestSchema = external_exports.discriminatedUnion("type", [ + functionToolCallRequestSchema + ]); + chatMessagePartToolCallRequestDataSchema = external_exports.object({ + type: external_exports.literal("toolCallRequest"), + toolCallRequest: toolCallRequestSchema + }); + external_exports.object({ + content: external_exports.string(), + toolCallId: external_exports.string().optional() + }); + chatMessagePartToolCallResultDataSchema = external_exports.object({ + type: external_exports.literal("toolCallResult"), + content: external_exports.string(), + toolCallId: external_exports.string().optional() + }); + external_exports.discriminatedUnion("type", [ + chatMessagePartTextDataSchema, + chatMessagePartFileDataSchema, + chatMessagePartToolCallRequestDataSchema, + chatMessagePartToolCallResultDataSchema + ]); + external_exports.enum(["assistant", "user", "system", "tool"]); + chatMessageDataSchema = external_exports.discriminatedUnion("role", [ + external_exports.object({ + role: external_exports.literal("assistant"), + content: external_exports.array(external_exports.discriminatedUnion("type", [ + chatMessagePartTextDataSchema, + chatMessagePartFileDataSchema, + chatMessagePartToolCallRequestDataSchema + ])) + }), + external_exports.object({ + role: external_exports.literal("user"), + content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema])) + }), + external_exports.object({ + role: external_exports.literal("system"), + content: external_exports.array(external_exports.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema])) + }), + external_exports.object({ + role: external_exports.literal("tool"), + content: external_exports.array(chatMessagePartToolCallResultDataSchema) + }) + ]); + chatHistoryDataSchema = external_exports.object({ + messages: external_exports.array(chatMessageDataSchema) + }); + citationSourceSchema = external_exports.object({ + fileName: external_exports.string(), + absoluteFilePath: external_exports.string().optional(), + pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(), + lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional() + }); + colorPalette = external_exports.enum([ + "red", + "green", + "blue", + "yellow", + "orange", + "purple", + "default" + ]); + colorPaletteSchema = colorPalette; + diagnosticsLogEventDataSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("llm.prediction.input"), + modelPath: external_exports.string(), + modelIdentifier: external_exports.string(), + input: external_exports.string() + }) + ]); + diagnosticsLogEventSchema = external_exports.object({ + timestamp: external_exports.number(), + data: diagnosticsLogEventDataSchema + }); + llmLlamaAccelerationOffloadRatioSchema = external_exports.union([ + external_exports.number().min(0).max(1), + external_exports.literal("max"), + external_exports.literal("off") + ]); + llmSplitStrategySchema = external_exports.enum(["evenly", "favorMainGpu"]); + gpuSettingSchema = external_exports.object({ + ratio: llmLlamaAccelerationOffloadRatioSchema.optional(), + mainGpu: external_exports.number().int().optional(), + splitStrategy: llmSplitStrategySchema.optional(), + disabledGpus: external_exports.array(external_exports.number().int()).optional() + }); + llmLlamaCacheQuantizationTypes = [ + "f32", + "f16", + "q8_0", + "q4_0", + "q4_1", + "iq4_nl", + "q5_0", + "q5_1" + ]; + llmLlamaCacheQuantizationTypeSchema = external_exports.enum(llmLlamaCacheQuantizationTypes); + llmMlxKvCacheBitsTypeSchema = external_exports.union([ + external_exports.literal(8), + external_exports.literal(6), + external_exports.literal(4), + external_exports.literal(3), + external_exports.literal(2) + ]); + llmMlxKvCacheGroupSizeTypesSchema = external_exports.union([ + external_exports.literal(32), + external_exports.literal(64), + external_exports.literal(128) + ]); + llmMlxKvCacheQuantizationSchema = external_exports.object({ + enabled: external_exports.boolean(), + bits: llmMlxKvCacheBitsTypeSchema, + groupSize: llmMlxKvCacheGroupSizeTypesSchema, + quantizedStart: external_exports.number().int().nonnegative() + }); + llmLoadModelConfigSchema = external_exports.object({ + gpu: gpuSettingSchema.optional(), + gpuStrictVramCap: external_exports.boolean().optional(), + offloadKVCacheToGpu: external_exports.boolean().optional(), + contextLength: external_exports.number().int().min(1).optional(), + ropeFrequencyBase: external_exports.number().optional(), + ropeFrequencyScale: external_exports.number().optional(), + evalBatchSize: external_exports.number().int().min(1).optional(), + flashAttention: external_exports.boolean().optional(), + keepModelInMemory: external_exports.boolean().optional(), + seed: external_exports.number().int().optional(), + useFp16ForKVCache: external_exports.boolean().optional(), + tryMmap: external_exports.boolean().optional(), + numExperts: external_exports.number().int().optional(), + llamaKCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional(), + llamaVCacheQuantizationType: external_exports.enum(llmLlamaCacheQuantizationTypes).or(external_exports.literal(false)).optional() + }); + embeddingLoadModelConfigSchema = external_exports.object({ + gpu: gpuSettingSchema.optional(), + contextLength: external_exports.number().int().min(1).optional(), + ropeFrequencyBase: external_exports.number().optional(), + ropeFrequencyScale: external_exports.number().optional(), + keepModelInMemory: external_exports.boolean().optional(), + tryMmap: external_exports.boolean().optional() + }); + modelCompatibilityTypeSchema = external_exports.enum([ + "gguf", + "safetensors", + "onnx", + "ggml", + "mlx_placeholder", + "torch_safetensors" + ]); + quantizationSchema = external_exports.object({ + name: external_exports.string(), + bits: external_exports.number().int() + }); + modelInfoBaseSchema = external_exports.object({ + modelKey: external_exports.string(), + format: modelCompatibilityTypeSchema, + displayName: external_exports.string(), + path: external_exports.string(), + sizeBytes: external_exports.number().int(), + paramsString: external_exports.string().optional(), + architecture: external_exports.string().optional(), + quantization: quantizationSchema.optional() + }); + modelInstanceInfoBaseSchema = modelInfoBaseSchema.extend({ + identifier: external_exports.string(), + instanceReference: external_exports.string() + }); + embeddingModelAdditionalInfoSchema = external_exports.object({ + maxContextLength: external_exports.number().int() + }); + embeddingModelInstanceAdditionalInfoSchema = external_exports.object({ + contextLength: external_exports.number().int() + }); + embeddingModelInfoSchema = external_exports.object({ + type: external_exports.literal("embedding") + }).extend(modelInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape); + embeddingModelInstanceInfoSchema = external_exports.object({ type: external_exports.literal("embedding") }).extend(modelInstanceInfoBaseSchema.shape).extend(embeddingModelAdditionalInfoSchema.shape).extend(embeddingModelInstanceAdditionalInfoSchema.shape); + modelDomainTypeSchema = external_exports.enum([ + "llm", + "embedding", + "imageGen", + "transcription", + "tts" + ]); + reasonableKeyStringSchema = external_exports.string().min(1).max(1024).refine((value) => value !== "__proto__", { + message: 'For security reasons, "__proto__" is not allowed' + }).refine((value) => new RegExp("\\p{C}", "u").test(value) === false, { + message: "Control characters are not allowed" + }); + modelQuerySchema = external_exports.object({ + domain: modelDomainTypeSchema.optional(), + identifier: reasonableKeyStringSchema.optional(), + path: reasonableKeyStringSchema.optional(), + vision: external_exports.boolean().optional() + }); + modelSpecifierSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("query"), + query: modelQuerySchema + }), + external_exports.object({ + type: external_exports.literal("instanceReference"), + instanceReference: external_exports.string() + }) + ]); + genericErrorDisplayDataSchema = [ + external_exports.object({ + code: external_exports.literal("generic.specificModelUnloaded") + }), + external_exports.object({ + code: external_exports.literal("generic.noModelMatchingQuery"), + query: modelQuerySchema, + loadedModelsSample: external_exports.array(external_exports.string()), + totalLoadedModels: external_exports.number().int() + }), + external_exports.object({ + code: external_exports.literal("generic.pathNotFound"), + path: external_exports.string(), + availablePathsSample: external_exports.array(external_exports.string()), + totalModels: external_exports.number().int() + }), + external_exports.object({ + code: external_exports.literal("generic.identifierNotFound"), + identifier: external_exports.string(), + loadedModelsSample: external_exports.array(external_exports.string()), + totalLoadedModels: external_exports.number().int() + }), + external_exports.object({ + code: external_exports.literal("generic.domainMismatch"), + path: external_exports.string(), + actualDomain: modelDomainTypeSchema, + expectedDomain: modelDomainTypeSchema + }), + external_exports.object({ + code: external_exports.literal("generic.engineDoesNotSupportFeature"), + feature: external_exports.string(), + engineName: external_exports.string(), + engineType: external_exports.string(), + installedVersion: external_exports.string(), + supportedVersion: external_exports.string().nullable() + }), + external_exports.object({ + code: external_exports.literal("generic.presetNotFound"), + specifiedFuzzyPresetIdentifier: external_exports.string(), + availablePresetsSample: external_exports.array(external_exports.object({ + identifier: external_exports.string(), + name: external_exports.string() + })), + totalAvailablePresets: external_exports.number().int() + }) + ]; + llmErrorDisplayDataSchema = []; + errorDisplayDataSchema = external_exports.discriminatedUnion("code", [ + ...llmErrorDisplayDataSchema, + ...genericErrorDisplayDataSchema + ]); + serializedLMSExtendedErrorSchema = external_exports.object({ + title: failOk(external_exports.string()).default("Unknown error"), + cause: failOk(external_exports.string()).optional(), + suggestion: failOk(external_exports.string()).optional(), + errorData: failOk(external_exports.record(external_exports.string(), external_exports.unknown())).optional(), + displayData: failOk(errorDisplayDataSchema).optional(), + stack: failOk(external_exports.string()).optional(), + rootTitle: failOk(external_exports.string()).optional() + }); + documentParsingLibraryIdentifierSchema = external_exports.object({ + library: external_exports.string(), + version: external_exports.string() + }); + documentParsingOptsSchema = external_exports.object({ + parserId: documentParsingLibraryIdentifierSchema.optional() + }); + external_exports.enum(["local", "base64"]); + external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("local"), + fileName: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("base64"), + base64Data: external_exports.string() + }) + ]); + gpuSplitStrategies = ["evenly", "priorityOrder", "custom"]; + gpuSplitStrategySchema = external_exports.enum(gpuSplitStrategies); + defaultGPUSplitConfig = { + strategy: "evenly", + disabledGpus: [], + priority: [], + customRatio: [] + }; + gpuSplitConfigSchema = external_exports.object({ + strategy: gpuSplitStrategySchema, + disabledGpus: external_exports.array(external_exports.number().int().min(0)), + priority: external_exports.array(external_exports.number().int().min(0)), + customRatio: external_exports.array(external_exports.number().min(0)) + }); + kvConfigFieldSchema = external_exports.object({ + key: external_exports.string(), + value: external_exports.any() + }); + kvConfigSchema = external_exports.object({ + fields: external_exports.array(kvConfigFieldSchema) + }); + kvConfigLayerNameSchema = external_exports.enum([ + "currentlyEditing", + "currentlyLoaded", + "apiOverride", + "conversationSpecific", + "conversationGlobal", + "preset", + "serverSession", + "httpServerRequestOverride", + "completeModeFormatting", + "instance", + "userModelDefault", + "virtualModel", + "modelDefault", + "hardware" + ]); + kvConfigStackLayerSchema = external_exports.object({ + layerName: kvConfigLayerNameSchema, + config: kvConfigSchema + }); + kvConfigStackSchema = external_exports.object({ + layers: external_exports.array(kvConfigStackLayerSchema) + }); + kvConfigFieldDependencySchema = external_exports.object({ + key: external_exports.string(), + condition: external_exports.discriminatedUnion("type", [ + external_exports.object({ type: external_exports.literal("equals"), value: external_exports.any() }), + external_exports.object({ type: external_exports.literal("notEquals"), value: external_exports.any() }) + ]) + }); + contentBlockStyleSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("default") + }), + external_exports.object({ + type: external_exports.literal("customLabel"), + label: external_exports.string(), + color: external_exports.optional(colorPaletteSchema) + }), + external_exports.object({ + type: external_exports.literal("thinking"), + ended: external_exports.boolean().optional(), + title: external_exports.string().optional() + }) + ]); + llmToolParametersSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("object"), + properties: external_exports.record(jsonSerializableSchema), + required: external_exports.array(external_exports.string()).optional(), + additionalProperties: external_exports.boolean().optional(), + $defs: external_exports.record(jsonSerializableSchema).optional() + }) + // add more parameter types here + // ... + ]); + llmToolSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("function"), + function: external_exports.object({ + name: external_exports.string(), + description: external_exports.string().optional(), + parameters: llmToolParametersSchema.optional() + }) + }) + // add more tool types here + // ... + ]); + external_exports.array(llmToolSchema); + llmToolUseSettingSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("none") + }), + external_exports.object({ + type: external_exports.literal("toolArray"), + tools: external_exports.array(llmToolSchema).optional(), + force: external_exports.boolean().optional() + }) + ]); + llmApplyPromptTemplateOptsSchema = external_exports.object({ + omitBosToken: external_exports.boolean().optional(), + omitEosToken: external_exports.boolean().optional(), + toolDefinitions: external_exports.array(llmToolSchema).optional() + }); + llmContextReferenceSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("jsonFile"), + absPath: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("yamlFile"), + absPath: external_exports.string() + }) + ]); + external_exports.array(external_exports.object({ + role: external_exports.enum(["user", "assistant", "system"]), + content: external_exports.string() + })); + external_exports.array(external_exports.union([ + external_exports.object({ + system: external_exports.string() + }), + external_exports.object({ + user: external_exports.string() + }), + external_exports.object({ + assistant: external_exports.string() + }) + ])); + llmAdditionalInfoSchema = external_exports.object({ + vision: external_exports.boolean(), + trainedForToolUse: external_exports.boolean(), + maxContextLength: external_exports.number().int() + }); + llmInstanceAdditionalInfoSchema = external_exports.object({ + contextLength: external_exports.number().int() + }); + llmInfoSchema = external_exports.object({ + type: external_exports.literal("llm") + }).extend(modelInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape); + llmInstanceInfoSchema = external_exports.object({ + type: external_exports.literal("llm") + }).extend(modelInstanceInfoBaseSchema.shape).extend(llmAdditionalInfoSchema.shape).extend(llmInstanceAdditionalInfoSchema.shape); + toolNamingSchema = external_exports.enum(["passThrough", "removeSpecial", "snakeCase", "camelCase"]); + zodSchemaSchema = external_exports.custom((value) => { + if (typeof value?.parse !== "function") { + return false; + } + return true; + }, "Expected a zod schema"); + llmManualPromptTemplateSchema = external_exports.object({ + beforeSystem: external_exports.string(), + afterSystem: external_exports.string(), + beforeUser: external_exports.string(), + afterUser: external_exports.string(), + beforeAssistant: external_exports.string(), + afterAssistant: external_exports.string() + }); + llmJinjaPromptTemplateSchema = external_exports.object({ + template: external_exports.string() + }); + llmPromptTemplateTypeSchema = external_exports.enum(["manual", "jinja"]); + llmPromptTemplateSchema = external_exports.object({ + type: llmPromptTemplateTypeSchema, + manualPromptTemplate: llmManualPromptTemplateSchema.optional(), + jinjaPromptTemplate: llmJinjaPromptTemplateSchema.optional(), + stopStrings: external_exports.array(external_exports.string()) + }); + llmStructuredPredictionTypeSchema = external_exports.enum(["none", "json", "gbnf"]); + llmStructuredPredictionSettingSchema = external_exports.object({ + type: llmStructuredPredictionTypeSchema, + jsonSchema: jsonSerializableSchema.optional(), + gbnfGrammar: external_exports.string().optional() + }); + llmContextOverflowPolicySchema = external_exports.enum([ + "stopAtLimit", + "truncateMiddle", + "rollingWindow" + ]); + llmReasoningParsingSchema = external_exports.object({ + enabled: external_exports.boolean(), + startString: external_exports.string(), + endString: external_exports.string() + }); + llmPredictionConfigInputSchema = external_exports.object({ + maxTokens: external_exports.number().int().min(-1).optional().or(external_exports.literal(false)), + temperature: external_exports.number().min(0).optional(), + stopStrings: external_exports.array(external_exports.string()).optional(), + toolCallStopStrings: external_exports.array(external_exports.string()).optional(), + contextOverflowPolicy: llmContextOverflowPolicySchema.optional(), + structured: external_exports.union([zodSchemaSchema, llmStructuredPredictionSettingSchema]).optional(), + rawTools: llmToolUseSettingSchema.optional(), + toolNaming: toolNamingSchema.optional(), + topKSampling: external_exports.number().optional(), + repeatPenalty: external_exports.number().optional().or(external_exports.literal(false)), + minPSampling: external_exports.number().optional().or(external_exports.literal(false)), + topPSampling: external_exports.number().optional().or(external_exports.literal(false)), + cpuThreads: external_exports.number().int().optional(), + promptTemplate: llmPromptTemplateSchema.optional(), + draftModel: external_exports.string().optional(), + speculativeDecodingNumDraftTokensExact: external_exports.number().int().min(1).optional(), + speculativeDecodingMinDraftLengthToConsider: external_exports.number().int().min(0).optional(), + speculativeDecodingMinContinueDraftingProbability: external_exports.number().optional(), + reasoningParsing: llmReasoningParsingSchema.optional(), + raw: kvConfigSchema.optional() + }); + external_exports.object({ + ...llmPredictionConfigInputSchema.shape, + structured: llmStructuredPredictionSettingSchema.optional() + }); + llmLlamaMirostatSamplingConfigSchema = external_exports.object({ + version: external_exports.union([external_exports.literal(0), external_exports.literal(1), external_exports.literal(2)]), + learningRate: external_exports.number(), + targetEntropy: external_exports.number() + }); + llmLlamaSingleLogitBiasModificationSchema = external_exports.union([external_exports.number(), external_exports.literal("-inf")]); + llmLlamaLogitBiasConfigSchema = external_exports.array(external_exports.tuple([external_exports.number(), llmLlamaSingleLogitBiasModificationSchema])); + llmPredictionFragmentReasoningTypeSchema = external_exports.enum([ + "none", + "reasoning", + "reasoningStartTag", + "reasoningEndTag" + ]); + llmPredictionFragmentSchema = external_exports.object({ + content: external_exports.string(), + tokensCount: external_exports.number().int(), + containsDrafted: external_exports.boolean(), + reasoningType: llmPredictionFragmentReasoningTypeSchema, + isStructural: external_exports.boolean() + }); + llmPredictionFragmentInputOptsSchema = external_exports.object({ + tokenCount: external_exports.number().int().optional(), + containsDrafted: external_exports.boolean().optional(), + reasoningType: llmPredictionFragmentReasoningTypeSchema.optional(), + isStructural: external_exports.boolean().optional() + }); + llmPredictionStopReasonSchema = external_exports.enum([ + "userStopped", + "modelUnloaded", + "failed", + "eosFound", + "stopStringFound", + "toolCalls", + "maxPredictedTokensReached", + "contextLengthReached" + ]); + llmPredictionStatsSchema = external_exports.object({ + stopReason: llmPredictionStopReasonSchema, + tokensPerSecond: external_exports.number().optional(), + numGpuLayers: external_exports.number().optional(), + timeToFirstTokenSec: external_exports.number().optional(), + totalTimeSec: external_exports.number().optional(), + promptTokensCount: external_exports.number().int().optional(), + predictedTokensCount: external_exports.number().int().optional(), + totalTokensCount: external_exports.number().int().optional(), + usedDraftModelKey: external_exports.string().optional(), + totalDraftTokensCount: external_exports.number().int().optional(), + acceptedDraftTokensCount: external_exports.number().int().optional(), + rejectedDraftTokensCount: external_exports.number().int().optional(), + ignoredDraftTokensCount: external_exports.number().int().optional() + }); + llmGenInfoSchema = external_exports.object({ + indexedModelIdentifier: external_exports.string(), + identifier: external_exports.string(), + loadModelConfig: kvConfigSchema, + predictionConfig: kvConfigSchema, + stats: llmPredictionStatsSchema + }); + blockLocationSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("beforeId"), + id: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("afterId"), + id: external_exports.string() + }) + ]); + statusStepStatusSchema = external_exports.enum([ + "waiting", + "loading", + "done", + "error", + "canceled" + ]); + statusStepStateSchema = external_exports.object({ + status: statusStepStatusSchema, + text: external_exports.string() + }); + processingUpdateStatusCreateSchema = external_exports.object({ + type: external_exports.literal("status.create"), + id: external_exports.string(), + state: statusStepStateSchema, + location: blockLocationSchema.optional(), + indentation: external_exports.number().int().optional() + }); + processingUpdateStatusUpdateSchema = external_exports.object({ + type: external_exports.literal("status.update"), + id: external_exports.string(), + state: statusStepStateSchema + }); + processingUpdateStatusRemoveSchema = external_exports.object({ + type: external_exports.literal("status.remove"), + id: external_exports.string() + }); + processingUpdateCitationBlockCreateSchema = external_exports.object({ + type: external_exports.literal("citationBlock.create"), + id: external_exports.string(), + citedText: external_exports.string(), + fileName: external_exports.string(), + fileIdentifier: external_exports.string(), + pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(), + lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional() + }); + processingUpdateDebugInfoBlockCreateSchema = external_exports.object({ + type: external_exports.literal("debugInfoBlock.create"), + id: external_exports.string(), + debugInfo: external_exports.string() + }); + processingUpdateContentBlockCreateSchema = external_exports.object({ + type: external_exports.literal("contentBlock.create"), + id: external_exports.string(), + includeInContext: external_exports.boolean(), + roleOverride: external_exports.enum(["user", "assistant", "system", "tool"]).optional(), + style: contentBlockStyleSchema.optional(), + prefix: external_exports.string().optional(), + suffix: external_exports.string().optional() + }); + processingUpdateContentBlockAppendTextSchema = external_exports.object({ + type: external_exports.literal("contentBlock.appendText"), + id: external_exports.string(), + text: external_exports.string(), + tokensCount: external_exports.number().int().optional(), + fromDraftModel: external_exports.boolean().optional(), + isStructural: external_exports.boolean().optional() + }); + processingUpdateContentBlockAppendToolResultSchema = external_exports.object({ + type: external_exports.literal("contentBlock.appendToolResult"), + id: external_exports.string(), + callId: external_exports.number().int(), + toolCallRequestId: external_exports.string().optional(), + content: external_exports.string() + }); + processingUpdateContentBlockAppendToolRequestSchema = external_exports.object({ + type: external_exports.literal("contentBlock.appendToolRequest"), + id: external_exports.string(), + callId: external_exports.number().int(), + toolCallRequestId: external_exports.string().optional(), + name: external_exports.string(), + parameters: external_exports.record(external_exports.unknown()), + pluginIdentifier: external_exports.string().optional() + }); + processingUpdateContentBlockReplaceToolRequestSchema = external_exports.object({ + type: external_exports.literal("contentBlock.replaceToolRequest"), + id: external_exports.string(), + callId: external_exports.number().int(), + toolCallRequestId: external_exports.string().optional(), + name: external_exports.string(), + parameters: external_exports.record(external_exports.unknown()), + pluginIdentifier: external_exports.string().optional() + }); + processingUpdateContentBlockReplaceTextSchema = external_exports.object({ + type: external_exports.literal("contentBlock.replaceText"), + id: external_exports.string(), + text: external_exports.string() + }); + processingUpdateContentBlockSetPrefixSchema = external_exports.object({ + type: external_exports.literal("contentBlock.setPrefix"), + id: external_exports.string(), + prefix: external_exports.string() + }); + processingUpdateContentBlockSetSuffixSchema = external_exports.object({ + type: external_exports.literal("contentBlock.setSuffix"), + id: external_exports.string(), + suffix: external_exports.string() + }); + processingUpdateContentBlockAttachGenInfoSchema = external_exports.object({ + type: external_exports.literal("contentBlock.attachGenInfo"), + id: external_exports.string(), + genInfo: llmGenInfoSchema + }); + processingUpdateContentBlockSetStyleSchema = external_exports.object({ + type: external_exports.literal("contentBlock.setStyle"), + id: external_exports.string(), + style: contentBlockStyleSchema + }); + toolStatusStepStateStatusSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("generatingToolCall"), + name: external_exports.string().optional(), + pluginIdentifier: external_exports.string().optional(), + argumentsString: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("toolCallGenerationFailed"), + error: external_exports.string(), + rawContent: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("toolCallQueued") + }), + external_exports.object({ + type: external_exports.literal("confirmingToolCall") + }), + external_exports.object({ + type: external_exports.literal("toolCallDenied"), + denyReason: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("callingTool") + }), + external_exports.object({ + type: external_exports.literal("toolCallFailed"), + error: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("toolCallSucceeded"), + timeMs: external_exports.number().int() + }) + ]); + toolStatusStepStateSchema = external_exports.object({ + status: toolStatusStepStateStatusSchema, + customStatus: external_exports.string(), + customWarnings: external_exports.array(external_exports.string()) + }); + processingUpdateToolStatusCreateSchema = external_exports.object({ + type: external_exports.literal("toolStatus.create"), + id: external_exports.string(), + callId: external_exports.number().int(), + state: toolStatusStepStateSchema + }); + processingUpdateToolStatusUpdateSchema = external_exports.object({ + type: external_exports.literal("toolStatus.update"), + id: external_exports.string(), + state: toolStatusStepStateSchema + }); + processingUpdateToolStatusArgumentFragmentSchema = external_exports.object({ + type: external_exports.literal("toolStatus.argumentFragment"), + id: external_exports.string(), + content: external_exports.string() + }); + processingUpdateSetSenderNameSchema = external_exports.object({ + type: external_exports.literal("setSenderName"), + name: external_exports.string() + }); + processingUpdateSchema = external_exports.discriminatedUnion("type", [ + processingUpdateStatusCreateSchema, + processingUpdateStatusUpdateSchema, + processingUpdateStatusRemoveSchema, + processingUpdateCitationBlockCreateSchema, + processingUpdateDebugInfoBlockCreateSchema, + processingUpdateContentBlockCreateSchema, + processingUpdateContentBlockAppendTextSchema, + processingUpdateContentBlockAppendToolRequestSchema, + processingUpdateContentBlockReplaceToolRequestSchema, + processingUpdateContentBlockAppendToolResultSchema, + processingUpdateContentBlockReplaceTextSchema, + processingUpdateContentBlockSetPrefixSchema, + processingUpdateContentBlockSetSuffixSchema, + processingUpdateContentBlockAttachGenInfoSchema, + processingUpdateContentBlockSetStyleSchema, + processingUpdateToolStatusCreateSchema, + processingUpdateToolStatusUpdateSchema, + processingUpdateToolStatusArgumentFragmentSchema, + processingUpdateSetSenderNameSchema + ]); + external_exports.discriminatedUnion("type", [ + processingUpdateStatusCreateSchema, + processingUpdateStatusUpdateSchema, + processingUpdateStatusRemoveSchema, + processingUpdateCitationBlockCreateSchema, + processingUpdateDebugInfoBlockCreateSchema, + processingUpdateContentBlockCreateSchema, + processingUpdateContentBlockAppendTextSchema, + processingUpdateContentBlockReplaceTextSchema, + processingUpdateContentBlockAppendToolRequestSchema, + processingUpdateContentBlockReplaceToolRequestSchema, + processingUpdateContentBlockAppendToolResultSchema, + processingUpdateContentBlockAttachGenInfoSchema, + processingUpdateContentBlockSetStyleSchema, + processingUpdateToolStatusCreateSchema, + processingUpdateToolStatusUpdateSchema, + processingUpdateToolStatusArgumentFragmentSchema, + processingUpdateSetSenderNameSchema + ]); + processingRequestConfirmToolCallSchema = external_exports.object({ + type: external_exports.literal("confirmToolCall"), + callId: external_exports.number().int(), + pluginIdentifier: external_exports.string().optional(), + name: external_exports.string(), + parameters: external_exports.record(external_exports.any()) + }); + processingRequestTextInputSchema = external_exports.object({ + type: external_exports.literal("textInput"), + prompt: external_exports.string() + }); + processingRequestSchema = external_exports.discriminatedUnion("type", [ + processingRequestConfirmToolCallSchema, + processingRequestTextInputSchema + ]); + processingRequestResponseConfirmToolCallSchema = external_exports.object({ + type: external_exports.literal("confirmToolCall"), + result: external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("allow"), + toolArgsOverride: external_exports.record(external_exports.any()).optional() + }), + external_exports.object({ + type: external_exports.literal("deny"), + denyReason: external_exports.string().optional() + }) + ]) + }); + processingRequestResponseTextInputSchema = external_exports.object({ + type: external_exports.literal("textInput"), + result: external_exports.string() + }); + processingRequestResponseSchema = external_exports.discriminatedUnion("type", [ + processingRequestResponseConfirmToolCallSchema, + processingRequestResponseTextInputSchema + ]); + external_exports.object({ + modelTag: external_exports.string().optional(), + ignoreUserConfig: external_exports.boolean().optional() + }); + external_exports.discriminatedUnion("type", [ + processingUpdateStatusCreateSchema, + processingUpdateStatusUpdateSchema, + processingUpdateStatusRemoveSchema, + processingUpdateCitationBlockCreateSchema, + processingUpdateDebugInfoBlockCreateSchema + ]); + tokenSourceIdentifierSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("model"), + identifier: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("generator"), + pluginIdentifier: external_exports.string() + }) + ]); + modelInfoSchema = external_exports.discriminatedUnion("type", [ + llmInfoSchema, + embeddingModelInfoSchema + ]); + modelInstanceInfoSchema = external_exports.discriminatedUnion("type", [ + llmInstanceInfoSchema, + embeddingModelInstanceInfoSchema + ]); + pluginConfigSpecifierSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("direct"), + config: kvConfigSchema, + workingDirectoryPath: external_exports.string().optional() + }), + external_exports.object({ + type: external_exports.literal("predictionProcess"), + pci: external_exports.string(), + token: external_exports.string() + }) + ]); + remotePluginInfoSchema = external_exports.object({ + identifier: external_exports.string(), + isDev: external_exports.boolean(), + isTrusted: external_exports.boolean(), + hasPromptPreprocessor: external_exports.boolean(), + hasPredictionLoopHandler: external_exports.boolean(), + hasToolsProvider: external_exports.boolean(), + hasGenerator: external_exports.boolean() + }); + artifactDownloadPlanModelInfoSchema = external_exports.object({ + displayName: external_exports.string(), + sizeBytes: external_exports.number(), + quantName: external_exports.string().optional(), + compatibilityType: modelCompatibilityTypeSchema + }); + artifactDownloadPlanNodeStateSchema = external_exports.enum(["pending", "fetching", "satisfied", "completed"]); + artifactDownloadPlanNodeSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("artifact"), + owner: kebabCaseSchema, + name: kebabCaseWithDotsSchema, + state: artifactDownloadPlanNodeStateSchema, + artifactType: artifactTypeSchema.optional(), + sizeBytes: external_exports.number().int().optional(), + dependencyNodes: external_exports.array(external_exports.number().int()) + }), + external_exports.object({ + type: external_exports.literal("model"), + state: artifactDownloadPlanNodeStateSchema, + resolvedSources: external_exports.number().int().optional(), + totalSources: external_exports.number().int().optional(), + alreadyOwned: artifactDownloadPlanModelInfoSchema.optional(), + selected: artifactDownloadPlanModelInfoSchema.optional() + }) + ]); + artifactDownloadPlanSchema = external_exports.object({ + nodes: external_exports.array(artifactDownloadPlanNodeSchema), + downloadSizeBytes: external_exports.number().int() + }); + localArtifactFileEntrySchema = external_exports.object({ + relativePath: external_exports.string(), + sizeBytes: external_exports.number().int() + }); + localArtifactFileListSchema = external_exports.object({ + files: external_exports.array(localArtifactFileEntrySchema), + usedIgnoreFile: external_exports.string().nullable() + }); + downloadProgressUpdateSchema = external_exports.object({ + downloadedBytes: external_exports.number().int(), + totalBytes: external_exports.number().int(), + speedBytesPerSecond: external_exports.number() + }); + modelSearchResultDownloadOptionFitEstimationSchema = external_exports.enum([ + "fullGPUOffload", + "partialGPUOffload", + "fitWithoutGPU", + "willNotFit" + ]); + modelSearchResultDownloadOptionDataSchema = external_exports.object({ + quantization: external_exports.string().optional(), + name: external_exports.string(), + sizeBytes: external_exports.number().int(), + fitEstimation: modelSearchResultDownloadOptionFitEstimationSchema, + recommended: external_exports.boolean().optional(), + downloadIdentifier: external_exports.string(), + indexedModelIdentifier: external_exports.string() + }); + modelSearchResultIdentifierSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("catalog"), + identifier: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("hf"), + identifier: external_exports.string() + }) + ]); + modelSearchResultEntryDataSchema = external_exports.object({ + name: external_exports.string(), + identifier: modelSearchResultIdentifierSchema, + exact: external_exports.boolean().optional(), + staffPick: external_exports.boolean().optional() + }); + modelSearchOptsSchema = external_exports.object({ + searchTerm: external_exports.string().optional(), + limit: external_exports.number().int().positive().max(25).optional(), + compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional() + }); + internalRetrievalResultEntrySchema = external_exports.object({ + content: external_exports.string(), + score: external_exports.number(), + sourceIndex: external_exports.number().int(), + pageNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional(), + lineNumber: external_exports.union([external_exports.number().int(), external_exports.tuple([external_exports.number().int(), external_exports.number().int()])]).optional() + }); + internalRetrievalResultSchema = external_exports.object({ + entries: external_exports.array(internalRetrievalResultEntrySchema) + }); + external_exports.object({ + content: external_exports.string(), + score: external_exports.number(), + citation: citationSourceSchema + }); + retrievalChunkingMethodSchema = external_exports.discriminatedUnion("type", [ + external_exports.object({ + type: external_exports.literal("recursive-v1"), + chunkSize: external_exports.number().int(), + chunkOverlap: external_exports.number().int() + }) + ]); + retrievalFileProcessingStepSchema = external_exports.enum(["loading", "chunking", "embedding"]); + acceleratorTypeSchema = external_exports.enum(["unknown", "integratedGpu", "dedicatedGpu"]); + acceleratorSchema = external_exports.object({ + name: external_exports.string(), + deviceId: external_exports.number().int(), + totalMemoryBytes: external_exports.number().int(), + type: acceleratorTypeSchema + }); + external_exports.object({ + key: external_exports.string(), + name: external_exports.string(), + accelerators: external_exports.array(acceleratorSchema) + }); + serializedKVConfigSchematicsFieldSchema = external_exports.object({ + shortKey: external_exports.string(), + fullKey: external_exports.string(), + typeKey: external_exports.string(), + typeParams: jsonSerializableSchema, + defaultValue: jsonSerializableSchema + }); + serializedKVConfigSchematicsSchema = external_exports.object({ + fields: external_exports.array(serializedKVConfigSchematicsFieldSchema), + extensionPrefixes: external_exports.array(external_exports.string()).optional() + }); + external_exports.object({ + fullKey: external_exports.string(), + error: jsonSerializableSchema + }); + booleanOrMixedSchema = external_exports.union([ + external_exports.literal(true), + external_exports.literal(false), + external_exports.literal("mixed") + ]); + virtualModelDefinitionMetadataOverridesSchema = external_exports.object({ + domain: modelDomainTypeSchema.optional(), + architectures: external_exports.array(external_exports.string()).optional(), + compatibilityTypes: external_exports.array(modelCompatibilityTypeSchema).optional(), + paramsStrings: external_exports.array(external_exports.string()).optional(), + minMemoryUsageBytes: external_exports.number().optional(), + contextLengths: external_exports.array(external_exports.number()).optional(), + trainedForToolUse: booleanOrMixedSchema.optional(), + vision: booleanOrMixedSchema.optional(), + reasoning: booleanOrMixedSchema.optional(), + fim: booleanOrMixedSchema.optional() + }); + virtualModelDefinitionConcreteModelBaseSchema = external_exports.object({ + key: external_exports.string(), + sources: external_exports.array(modelDownloadSourceSchema) + }); + virtualModelCustomFieldSetJinjaVariableEffectSchema = external_exports.object({ + type: external_exports.literal("setJinjaVariable"), + variable: external_exports.string() + }); + virtualModelCustomFieldPrependSystemPromptEffectSchema = external_exports.object({ + type: external_exports.literal("prependSystemPrompt"), + content: external_exports.string() + }); + virtualModelCustomFieldAppendSystemPromptEffectSchema = external_exports.object({ + type: external_exports.literal("appendSystemPrompt"), + content: external_exports.string() + }); + virtualModelCustomFieldDefinitionBaseSchema = external_exports.object({ + key: external_exports.string(), + displayName: external_exports.string(), + description: external_exports.string() + }); + virtualModelBooleanCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ + type: external_exports.literal("boolean"), + defaultValue: external_exports.boolean(), + effects: external_exports.array(external_exports.discriminatedUnion("type", [ + virtualModelCustomFieldSetJinjaVariableEffectSchema, + virtualModelCustomFieldPrependSystemPromptEffectSchema, + virtualModelCustomFieldAppendSystemPromptEffectSchema + ])) + }); + virtualModelStringCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ + type: external_exports.literal("string"), + defaultValue: external_exports.string(), + effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema])) + }); + virtualModelSelectCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ + type: external_exports.literal("select"), + options: external_exports.array(external_exports.object({ + label: external_exports.string(), + value: external_exports.string() + })), + defaultValue: external_exports.string(), + effects: external_exports.array(external_exports.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema])) + }); + virtualModelCustomFieldDefinitionSchema = external_exports.discriminatedUnion("type", [ + virtualModelBooleanCustomFieldDefinitionSchema, + virtualModelStringCustomFieldDefinitionSchema, + virtualModelSelectCustomFieldDefinitionSchema + ]); + virtualModelConditionEqualsSchema = external_exports.object({ + type: external_exports.literal("equals"), + key: external_exports.string(), + value: jsonSerializableSchema + }); + virtualModelConditionSchema = external_exports.discriminatedUnion("type", [ + virtualModelConditionEqualsSchema + ]); + virtualModelSuggestionSchema = external_exports.object({ + message: external_exports.string(), + conditions: external_exports.array(virtualModelConditionSchema), + fields: external_exports.array(kvConfigFieldSchema).optional() + }); + external_exports.object({ + model: external_exports.string().regex(/^[^/]+\/[^/]+$/), + base: external_exports.union([external_exports.string(), external_exports.array(virtualModelDefinitionConcreteModelBaseSchema)]), + tags: external_exports.array(external_exports.string().max(100)).optional(), + config: external_exports.object({ + load: kvConfigSchema.optional(), + operation: kvConfigSchema.optional() + }).optional(), + metadataOverrides: virtualModelDefinitionMetadataOverridesSchema.optional(), + customFields: external_exports.array(virtualModelCustomFieldDefinitionSchema).optional(), + suggestions: external_exports.array(virtualModelSuggestionSchema).optional() + }); + logLevelSchema = external_exports.enum(["debug", "info", "warn", "error"]); + defaultInfoPrefix = import_chalk.default.greenBright("I"); + defaultWarnPrefix = import_chalk.default.yellowBright("W"); + defaultErrorPrefix = import_chalk.default.redBright("E"); + defaultDebugPrefix = import_chalk.default.blueBright("D"); + SimpleLogger = class _SimpleLogger { + constructor(prefixText = "", parentLogger = console, { useLogLevelPrefixes, infoPrefix, warnPrefix, errorPrefix, debugPrefix } = {}) { + this.isSimpleLogger = true; + this.infoPrefix = []; + this.warnPrefix = []; + this.errorPrefix = []; + this.debugPrefix = []; + if (isSimpleLogger(parentLogger)) { + useLogLevelPrefixes = useLogLevelPrefixes ?? parentLogger.opts.useLogLevelPrefixes; + infoPrefix = infoPrefix === void 0 ? parentLogger.opts.infoPrefix : infoPrefix; + warnPrefix = warnPrefix === void 0 ? parentLogger.opts.warnPrefix : warnPrefix; + errorPrefix = errorPrefix === void 0 ? parentLogger.opts.errorPrefix : errorPrefix; + debugPrefix = debugPrefix === void 0 ? parentLogger.opts.debugPrefix : debugPrefix; + if (prefixText === "") { + this.innerPrefix = parentLogger.innerPrefix; + this.fullPrefix = parentLogger.fullPrefix; + } else { + if (parentLogger.fullPrefix === "") { + this.innerPrefix = prefixText; + } else { + this.innerPrefix = `${parentLogger.innerPrefix}][${prefixText}`; + } + this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`); + } + this.parentLogger = parentLogger.parentLogger; + } else { + useLogLevelPrefixes = useLogLevelPrefixes ?? false; + infoPrefix = infoPrefix === void 0 ? defaultInfoPrefix : infoPrefix; + warnPrefix = warnPrefix === void 0 ? defaultWarnPrefix : warnPrefix; + errorPrefix = errorPrefix === void 0 ? defaultErrorPrefix : errorPrefix; + debugPrefix = debugPrefix === void 0 ? defaultDebugPrefix : debugPrefix; + if (prefixText === "") { + this.innerPrefix = ""; + this.fullPrefix = ""; + } else { + this.innerPrefix = prefixText; + this.fullPrefix = import_chalk.default.whiteBright(`[${this.innerPrefix}]`); + } + this.parentLogger = parentLogger; + } + if (useLogLevelPrefixes) { + if (infoPrefix !== null) { + this.infoPrefix.push(infoPrefix); + } + if (warnPrefix !== null) { + this.warnPrefix.push(warnPrefix); + } + if (errorPrefix !== null) { + this.errorPrefix.push(errorPrefix); + } + if (debugPrefix !== null) { + this.debugPrefix.push(debugPrefix); + } + } + if (this.fullPrefix !== "") { + this.infoPrefix.push(this.fullPrefix); + this.warnPrefix.push(this.fullPrefix); + this.errorPrefix.push(this.fullPrefix); + this.debugPrefix.push(this.fullPrefix); + } + this.opts = { + useLogLevelPrefixes, + infoPrefix, + warnPrefix, + errorPrefix, + debugPrefix + }; + } + subclass(prefixText) { + return new _SimpleLogger(`${this.innerPrefix}:${prefixText}`, this.parentLogger); + } + info(...messages) { + this.parentLogger.info(...this.infoPrefix, ...messages); + } + infoText(strings, ...values2) { + this.info(text(strings, ...values2)); + } + infoWithoutPrefix(...messages) { + this.parentLogger.info(...messages); + } + error(...messages) { + this.parentLogger.error(...this.errorPrefix, ...messages); + } + errorText(strings, ...values2) { + this.error(text(strings, ...values2)); + } + errorWithoutPrefix(...messages) { + this.parentLogger.error(...messages); + } + warn(...messages) { + this.parentLogger.warn(...this.warnPrefix, ...messages); + } + warnText(strings, ...values2) { + this.warn(text(strings, ...values2)); + } + warnWithoutPrefix(...messages) { + this.parentLogger.warn(...messages); + } + debug(...messages) { + this.parentLogger.debug(...this.debugPrefix, ...messages); + } + debugText(strings, ...values2) { + this.debug(text(strings, ...values2)); + } + debugWithoutPrefix(...messages) { + this.parentLogger.debug(...messages); + } + throw(message) { + throw new Error(`${this.fullPrefix} ${message}`); + } + logAtLevel(level, ...messages) { + switch (level) { + case "debug": + this.debug(...messages); + break; + case "info": + this.info(...messages); + break; + case "warn": + this.warn(...messages); + break; + case "error": + this.error(...messages); + break; + } + } + static fromMultiple(loggers, opts) { + return new _SimpleLogger("", { + debug: (...messages) => { + for (const logger2 of loggers) { + logger2.debug(...messages); + } + }, + info: (...messages) => { + for (const logger2 of loggers) { + logger2.info(...messages); + } + }, + warn: (...messages) => { + for (const logger2 of loggers) { + logger2.warn(...messages); + } + }, + error: (...messages) => { + for (const logger2 of loggers) { + logger2.error(...messages); + } + } + }, { + ...opts, + useLogLevelPrefixes: false + }); + } + }; + finished = Symbol("finished"); + StreamablePromise = class { + /** + * Called by the producer when it has finished producing values. If an error is provided, the + * promise will be rejected with that error. If no error is provided, the promise will be resolved + * with the final value. + * + * This method should be exposed in the static constructor of the subclass. + * + * @param error - The error to reject the promise with, if any. + */ + finished(error) { + if (this.status !== "pending") { + throw new Error("`finished` called while not pending"); + } + if (error === void 0) { + this.status = "resolved"; + this.nextFragmentPromiseBundle?.resolve(finished); + this.resolveFinal(this.collect(this.buffer)); + } else { + this.status = "rejected"; + this.nextFragmentPromiseBundle?.reject(error); + this.rejectFinal(error); + } + } + /** + * Called by the producer to push a new fragment into the buffer. This method should be exposed in + * the static constructor of the subclass. + * + * This method should be exposed in the static constructor of the subclass. + * + * @param fragment - The fragment to push into the buffer. + */ + push(fragment2) { + if (this.status !== "pending") { + throw new Error("`push` called while not pending"); + } + this.buffer.push(fragment2); + this.nextFragmentPromiseBundle?.resolve(fragment2); + this.nextFragmentPromiseBundle = null; + } + constructor() { + this.status = "pending"; + this.buffer = []; + this.nextFragmentPromiseBundle = null; + this.hasIterator = false; + this[_a5] = "StreamablePromise"; + const { promise, resolve: resolve2, reject } = makePromise(); + this.promiseFinal = promise; + this.resolveFinal = resolve2; + this.rejectFinal = reject; + } + then(onfulfilled, onrejected) { + return this.promiseFinal.then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.promiseFinal.catch(onrejected); + } + finally(onfinally) { + return this.promiseFinal.finally(onfinally); + } + /** + * If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and + * returned. + */ + obtainNextFragmentPromiseBundle() { + if (this.nextFragmentPromiseBundle === null) { + this.nextFragmentPromiseBundle = makePromise(); + } + return this.nextFragmentPromiseBundle; + } + async *[(_a5 = Symbol.toStringTag, Symbol.asyncIterator)]() { + if (!this.hasIterator) { + this.promiseFinal.catch(() => { + }); + this.hasIterator = true; + } + let i7 = 0; + while (i7 < this.buffer.length || this.status === "pending") { + if (i7 < this.buffer.length) { + yield this.buffer[i7]; + i7++; + } else { + const nextFragmentPromiseBundle = this.obtainNextFragmentPromiseBundle(); + const nextFragment = await nextFragmentPromiseBundle.promise; + if (nextFragment === finished) { + break; + } + yield nextFragment; + i7++; + } + } + await this.promiseFinal; + await Promise.resolve(); + } + }; + Validator = class _Validator { + constructor({ attachStack } = {}) { + this.attachStack = attachStack ?? true; + } + /** + * Pretty-prints a Zod error. + * + * @param rootObjectName - The name of the object being validated (used for error messages) + * @param error - The Zod error to pretty-print + * + * @returns The pretty-printed error in a string + */ + static prettyPrintZod(rootObjectName, error) { + return error.errors.map((e9) => { + if (e9.path.length === 0) { + return `- ${import_chalk.default.redBright(rootObjectName)}: ${e9.message}`; + } + const path6 = import_chalk.default.red(`.${e9.path.join(".")}`); + return `- ${import_chalk.default.redBright(rootObjectName)}${path6}: ${e9.message}`; + }).join("\n"); + } + /** + * Validates a value against a schema and throws an error if it's invalid. + * + * @param lead - The start of the error message (used for error messages) + * @param rootObjectName - The name of the object being validated (used for error messages) + * @param schema - The schema to validate against + * @param value - The value to validate + * + * @returns The validated value + * @throws An error if the value is invalid + */ + validateOrThrow(lead, rootObjectName, schema, value, stack) { + const result = schema.safeParse(value); + if (result.success) { + return result.data; + } else { + throw makePrettyError(`${lead} + +${_Validator.prettyPrintZod(rootObjectName, result.error)}`, this.attachStack ? stack : void 0); + } + } + /** + * Validates multiple values against multiple schemas and throws an error if any of them are + * invalid. All values are validated before any errors are thrown. This is useful when you want to + * validate multiple values at once and want to see all the errors at once. + * + * @param leadProducer - The function to produce the start of the error message (used for error). + * It is called with a set of indices of the invalid values. + * @param rootObjectNames - The names of the objects being validated (used for error messages) + * @param schemas - The schemas to validate against + * @param values - The values to validate + * + * @returns The validated values + * @throws An error if any of the values are invalid + */ + validateMultipleOrThrow(leadProducer, rootObjectNames, schemas, values2, stack) { + const results = schemas.map((schema, index2) => schema.safeParse(values2[index2])); + const errors = results.map((result, index2) => ({ result, index: index2, rootObjectName: rootObjectNames[index2] })).filter(({ result }) => !result.success).map(({ result, rootObjectName, index: index2 }) => ({ + error: result.error, + rootObjectName, + index: index2 + })); + if (errors.length === 0) { + return results.map((result) => result.data); + } else { + const erroredValues = new Set(errors.map(({ index: index2 }) => index2)); + const lead = leadProducer(erroredValues); + throw makePrettyError(`${lead} + +${errors.map(({ error, rootObjectName }) => _Validator.prettyPrintZod(rootObjectName, error)).join("\n")}`, this.attachStack ? stack : void 0); + } + } + /** + * Validates a value against a schema and throws an error if it's invalid. This is a convenience + * function for validating one single method parameter. + * + * @param className - The name of the class containing the method (used for error messages) + * @param methodName - The name of the method (used for error messages) + * @param paramName - The name of the parameter being validated (used for error messages) + * @param schema - The schema to validate against + * @param value - The value to validate + * + * @returns The validated value + * @throws An error if the value is invalid + */ + validateMethodParamOrThrow(className, methodName, paramName, schema, value, stack) { + const functionCall = import_chalk.default.yellowBright(text` + ${className}.${methodName}(${import_chalk.default.redBright(paramName)}) + `); + return this.validateOrThrow(`Invalid parameter(s) for ${functionCall}:`, paramName, schema, value, stack); + } + /** + * Validates multiple values against multiple schemas and throws an error if any of them are + * invalid. This is a convenience function for validating multiple method parameters. + * + * @param className - The name of the class containing the method (used for error messages) + * @param methodName - The name of the method (used for error messages) + * @param paramNames - The names of the parameters being validated (used for error messages) + * @param schemas - The schemas to validate against + * @param values - The values to validate + * + * @returns The validated values + * @throws An error if any of the values are invalid + */ + validateMethodParamsOrThrow(className, methodName, paramNames, schemas, values2, stack) { + return this.validateMultipleOrThrow((erroredValues) => { + const coloredParamNames = paramNames.map((name, index2) => erroredValues.has(index2) ? import_chalk.default.redBright(name) : name); + const functionCall = import_chalk.default.yellowBright(text` + ${className}.${methodName}(${coloredParamNames.join(", ")}) + `); + return `Invalid parameter(s) for ${functionCall}:`; + }, paramNames, schemas, values2, stack); + } + /** + * Validates a value against a schema and throws an error if it's invalid. This is a convenience + * function for validating one single constructor parameter. + * + * @param className - The name of the class (used for error messages) + * @param paramName - The name of the parameter being validated (used for error messages) + * @param schema - The schema to validate against + * @param value - The value to validate + * + * @returns The validated value + * @throws An error if the value is invalid + */ + validateConstructorParamOrThrow(className, paramName, schema, value, stack) { + const functionCall = import_chalk.default.yellowBright(text` + ${className}(${import_chalk.default.redBright(paramName)}) + `); + return this.validateOrThrow(`Invalid parameter(s) when constructing ${functionCall}`, paramName, schema, value, stack); + } + /** + * Validates multiple values against multiple schemas and throws an error if any of them are + * invalid. This is a convenience function for validating multiple constructor parameters. + * + * @param className - The name of the class (used for error messages) + * @param paramNames - The names of the parameters being validated (used for error messages) + * + * @param schemas - The schemas to validate against + * @param values - The values to validate + */ + validateConstructorParamsOrThrow(className, paramNames, schemas, values2, stack) { + return this.validateMultipleOrThrow((erroredValues) => { + const coloredParamNames = paramNames.map((name, index2) => erroredValues.has(index2) ? import_chalk.default.redBright(name) : name); + const functionCall = import_chalk.default.yellowBright(text` + ${className}(${coloredParamNames.join(", ")}) + `); + return `Invalid parameter(s) when constructing ${functionCall}:`; + }, paramNames, schemas, values2, stack); + } + }; + sharedValidator = new Validator(); + FileHandle = class { + /** + * @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead + */ + constructor(filesNamespace, identifier, type, sizeBytes, name) { + this.filesNamespace = filesNamespace; + this.identifier = identifier; + this.type = type; + this.sizeBytes = sizeBytes; + this.name = name; + this.parsedIdentifier = parseFileIdentifier(identifier); + } + /** + * Gets the absolute file path of this file. + */ + async getFilePath() { + switch (this.parsedIdentifier.type) { + case "local": { + return (await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)).path; + } + case "base64": { + throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error."); + } + default: { + const _exhaustiveCheck = this.parsedIdentifier; + throw new Error(`Unexpected file identifier type: ${JSON.stringify(_exhaustiveCheck)}`); + } + } + } + isImage() { + return this.type === "image"; + } + }; + chatMessageInputSchema = external_exports.object({ + role: external_exports.enum(["user", "assistant", "system"]).optional(), + content: external_exports.string().optional(), + images: external_exports.array(external_exports.instanceof(FileHandle)).optional() + }); + chatHistoryInputSchema = external_exports.array(chatMessageInputSchema); + Chat3 = class _Chat extends MaybeMutable { + getClassName() { + return "Chat"; + } + create(data, mutable) { + return new _Chat(data, mutable); + } + cloneData(data) { + return chatHistoryDataSchema.parse(data); + } + /** + * Don't use this constructor directly. + * + * - To create an empty chat history, use `Chat.empty()`. + * - To create a chat history with existing data, use `Chat.from()`. + */ + constructor(data, mutable) { + super(data, mutable); + } + /** + * Creates an empty mutable chat history. + */ + static empty() { + return new _Chat({ messages: [] }, true); + } + /** + * Quickly create a mutable chat history with something that can be converted to a chat history. + * + * The created chat history will be a mutable copy of the input. + * + * @example + * ```ts + * const history = Chat.from([ + * { role: "user", content: "Hello" }, + * { role: "assistant", content: "Hi!" }, + * { role: "user", content: "What is your name?" }, + * ]); + * ``` + */ + static from(initializer) { + const stack = getCurrentStack(1); + sharedValidator.validateMethodParamOrThrow("Chat", "from", "initializer", chatHistoryLikeSchema, initializer, stack); + if (initializer instanceof _Chat) { + return initializer.asMutableCopy(); + } + if (typeof initializer === "string") { + const chatHistory = _Chat.empty(); + chatHistory.append("user", initializer); + return chatHistory; + } + if (Array.isArray(initializer)) { + return new _Chat({ messages: initializer.map(chatMessageInputToChatMessageData) }, true); + } + if (isChatMessageInputAsOpposeToChatHistoryData(initializer)) { + return new _Chat({ messages: [chatMessageInputToChatMessageData(initializer)] }, true); + } else { + return new _Chat(initializer, false).asMutableCopy(); + } + } + /** + * Creates a chat history with raw data. This method is intended for internal use only. + * + * If mutable is set to false, you MUST ensure that the data is not mutated. + * + * @internal + */ + static createRaw(data, mutable) { + return new _Chat(data, mutable); + } + /** + * Gets the raw data of this message. This method is intended for internal use only. + * + * If mutable is set to false, you MUST ensure that the data is not mutated. + * + * @internal + */ + getRaw() { + return this.data; + } + append(...args) { + this.guardMutable(); + if (args.length === 1) { + const [chatMessageLike] = args; + const chatMessage = ChatMessage.from(chatMessageLike); + const messageMutable = accessMaybeMutableInternals(chatMessage)._internalToMutable(); + this.data.messages.push(accessMaybeMutableInternals(messageMutable)._internalGetData()); + } else { + const [role, content, opts = {}] = args; + if (role === "user" || role === "system" || role === "assistant") { + const parts = [ + { type: "text", text: content } + ]; + if (opts.images !== void 0) { + for (const image of opts.images) { + parts.push({ + type: "file", + name: image.name, + identifier: image.identifier, + sizeBytes: image.sizeBytes, + fileType: image.type + }); + } + } + this.data.messages.push({ role, content: parts }); + } else { + throw new Error(text` + Unsupported role for append() API with [role, content] parameters: ${role}. + Supported roles are 'user', 'system', and 'assistant'. + `); + } + } + } + withAppended(...args) { + const copy2 = this.asMutableCopy(); + copy2.append(...args); + return copy2; + } + /** + * Get the number of messages in the history. + */ + getLength() { + return this.data.messages.length; + } + /** + * Get the number of messages in the history. + */ + get length() { + return this.getLength(); + } + /** + * Remove the last message from the history. If the history is empty, this method will throw. + */ + pop() { + this.guardMutable(); + if (this.data.messages.length === 0) { + throw new Error("Tried to pop from an empty history."); + } + const popped = this.data.messages.pop(); + return ChatMessage.createRaw(popped, true); + } + /** + * Gets all files contained in this history. + * + * @param client - LMStudio client + */ + getAllFiles(client) { + return this.data.messages.flatMap((message) => message.content.filter((part) => part.type === "file")).map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name)); + } + /** + * Allows iterating over the files in the history. + */ + *files(client) { + for (const message of this.data.messages) { + for (const part of message.content) { + if (part.type === "file") { + yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); + } + } + } + } + /** + * Returns true if this history contains any files. + */ + hasFiles() { + return this.data.messages.some((message) => message.content.some((part) => part.type === "file")); + } + /** + * Gets the message at the given index. If the index is negative, it will be counted from the end. + * + * If the index is out of bounds, this method will throw as oppose to returning undefined. This is + * to help catch bugs early. + */ + at(index2) { + let actualIndex = index2; + if (index2 < 0) { + actualIndex = this.data.messages.length + index2; + } + if (actualIndex < 0 || actualIndex >= this.data.messages.length) { + throw new Error(text` + Tried to access the message at index ${index2}, but the history only has + ${this.data.messages.length} messages. + `); + } + return ChatMessage.createRaw(this.data.messages[actualIndex], this.mutable); + } + /** + * Get all the messages in the history as an array of ChatMessage objects. + */ + getMessagesArray() { + return this.data.messages.map((message) => ChatMessage.createRaw(message, this.mutable)); + } + /** + * Maps over the messages in the history and returns an array of the results. + */ + map(mapper) { + return this.getMessagesArray().map(mapper); + } + /** + * Maps over the messages in the history and returns a flattened array of the results. + * + * This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects. + */ + flatMap(mapper) { + return this.getMessagesArray().flatMap(mapper); + } + /** + * Allows iterating over the messages in the history. + */ + *[Symbol.iterator]() { + for (const message of this.data.messages) { + yield ChatMessage.createRaw(message, this.mutable); + } + } + /** + * Given a predicate, the predicate is called for each file in the history. + * + * - If the predicate returns true, the file is removed from the history and is collected into the + * returned array. + * - If the predicate returns false, the file is kept in the history. + * + * This method is useful if you are implementing a promptPreprocessor that needs to convert certain + * types of files. + * + * If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method. + * + * @param client - LMStudio client + * @param predicate - The predicate to call for each file. + * @returns The files that were consumed. + */ + consumeFiles(client, predicate) { + this.guardMutable(); + const consumedFiles = []; + for (const message of this.data.messages) { + consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate)); + } + return consumedFiles; + } + /** + * Given an async predicate, the predicate is called for each file in the history. + * + * - If the predicate returns true, the file is removed from the history and is collected into the + * returned array. + * - If the predicate returns false, the file is kept in the history. + * + * This method is useful if you are implementing a promptPreprocessor that needs to convert certain + * types of files. + * + * If you need a synchronous version, use the {@link Chat#consumeFiles} method. + * + * @param client - LMStudio client + * @param predicate - The predicate to call for each file. + * @returns The files that were consumed. + */ + async consumeFilesAsync(client, predicate) { + this.guardMutable(); + const consumedFiles = []; + for (const message of this.data.messages) { + consumedFiles.push(...await ChatMessage.createRaw(message, true).consumeFilesAsync(client, predicate)); + } + return consumedFiles; + } + getSystemPrompt() { + return this.data.messages.filter((message) => message.role === "system").map((message) => message.content.filter((part) => part.type === "text").map((part) => part.text).join(" ")).join("\n\n"); + } + replaceSystemPrompt(content) { + this.guardMutable(); + this.data.messages = this.data.messages.filter((message) => message.role !== "system"); + this.data.messages.unshift({ role: "system", content: [{ type: "text", text: content }] }); + } + filterInPlace(predicate) { + this.guardMutable(); + this.data.messages = this.data.messages.filter((message) => predicate(ChatMessage.createRaw(message, true))); + } + toString() { + return "Chat {\n" + this.data.messages.map((message) => { + const messageString = ChatMessage.createRaw(message, false).toString(); + return messageString.split("\n").map((line) => " " + line).join("\n"); + }).join("\n") + "\n}"; + } + }; + chatHistoryLikeSchema = external_exports.union([ + external_exports.instanceof(Chat3), + chatHistoryDataSchema, + external_exports.string(), + chatHistoryInputSchema, + chatMessageInputSchema + ]); + ChatMessage = class _ChatMessage extends MaybeMutable { + getClassName() { + return "ChatMessage"; + } + create(data, mutable) { + return new _ChatMessage(data, mutable); + } + cloneData(data) { + return chatMessageDataSchema.parse(data); + } + constructor(data, mutable) { + super(data, mutable); + } + /** + * Create a mutable text only message. + */ + static create(role, content) { + return new _ChatMessage(chatMessageDataSchema.parse({ + role, + content: [{ type: "text", text: content }] + }), true); + } + /** + * Quickly create a mutable message with something that can be converted to a message. + */ + static from(initializer) { + const stack = getCurrentStack(1); + sharedValidator.validateMethodParamOrThrow("ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack); + if (initializer instanceof _ChatMessage) { + return initializer.asMutableCopy(); + } + if (typeof initializer === "string") { + return new _ChatMessage(chatMessageDataSchema.parse({ + role: "user", + content: [{ type: "text", text: initializer }] + }), true); + } + if (isChatMessageInputAsOpposeToChatMessageData(initializer)) { + return new _ChatMessage(chatMessageInputToChatMessageData(initializer), true); + } else { + return new _ChatMessage(initializer, true); + } + } + /** + * Creates a chat history with raw data. This method is intended for internal use only. + * + * If mutable is set to false, you MUST ensure that the data is not mutated. + * + * @internal + */ + static createRaw(data, mutable) { + return new _ChatMessage(data, mutable); + } + /** + * Gets the raw data of this message. This method is intended for internal use only. + * + * If mutable is set to false, you MUST ensure that the data is not mutated. + * + * @internal + */ + getRaw() { + return this.data; + } + getRole() { + return this.data.role; + } + setRole(role) { + this.guardMutable(); + this.data.role = role; + } + getFileParts() { + return this.data.content.filter((part) => part.type === "file"); + } + /** + * Gets all text contained in this message. + */ + getText() { + return this.data.content.filter((part) => part.type === "text").map((part) => part.text).join(" "); + } + /** + * Get all tool call results within this message. + */ + getToolCallResults() { + return this.data.content.filter((part) => part.type === "toolCallResult").map((part) => ({ + content: part.content, + toolCallId: part.toolCallId + })); + } + /** + * Gets all file parts contained in this message. + */ + getToolCallRequests() { + return this.data.content.filter((part) => part.type === "toolCallRequest").map((part) => part.toolCallRequest); + } + /** + * Gets all files contained in this message. + * + * @param client - LMStudio client + */ + getFiles(client) { + return this.getFileParts().map((part) => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name)); + } + /** + * Allows iterating over the files in the message. + */ + *files(client) { + for (const part of this.getFileParts()) { + yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); + } + } + /** + * Given a predicate, the predicate is called for each file in the message. + * + * - If the predicate returns true, the file is removed from the message and is collected into the + * returned array. + * - If the predicate returns false, the file is kept in the message. + * + * This method is useful if you are implementing a promptPreprocessor that needs to convert certain + * types of files. + * + * If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method. + * + * @param client - LMStudio client + * @param predicate - The predicate to call for each file. + * @returns The files that were consumed. + */ + consumeFiles(client, predicate) { + this.guardMutable(); + const consumedFiles = []; + const partIndexesToRemove = /* @__PURE__ */ new Set(); + for (const [index2, part] of this.data.content.entries()) { + if (part.type !== "file") { + continue; + } + const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); + if (predicate(file)) { + consumedFiles.push(file); + partIndexesToRemove.add(index2); + } + } + this.data.content = this.data.content.filter((_3, index2) => !partIndexesToRemove.has(index2)); + return consumedFiles; + } + /** + * Given an async predicate, the predicate is called for each file in the message. + * + * - If the predicate returns true, the file is removed from the message and is collected into the + * returned array. + * - If the predicate returns false, the file is kept in the message. + * + * This method is useful if you are implementing a promptPreprocessor that needs to convert certain + * types of files. + * + * If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method. + * + * @param client - LMStudio client + * @param predicate - The predicate to call for each file. + * @returns The files that were consumed. + */ + async consumeFilesAsync(client, predicate) { + this.guardMutable(); + const consumedFiles = []; + const partIndexesToRemove = /* @__PURE__ */ new Set(); + for (const [index2, part] of this.data.content.entries()) { + if (part.type !== "file") { + continue; + } + const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); + if (await predicate(file)) { + consumedFiles.push(file); + partIndexesToRemove.add(index2); + } + } + this.data.content = this.data.content.filter((_3, index2) => !partIndexesToRemove.has(index2)); + return consumedFiles; + } + /** + * Returns true if this message contains any files. + */ + hasFiles() { + return this.data.content.some((part) => part.type === "file"); + } + /** + * Append text to the message. + */ + appendText(text3) { + this.guardMutable(); + switch (this.data.role) { + case "assistant": + case "user": + case "system": + this.data.content.push({ + type: "text", + text: text3 + }); + break; + case "tool": + throw new Error(`Cannot append text to a message with role "${this.data.role}"`); + default: { + const exhaustiveCheck = this.data; + throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); + } + } + } + /** + * Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from + * `client.files.prepareImage`. + */ + appendFile(file) { + this.guardMutable(); + switch (this.data.role) { + case "assistant": + case "user": + case "system": + this.data.content.push({ + type: "file", + name: file.name, + identifier: file.identifier, + sizeBytes: file.sizeBytes, + fileType: file.type + }); + break; + case "tool": + throw new Error(`Cannot append text to a message with role "${this.data.role}"`); + default: { + const exhaustiveCheck = this.data; + throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); + } + } + } + /** + * Replaces all text in the messages. + * + * If the message contains other components (such as files), they will kept. The replaced text + * will be inserted to the beginning of the message. + */ + replaceText(text3) { + this.guardMutable(); + switch (this.data.role) { + case "assistant": + case "user": + case "system": + this.data.content = [ + { type: "text", text: text3 }, + ...this.data.content.filter((part) => part.type !== "text") + ]; + break; + case "tool": + throw new Error(`Cannot replace text in a message with role "${this.data.role}"`); + default: { + const exhaustiveCheck = this.data; + throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); + } + } + } + isSystemPrompt() { + return this.data.role === "system"; + } + isUserMessage() { + return this.data.role === "user"; + } + isAssistantMessage() { + return this.data.role === "assistant"; + } + toString() { + const text3 = this.data.content.map((part) => { + switch (part.type) { + case "text": + return part.text; + case "file": + return ``; + case "toolCallRequest": + return part.toolCallRequest.name + `(${JSON.stringify(part.toolCallRequest.arguments)})`; + case "toolCallResult": + return part.content; + default: { + const exhaustiveCheck = part; + throw new Error(`Unknown part type: ${exhaustiveCheck.type}`); + } + } + }).join(" "); + if (text3.includes("\n")) { + return this.data.role + ":\n" + text3.split("\n").map((line) => " " + line).join("\n"); + } else { + return this.data.role + ": " + text3; + } + } + }; + chatMessageLikeSchema = external_exports.union([ + external_exports.instanceof(ChatMessage), + chatMessageInputSchema, + external_exports.string(), + chatMessageDataSchema + ]); + KVFieldValueTypesLibraryBuilder = class { + constructor(baseSchema) { + this.baseSchema = baseSchema; + this.valueTypes = /* @__PURE__ */ new Map(); + } + /** + * Define a new field value type. + */ + valueType(key, param) { + if (this.valueTypes.has(key)) { + throw new Error(`ValueType with key ${key} already exists`); + } + this.valueTypes.set(key, { + paramType: external_exports.object({ + ...this.baseSchema, + ...param.paramType + }), + schemaMaker: param.schemaMaker, + effectiveEquals: param.effectiveEquals, + stringify: param.stringify + }); + return this; + } + build() { + return new KVFieldValueTypeLibrary(new Map(this.valueTypes)); + } + }; + KVFieldValueTypeLibrary = class { + constructor(valueTypes) { + this.valueTypes = valueTypes; + } + /** + * Gets the schema for a specific field value type with the given key and parameters. + */ + getSchema(key, param) { + const valueType = this.valueTypes.get(key); + if (valueType === void 0) { + throw new Error(`Cannot find value type ${key}`); + } + return valueType.schemaMaker(valueType.paramType.parse(param)); + } + parseParamTypes(key, param) { + return this.valueTypes.get(key).paramType.parse(param); + } + effectiveEquals(key, typeParam, a3, b4) { + return this.valueTypes.get(key).effectiveEquals(a3, b4, typeParam); + } + stringify(key, typeParam, opts, value) { + return this.valueTypes.get(key).stringify(value, typeParam, opts); + } + }; + KVConfigSchematicsBuilder = class _KVConfigSchematicsBuilder { + constructor(valueTypeLibrary) { + this.valueTypeLibrary = valueTypeLibrary; + this.fields = /* @__PURE__ */ new Map(); + this.extensionPrefixes = []; + } + /** + * Adds a field + */ + field(key, valueTypeKey, valueTypeParams, defaultValue) { + const schema = this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams); + const defaultValueParseResult = schema.safeParse(defaultValue); + if (!defaultValueParseResult.success) { + throw new Error(`Invalid default value for field ${key}: ${defaultValueParseResult.error.message}`); + } + defaultValue = defaultValueParseResult.data; + if (this.fields.has(key)) { + throw new Error(`Cannot add field with key ${key}. Key already exists in the schematics.`); + } + this.fields.set(key, { + valueTypeKey, + valueTypeParams, + schema: this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams), + fullKey: key, + defaultValue + }); + return this; + } + /** + * Adds an extension point. For example, if called with .extension("hello.world"), then any keys + * that match "hello.world.*" will be allowed when going through lenient zod schema. However, + * any extension fields will still not be accessible via this schematics. + */ + extension(prefix) { + this.extensionPrefixes.push(`${prefix}.`); + return this; + } + /** + * Convenience method for grouping a set of fields under a shared namespace. + * + * For example, if we want to create two fields: `some:namespace:a` and `some:namespace:b`. + * Instead of doing: + * + * ```ts + * builder + * .field("some:namespace:a", ...) + * .field("some:namespace:b", ...) + * ``` + * + * We can do: + * + * ```ts + * builder.scope("some:namespace", builder => + * builder + * .field("a", ...) + * .field("b", ...) + * ) + * ``` + * + * This method does support nesting. Whether to nest or not is up to the user. + */ + scope(scopeKey, fn) { + const innerBuilder = fn(new _KVConfigSchematicsBuilder(this.valueTypeLibrary)); + for (const [key, { valueTypeKey, valueTypeParams, schema, defaultValue }] of innerBuilder.fields.entries()) { + const fullKey = `${scopeKey}.${key}`; + if (this.fields.has(fullKey)) { + throw new Error(`Cannot add field with key ${fullKey}. Key already exists in the schematics.`); + } + this.fields.set(fullKey, { + valueTypeKey, + valueTypeParams, + schema, + fullKey, + defaultValue + }); + } + this.extensionPrefixes.push(...innerBuilder.extensionPrefixes.map((prefix) => `${scopeKey}.${prefix}`)); + return this; + } + build() { + return new KVConfigSchematics(this.valueTypeLibrary, this.fields, this.extensionPrefixes); + } + }; + createParsedKVConfig = Symbol("createParsedKVConfig"); + KVConfigSchematics = class _KVConfigSchematics { + constructor(valueTypeLibrary, fields, extensionPrefixes) { + this.valueTypeLibrary = valueTypeLibrary; + this.fields = fields; + this.extensionPrefixes = extensionPrefixes; + this.fullKepMap = void 0; + this.lenientZodSchema = void 0; + } + getFieldsMap() { + return new Map([...this.fields.values()].map((field) => [field.fullKey, field])); + } + obtainField(key) { + const field = this.fields.get(key); + if (field === void 0) { + const fieldKeys = [...this.fields.keys()]; + let availableList = fieldKeys.slice(0, 10).map((key2) => `- ${key2}`).join("\n"); + if (fieldKeys.length > 10) { + availableList += ` +... and ${fieldKeys.length - 10} more`; + } + throw new Error(`Cannot access key ${key}. Key does not exist in the schematics. Available keys: + +` + availableList); + } + return field; + } + obtainFieldByFullKey(fullKey) { + const field = this.getFullKeyMap().get(fullKey); + if (field === void 0) { + const fieldKeys = [...this.getFullKeyMap().keys()]; + let availableList = fieldKeys.slice(0, 10).map((key) => `- ${key}`).join("\n"); + if (fieldKeys.length > 10) { + availableList += ` +... and ${fieldKeys.length - 10} more`; + } + throw new Error(`Cannot access full key ${fullKey}. Full key does not exist in the schematics. Availablekeys: + +` + availableList); + } + return field; + } + getSchemaForKey(key) { + const field = this.obtainField(key); + return field.schema; + } + parseField(fieldSchema, value) { + if (value === void 0) { + if (fieldSchema.defaultValue === void 0) { + throw new Error(`Field with key ${fieldSchema.fullKey} is missing and has no default value`); + } + return fieldSchema.defaultValue; + } + const parseResult = fieldSchema.schema.safeParse(value); + if (!parseResult.success) { + throw new Error(`Field with key ${fieldSchema.fullKey} does not satisfy the schema:` + parseResult.error.message); + } + return parseResult.data; + } + parseFieldWithoutDefault(field, value) { + if (value === void 0) { + return void 0; + } + const parseResult = field.schema.safeParse(value); + if (!parseResult.success) { + throw new Error(`Field with key ${field.fullKey} does not satisfy the schema:` + parseResult.error.message); + } + return parseResult.data; + } + /** + * Parse and access a field in the config. + */ + access(config, key) { + const field = this.obtainField(key); + return this.parseField(field, config.fields.find((f4) => f4.key === field.fullKey)?.value); + } + accessByFullKey(config, fullKey) { + const field = this.obtainFieldByFullKey(fullKey); + return this.parseField(field, config.fields.find((f4) => f4.key === field.fullKey)?.value); + } + /** + * Parse and access a field in the config. Returns undefined if the field is missing. + */ + accessPartial(config, key) { + const field = this.obtainField(key); + return this.parseFieldWithoutDefault(field, config.fields.find((f4) => f4.key === field.fullKey)?.value); + } + /** + * Gets a slice of the config schema with the given key patterns. Support syntax: + * + * - `some.namespace.key`: Matches exactly `some.namespace.key` + * - `some.namespace.*`: Matches anything that starts with `some.namespace.` + */ + sliced(...patterns) { + const parsedPatterns = patterns.map((p4) => { + if (p4.endsWith("*")) { + return { type: "prefix", value: p4.substring(0, p4.length - 1) }; + } + return { type: "exact", value: p4 }; + }); + const newFields = /* @__PURE__ */ new Map(); + for (const [key, field] of this.fields.entries()) { + for (const pattern of parsedPatterns) { + if (pattern.type === "exact" && key === pattern.value || pattern.type === "prefix" && key.startsWith(pattern.value)) { + newFields.set(key, field); + } + } + } + return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); + } + /** + * Get a subset of the config schema with a specific scope. + */ + scoped(scopeKey) { + const newFields = /* @__PURE__ */ new Map(); + for (const [key, field] of this.fields.entries()) { + if (key.startsWith(`${scopeKey}.`)) { + newFields.set(key.substring(scopeKey.length + 1), field); + } + } + return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); + } + union(other) { + const newFields = /* @__PURE__ */ new Map(); + for (const [key, field] of this.fields.entries()) { + newFields.set(key, field); + } + for (const [key, field] of other.fields.entries()) { + if (newFields.has(key)) { + throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: " + key); + } + newFields.set(key, field); + } + return new _KVConfigSchematics(this.valueTypeLibrary, newFields, [ + ...this.extensionPrefixes, + ...other.extensionPrefixes + ]); + } + /** + * Combine baseKey into the fields. Effectively removes the baseKey. + */ + flattenBaseKey() { + const newFields = /* @__PURE__ */ new Map(); + for (const field of this.fields.values()) { + newFields.set(field.fullKey, field); + } + return new _KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); + } + parseToMap(config) { + const rawConfigMap = kvConfigToMap(config); + const parsedConfigMap = /* @__PURE__ */ new Map(); + for (const [key, field] of this.fields.entries()) { + const value = rawConfigMap.get(field.fullKey); + const parsedValue = this.parseField(field, value); + parsedConfigMap.set(key, parsedValue); + } + return parsedConfigMap; + } + parseToMapWithFullKey(config) { + const rawConfigMap = kvConfigToMap(config); + const parsedConfigMap = /* @__PURE__ */ new Map(); + for (const field of this.fields.values()) { + const value = rawConfigMap.get(field.fullKey); + const parsedValue = this.parseField(field, value); + parsedConfigMap.set(field.fullKey, parsedValue); + } + return parsedConfigMap; + } + parseToMapPartial(config) { + const rawConfigMap = kvConfigToMap(config); + const parsedConfigMap = /* @__PURE__ */ new Map(); + for (const [key, field] of this.fields.entries()) { + const value = rawConfigMap.get(field.fullKey); + const parsedValue = this.parseFieldWithoutDefault(field, value); + if (parsedValue !== void 0) { + parsedConfigMap.set(key, parsedValue); + } + } + return parsedConfigMap; + } + /** + * Parse the given config to a ParsedKVConfig. **Will throw** if the config does not satisfy the + * schema. + */ + parse(config) { + return ParsedKVConfig[createParsedKVConfig](this.parseToMap(config)); + } + parsePartial(config) { + return PartialParsedKVConfig[createParsedKVConfig](this.parseToMapPartial(config)); + } + /** + * Builds a full KV config from the given values record. **Will throw** if any of the values are + * missing or do not satisfy the schema. + */ + buildFullConfig(valuesRecord) { + return { + fields: Array.from(this.fields.entries()).map(([key, field]) => { + const value = this.parseField(field, valuesRecord[key]); + return { key: field.fullKey, value }; + }) + }; + } + /** + * Builds a partial KV config from the given values record. Will leave holes in the config if the + * values are missing. **Will throw** if any of the values do not satisfy the schema. + */ + buildPartialConfig(valuesRecord) { + return { + fields: Object.entries(valuesRecord).filter(([_key, value]) => value !== void 0).map(([key, value]) => { + const field = this.obtainField(key); + return { key: field.fullKey, value: this.parseField(field, value) }; + }) + }; + } + createBuildPartialConfigInput() { + return {}; + } + configBuilder() { + return new KVConfigBuilder(this.fields); + } + clone() { + return new _KVConfigSchematics(this.valueTypeLibrary, new Map(this.fields), this.extensionPrefixes); + } + withTypeParamOverride(key, paramMapper) { + const field = this.obtainField(key); + const clone3 = this.clone(); + clone3.fields.set(key, { + ...field, + valueTypeParams: paramMapper(field.valueTypeParams), + schema: this.valueTypeLibrary.getSchema(field.valueTypeKey, paramMapper(field.valueTypeParams)) + }); + return clone3; + } + getFullKeyMap() { + if (this.fullKepMap !== void 0) { + return this.fullKepMap; + } + this.fullKepMap = new Map([...this.fields.values()].map((field) => [field.fullKey, field])); + return this.fullKepMap; + } + makeLenientZodSchema() { + const fullKeyMap = this.getFullKeyMap(); + return kvConfigSchema.transform((value) => { + const seenKeys = /* @__PURE__ */ new Set(); + return { + fields: value.fields.filter((field) => { + if (this.extensionPrefixes.some((prefix) => field.key.startsWith(prefix))) { + return true; + } + if (seenKeys.has(field.key)) { + return false; + } + const fieldDef = fullKeyMap.get(field.key); + if (fieldDef === void 0) { + return false; + } + const parsed = fieldDef.schema.safeParse(field.value); + if (!parsed.success) { + return false; + } + seenKeys.add(field.key); + return true; + }) + }; + }); + } + /** + * Makes a zod schema that parses a KVConfig which only allows fields with correct keys and types + * through. + * + * Will filter out any fields that are not in the schema. + */ + getLenientZodSchema() { + if (this.lenientZodSchema !== void 0) { + return this.lenientZodSchema; + } + this.lenientZodSchema = this.makeLenientZodSchema(); + return this.lenientZodSchema; + } + getValueType(key) { + const field = this.fields.get(key); + if (field === void 0) { + return null; + } + return field.valueTypeKey; + } + getValueTypeParam(key) { + const field = this.fields.get(key); + if (field === void 0) { + return null; + } + return field.valueTypeParams; + } + getValueTypeParamByFullKey(key) { + const field = this.getFullKeyMap().get(key); + if (field === void 0) { + throw new Error(`Field with key ${key} does not exist in the schematics`); + } + return field.valueTypeParams; + } + hasFullKey(key) { + const field = this.getFullKeyMap().get(key); + return field !== void 0; + } + /** + * Given a KVConfig, filter it to only include fields that are in the schematics. + */ + filterConfig(config, additionalFilter) { + const fullKeyMap = this.getFullKeyMap(); + return { + fields: config.fields.filter((configField) => { + const field = fullKeyMap.get(configField.key); + if (field === void 0) { + return false; + } + if (additionalFilter !== void 0) { + return additionalFilter(field.fullKey, { + type: field.valueTypeKey, + param: field.valueTypeParams + }); + } + return true; + }) + }; + } + /** + * Given a KVConfigStack, filter it to only include fields that are in the schematics. + */ + filterStack(stack) { + return { + layers: stack.layers.map((layer) => ({ + layerName: layer.layerName, + config: this.filterConfig(layer.config) + })) + }; + } + twoWayFilterConfig(config, additionalFilter) { + const includedFields = []; + const excludedFields = []; + const fullKeyMap = this.getFullKeyMap(); + for (const configField of config.fields) { + const field = fullKeyMap.get(configField.key); + let include = field !== void 0; + if (field !== void 0 && additionalFilter !== void 0) { + include = additionalFilter(field.fullKey, { + type: field.valueTypeKey, + param: field.valueTypeParams + }); + } + if (include) { + includedFields.push(configField); + } else { + excludedFields.push(configField); + } + } + return [{ fields: includedFields }, { fields: excludedFields }]; + } + /** + * Given a list of keys, filter it to only include keys that are in the schematics. + */ + filterFullKeys(keys2) { + const fullKeyMap = this.getFullKeyMap(); + return keys2.filter((key) => fullKeyMap.has(key)); + } + /** + * Compares two KV config. Compare with "effective equals". Only compare fields in the schematics. + * Does not apply defaults. + */ + configEffectiveEquals(a3, b4) { + const aMap = kvConfigToMap(a3); + const bMap = kvConfigToMap(b4); + for (const field of this.fields.values()) { + const aValue = aMap.get(field.fullKey); + const bValue = bMap.get(field.fullKey); + if (aValue === void 0) { + if (bValue === void 0) { + continue; + } else { + return false; + } + } + this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue); + } + return true; + } + /** + * Compares two KV config field. Compare with "effective equals". Can only compare fields in the + * schematics. + */ + fieldEffectiveEquals(key, a3, b4) { + const field = this.obtainField(key); + return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a3), field.schema.parse(b4)); + } + fieldEffectiveEqualsWithFullKey(fullKey, a3, b4) { + const fullKeyMap = this.getFullKeyMap(); + const field = fullKeyMap.get(fullKey); + if (field === void 0) { + throw new Error(`Field with key ${fullKey} does not exist in the schematics`); + } + return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a3), field.schema.parse(b4)); + } + makeInternalFieldStringifyOpts(opts) { + return { + t: opts.t ?? ((_key, fallback) => fallback), + desiredLength: opts.desiredLength + }; + } + stringifyField(key, value, opts = {}) { + const field = this.obtainField(key); + return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value); + } + tryStringifyFieldWithFullKey(key, value, opts) { + const fullKeyMap = this.getFullKeyMap(); + const field = fullKeyMap.get(key); + if (field === void 0) { + return null; + } + return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value); + } + /** + * Apply config in patch to target. Only apply fields that are in the schematics. + */ + apply(target, patch) { + const filteredPatch = this.filterConfig(patch); + return collapseKVStackRaw([target, filteredPatch]); + } + /** + * Tries to un-apply the patch from the target. Will only un-apply fields that are in the + * schematics. + * + * If the value in the target is not effective equal to the value in the patch, it will not be + * removed. + */ + unApply(target, patch) { + const filteredPatch = this.filterConfig(patch); + const patchMap = kvConfigToMap(filteredPatch); + const newMap = new Map(kvConfigToMap(target)); + const fullKeyMap = this.getFullKeyMap(); + for (const [key, value] of patchMap.entries()) { + const field = fullKeyMap.get(key); + if (field === void 0) { + continue; + } + const targetValue = newMap.get(key); + if (targetValue !== void 0) { + if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, value, targetValue)) { + continue; + } + newMap.delete(key); + } + } + return mapToKVConfig(newMap); + } + /** + * Given a KVConfig, iterate through all the fields that are in the schematics. Keys will be full + * keys. + */ + *iterateFieldsOfConfig(config) { + const fullKeyMap = this.getFullKeyMap(); + for (const { key, value } of config.fields) { + const field = fullKeyMap.get(key); + if (field !== void 0) { + yield [key, value]; + } + } + } + /** + * Given a KVConfig, iterate through all the fields that are in the schematics. + */ + *fullKeys() { + const fullKeyMap = this.getFullKeyMap(); + for (const key of fullKeyMap.keys()) { + yield key; + } + } + /** + * Effectively compare two KV config, and return full keys of fields that are different. + */ + effectiveCompareConfig(a3, b4, opts = {}) { + const { fieldFilter } = opts; + const aMap = kvConfigToMap(a3); + const bMap = kvConfigToMap(b4); + const onlyInA = []; + const onlyInB = []; + const inBothButDifferent = []; + for (const field of this.fields.values()) { + if (fieldFilter !== void 0) { + if (!fieldFilter(field.fullKey, { + type: field.valueTypeKey, + param: field.valueTypeParams + })) { + continue; + } + } + const aValue = aMap.get(field.fullKey); + const bValue = bMap.get(field.fullKey); + if (aValue === void 0) { + if (bValue === void 0) { + continue; + } else { + onlyInB.push(field.fullKey); + } + } else { + if (bValue === void 0) { + onlyInA.push(field.fullKey); + } else { + if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue)) { + inBothButDifferent.push(field.fullKey); + } + } + } + } + return { onlyInA, onlyInB, inBothButDifferent }; + } + serialize() { + return { + fields: [...this.fields.entries()].map(([key, field]) => ({ + shortKey: key, + fullKey: field.fullKey, + typeKey: field.valueTypeKey, + typeParams: field.valueTypeParams, + defaultValue: field.defaultValue + })), + extensionPrefixes: this.extensionPrefixes + }; + } + /** + * Check if any of the fields in the schematics has a full key that starts with the given prefix. + */ + hasFieldsWithPrefix(prefix) { + for (const field of this.fields.values()) { + if (field.fullKey.startsWith(prefix)) { + return true; + } + } + return false; + } + static deserialize(valueTypeLibrary, serialized) { + const fields = new Map(serialized.fields.map((field) => { + const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams); + const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams); + return [ + field.shortKey, + { + valueTypeKey: field.typeKey, + valueTypeParams: typeParams, + schema: valueSchema, + fullKey: field.fullKey, + defaultValue: valueSchema.parse(field.defaultValue) + } + ]; + })); + return new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []); + } + static tryDeserialize(valueTypeLibrary, serialized) { + const fields = /* @__PURE__ */ new Map(); + const errors = []; + for (const field of serialized.fields) { + try { + const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams); + const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams); + fields.set(field.shortKey, { + valueTypeKey: field.typeKey, + valueTypeParams: typeParams, + schema: valueSchema, + fullKey: field.fullKey, + defaultValue: valueSchema.parse(field.defaultValue) + }); + } catch (error) { + errors.push({ + fullKey: field.fullKey, + error: serializeError(error) + }); + } + } + return { + schematics: new _KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []), + errors + }; + } + }; + KVConfigBuilder = class { + constructor(fieldDefs) { + this.fieldDefs = fieldDefs; + this.fields = /* @__PURE__ */ new Map(); + } + with(key, value) { + const field = this.fieldDefs.get(key); + if (field === void 0) { + throw new Error(`Field with key ${key} does not exist in the schematics.`); + } + this.fields.set(field.fullKey, value); + return this; + } + build() { + return mapToKVConfig(this.fields); + } + }; + ParsedKVConfig = class _ParsedKVConfig { + constructor(configMap) { + this.configMap = configMap; + } + /** + * @internal + */ + static [createParsedKVConfig](configMap) { + return new _ParsedKVConfig(configMap); + } + get(key) { + return this.configMap.get(key); + } + }; + PartialParsedKVConfig = class _PartialParsedKVConfig { + constructor(configMap) { + this.configMap = configMap; + } + static [createParsedKVConfig](configMap) { + return new _PartialParsedKVConfig(configMap); + } + get(key) { + return this.configMap.get(key); + } + has(key) { + return this.configMap.has(key); + } + }; + emptyKVConfig = { + fields: [] + }; + baseKVValueTypesLibraryBuilder = new KVFieldValueTypesLibraryBuilder({ + /** + * Display name of the field. + */ + displayName: external_exports.string().optional(), + /** + * Hint about the field. Shown when hovering over the field. + */ + hint: external_exports.string().optional(), + /** + * A field can be marked as model centric when it loses its meaning when there is no model to + * reference. + * + * An example would be prompt template. There is no point to configure prompt template when there + * isn't a specific model. + * + * @experimental This field is experimental and may change in the future. + */ + modelCentric: external_exports.boolean().optional(), + /** + * A field can be marked as non-configurable when it is only used as a means to carry information. + * As a result, it will not be shown in the UI. + * + * An example would be context length for MLX, as you cannot change it. + * + * @experimental This field is experimental and may change in the future. + */ + nonConfigurable: external_exports.boolean().optional(), + /** + * A field can be marked as engineDoesNotSupport when when the engine running the model does not + * support the field. + * + * @experimental This field is experimental and may change in the future. + */ + engineDoesNotSupport: external_exports.boolean().optional(), + /** + * A field can be marked as machine dependent when its value is highly dependent on the machine + * that is being used. When exporting the config, one may decide to not include machine dependent + * fields by default. + * + * An example would be GPU offload settings. + * + * @experimental This field is experimental and may change in the future. + */ + machineDependent: external_exports.boolean().optional(), + warning: external_exports.string().optional(), + subtitle: external_exports.string().optional(), + isExperimental: external_exports.boolean().optional(), + dependencies: external_exports.array(kvConfigFieldDependencySchema).optional() + }).valueType("numeric", { + paramType: { + min: external_exports.number().optional(), + max: external_exports.number().optional(), + step: external_exports.number().optional(), + int: external_exports.boolean().optional(), + precision: external_exports.number().int().nonnegative().optional(), + slider: external_exports.object({ + min: external_exports.number(), + max: external_exports.number(), + step: external_exports.number() + }).optional(), + shortHand: external_exports.string().optional() + }, + schemaMaker: ({ min, max, int, precision }) => { + let schema = external_exports.number(); + if (min !== void 0) { + schema = schema.min(min); + } + if (max !== void 0) { + schema = schema.max(max); + } + if (int) { + if (precision !== void 0) { + throw new Error("Cannot specify both int and precision."); + } + schema = schema.int(); + } + return schema; + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value, { int, precision }) => { + if (int) { + return String(Math.round(value)); + } + return value.toFixed(precision ?? 2); + } + }).valueType("string", { + paramType: { + minLength: external_exports.number().optional(), + maxLength: external_exports.number().optional(), + isParagraph: external_exports.boolean().optional(), + isProtected: external_exports.boolean().optional(), + /** + * If true, the string should match to a single token. + */ + isToken: external_exports.boolean().optional(), + placeholder: external_exports.string().optional() + }, + schemaMaker: ({ minLength, maxLength }) => { + let schema = external_exports.string(); + if (minLength !== void 0) { + schema = schema.min(minLength); + } + if (maxLength !== void 0) { + schema = schema.max(maxLength); + } + return schema; + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value, { isParagraph, isProtected }, { t: t6, desiredLength }) => { + if (isProtected) { + return "********"; + } + if (isParagraph) { + if (value === "") { + return t6("config:customInputs.string.emptyParagraph", ""); + } else { + if (desiredLength === void 0 || value.length <= desiredLength) { + return value; + } else { + return value.slice(0, Math.floor(desiredLength / 2)) + " ... " + value.slice(-Math.ceil(desiredLength / 2)); + } + } + } else { + const quoted = quoteString(value); + if (desiredLength === void 0 || quoted.length <= desiredLength) { + return quoted; + } else { + return quoted.slice(0, Math.floor(desiredLength / 2)) + "..." + quoted.slice(-Math.ceil(desiredLength / 2)); + } + } + } + }).valueType("select", { + paramType: { + options: external_exports.array(external_exports.object({ value: external_exports.string().nonempty(), displayName: external_exports.string() }).or(external_exports.string())).refine((options) => { + const values2 = /* @__PURE__ */ new Set(); + for (const option of options) { + const value = typeof option === "string" ? option : option.value; + if (values2.has(value)) { + return false; + } + values2.add(value); + } + return true; + }, { + message: "Duplicate values in options." + }) + }, + schemaMaker: ({ options }) => { + const allowedValues = new Set(options.map((option) => typeof option === "string" ? option : option.value)); + return external_exports.string().refine((value) => allowedValues.has(value)); + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value) => { + return value; + } + }).valueType("boolean", { + paramType: {}, + schemaMaker: () => { + return external_exports.boolean(); + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value) => { + return value ? "ON" : "OFF"; + } + }).valueType("stringArray", { + paramType: { + maxNumItems: external_exports.number().optional(), + /** + * Whether to allow empty strings in the array. Default is false. + */ + allowEmptyStrings: external_exports.boolean().optional() + }, + schemaMaker: ({ maxNumItems, allowEmptyStrings }) => { + let stringSchema = external_exports.string(); + if (!allowEmptyStrings) { + stringSchema = stringSchema.min(1); + } + let schema = external_exports.array(stringSchema); + if (maxNumItems !== void 0) { + schema = schema.max(maxNumItems); + } + return schema; + }, + effectiveEquals: (a3, b4) => { + return a3.length === b4.length && a3.every((v4, i7) => v4 === b4[i7]); + }, + stringify: (value, _typeParam, { t: t6, desiredLength }) => { + const quoted = value.map((v4) => quoteString(v4)); + if (quoted.length === 0) { + return t6("config:customInputs.stringArray.empty", ""); + } + if (quoted.length <= 2 || desiredLength === void 0) { + return quoted.join(", "); + } + let currentLength = quoted[0].length + quoted[1].length + 6; + for (let i7 = 1; i7 < quoted.length - 1; i7++) { + currentLength += quoted[i7].length + 2; + if (currentLength >= desiredLength) { + return quoted.slice(0, i7).join(", ") + ", ..." + quoted[quoted.length - 1]; + } + } + return quoted.join(", "); + } + }); + baseKVValueTypesLibraryBuilder.build(); + kvValueTypesLibrary = baseKVValueTypesLibraryBuilder.valueType("checkboxNumeric", { + paramType: { + min: external_exports.number().optional(), + max: external_exports.number().optional(), + step: external_exports.number().optional(), + int: external_exports.boolean().optional(), + uncheckedHint: external_exports.string().optional(), + precision: external_exports.number().int().nonnegative().optional(), + slider: external_exports.object({ + min: external_exports.number(), + max: external_exports.number(), + step: external_exports.number() + }).optional() + }, + schemaMaker: ({ min, max, int, precision }) => { + let numberSchema = external_exports.number(); + if (min !== void 0) { + numberSchema = numberSchema.min(min); + } + if (max !== void 0) { + numberSchema = numberSchema.max(max); + } + if (int) { + if (precision !== void 0) { + throw new Error("Cannot specify both int and precision."); + } + numberSchema = numberSchema.int(); + } + return external_exports.object({ + checked: external_exports.boolean(), + value: numberSchema + }); + }, + effectiveEquals: (a3, b4) => { + if (a3.checked !== b4.checked) { + return false; + } + if (!a3.checked) { + return true; + } + return a3.value === b4.value; + }, + stringify: (value, { int, precision }, { t: t6 }) => { + if (!value.checked) { + return t6("config:customInputs.checkboxNumeric.off", "OFF"); + } + if (int) { + return String(Math.round(value.value)); + } + return value.value.toFixed(precision ?? 2); + } + }).valueType("numericArray", { + paramType: { + min: external_exports.number().optional(), + max: external_exports.number().optional(), + int: external_exports.boolean().optional() + }, + schemaMaker: ({ min, max, int }) => { + let numberSchema = external_exports.number(); + if (min !== void 0) { + numberSchema = numberSchema.min(min); + } + if (max !== void 0) { + numberSchema = numberSchema.max(max); + } + if (int) { + numberSchema = numberSchema.int(); + } + return external_exports.array(numberSchema); + }, + effectiveEquals: (a3, b4) => { + return a3.length === b4.length && a3.every((v4, i7) => v4 === b4[i7]); + }, + stringify: (value, { int }) => { + return value.map((v4) => int ? String(Math.round(v4)) : String(v4)).join(", "); + } + }).valueType("contextOverflowPolicy", { + paramType: {}, + schemaMaker: () => { + return llmContextOverflowPolicySchema; + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value, _typeParam, { t: t6 }) => { + switch (value) { + case "stopAtLimit": + return t6("config:customInputs.contextOverflowPolicy.stopAtLimit", "Stop At Limit"); + case "truncateMiddle": + return t6("config:customInputs.contextOverflowPolicy.truncateMiddle", "Truncate Middle"); + case "rollingWindow": + return t6("config:customInputs.contextOverflowPolicy.rollingWindow", "Rolling Window"); + } + } + }).valueType("context", { + paramType: {}, + schemaMaker: () => { + return external_exports.array(llmContextReferenceSchema); + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("contextLength", { + paramType: { + max: external_exports.number().optional() + }, + schemaMaker: () => { + return external_exports.number().int().positive(); + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value, { max }) => { + if (max === void 0) { + return String(value); + } + return `${value}/${max}`; + } + }).valueType("modelIdentifier", { + paramType: { + domain: external_exports.array(modelDomainTypeSchema).optional() + }, + schemaMaker: () => { + return external_exports.string(); + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value) => { + return value; + } + }).valueType("llmPromptTemplate", { + paramType: {}, + schemaMaker: () => { + return llmPromptTemplateSchema; + }, + effectiveEquals: (a3, b4) => { + if (a3.type !== b4.type) { + return false; + } + if (a3.stopStrings.length !== b4.stopStrings.length) { + return false; + } + if (!a3.stopStrings.every((v4, i7) => v4 === b4.stopStrings[i7])) { + return false; + } + switch (a3.type) { + case "jinja": + return a3.jinjaPromptTemplate?.template === b4.jinjaPromptTemplate?.template; + case "manual": + return a3.manualPromptTemplate?.beforeSystem === b4.manualPromptTemplate?.beforeSystem && a3.manualPromptTemplate?.afterSystem === b4.manualPromptTemplate?.afterSystem && a3.manualPromptTemplate?.beforeUser === b4.manualPromptTemplate?.beforeUser && a3.manualPromptTemplate?.afterUser === b4.manualPromptTemplate?.afterUser && a3.manualPromptTemplate?.beforeAssistant === b4.manualPromptTemplate?.beforeAssistant && a3.manualPromptTemplate?.afterAssistant === b4.manualPromptTemplate?.afterAssistant; + default: { + const exhaustiveCheck = a3.type; + throw new Error("Unknown template type: " + exhaustiveCheck); + } + } + }, + stringify: (value, _typeParam, { t: t6, desiredLength }) => { + switch (value.type) { + case "jinja": { + const lead = `${t6("config:customInputs.llmPromptTemplate.type", "Type")}: ${t6("config:customInputs.llmPromptTemplate.types.jinja/label", "Jinja")} +${t6("config:customInputs.llmPromptTemplate.jinja.template/label", "Template")}: `; + if (desiredLength === void 0) { + return lead + value.jinjaPromptTemplate?.template; + } + const currentLength = lead.length; + const remainingLength = Math.min(100, desiredLength - currentLength); + const template = value.jinjaPromptTemplate?.template ?? ""; + if (template.length <= remainingLength) { + return lead + template; + } + return lead + template.slice(0, Math.floor(remainingLength / 2)) + "..." + template.slice(-Math.ceil(remainingLength / 2)); + } + case "manual": { + return `${t6("config:customInputs.llmPromptTemplate.type", "Type")}: ${t6("config:customInputs.llmPromptTemplate.types.manual/label", "Manual")} +${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label", "Before System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeSystem)} +${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label", "After System")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterSystem)} +${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label", "Before User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeUser)} +${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label", "After User")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterUser)} +${t6("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label", "Before Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeAssistant)} +${t6("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label", "After Assistant")}: ${quoteStringWithManualEscape(value.manualPromptTemplate?.afterAssistant)}`; + } + default: { + const exhaustiveCheck = value.type; + throw new Error("Unknown template type: " + exhaustiveCheck); + } + } + } + }).valueType("llmReasoningParsing", { + paramType: {}, + schemaMaker: () => { + return llmReasoningParsingSchema; + }, + effectiveEquals: (a3, b4) => { + return a3.startString === b4.startString && a3.endString === b4.endString; + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("llamaStructuredOutput", { + paramType: {}, + schemaMaker: () => { + return llmStructuredPredictionSettingSchema; + }, + effectiveEquals: (a3, b4) => { + if (a3.type === "json" && b4.type === "json") { + return deepEquals(a3, b4); + } else if (a3.type === "none" && b4.type === "none") { + return true; + } else { + return false; + } + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("speculativeDecodingDraftModel", { + paramType: {}, + schemaMaker: () => { + return external_exports.string(); + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value, _typeParam, { t: t6 }) => { + if (value === "") { + return t6("config:customInputs.speculativeDecodingDraftModel.off", "OFF"); + } + return value; + } + }).valueType("toolUse", { + paramType: {}, + schemaMaker: () => { + return llmToolUseSettingSchema; + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("toolNaming", { + paramType: {}, + schemaMaker: () => { + return toolNamingSchema; + }, + effectiveEquals: (a3, b4) => { + return a3 === b4; + }, + stringify: (value) => { + return value; + } + }).valueType("llamaAccelerationOffloadRatio", { + paramType: { + numLayers: external_exports.number().optional() + }, + schemaMaker: () => { + return llmLlamaAccelerationOffloadRatioSchema; + }, + effectiveEquals: (a3, b4) => { + const ratioA = a3 === "max" ? 1 : a3 === "off" ? 0 : a3; + const ratioB = b4 === "max" ? 1 : b4 === "off" ? 0 : b4; + return ratioA === ratioB; + }, + stringify: (value, { numLayers }, { t: t6 }) => { + if (value === "max" || value === 1) { + const label = t6("config:customInputs.llamaAccelerationOffloadRatio.max", "MAX"); + if (numLayers !== 0) { + return `${label} (${numLayers})`; + } + return label; + } + if (value === "off" || value === 0) { + return t6("config:customInputs.llamaAccelerationOffloadRatio.off", "OFF"); + } + if (numLayers !== void 0) { + return String(Math.round(numLayers * value)); + } + return (value * 100).toFixed(0) + "%"; + } + }).valueType("llamaMirostatSampling", { + paramType: {}, + schemaMaker: () => { + return llmLlamaMirostatSamplingConfigSchema; + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("llamaLogitBias", { + paramType: {}, + schemaMaker: () => { + return llmLlamaLogitBiasConfigSchema; + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("llamaCacheQuantizationType", { + paramType: {}, + schemaMaker: () => { + return external_exports.object({ + checked: external_exports.boolean(), + value: llmLlamaCacheQuantizationTypeSchema + }); + }, + effectiveEquals: (a3, b4) => { + if (a3.checked !== b4.checked) { + return false; + } + if (!a3.checked) { + return true; + } + return a3.value === b4.value; + }, + stringify: (value, _typeParam, { t: t6 }) => { + if (!value.checked) { + return t6("config:customInputs.llamaCacheQuantizationType.off", "OFF"); + } + return value.value; + } + }).valueType("mlxKvCacheQuantizationType", { + paramType: {}, + schemaMaker: () => { + return llmMlxKvCacheQuantizationSchema; + }, + effectiveEquals: (a3, b4) => { + if (a3.enabled !== b4.enabled) { + return false; + } + if (!a3.enabled) { + return true; + } + return a3.bits === b4.bits && a3.groupSize === b4.groupSize && a3.quantizedStart === b4.quantizedStart; + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("retrievalChunkingMethod", { + paramType: {}, + schemaMaker: () => { + return retrievalChunkingMethodSchema; + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("envVars", { + paramType: {}, + schemaMaker: () => { + return allowableEnvVarsSchema; + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).valueType("gpuSplitConfig", { + paramType: {}, + schemaMaker: () => { + return gpuSplitConfigSchema; + }, + effectiveEquals: (a3, b4) => { + return deepEquals(a3, b4); + }, + stringify: (value) => { + return JSON.stringify(value, null, 2); + } + }).build(); + globalConfigSchematics = new KVConfigSchematicsBuilder(kvValueTypesLibrary).extension("ext.virtualModel.customField").field("envVars", "envVars", {}, {}).scope("llm.prediction", (builder) => builder.field("temperature", "numeric", { + min: 0, + step: 0.01, + slider: { min: 0, max: 1, step: 0.01 }, + precision: 2, + shortHand: "temp" + }, 0.8).field("contextOverflowPolicy", "contextOverflowPolicy", {}, "truncateMiddle").field("maxPredictedTokens", "checkboxNumeric", { min: 1, int: true }, { checked: false, value: 1e3 }).field("stopStrings", "stringArray", {}, []).field("toolCallStopStrings", "stringArray", {}, []).field("structured", "llamaStructuredOutput", {}, { type: "none" }).scope("speculativeDecoding", (builder2) => builder2.field("draftModel", "speculativeDecodingDraftModel", { + modelCentric: true + }, "").field("minDraftLengthToConsider", "numeric", { + modelCentric: true, + min: 0, + int: true, + slider: { min: 0, max: 10, step: 1 } + }, 0).field("numReuseTokens", "numeric", { modelCentric: true, min: 1, int: true }, 256).field("minContinueDraftingProbability", "numeric", { + modelCentric: true, + min: 0, + max: 1, + step: 0.01, + precision: 2, + slider: { min: 0, max: 1, step: 0.01 } + }, 0.75).field("maxTokensToDraft", "numeric", { modelCentric: true, min: 1, int: true, slider: { min: 10, max: 30, step: 1 } }, 16).field("numDraftTokensExact", "numeric", { + modelCentric: true, + min: 1, + int: true, + slider: { min: 1, max: 10, step: 1 } + }, 2)).field("tools", "toolUse", {}, { type: "none" }).field("toolNaming", "toolNaming", {}, "removeSpecial").field("promptTemplate", "llmPromptTemplate", { modelCentric: true }, { + type: "manual", + manualPromptTemplate: { + beforeSystem: "Instruct: ", + afterSystem: "\n", + beforeAssistant: "AI: ", + afterAssistant: "\n", + beforeUser: "Human: ", + afterUser: "\n" + }, + stopStrings: [] + }).field("systemPrompt", "string", { isParagraph: true }, "").field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("contextPrefill", "context", {}, []).field("topKSampling", "numeric", { min: -1, max: 500, int: true }, 40).field("repeatPenalty", "checkboxNumeric", { min: -1, step: 0.01 }, { checked: true, value: 1.1 }).field("minPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.05 }).field("topPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.95 }).field("logProbs", "checkboxNumeric", { min: 0, max: 100, int: true }, { checked: false, value: 0 }).scope("reasoning", (builder2) => builder2.field("parsing", "llmReasoningParsing", {}, { + enabled: true, + startString: "", + endString: "" + })).scope("llama", (builder2) => builder2.field("cpuThreads", "numeric", { min: 1, int: true }, 4).field("frequencyPenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("xtcProbability", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.5 }).field("xtcThreshold", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 0.5, step: 0.01 } }, { checked: false, value: 0.1 }).field("presencePenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0 }).field("mirostatSampling", "llamaMirostatSampling", {}, { + // Disabled by default + version: 0, + learningRate: 0.1, + targetEntropy: 5 + }).field("tailFreeSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.95 }).field("locallyTypicalSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.9 }).field("logitBias", "llamaLogitBias", {}, []))).scope("llm.load", (builder) => builder.field("contextLength", "contextLength", { + machineDependent: true + }, 2048).field("numExperts", "numeric", { min: 0, int: true }, 0).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).field("offloadKVCacheToGpu", "boolean", {}, true).field("numCpuExpertLayersRatio", "llamaAccelerationOffloadRatio", { machineDependent: true, isExperimental: true }, "off").scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("cpuThreadPoolSize", "numeric", { min: 1, machineDependent: true }, 4).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("flashAttention", "boolean", { isExperimental: true, warning: "config:flashAttentionWarning" }, false).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("useFp16ForKVCache", "boolean", {}, true).field("tryMmap", "boolean", {}, true).field("kCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true }, { checked: false, value: "f16" }).field("vCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true, warning: "config:llamaKvCacheQuantizationWarning" }, { checked: false, value: "f16" })).scope("mlx", (builder2) => builder2.field("kvCacheQuantization", "mlxKvCacheQuantizationType", { isExperimental: true }, { enabled: false, bits: 8, groupSize: 64, quantizedStart: 5e3 }))).scope("load", (builder) => builder.field("gpuSplitConfig", "gpuSplitConfig", {}, defaultGPUSplitConfig).field("gpuStrictVramCap", "boolean", {}, false)).scope("embedding.load", (builder) => builder.field("contextLength", "contextLength", { machineDependent: true }, 2048).field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }).scope("llama", (builder2) => builder2.scope("acceleration", (builder3) => builder3.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")).field("evalBatchSize", "numeric", { min: 1, int: true }, 512).field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }).field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }).field("keepModelInMemory", "boolean", {}, true).field("tryMmap", "boolean", {}, true))).scope("retrieval", (builder) => builder.field("databaseFile", "string", { machineDependent: true }, "").field("chunkingMethod", "retrievalChunkingMethod", {}, { + type: "recursive-v1", + chunkSize: 512, + chunkOverlap: 100 + }).field("limit", "numeric", { min: 1, int: true }, 5).field("embeddingModel", "modelIdentifier", { domain: ["embedding"] }, "")).build(); + llmPredictionConfigSchematics = globalConfigSchematics.scoped("llm.prediction"); + llmSharedPredictionConfigSchematics = llmPredictionConfigSchematics.sliced("temperature", "maxPredictedTokens", "promptTemplate", "systemPrompt", "seed", "contextPrefill", "tools", "toolNaming", "reasoning.*"); + llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("llama.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "topKSampling", "repeatPenalty", "minPSampling", "topPSampling", "logProbs", "speculativeDecoding.draftModel", "speculativeDecoding.minContinueDraftingProbability", "speculativeDecoding.minDraftLengthToConsider", "speculativeDecoding.maxTokensToDraft", "speculativeDecoding.numReuseTokens")); + llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("mlx.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "repeatPenalty", "minPSampling", "topPSampling", "topKSampling", "speculativeDecoding.draftModel", "speculativeDecoding.numDraftTokensExact")); + llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("transformers.*")); + llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("onnx.*", "repeatPenalty", "topPSampling", "topKSampling")); + llmLoadSchematics = globalConfigSchematics.scoped("llm.load").union(globalConfigSchematics.sliced("envVars")); + llmSharedLoadConfigSchematics = llmLoadSchematics.sliced("contextLength", "seed", "envVars"); + llamaLoadConfigSchematics = globalConfigSchematics.sliced("llama.load.*", "load.*"); + llmLlamaLoadConfigSchematics = llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("llama.*", "load.*", "offloadKVCacheToGpu")).union(llamaLoadConfigSchematics); + llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("mlx.*")); + llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("transformers.*")); + llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("onnx.*")); + llmLlamaMoeAdditionalLoadConfigSchematics = llmLoadSchematics.sliced("numExperts", "numCpuExpertLayersRatio"); + llmLlamaMoeLoadConfigSchematics = llmLlamaLoadConfigSchematics.union(llmLlamaMoeAdditionalLoadConfigSchematics); + embeddingLoadSchematics = globalConfigSchematics.scoped("embedding.load").union(globalConfigSchematics.sliced("load.*")); + embeddingSharedLoadConfigSchematics = embeddingLoadSchematics.sliced("contextLength", "seed"); + retrievalSchematics = globalConfigSchematics.scoped("retrieval"); + embeddingLlamaLoadConfigSchematics = embeddingSharedLoadConfigSchematics.union(embeddingLoadSchematics.sliced("llama.*")).union(llamaLoadConfigSchematics); + new KVConfigSchematicsBuilder(kvValueTypesLibrary).build(); + lib = {}; + helpers = {}; + scan = {}; + libExports = requireLib(); + toolBaseSchema = external_exports.object({ + name: external_exports.string(), + description: external_exports.string() + }); + SimpleToolCallContext = class { + constructor(logger2, signal, callId) { + this.logger = logger2; + this.signal = signal; + this.callId = callId; + } + status(text3) { + this.logger.info(text3); + } + warn(text3) { + this.logger.warn(text3); + } + }; + functionToolSchema = toolBaseSchema.extend({ + type: external_exports.literal("function"), + parametersSchema: zodSchemaSchema, + checkParameters: external_exports.function(), + implementation: external_exports.function() + }); + rawFunctionToolSchema = toolBaseSchema.extend({ + type: external_exports.literal("rawFunction"), + parametersSchema: zodSchemaSchema, + checkParameters: external_exports.function(), + implementation: external_exports.function() + }); + unimplementedRawFunctionToolSchema = toolBaseSchema.extend({ + type: external_exports.literal("unimplementedRawFunction"), + parametersJsonSchema: zodSchemaSchema, + checkParameters: external_exports.function(), + implementation: external_exports.function() + }); + remoteToolSchema = toolBaseSchema.extend({ + type: external_exports.literal("remoteTool"), + pluginIdentifier: external_exports.string(), + parametersJsonSchema: zodSchemaSchema, + checkParameters: external_exports.function(), + implementation: external_exports.function() + }); + external_exports.discriminatedUnion("type", [ + functionToolSchema, + rawFunctionToolSchema, + unimplementedRawFunctionToolSchema, + remoteToolSchema + ]); + UnimplementedToolError = class extends Error { + constructor(toolName) { + super(`Tool "${toolName}" is not implemented.`); + } + }; + ToolCallRequestError = class extends Error { + constructor(message, rawContent) { + super(message); + this.rawContent = rawContent; + } + }; + BackendInterface = class { + constructor() { + this.unhandledEndpoints = /* @__PURE__ */ new Set(); + this.existingEndpointNames = /* @__PURE__ */ new Set(); + this.rpcEndpoints = /* @__PURE__ */ new Map(); + this.channelEndpoints = /* @__PURE__ */ new Map(); + this.signalEndpoints = /* @__PURE__ */ new Map(); + this.writableSignalEndpoints = /* @__PURE__ */ new Map(); + } + withContextType() { + return this; + } + assertEndpointNameNotExists(endpointName) { + if (this.existingEndpointNames.has(endpointName)) { + throw new Error(`Endpoint with name ${endpointName} already exists`); + } + } + /** + * Register an Rpc endpoint. + */ + addRpcEndpoint(endpointName, { parameter, returns, serialization = "raw" }) { + this.assertEndpointNameNotExists(endpointName); + this.existingEndpointNames.add(endpointName); + this.rpcEndpoints.set(endpointName, { + name: endpointName, + parameter, + returns, + serialization, + handler: null + }); + return this; + } + addChannelEndpoint(endpointName, { creationParameter, toServerPacket, toClientPacket, serialization = "raw" }) { + this.assertEndpointNameNotExists(endpointName); + this.existingEndpointNames.add(endpointName); + this.channelEndpoints.set(endpointName, { + name: endpointName, + creationParameter, + toServerPacket, + toClientPacket, + serialization, + handler: null + }); + return this; + } + addSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw" }) { + this.assertEndpointNameNotExists(endpointName); + this.existingEndpointNames.add(endpointName); + this.signalEndpoints.set(endpointName, { + name: endpointName, + creationParameter, + signalData, + serialization, + handler: null + }); + return this; + } + addWritableSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw" }) { + this.assertEndpointNameNotExists(endpointName); + this.existingEndpointNames.add(endpointName); + this.writableSignalEndpoints.set(endpointName, { + name: endpointName, + creationParameter, + signalData, + serialization, + handler: null + }); + return this; + } + /** + * Adds a handler for an Rpc endpoint. + * + * @param endpointName - The name of the endpoint. + * @param handler - The handler function. Will be called when the endpoint is invoked. When + * called, the first parameter is the context, and the second parameter is the "parameter" for the + * RPC call. Can return a value or a promise that resolves to the result. + */ + handleRpcEndpoint(endpointName, handler) { + const endpoint = this.rpcEndpoints.get(endpointName); + if (endpoint === void 0) { + throw new Error(`No Rpc endpoint with name ${endpointName}`); + } + if (endpoint.handler !== null) { + throw new Error(`Rpc endpoint with name ${endpointName} already has a handler`); + } + endpoint.handler = handler; + this.unhandledEndpoints.delete(endpointName); + } + /** + * Adds a handler for a channel endpoint. + * + * @param endpointName - The name of the endpoint. + * @param handler - The handler function. Will be called when the client creates a channel for + * this endpoint. When called, the first parameter is the context, the second parameter is the + * "creationParameter" for the channel, and the third parameter is a channel object that can be + * used to send and receive messages from the client. + * + * Must return a promise. Once that promise is settled, the channel will be closed. + */ + handleChannelEndpoint(endpointName, handler) { + const endpoint = this.channelEndpoints.get(endpointName); + if (endpoint === void 0) { + throw new Error(`No channel endpoint with name ${endpointName}`); + } + if (endpoint.handler !== null) { + throw new Error(`Channel endpoint with name ${endpointName} already has a handler`); + } + endpoint.handler = handler; + this.unhandledEndpoints.delete(endpointName); + } + /** + * Adds a handler for a signal endpoint. + * + * @param endpointName - The name of the endpoint. + * @param handler - The handler function. Will be called when the client creates a signal, and at + * least one subscriber is attached to that signal. When called, the first parameter is the + * context, and the second parameter is the "creationParameter" for the signal. This method should + * return a SignalLike, or a promise that resolves to a SignalLike. + * + * Note: There is no 1-to-1 correlation between the signal on the client side and the number of + * times this handler is called. Every time the number of client subscribers changes from 0 to 1, + * this handler will be called. Every time the number of client subscribers changes from 1 to 0, + * the signal returned from this handler will be unsubscribed. + * + * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will + * cause memory leaks. That is, either: + * + * - Return a signal that already exists + * - Create and return a LazySignal + */ + handleSignalEndpoint(endpointName, handler) { + const endpoint = this.signalEndpoints.get(endpointName); + if (endpoint === void 0) { + throw new Error(`No signal endpoint with name ${endpointName}`); + } + if (endpoint.handler !== null) { + throw new Error(`Signal endpoint with name ${endpointName} already has a handler`); + } + endpoint.handler = handler; + this.unhandledEndpoints.delete(endpointName); + } + /** + * Adds a handler for a writable signal endpoint. + * + * @param endpointName - The name of the endpoint. + * @param handler - The handler function. Will be called when the client creates a writable + * signal, and at least one subscriber is attached to that signal. When called, the first + * parameter is the context, and the second parameter is the "creationParameter" for the signal. + * This method should return a tuple of the signal and an update function. The update function + * should be called with the new data, patches, and tags to update the signal. + * + * Note: There is no 1-to-1 correlation between the signal on the client side and the number of + * times this handler is called. Every time the number of client subscribers changes from 0 to 1, + * this handler will be called. Every time the number of client subscribers changes from 1 to 0 + * the signal returned from this handler will be unsubscribed. + * + * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will + * cause memory leaks. That is, either: + * + * - Return a signal that already exists + * - Create and return a LazySignal + */ + handleWritableSignalEndpoint(endpointName, handler) { + const endpoint = this.writableSignalEndpoints.get(endpointName); + if (endpoint === void 0) { + throw new Error(`No writable signal endpoint with name ${endpointName}`); + } + if (endpoint.handler !== null) { + throw new Error(`Writable signal endpoint with name ${endpointName} already has a handler`); + } + endpoint.handler = handler; + this.unhandledEndpoints.delete(endpointName); + } + assertAllEndpointsHandled() { + if (this.unhandledEndpoints.size > 0) { + throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`); + } + } + getRpcEndpoint(endpointName) { + return this.rpcEndpoints.get(endpointName); + } + getAllRpcEndpoints() { + return [...this.rpcEndpoints.values()]; + } + getChannelEndpoint(endpointName) { + return this.channelEndpoints.get(endpointName); + } + getAllChannelEndpoints() { + return [...this.channelEndpoints.values()]; + } + getSignalEndpoint(endpointName) { + return this.signalEndpoints.get(endpointName); + } + getAllSignalEndpoints() { + return [...this.signalEndpoints.values()]; + } + getWritableSignalEndpoint(endpointName) { + return this.writableSignalEndpoints.get(endpointName); + } + getAllWritableSignalEndpoints() { + return [...this.writableSignalEndpoints.values()]; + } + }; + (function(ConnectionStatus2) { + ConnectionStatus2["Connected"] = "CONNECTED"; + ConnectionStatus2["Errored"] = "ERRORED"; + ConnectionStatus2["Closed"] = "CLOSED"; + })(ConnectionStatus || (ConnectionStatus = {})); + logger = new SimpleLogger("Channel"); + Channel = class _Channel { + constructor(innerSend) { + this.innerSend = innerSend; + this.nextAckId = 0; + this.waitingForAck = /* @__PURE__ */ new Map(); + this.receivedACK = (ackId) => { + if (this.connectionStatus.get() !== ConnectionStatus.Connected) { + logger.warn("Received ACK while in status", this.connectionStatus.get()); + return; + } + const waiting = this.waitingForAck.get(ackId); + if (waiting === void 0) { + logger.warn("Received ACK for a message that is no longer waiting for ACK, ackId =", ackId); + return; + } + waiting.resolve(); + this.waitingForAck.delete(ackId); + }; + this.receivedMessage = (packet) => { + if (this.connectionStatus.get() !== ConnectionStatus.Connected) { + logger.warn("Received message while in status", this.connectionStatus.get()); + return; + } + this.emitOnMessage(packet); + }; + this.errored = (error) => { + if (this.connectionStatus.get() !== ConnectionStatus.Connected) { + logger.warn("Received error while in status", this.connectionStatus.get()); + return; + } + this.rejectAllWaitingForAck(error); + this.setConnectionStatus(ConnectionStatus.Errored); + this.emitOnError(error); + }; + this.closed = () => { + this.rejectAllWaitingForAck(new Error("Channel closed")); + this.setConnectionStatus(ConnectionStatus.Closed); + this.emitOnClose(); + }; + [this.onMessage, this.emitOnMessage] = BufferedEvent.create(); + [this.onError, this.emitOnError] = BufferedEvent.create(); + [this.onClose, this.emitOnClose] = BufferedEvent.create(); + [this.connectionStatus, this.setConnectionStatus] = Signal.create(ConnectionStatus.Connected); + } + rejectAllWaitingForAck(error) { + const rejects = Array.from(this.waitingForAck.values()).map(({ reject }) => reject); + this.waitingForAck.clear(); + for (const reject of rejects) { + reject(error); + } + } + static create(innerSend) { + const channel = new _Channel(innerSend); + return { + channel, + receivedAck: channel.receivedACK, + receivedMessage: channel.receivedMessage, + errored: channel.errored, + closed: channel.closed + }; + } + send(packet) { + this.innerSend(packet); + } + sendAndWaitForACK(packet) { + const { promise, resolve: resolve2, reject } = makePromise(); + const ackId = this.nextAckId; + this.nextAckId++; + this.waitingForAck.set(ackId, { resolve: resolve2, reject }); + this.innerSend(packet, ackId); + return promise; + } + }; + DoubleIndexedKV = /** @class */ + (function() { + function DoubleIndexedKV2() { + this.keyToValue = /* @__PURE__ */ new Map(); + this.valueToKey = /* @__PURE__ */ new Map(); + } + DoubleIndexedKV2.prototype.set = function(key, value) { + this.keyToValue.set(key, value); + this.valueToKey.set(value, key); + }; + DoubleIndexedKV2.prototype.getByKey = function(key) { + return this.keyToValue.get(key); + }; + DoubleIndexedKV2.prototype.getByValue = function(value) { + return this.valueToKey.get(value); + }; + DoubleIndexedKV2.prototype.clear = function() { + this.keyToValue.clear(); + this.valueToKey.clear(); + }; + return DoubleIndexedKV2; + })(); + Registry = /** @class */ + (function() { + function Registry3(generateIdentifier) { + this.generateIdentifier = generateIdentifier; + this.kv = new DoubleIndexedKV(); + } + Registry3.prototype.register = function(value, identifier) { + if (this.kv.getByValue(value)) { + return; + } + if (!identifier) { + identifier = this.generateIdentifier(value); + } + this.kv.set(identifier, value); + }; + Registry3.prototype.clear = function() { + this.kv.clear(); + }; + Registry3.prototype.getIdentifier = function(value) { + return this.kv.getByValue(value); + }; + Registry3.prototype.getValue = function(identifier) { + return this.kv.getByKey(identifier); + }; + return Registry3; + })(); + __extends = globalThis && globalThis.__extends || /* @__PURE__ */ (function() { + var extendStatics = function(d4, b4) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d5, b5) { + d5.__proto__ = b5; + } || function(d5, b5) { + for (var p4 in b5) if (Object.prototype.hasOwnProperty.call(b5, p4)) d5[p4] = b5[p4]; + }; + return extendStatics(d4, b4); + }; + return function(d4, b4) { + if (typeof b4 !== "function" && b4 !== null) + throw new TypeError("Class extends value " + String(b4) + " is not a constructor or null"); + extendStatics(d4, b4); + function __() { + this.constructor = d4; + } + d4.prototype = b4 === null ? Object.create(b4) : (__.prototype = b4.prototype, new __()); + }; + })(); + ClassRegistry = /** @class */ + (function(_super) { + __extends(ClassRegistry2, _super); + function ClassRegistry2() { + var _this = _super.call(this, function(c6) { + return c6.name; + }) || this; + _this.classToAllowedProps = /* @__PURE__ */ new Map(); + return _this; + } + ClassRegistry2.prototype.register = function(value, options) { + if (typeof options === "object") { + if (options.allowProps) { + this.classToAllowedProps.set(value, options.allowProps); + } + _super.prototype.register.call(this, value, options.identifier); + } else { + _super.prototype.register.call(this, value, options); + } + }; + ClassRegistry2.prototype.getAllowedProps = function(value) { + return this.classToAllowedProps.get(value); + }; + return ClassRegistry2; + })(Registry); + __read$3 = globalThis && globalThis.__read || function(o9, n7) { + var m4 = typeof Symbol === "function" && o9[Symbol.iterator]; + if (!m4) return o9; + var i7 = m4.call(o9), r8, ar = [], e9; + try { + while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value); + } catch (error) { + e9 = { error }; + } finally { + try { + if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7); + } finally { + if (e9) throw e9.error; + } + } + return ar; + }; + CustomTransformerRegistry = /** @class */ + (function() { + function CustomTransformerRegistry2() { + this.transfomers = {}; + } + CustomTransformerRegistry2.prototype.register = function(transformer) { + this.transfomers[transformer.name] = transformer; + }; + CustomTransformerRegistry2.prototype.findApplicable = function(v4) { + return find(this.transfomers, function(transformer) { + return transformer.isApplicable(v4); + }); + }; + CustomTransformerRegistry2.prototype.findByName = function(name) { + return this.transfomers[name]; + }; + return CustomTransformerRegistry2; + })(); + getType$1 = function(payload) { + return Object.prototype.toString.call(payload).slice(8, -1); + }; + isUndefined = function(payload) { + return typeof payload === "undefined"; + }; + isNull = function(payload) { + return payload === null; + }; + isPlainObject$1 = function(payload) { + if (typeof payload !== "object" || payload === null) + return false; + if (payload === Object.prototype) + return false; + if (Object.getPrototypeOf(payload) === null) + return true; + return Object.getPrototypeOf(payload) === Object.prototype; + }; + isEmptyObject = function(payload) { + return isPlainObject$1(payload) && Object.keys(payload).length === 0; + }; + isArray$1 = function(payload) { + return Array.isArray(payload); + }; + isString = function(payload) { + return typeof payload === "string"; + }; + isNumber = function(payload) { + return typeof payload === "number" && !isNaN(payload); + }; + isBoolean = function(payload) { + return typeof payload === "boolean"; + }; + isRegExp = function(payload) { + return payload instanceof RegExp; + }; + isMap = function(payload) { + return payload instanceof Map; + }; + isSet = function(payload) { + return payload instanceof Set; + }; + isSymbol = function(payload) { + return getType$1(payload) === "Symbol"; + }; + isDate = function(payload) { + return payload instanceof Date && !isNaN(payload.valueOf()); + }; + isError = function(payload) { + return payload instanceof Error; + }; + isNaNValue = function(payload) { + return typeof payload === "number" && isNaN(payload); + }; + isPrimitive = function(payload) { + return isBoolean(payload) || isNull(payload) || isUndefined(payload) || isNumber(payload) || isString(payload) || isSymbol(payload); + }; + isBigint = function(payload) { + return typeof payload === "bigint"; + }; + isInfinite = function(payload) { + return payload === Infinity || payload === -Infinity; + }; + isTypedArray = function(payload) { + return ArrayBuffer.isView(payload) && !(payload instanceof DataView); + }; + isURL = function(payload) { + return payload instanceof URL; + }; + escapeKey = function(key) { + return key.replace(/\./g, "\\."); + }; + stringifyPath = function(path6) { + return path6.map(String).map(escapeKey).join("."); + }; + parsePath = function(string) { + var result = []; + var segment = ""; + for (var i7 = 0; i7 < string.length; i7++) { + var char = string.charAt(i7); + var isEscapedDot = char === "\\" && string.charAt(i7 + 1) === "."; + if (isEscapedDot) { + segment += "."; + i7++; + continue; + } + var isEndOfSegment = char === "."; + if (isEndOfSegment) { + result.push(segment); + segment = ""; + continue; + } + segment += char; + } + var lastSegment = segment; + result.push(lastSegment); + return result; + }; + __assign$1 = globalThis && globalThis.__assign || function() { + __assign$1 = Object.assign || function(t6) { + for (var s6, i7 = 1, n7 = arguments.length; i7 < n7; i7++) { + s6 = arguments[i7]; + for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4)) + t6[p4] = s6[p4]; + } + return t6; + }; + return __assign$1.apply(this, arguments); + }; + __read$2 = globalThis && globalThis.__read || function(o9, n7) { + var m4 = typeof Symbol === "function" && o9[Symbol.iterator]; + if (!m4) return o9; + var i7 = m4.call(o9), r8, ar = [], e9; + try { + while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value); + } catch (error) { + e9 = { error }; + } finally { + try { + if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7); + } finally { + if (e9) throw e9.error; + } + } + return ar; + }; + __spreadArray$2 = globalThis && globalThis.__spreadArray || function(to2, from2) { + for (var i7 = 0, il = from2.length, j3 = to2.length; i7 < il; i7++, j3++) + to2[j3] = from2[i7]; + return to2; + }; + simpleRules = [ + simpleTransformation(isUndefined, "undefined", function() { + return null; + }, function() { + return void 0; + }), + simpleTransformation(isBigint, "bigint", function(v4) { + return v4.toString(); + }, function(v4) { + if (typeof BigInt !== "undefined") { + return BigInt(v4); + } + console.error("Please add a BigInt polyfill."); + return v4; + }), + simpleTransformation(isDate, "Date", function(v4) { + return v4.toISOString(); + }, function(v4) { + return new Date(v4); + }), + simpleTransformation(isError, "Error", function(v4, superJson) { + var baseError = { + name: v4.name, + message: v4.message + }; + superJson.allowedErrorProps.forEach(function(prop) { + baseError[prop] = v4[prop]; + }); + return baseError; + }, function(v4, superJson) { + var e9 = new Error(v4.message); + e9.name = v4.name; + e9.stack = v4.stack; + superJson.allowedErrorProps.forEach(function(prop) { + e9[prop] = v4[prop]; + }); + return e9; + }), + simpleTransformation(isRegExp, "regexp", function(v4) { + return "" + v4; + }, function(regex) { + var body = regex.slice(1, regex.lastIndexOf("/")); + var flags = regex.slice(regex.lastIndexOf("/") + 1); + return new RegExp(body, flags); + }), + simpleTransformation( + isSet, + "set", + // (sets only exist in es6+) + // eslint-disable-next-line es5/no-es6-methods + function(v4) { + return __spreadArray$2([], __read$2(v4.values())); + }, + function(v4) { + return new Set(v4); + } + ), + simpleTransformation(isMap, "map", function(v4) { + return __spreadArray$2([], __read$2(v4.entries())); + }, function(v4) { + return new Map(v4); + }), + simpleTransformation(function(v4) { + return isNaNValue(v4) || isInfinite(v4); + }, "number", function(v4) { + if (isNaNValue(v4)) { + return "NaN"; + } + if (v4 > 0) { + return "Infinity"; + } else { + return "-Infinity"; + } + }, Number), + simpleTransformation(function(v4) { + return v4 === 0 && 1 / v4 === -Infinity; + }, "number", function() { + return "-0"; + }, Number), + simpleTransformation(isURL, "URL", function(v4) { + return v4.toString(); + }, function(v4) { + return new URL(v4); + }) + ]; + symbolRule = compositeTransformation(function(s6, superJson) { + if (isSymbol(s6)) { + var isRegistered = !!superJson.symbolRegistry.getIdentifier(s6); + return isRegistered; + } + return false; + }, function(s6, superJson) { + var identifier = superJson.symbolRegistry.getIdentifier(s6); + return ["symbol", identifier]; + }, function(v4) { + return v4.description; + }, function(_3, a3, superJson) { + var value = superJson.symbolRegistry.getValue(a3[1]); + if (!value) { + throw new Error("Trying to deserialize unknown symbol"); + } + return value; + }); + constructorToName = [ + Int8Array, + Uint8Array, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array, + Uint8ClampedArray + ].reduce(function(obj, ctor) { + obj[ctor.name] = ctor; + return obj; + }, {}); + typedArrayRule = compositeTransformation(isTypedArray, function(v4) { + return ["typed-array", v4.constructor.name]; + }, function(v4) { + return __spreadArray$2([], __read$2(v4)); + }, function(v4, a3) { + var ctor = constructorToName[a3[1]]; + if (!ctor) { + throw new Error("Trying to deserialize unknown typed array"); + } + return new ctor(v4); + }); + classRule = compositeTransformation(isInstanceOfRegisteredClass, function(clazz, superJson) { + var identifier = superJson.classRegistry.getIdentifier(clazz.constructor); + return ["class", identifier]; + }, function(clazz, superJson) { + var allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor); + if (!allowedProps) { + return __assign$1({}, clazz); + } + var result = {}; + allowedProps.forEach(function(prop) { + result[prop] = clazz[prop]; + }); + return result; + }, function(v4, a3, superJson) { + var clazz = superJson.classRegistry.getValue(a3[1]); + if (!clazz) { + throw new Error("Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564"); + } + return Object.assign(Object.create(clazz.prototype), v4); + }); + customRule = compositeTransformation(function(value, superJson) { + return !!superJson.customTransformerRegistry.findApplicable(value); + }, function(value, superJson) { + var transformer = superJson.customTransformerRegistry.findApplicable(value); + return ["custom", transformer.name]; + }, function(value, superJson) { + var transformer = superJson.customTransformerRegistry.findApplicable(value); + return transformer.serialize(value); + }, function(v4, a3, superJson) { + var transformer = superJson.customTransformerRegistry.findByName(a3[1]); + if (!transformer) { + throw new Error("Trying to deserialize unknown custom value"); + } + return transformer.deserialize(v4); + }); + compositeRules = [classRule, symbolRule, customRule, typedArrayRule]; + transformValue = function(value, superJson) { + var applicableCompositeRule = findArr(compositeRules, function(rule) { + return rule.isApplicable(value, superJson); + }); + if (applicableCompositeRule) { + return { + value: applicableCompositeRule.transform(value, superJson), + type: applicableCompositeRule.annotation(value, superJson) + }; + } + var applicableSimpleRule = findArr(simpleRules, function(rule) { + return rule.isApplicable(value, superJson); + }); + if (applicableSimpleRule) { + return { + value: applicableSimpleRule.transform(value, superJson), + type: applicableSimpleRule.annotation + }; + } + return void 0; + }; + simpleRulesByAnnotation = {}; + simpleRules.forEach(function(rule) { + simpleRulesByAnnotation[rule.annotation] = rule; + }); + untransformValue = function(json2, type, superJson) { + if (isArray$1(type)) { + switch (type[0]) { + case "symbol": + return symbolRule.untransform(json2, type, superJson); + case "class": + return classRule.untransform(json2, type, superJson); + case "custom": + return customRule.untransform(json2, type, superJson); + case "typed-array": + return typedArrayRule.untransform(json2, type, superJson); + default: + throw new Error("Unknown transformation: " + type); + } + } else { + var transformation = simpleRulesByAnnotation[type]; + if (!transformation) { + throw new Error("Unknown transformation: " + type); + } + return transformation.untransform(json2, superJson); + } + }; + getNthKey = function(value, n7) { + var keys2 = value.keys(); + while (n7 > 0) { + keys2.next(); + n7--; + } + return keys2.next().value; + }; + getDeep = function(object, path6) { + validatePath(path6); + for (var i7 = 0; i7 < path6.length; i7++) { + var key = path6[i7]; + if (isSet(object)) { + object = getNthKey(object, +key); + } else if (isMap(object)) { + var row = +key; + var type = +path6[++i7] === 0 ? "key" : "value"; + var keyOfRow = getNthKey(object, row); + switch (type) { + case "key": + object = keyOfRow; + break; + case "value": + object = object.get(keyOfRow); + break; + } + } else { + object = object[key]; + } + } + return object; + }; + setDeep = function(object, path6, mapper) { + validatePath(path6); + if (path6.length === 0) { + return mapper(object); + } + var parent = object; + for (var i7 = 0; i7 < path6.length - 1; i7++) { + var key = path6[i7]; + if (isArray$1(parent)) { + var index2 = +key; + parent = parent[index2]; + } else if (isPlainObject$1(parent)) { + parent = parent[key]; + } else if (isSet(parent)) { + var row = +key; + parent = getNthKey(parent, row); + } else if (isMap(parent)) { + var isEnd = i7 === path6.length - 2; + if (isEnd) { + break; + } + var row = +key; + var type = +path6[++i7] === 0 ? "key" : "value"; + var keyOfRow = getNthKey(parent, row); + switch (type) { + case "key": + parent = keyOfRow; + break; + case "value": + parent = parent.get(keyOfRow); + break; + } + } + } + var lastKey = path6[path6.length - 1]; + if (isArray$1(parent)) { + parent[+lastKey] = mapper(parent[+lastKey]); + } else if (isPlainObject$1(parent)) { + parent[lastKey] = mapper(parent[lastKey]); + } + if (isSet(parent)) { + var oldValue = getNthKey(parent, +lastKey); + var newValue = mapper(oldValue); + if (oldValue !== newValue) { + parent["delete"](oldValue); + parent.add(newValue); + } + } + if (isMap(parent)) { + var row = +path6[path6.length - 2]; + var keyToRow = getNthKey(parent, row); + var type = +lastKey === 0 ? "key" : "value"; + switch (type) { + case "key": { + var newKey = mapper(keyToRow); + parent.set(newKey, parent.get(keyToRow)); + if (newKey !== keyToRow) { + parent["delete"](keyToRow); + } + break; + } + case "value": { + parent.set(keyToRow, mapper(parent.get(keyToRow))); + break; + } + } + } + return object; + }; + __read$1 = globalThis && globalThis.__read || function(o9, n7) { + var m4 = typeof Symbol === "function" && o9[Symbol.iterator]; + if (!m4) return o9; + var i7 = m4.call(o9), r8, ar = [], e9; + try { + while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value); + } catch (error) { + e9 = { error }; + } finally { + try { + if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7); + } finally { + if (e9) throw e9.error; + } + } + return ar; + }; + __spreadArray$1 = globalThis && globalThis.__spreadArray || function(to2, from2) { + for (var i7 = 0, il = from2.length, j3 = to2.length; i7 < il; i7++, j3++) + to2[j3] = from2[i7]; + return to2; + }; + isDeep = function(object, superJson) { + return isPlainObject$1(object) || isArray$1(object) || isMap(object) || isSet(object) || isInstanceOfRegisteredClass(object, superJson); + }; + walker = function(object, identities, superJson, dedupe, path6, objectsInThisPath, seenObjects) { + var _a7; + if (path6 === void 0) { + path6 = []; + } + if (objectsInThisPath === void 0) { + objectsInThisPath = []; + } + if (seenObjects === void 0) { + seenObjects = /* @__PURE__ */ new Map(); + } + var primitive = isPrimitive(object); + if (!primitive) { + addIdentity(object, path6, identities); + var seen = seenObjects.get(object); + if (seen) { + return dedupe ? { + transformedValue: null + } : seen; + } + } + if (!isDeep(object, superJson)) { + var transformed_1 = transformValue(object, superJson); + var result_1 = transformed_1 ? { + transformedValue: transformed_1.value, + annotations: [transformed_1.type] + } : { + transformedValue: object + }; + if (!primitive) { + seenObjects.set(object, result_1); + } + return result_1; + } + if (includes(objectsInThisPath, object)) { + return { + transformedValue: null + }; + } + var transformationResult = transformValue(object, superJson); + var transformed = (_a7 = transformationResult === null || transformationResult === void 0 ? void 0 : transformationResult.value) !== null && _a7 !== void 0 ? _a7 : object; + var transformedValue = isArray$1(transformed) ? [] : {}; + var innerAnnotations = {}; + forEach(transformed, function(value, index2) { + var recursiveResult = walker(value, identities, superJson, dedupe, __spreadArray$1(__spreadArray$1([], __read$1(path6)), [index2]), __spreadArray$1(__spreadArray$1([], __read$1(objectsInThisPath)), [object]), seenObjects); + transformedValue[index2] = recursiveResult.transformedValue; + if (isArray$1(recursiveResult.annotations)) { + innerAnnotations[index2] = recursiveResult.annotations; + } else if (isPlainObject$1(recursiveResult.annotations)) { + forEach(recursiveResult.annotations, function(tree, key) { + innerAnnotations[escapeKey(index2) + "." + key] = tree; + }); + } + }); + var result = isEmptyObject(innerAnnotations) ? { + transformedValue, + annotations: !!transformationResult ? [transformationResult.type] : void 0 + } : { + transformedValue, + annotations: !!transformationResult ? [transformationResult.type, innerAnnotations] : innerAnnotations + }; + if (!primitive) { + seenObjects.set(object, result); + } + return result; + }; + __assign = globalThis && globalThis.__assign || function() { + __assign = Object.assign || function(t6) { + for (var s6, i7 = 1, n7 = arguments.length; i7 < n7; i7++) { + s6 = arguments[i7]; + for (var p4 in s6) if (Object.prototype.hasOwnProperty.call(s6, p4)) + t6[p4] = s6[p4]; + } + return t6; + }; + return __assign.apply(this, arguments); + }; + __read = globalThis && globalThis.__read || function(o9, n7) { + var m4 = typeof Symbol === "function" && o9[Symbol.iterator]; + if (!m4) return o9; + var i7 = m4.call(o9), r8, ar = [], e9; + try { + while ((n7 === void 0 || n7-- > 0) && !(r8 = i7.next()).done) ar.push(r8.value); + } catch (error) { + e9 = { error }; + } finally { + try { + if (r8 && !r8.done && (m4 = i7["return"])) m4.call(i7); + } finally { + if (e9) throw e9.error; + } + } + return ar; + }; + __spreadArray = globalThis && globalThis.__spreadArray || function(to2, from2) { + for (var i7 = 0, il = from2.length, j3 = to2.length; i7 < il; i7++, j3++) + to2[j3] = from2[i7]; + return to2; + }; + SuperJSON = /** @class */ + (function() { + function SuperJSON2(_a7) { + var _b = _a7 === void 0 ? {} : _a7, _c = _b.dedupe, dedupe = _c === void 0 ? false : _c; + this.classRegistry = new ClassRegistry(); + this.symbolRegistry = new Registry(function(s6) { + var _a8; + return (_a8 = s6.description) !== null && _a8 !== void 0 ? _a8 : ""; + }); + this.customTransformerRegistry = new CustomTransformerRegistry(); + this.allowedErrorProps = []; + this.dedupe = dedupe; + } + SuperJSON2.prototype.serialize = function(object) { + var identities = /* @__PURE__ */ new Map(); + var output = walker(object, identities, this, this.dedupe); + var res = { + json: output.transformedValue + }; + if (output.annotations) { + res.meta = __assign(__assign({}, res.meta), { values: output.annotations }); + } + var equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe); + if (equalityAnnotations) { + res.meta = __assign(__assign({}, res.meta), { referentialEqualities: equalityAnnotations }); + } + return res; + }; + SuperJSON2.prototype.deserialize = function(payload) { + var json2 = payload.json, meta = payload.meta; + var result = copy(json2); + if (meta === null || meta === void 0 ? void 0 : meta.values) { + result = applyValueAnnotations(result, meta.values, this); + } + if (meta === null || meta === void 0 ? void 0 : meta.referentialEqualities) { + result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities); + } + return result; + }; + SuperJSON2.prototype.stringify = function(object) { + return JSON.stringify(this.serialize(object)); + }; + SuperJSON2.prototype.parse = function(string) { + return this.deserialize(JSON.parse(string)); + }; + SuperJSON2.prototype.registerClass = function(v4, options) { + this.classRegistry.register(v4, options); + }; + SuperJSON2.prototype.registerSymbol = function(v4, identifier) { + this.symbolRegistry.register(v4, identifier); + }; + SuperJSON2.prototype.registerCustom = function(transformer, name) { + this.customTransformerRegistry.register(__assign({ name }, transformer)); + }; + SuperJSON2.prototype.allowErrorProps = function() { + var _a7; + var props = []; + for (var _i = 0; _i < arguments.length; _i++) { + props[_i] = arguments[_i]; + } + (_a7 = this.allowedErrorProps).push.apply(_a7, __spreadArray([], __read(props))); + }; + SuperJSON2.defaultInstance = new SuperJSON2(); + SuperJSON2.serialize = SuperJSON2.defaultInstance.serialize.bind(SuperJSON2.defaultInstance); + SuperJSON2.deserialize = SuperJSON2.defaultInstance.deserialize.bind(SuperJSON2.defaultInstance); + SuperJSON2.stringify = SuperJSON2.defaultInstance.stringify.bind(SuperJSON2.defaultInstance); + SuperJSON2.parse = SuperJSON2.defaultInstance.parse.bind(SuperJSON2.defaultInstance); + SuperJSON2.registerClass = SuperJSON2.defaultInstance.registerClass.bind(SuperJSON2.defaultInstance); + SuperJSON2.registerSymbol = SuperJSON2.defaultInstance.registerSymbol.bind(SuperJSON2.defaultInstance); + SuperJSON2.registerCustom = SuperJSON2.defaultInstance.registerCustom.bind(SuperJSON2.defaultInstance); + SuperJSON2.allowErrorProps = SuperJSON2.defaultInstance.allowErrorProps.bind(SuperJSON2.defaultInstance); + return SuperJSON2; + })(); + serialize$1 = SuperJSON.serialize; + deserialize$1 = SuperJSON.deserialize; + serializedOpaqueSchema = external_exports.any(); + clientToServerMessageSchema = external_exports.discriminatedUnion("type", [ + // Communication + external_exports.object({ + type: external_exports.literal("communicationWarning"), + warning: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("keepAlive") + }), + // Channel + external_exports.object({ + type: external_exports.literal("channelCreate"), + endpoint: external_exports.string(), + channelId: external_exports.number().int(), + creationParameter: serializedOpaqueSchema + }), + external_exports.object({ + type: external_exports.literal("channelSend"), + channelId: external_exports.number().int(), + message: serializedOpaqueSchema, + ackId: external_exports.number().int().optional() + }), + external_exports.object({ + type: external_exports.literal("channelAck"), + channelId: external_exports.number().int(), + ackId: external_exports.number().int() + }), + // RPC + external_exports.object({ + type: external_exports.literal("rpcCall"), + endpoint: external_exports.string(), + callId: external_exports.number().int(), + parameter: serializedOpaqueSchema + }), + // Readonly signal + external_exports.object({ + type: external_exports.literal("signalSubscribe"), + creationParameter: serializedOpaqueSchema, + endpoint: external_exports.string(), + subscribeId: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("signalUnsubscribe"), + subscribeId: external_exports.number().int() + }), + // Writable signal + external_exports.object({ + type: external_exports.literal("writableSignalSubscribe"), + creationParameter: serializedOpaqueSchema, + endpoint: external_exports.string(), + subscribeId: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("writableSignalUnsubscribe"), + subscribeId: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("writableSignalUpdate"), + subscribeId: external_exports.number().int(), + patches: external_exports.array(serializedOpaqueSchema), + tags: external_exports.array(external_exports.string()) + }) + ]); + serverToClientMessageSchema = external_exports.discriminatedUnion("type", [ + // Communication + external_exports.object({ + type: external_exports.literal("communicationWarning"), + warning: external_exports.string() + }), + external_exports.object({ + type: external_exports.literal("keepAliveAck") + }), + // Channel + external_exports.object({ + type: external_exports.literal("channelSend"), + channelId: external_exports.number().int(), + message: serializedOpaqueSchema, + ackId: external_exports.number().int().optional() + }), + external_exports.object({ + type: external_exports.literal("channelAck"), + channelId: external_exports.number().int(), + ackId: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("channelClose"), + channelId: external_exports.number().int() + }), + external_exports.object({ + type: external_exports.literal("channelError"), + channelId: external_exports.number().int(), + error: serializedLMSExtendedErrorSchema + }), + // RPC + external_exports.object({ + type: external_exports.literal("rpcResult"), + callId: external_exports.number().int(), + result: serializedOpaqueSchema + }), + external_exports.object({ + type: external_exports.literal("rpcError"), + callId: external_exports.number().int(), + error: serializedLMSExtendedErrorSchema + }), + // Readonly signal + external_exports.object({ + type: external_exports.literal("signalUpdate"), + subscribeId: external_exports.number().int(), + patches: external_exports.array(serializedOpaqueSchema), + tags: external_exports.array(external_exports.string()) + }), + external_exports.object({ + type: external_exports.literal("signalError"), + subscribeId: external_exports.number().int(), + error: serializedLMSExtendedErrorSchema + }), + // Writable signal + external_exports.object({ + type: external_exports.literal("writableSignalUpdate"), + subscribeId: external_exports.number().int(), + patches: external_exports.array(serializedOpaqueSchema), + tags: external_exports.array(external_exports.string()) + }), + external_exports.object({ + type: external_exports.literal("writableSignalError"), + subscribeId: external_exports.number().int(), + error: serializedLMSExtendedErrorSchema + }) + ]); + Transport = class { + constructor() { + this.disposed = false; + } + async [Symbol.asyncDispose]() { + if (this.disposed) { + throw new Error("Cannot dispose twice"); + } + this.disposed = true; + } + }; + ClientTransport = class extends Transport { + parseIncomingMessage(message) { + return serverToClientMessageSchema.parse(message); + } + send(message) { + const result = clientToServerMessageSchema.parse(message); + this.sendViaTransport(result); + } + /** + * Called by the client port when the number of open communications changes from 0 to 1. This + * usually indicates the `socket.ref()` should be called to prevent the process from exiting. + */ + onHavingOneOrMoreOpenCommunication() { + } + // The following snippet is intentionally not a tsdoc (only 1 star as oppose to 2). There is + // likely a bug in TypeScript that when we change it to tsdoc, on darwin and linux, it causes the + // generated .d.ts file to be invalid. We have considered reporting this to TypeScript, but it is + // way too difficult to narrow down, thus we just hope this is the only case that this error + // occurs. + /* + * Called by the client port when the number of open communications changes from 1 or more to 0. + * This usually indicates the `socket.unref()` should be called to allow the process to exit. + */ + onHavingNoOpenCommunication() { + } + }; + wsAuthenticationResultSchema = external_exports.discriminatedUnion("success", [ + external_exports.object({ + success: external_exports.literal(true) + }), + external_exports.object({ + success: external_exports.literal(false), + error: external_exports.string() + }) + ]); + (function(WsClientTransportStatus2) { + WsClientTransportStatus2["Disconnected"] = "DISCONNECTED"; + WsClientTransportStatus2["Connecting"] = "CONNECTING"; + WsClientTransportStatus2["Connected"] = "CONNECTED"; + })(WsClientTransportStatus || (WsClientTransportStatus = {})); + WsClientTransport = class _WsClientTransport extends ClientTransport { + constructor(url, receivedMessage, errored, { abortSignal, parentLogger } = {}) { + super(); + this.url = url; + this.receivedMessage = receivedMessage; + this.errored = errored; + this.ws = null; + this.queuedMessages = []; + this.status = WsClientTransportStatus.Disconnected; + this.resolvedUrl = null; + this.shouldRef = false; + this.resolveDisposed = null; + this.abortSignal = abortSignal; + this.logger = new SimpleLogger("WsClientTransport", parentLogger); + } + static createWsClientTransportFactory(url, { abortSignal } = {}) { + return (receivedMessage, errored, parentLogger) => new _WsClientTransport(url, receivedMessage, errored, { + abortSignal, + parentLogger + }); + } + connect() { + if (this.status !== WsClientTransportStatus.Disconnected) { + this.logger.warn("connect() called while not disconnected"); + return; + } + if (this.disposed) { + throw new Error(text` + Cannot establish WebSocket connection because the transport has been disposed. + `); + } + if (this.abortSignal !== void 0 && this.abortSignal.aborted) { + throw new Error(this.abortSignal.reason); + } + this.status = WsClientTransportStatus.Connecting; + Promise.resolve(this.url).then((url) => { + this.resolvedUrl = url; + this.ws = new import_lms_isomorphic.WebSocket(url); + this.ws.addEventListener("open", this.onWsOpen.bind(this)); + this.ws.addEventListener("error", (event) => this.onWsError(event.error)); + this.ws.addEventListener("close", () => { + this.onWsError(new Error("WebSocket connection closed")); + }); + const abortSignal = this.abortSignal; + if (abortSignal !== void 0) { + if (abortSignal.aborted) { + this.onWsError(abortSignal.reason); + } else { + const abortListener = () => { + this.onWsError(abortSignal.reason); + }; + abortSignal.addEventListener("abort", abortListener, { once: true }); + this.ws.addEventListener("close", () => { + abortSignal.removeEventListener("abort", abortListener); + }); + } + } + }); + } + onWsOpen() { + this.ws.addEventListener("message", this.onWsMessage.bind(this)); + this.status = WsClientTransportStatus.Connected; + this.queuedMessages.forEach((message) => this.sendViaTransport(message)); + this.queuedMessages = []; + this.updateShouldRef(this.shouldRef); + } + onWsMessage(event) { + if (this.status !== WsClientTransportStatus.Connected) { + this.logger.warn("Received message while not connected. Message ignored:", event.data); + return; + } + let message; + try { + message = JSON.parse(String(event.data)); + } catch (error) { + this.logger.warn("Received invalid JSON message from server:", event.data); + return; + } + let parsed; + try { + parsed = this.parseIncomingMessage(message); + } catch (error) { + this.logger.warn("Received invalid message from server:", message); + return; + } + this.receivedMessage(parsed); + } + onWsError(error) { + if (this.status === WsClientTransportStatus.Disconnected) { + return; + } + this.logger.warn("WebSocket error:", error); + if (error.code === "ECONNREFUSED") { + this.logger.warnText` + WebSocket connection refused. This can happen if the server is not running or the client + is trying to connect to the wrong path. The server path that this client is + attempting to connect to is: + ${this.resolvedUrl ?? "Unknown"}. + + Please make sure the following: + + 1. LM Studio is running + + 2. The API server in LM Studio has started + + 3. The client is attempting to connect to the correct path + `; + } + try { + this.ws?.close(); + } catch (error2) { + } + this.status = WsClientTransportStatus.Disconnected; + this.errored(error); + } + onWsTimeout() { + if (this.status === WsClientTransportStatus.Disconnected) { + return; + } + this.logger.warn("Websocket timed out"); + try { + this.ws?.close(); + } catch (error) { + } + this.status = WsClientTransportStatus.Disconnected; + this.errored(new Error("WebSocket timed out")); + } + onHavingNoOpenCommunication() { + this.updateShouldRef(false); + if (this.disposed && this.resolveDisposed !== null) { + this.resolveDisposed(); + this.resolveDisposed = null; + } + } + onHavingOneOrMoreOpenCommunication() { + this.updateShouldRef(true); + } + updateShouldRef(shouldRef) { + this.shouldRef = shouldRef; + if (this.ws === null) { + return; + } + if (!this.ws._socket) { + return; + } + if (shouldRef) { + this.ws._socket.ref(); + } else { + this.ws._socket.unref(); + } + } + sendViaTransport(message) { + if (this.status === WsClientTransportStatus.Connected) { + this.ws.send(JSON.stringify(message)); + } else { + this.queuedMessages.push(message); + if (this.status === WsClientTransportStatus.Disconnected) { + this.connect(); + } + } + } + async [Symbol.asyncDispose]() { + await super[Symbol.asyncDispose](); + if (this.shouldRef) { + const { promise: disposedPromise, resolve: resolveDisposed } = makePromise(); + this.resolveDisposed = resolveDisposed; + await disposedPromise; + } + if (this.ws !== null) { + try { + this.ws.close(); + } catch (error) { + } + this.ws = null; + } + this.errored(new Error("WebSocket client transport disposed")); + this.status = WsClientTransportStatus.Disconnected; + } + }; + AuthenticatedWsClientTransport = class _AuthenticatedWsClientTransport extends WsClientTransport { + constructor(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal } = {}) { + super(url, receivedMessage, errored, { parentLogger, abortSignal }); + this.clientIdentifier = clientIdentifier; + this.clientPasskey = clientPasskey; + this.logger = this.logger.subclass("AuthenticatedWsClientTransport"); + } + static createAuthenticatedWsClientTransportFactory({ url, clientIdentifier, clientPasskey, abortSignal }) { + return (receivedMessage, errored, parentLogger) => new _AuthenticatedWsClientTransport(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal }); + } + onWsOpen() { + this.ws.send(JSON.stringify({ + authVersion: 1, + clientIdentifier: this.clientIdentifier, + clientPasskey: this.clientPasskey + })); + this.ws.addEventListener("message", (event) => { + try { + const data = JSON.parse(event.data.toString("utf-8")); + const result = wsAuthenticationResultSchema.parse(data); + if (result.success) { + super.onWsOpen(); + } else { + this.onWsError(new Error("Failed to authenticate: " + result.error)); + } + } catch (error) { + this.onWsError(new Error("Failed to parse authentication result: " + error?.message)); + } + }, { + once: true + }); + } + }; + ClientPort = class { + constructor(backendInterface, factory, { parentLogger, errorDeserializer, verboseErrorMessage } = {}) { + this.backendInterface = backendInterface; + this.openChannels = /* @__PURE__ */ new Map(); + this.ongoingRpcs = /* @__PURE__ */ new Map(); + this.openSignalSubscriptions = /* @__PURE__ */ new Map(); + this.openWritableSignalSubscriptions = /* @__PURE__ */ new Map(); + this.openCommunicationsCount = 0; + this.nextChannelId = 0; + this.nextSubscribeId = 0; + this.nextWritableSubscribeId = 0; + this.producedCommunicationWarningsCount = 0; + this.receivedMessage = (message) => { + switch (message.type) { + case "channelSend": { + this.receivedChannelSend(message); + break; + } + case "channelAck": { + this.receivedChannelAck(message); + break; + } + case "channelClose": { + this.receivedChannelClose(message); + break; + } + case "channelError": { + this.receivedChannelError(message); + break; + } + case "rpcResult": { + this.receivedRpcResult(message); + break; + } + case "rpcError": { + this.receivedRpcError(message); + break; + } + case "signalUpdate": { + this.receivedSignalUpdate(message); + break; + } + case "signalError": { + this.receivedSignalError(message); + break; + } + case "writableSignalUpdate": { + this.receivedWritableSignalUpdate(message); + break; + } + case "writableSignalError": { + this.receivedWritableSignalError(message); + break; + } + case "communicationWarning": { + this.receivedCommunicationWarning(message); + break; + } + case "keepAliveAck": { + this.receivedKeepAliveAck(message); + break; + } + } + }; + this.errored = (error) => { + for (const openChannel of this.openChannels.values()) { + openChannel.errored(error); + } + this.openChannels.clear(); + for (const ongoingRpc of this.ongoingRpcs.values()) { + ongoingRpc.reject(error); + } + this.ongoingRpcs.clear(); + for (const openSignalSubscription of this.openSignalSubscriptions.values()) { + openSignalSubscription.errored(error); + } + this.openSignalSubscriptions.clear(); + for (const openWritableSignalSubscription of this.openWritableSignalSubscriptions.values()) { + openWritableSignalSubscription.errored(error); + } + this.openWritableSignalSubscriptions.clear(); + this.updateOpenCommunicationsCount(); + }; + this.logger = new SimpleLogger("ClientPort", parentLogger); + this.errorDeserializer = errorDeserializer ?? defaultErrorDeserializer; + this.verboseErrorMessage = verboseErrorMessage ?? true; + this.transport = factory(this.receivedMessage, this.errored, this.logger); + } + communicationWarning(warning) { + if (this.producedCommunicationWarningsCount >= 5) { + return; + } + this.logger.warnText` + Produced communication warning: ${warning} + + This is usually caused by communication protocol incompatibility. Please make sure you are + using the up-to-date versions of the SDK and LM Studio. + `; + this.transport.send({ + type: "communicationWarning", + warning + }); + this.producedCommunicationWarningsCount++; + if (this.producedCommunicationWarningsCount >= 5) { + this.logger.errorText` + 5 communication warnings have been produced. Further warnings will not be printed. + `; + } + } + updateOpenCommunicationsCount() { + const previousCount = this.openCommunicationsCount; + this.openCommunicationsCount = this.openChannels.size + this.ongoingRpcs.size + this.openSignalSubscriptions.size + this.openWritableSignalSubscriptions.size; + if (this.openCommunicationsCount === 0 && previousCount > 0) { + this.transport.onHavingNoOpenCommunication(); + } else if (this.openCommunicationsCount === 1 && previousCount === 0) { + this.transport.onHavingOneOrMoreOpenCommunication(); + } + } + receivedChannelSend(message) { + const openChannel = this.openChannels.get(message.channelId); + if (openChannel === void 0) { + this.communicationWarning(`Received channelSend for unknown channel, channelId = ${message.channelId}`); + return; + } + const deserializedMessage = deserialize(openChannel.endpoint.serialization, message.message); + const parsed = openChannel.endpoint.toClientPacket.safeParse(deserializedMessage); + if (!parsed.success) { + this.communicationWarning(text` + Received invalid message for channel: endpointName = ${openChannel.endpoint.name}, message = + ${deserializedMessage}. Zod error: + + ${Validator.prettyPrintZod("message", parsed.error)} + `); + return; + } + openChannel.receivedMessage(parsed.data); + } + receivedChannelAck(message) { + const openChannel = this.openChannels.get(message.channelId); + if (openChannel === void 0) { + this.communicationWarning(`Received channelAck for unknown channel, channelId = ${message.channelId}`); + return; + } + openChannel.receivedAck(message.ackId); + } + receivedChannelClose(message) { + const openChannel = this.openChannels.get(message.channelId); + if (openChannel === void 0) { + this.communicationWarning(`Received channelClose for unknown channel, channelId = ${message.channelId}`); + return; + } + this.openChannels.delete(message.channelId); + openChannel.closed(); + this.updateOpenCommunicationsCount(); + } + receivedChannelError(message) { + const openChannel = this.openChannels.get(message.channelId); + if (openChannel === void 0) { + this.communicationWarning(`Received channelError for unknown channel, channelId = ${message.channelId}`); + return; + } + this.openChannels.delete(message.channelId); + const error = this.errorDeserializer(message.error, "Channel Error", this.verboseErrorMessage ? openChannel.stack : void 0); + openChannel.errored(error); + this.updateOpenCommunicationsCount(); + } + receivedRpcResult(message) { + const ongoingRpc = this.ongoingRpcs.get(message.callId); + if (ongoingRpc === void 0) { + this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${message.callId}`); + return; + } + const deserializedResult = deserialize(ongoingRpc.endpoint.serialization, message.result); + const parsed = ongoingRpc.endpoint.returns.safeParse(deserializedResult); + if (!parsed.success) { + this.communicationWarning(text` + Received invalid result for rpc, endpointName = ${ongoingRpc.endpoint.name}, result = + ${deserializedResult}. Zod error: + + ${Validator.prettyPrintZod("result", parsed.error)} + `); + return; + } + ongoingRpc.resolve(parsed.data); + this.ongoingRpcs.delete(message.callId); + this.updateOpenCommunicationsCount(); + } + receivedRpcError(message) { + const ongoingRpc = this.ongoingRpcs.get(message.callId); + if (ongoingRpc === void 0) { + this.communicationWarning(`Received rpcError for unknown rpc, callId = ${message.callId}`); + return; + } + const error = this.errorDeserializer(message.error, "RPC Error", this.verboseErrorMessage ? ongoingRpc.stack : void 0); + ongoingRpc.reject(error); + this.ongoingRpcs.delete(message.callId); + this.updateOpenCommunicationsCount(); + } + receivedSignalUpdate(message) { + const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId); + if (openSignalSubscription === void 0) { + return; + } + const patches = message.patches.map((patch) => deserialize(openSignalSubscription.endpoint.serialization, patch)); + const beforeValue = openSignalSubscription.getValue(); + let afterValue; + try { + afterValue = applyPatches(beforeValue, patches); + } catch (error) { + this.communicationWarning(text` + Failed to apply patches to signal on signalUpdate. subscribeId = ${message.subscribeId}. + + beforeValue = ${JSON.stringify(beforeValue, null, 2)}, + + patches = ${JSON.stringify(patches, null, 2)}. + + Error: ${String(error)} + `); + return; + } + const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue); + if (!parseResult.success) { + this.communicationWarning(text` + Received invalid signal patch data, subscribeId = ${message.subscribeId} + + patches = ${patches}, + + beforeValue = ${beforeValue}, + + afterValue = ${afterValue}. + + Zod error: + + ${Validator.prettyPrintZod("value", parseResult.error)} + `); + return; + } + openSignalSubscription.receivedPatches(afterValue, patches, message.tags); + } + receivedSignalError(message) { + const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId); + if (openSignalSubscription === void 0) { + this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${message.subscribeId}`); + return; + } + const error = this.errorDeserializer(message.error, "Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : void 0); + openSignalSubscription.errored(error); + this.openSignalSubscriptions.delete(message.subscribeId); + this.updateOpenCommunicationsCount(); + } + receivedWritableSignalUpdate(message) { + const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId); + if (openSignalSubscription === void 0) { + return; + } + const patches = message.patches.map((patch) => deserialize(openSignalSubscription.endpoint.serialization, patch)); + const beforeValue = openSignalSubscription.getValue(); + let afterValue; + try { + afterValue = applyPatches(openSignalSubscription.getValue(), patches); + } catch (error) { + this.communicationWarning(text` + Failed to apply patches to writable signal on writableSignalUpdate. subscribeId = + ${message.subscribeId}. + + beforeValue = ${JSON.stringify(beforeValue, null, 2)}, + + patches = ${JSON.stringify(patches, null, 2)}. + + Error: ${String(error)} + `); + } + const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue); + if (!parseResult.success) { + this.communicationWarning(text` + Received invalid writable signal patch data, subscribeId = ${message.subscribeId} + + patches = ${patches}, + + beforeValue = ${beforeValue}, + + afterValue = ${afterValue}. + + Zod error: + + ${Validator.prettyPrintZod("value", parseResult.error)} + `); + return; + } + openSignalSubscription.firstUpdateReceived = true; + openSignalSubscription.receivedPatches(afterValue, patches, message.tags); + } + receivedWritableSignalError(message) { + const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId); + if (openSignalSubscription === void 0) { + this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${message.subscribeId}`); + return; + } + const error = this.errorDeserializer(message.error, "Writable Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : void 0); + openSignalSubscription.errored(error); + this.openWritableSignalSubscriptions.delete(message.subscribeId); + this.updateOpenCommunicationsCount(); + } + receivedCommunicationWarning(message) { + this.logger.warnText` + Received communication warning from the server: ${message.warning} + + This is usually caused by communication protocol incompatibility. Please make sure you are + using the up-to-date versions of the SDK and LM Studio. + + Note: This warning was received from the server and is printed on the client for convenience. + `; + } + receivedKeepAliveAck(_message) { + } + async callRpc(endpointName, param, { stack } = {}) { + const endpoint = this.backendInterface.getRpcEndpoint(endpointName); + if (endpoint === void 0) { + throw new Error(`No Rpc endpoint with name ${endpointName}`); + } + const parameter = endpoint.parameter.parse(param); + const serializedParameter = serialize(endpoint.serialization, parameter); + const callId = this.nextChannelId; + this.nextChannelId++; + const { promise, resolve: resolve2, reject } = makePromise(); + stack = stack ?? getCurrentStack(1); + this.ongoingRpcs.set(callId, { + endpoint, + stack, + resolve: resolve2, + reject + }); + this.transport.send({ + type: "rpcCall", + endpoint: endpointName, + callId, + parameter: serializedParameter + }); + this.updateOpenCommunicationsCount(); + return await promise; + } + createChannel(endpointName, param, onMessage, { stack } = {}) { + const channelEndpoint = this.backendInterface.getChannelEndpoint(endpointName); + if (channelEndpoint === void 0) { + throw new Error(`No channel endpoint with name ${endpointName}`); + } + const creationParameter = channelEndpoint.creationParameter.parse(param); + const serializedCreationParameter = serialize(channelEndpoint.serialization, creationParameter); + const channelId = this.nextChannelId; + this.nextChannelId++; + this.transport.send({ + type: "channelCreate", + endpoint: endpointName, + channelId, + creationParameter: serializedCreationParameter + }); + stack = stack ?? getCurrentStack(1); + const openChannel = { + endpoint: channelEndpoint, + stack, + ...Channel.create((packet) => { + const parsed = channelEndpoint.toServerPacket.parse(packet); + const serializedMessage = serialize(channelEndpoint.serialization, parsed); + this.transport.send({ + type: "channelSend", + channelId, + message: serializedMessage + }); + }) + }; + if (onMessage !== void 0) { + openChannel.channel.onMessage.subscribe(onMessage); + } + this.openChannels.set(channelId, openChannel); + this.updateOpenCommunicationsCount(); + return openChannel.channel; + } + /** + * Creates a readonly lazy signal will subscribe to the signal endpoint with the given name. + */ + createSignal(endpointName, param, { stack } = {}) { + const signalEndpoint = this.backendInterface.getSignalEndpoint(endpointName); + if (signalEndpoint === void 0) { + throw new Error(`No signal endpoint with name ${endpointName}`); + } + const creationParameter = signalEndpoint.creationParameter.parse(param); + const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter); + stack = stack ?? getCurrentStack(1); + const signal = LazySignal.createWithoutInitialValue((setDownstream, errorListener) => { + const subscribeId = this.nextSubscribeId; + this.nextSubscribeId++; + this.transport.send({ + type: "signalSubscribe", + endpoint: endpointName, + subscribeId, + creationParameter: serializedCreationParameter + }); + this.openSignalSubscriptions.set(subscribeId, { + endpoint: signalEndpoint, + getValue: () => signal.get(), + receivedPatches: setDownstream.withValueAndPatches, + errored: errorListener, + stack + }); + this.updateOpenCommunicationsCount(); + return () => { + this.transport.send({ + type: "signalUnsubscribe", + subscribeId + }); + this.openSignalSubscriptions.delete(subscribeId); + }; + }); + return signal; + } + createWritableSignal(endpointName, param, { stack } = {}) { + const signalEndpoint = this.backendInterface.getWritableSignalEndpoint(endpointName); + if (signalEndpoint === void 0) { + throw new Error(`No writable signal endpoint with name ${endpointName}`); + } + const creationParameter = signalEndpoint.creationParameter.parse(param); + const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter); + stack = stack ?? getCurrentStack(1); + let currentSubscribeId = null; + const writeUpstream = (_data, patches, tags) => { + if (currentSubscribeId === null) { + console.warn("writeUpstream called when not subscribed"); + return false; + } + const subscription = this.openWritableSignalSubscriptions.get(currentSubscribeId); + if (!subscription?.firstUpdateReceived) { + console.warn("writeUpstream called before the first update is received"); + return false; + } + this.transport.send({ + type: "writableSignalUpdate", + subscribeId: currentSubscribeId, + patches: patches.map((patch) => serialize(signalEndpoint.serialization, patch)), + tags + }); + return true; + }; + const [signal, setter] = OWLSignal.createWithoutInitialValue((setDownstream, errorListener) => { + const subscribeId = this.nextWritableSubscribeId; + currentSubscribeId = subscribeId; + this.nextWritableSubscribeId++; + this.transport.send({ + type: "writableSignalSubscribe", + endpoint: endpointName, + subscribeId, + creationParameter: serializedCreationParameter + }); + this.openWritableSignalSubscriptions.set(subscribeId, { + endpoint: signalEndpoint, + getValue: () => signal.getPessimistic(), + receivedPatches: setDownstream.withValueAndPatches, + firstUpdateReceived: false, + errored: errorListener, + stack + }); + this.updateOpenCommunicationsCount(); + return () => { + currentSubscribeId = null; + this.transport.send({ + type: "writableSignalUnsubscribe", + subscribeId + }); + this.openWritableSignalSubscriptions.delete(subscribeId); + }; + }, writeUpstream); + return [signal, setter]; + } + async [Symbol.asyncDispose]() { + await this.transport[Symbol.asyncDispose](); + } + }; + GenericClientTransport = class _GenericClientTransport extends ClientTransport { + constructor(onMessage, onClose, sendMessage2, receivedMessage, errored, parentLogger) { + super(); + this.sendMessage = sendMessage2; + this.receivedMessage = receivedMessage; + this.errored = errored; + this.closed = false; + this.logger = new SimpleLogger("GenericClientTransport", parentLogger); + onMessage.subscribe((message) => { + let parsed; + try { + parsed = this.parseIncomingMessage(message); + } catch (error) { + this.logger.warn("Received invalid message from server:", message); + return; + } + this.receivedMessage(parsed); + }); + onClose.subscribeOnce(() => { + if (this.closed) { + return; + } + this.closed = true; + this.errored(new Error("Server closed the connection")); + }); + } + static createFactory(onMessage, onClose, sendMessage2) { + return (receivedMessage, errored, parentLogger) => new _GenericClientTransport(onMessage, onClose, sendMessage2, receivedMessage, errored, parentLogger); + } + sendViaTransport(message) { + this.sendMessage(message); + } + }; + DiagnosticsNamespace = class { + /** @internal */ + constructor(diagnosticsPort, validator2, parentLogger) { + this.diagnosticsPort = diagnosticsPort; + this.validator = validator2; + this.logger = new SimpleLogger("Diagnostics", parentLogger); + } + /** + * Register a callback to receive log events. Return a function to stop receiving log events. + * + * This method is in alpha. Do not use this method in production yet. + * @alpha + */ + unstable_streamLogs(listener) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("client.diagnostics", "unstable_streamLogs", "listener", external_exports.function(), listener, stack); + const channel = this.diagnosticsPort.createChannel("streamLogs", void 0, void 0, { + stack + }); + const unsubscribe = channel.onMessage.subscribe((message) => { + if (message.type === "log") { + listener(message.log); + } + }); + return () => { + unsubscribe(); + channel.send({ + type: "stop" + }); + }; + } + }; + ModelNamespace = class { + /** @internal */ + getLoadModelOptsSchema() { + if (this.loadModelOptsSchema === null) { + this.loadModelOptsSchema = makeLoadModelOptsSchema(this.loadModelConfigSchema); + } + return this.loadModelOptsSchema; + } + /** @internal */ + constructor(client, port2, logger2, validator2) { + this.client = client; + this.port = port2; + this.logger = logger2; + this.validator = validator2; + this.loadModelOptsSchema = null; + } + /** + * Load a model for inferencing. The first parameter is the model key. The second parameter is an + * optional object with additional options. + * + * To find out what models are available, you can use the `lms ls` command, or programmatically + * use the `client.system.listDownloadedModels` method. + * + * Here are some examples: + * + * Loading Llama 3.2: + * + * ```typescript + * const model = await client.llm.load("llama-3.2-3b-instruct"); + * ``` + * + * Once loaded, see {@link LLMDynamicHandle} or {@link EmbeddingDynamicHandle} for how to use the + * model for inferencing or other things you can do with the model. + * + * @param modelKey - The path of the model to load. + * @param opts - Options for loading the model. + * @returns A promise that resolves to the model that can be used for inferencing + */ + async load(modelKey, opts = {}) { + const stack = getCurrentStack(1); + [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "load", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack); + const { identifier, signal, verbose = "info", config, onProgress } = opts; + let lastVerboseCallTime = 0; + const { promise, resolve: resolve2, reject } = makePromise(); + const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; + const startTime = Date.now(); + if (verbose) { + this.logger.logAtLevel(verboseLevel, text` + Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in + client.llm.load. + `); + } + let fullPath = modelKey; + const channel = this.port.createChannel("loadModel", { + modelKey, + identifier, + ttlMs: opts.ttl === void 0 ? void 0 : opts.ttl * 1e3, + loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig)) + }, (message) => { + switch (message.type) { + case "resolved": { + fullPath = message.info.modelKey; + if (message.ambiguous !== void 0) { + this.logger.warn(text` + Multiple models found for key ${modelKey}: + + ${message.ambiguous.map((x2) => ` - ${x2}`).join("\n")} + + Using the first one. + `); + } + if (verbose) { + this.logger.logAtLevel(verboseLevel, text` + Start loading model ${fullPath}... + `); + } + break; + } + case "success": { + if (verbose) { + this.logger.logAtLevel(verboseLevel, text` + Successfully loaded model ${fullPath} in ${Date.now() - startTime}ms + `); + } + resolve2(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); + break; + } + case "progress": { + const { progress } = message; + if (onProgress !== void 0) { + safeCallCallback(this.logger, "onProgress", onProgress, [progress]); + } else if (verbose) { + const now = Date.now(); + if (now - lastVerboseCallTime > 500 || progress === 1) { + const progressText = (progress * 100).toFixed(1); + this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`); + lastVerboseCallTime = now; + } + } + } + } + }, { stack }); + channel.onError.subscribeOnce(reject); + if (signal !== void 0) { + if (signal.aborted) { + channel.send({ type: "cancel" }); + reject(signal.reason); + } else { + signal.addEventListener("abort", () => { + channel.send({ type: "cancel" }); + reject(signal.reason); + }, { once: true }); + } + } + return await promise; + } + /** + * Unload a model. Once a model is unloaded, it can no longer be used. If you wish to use the + * model afterwards, you will need to load it with {@link LLMNamespace#loadModel} again. + * + * @param identifier - The identifier of the model to unload. + */ + unload(identifier) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "unload", "identifier", reasonableKeyStringSchema, identifier, stack); + return this.port.callRpc("unloadModel", { identifier }, { stack }); + } + /** + * List all the currently loaded models. + */ + async listLoaded() { + const stack = getCurrentStack(1); + const infos = await this.port.callRpc("listLoaded", void 0, { stack }); + return infos.map((info2) => this.createDomainSpecificModel(this.port, info2, this.validator, this.logger)); + } + /** + * Get any loaded model of this domain. + */ + async getAny(stack) { + const info2 = await this.port.callRpc("getModelInfo", { specifier: { type: "query", query: {} }, throwIfNotFound: true }, { stack }); + if (info2 === void 0) { + throw new Error("Backend should have thrown."); + } + return this.createDomainSpecificModel(this.port, info2, this.validator, new SimpleLogger("LLM", this.logger)); + } + createDynamicHandle(param) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandle", "param", external_exports.union([reasonableKeyStringSchema, modelQuerySchema]), param, stack); + let query; + if (typeof param === "string") { + query = { + identifier: param + }; + } else { + query = param; + } + if (query.path?.includes("\\")) { + throw makePrettyError(text` + Model path should not contain backslashes, even if you are on Windows. Use forward + slashes instead. + `, stack); + } + return this.createDomainDynamicHandle(this.port, { + type: "query", + query + }, this.validator, new SimpleLogger("DynamicHandle", this.logger)); + } + /** + * Create a dynamic handle from the internal instance reference. + * + * @alpha + */ + createDynamicHandleFromInstanceReference(instanceReference) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandleFromInstanceReference", "instanceReference", external_exports.string(), instanceReference, stack); + return this.createDomainDynamicHandle(this.port, { + type: "instanceReference", + instanceReference + }, this.validator, new SimpleLogger("DynamicHandle", this.logger)); + } + async model(modelKey, opts = {}) { + const stack = getCurrentStack(1); + if (modelKey === void 0) { + return await this.getAny(stack); + } + [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "model", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack); + const { identifier, signal, verbose = "info", config, onProgress } = opts; + if (identifier !== void 0) { + throw new Error("The identifier option is not allowed when using `.model`."); + } + let lastVerboseCallTime = 0; + const { promise, resolve: resolve2, reject } = makePromise(); + const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; + const startTime = Date.now(); + const channel = this.port.createChannel("getOrLoad", { + identifier: modelKey, + loadTtlMs: opts.ttl === void 0 ? void 0 : opts.ttl * 1e3, + loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig)) + }, (message) => { + switch (message.type) { + case "alreadyLoaded": { + return resolve2(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); + } + case "unloadingOtherJITModel": { + if (verbose) { + this.logger.logAtLevel(verboseLevel, text` + Unloading other JIT model ${message.info.modelKey}. (You can disable this behavior + by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict) + `); + } + break; + } + case "startLoading": { + if (verbose) { + this.logger.logAtLevel(verboseLevel, text` + Verbose logging is enabled. To hide progress logs, set the "verbose" option to + false in .model(). + `); + this.logger.logAtLevel(verboseLevel, text` + Model ${modelKey} is not loaded. Start loading... + `); + } + break; + } + case "loadProgress": { + const { progress } = message; + if (onProgress !== void 0) { + safeCallCallback(this.logger, "onProgress", onProgress, [progress]); + } else if (verbose) { + const now = Date.now(); + if (now - lastVerboseCallTime > 500 || progress === 1) { + const progressText = (progress * 100).toFixed(1); + this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`); + lastVerboseCallTime = now; + } + } + break; + } + case "loadSuccess": { + if (verbose) { + this.logger.logAtLevel(verboseLevel, text` + Successfully loaded model ${message.info.modelKey} in ${Date.now() - startTime}ms + `); + } + resolve2(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); + } + } + }, { stack }); + channel.onError.subscribeOnce(reject); + signal?.addEventListener("abort", () => { + channel.send({ type: "cancel" }); + reject(signal.reason); + }); + return await promise; + } + }; + DynamicHandle = class { + /** + * Don't construct this on your own. Use {@link LLMNamespace#get} or {@link LLMNamespace#load} + * instead. + * + * @internal + */ + constructor(port2, specifier) { + this.port = port2; + this.specifier = specifier; + } + /** + * Gets the information of the model that is currently associated with this `DynamicHandle`. If no + * model is currently associated, this will return `undefined`. + * + * Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at + * any moment. + */ + async getModelInfo() { + const info2 = await this.port.callRpc("getModelInfo", { specifier: this.specifier, throwIfNotFound: false }, { stack: getCurrentStack(1) }); + if (info2 === void 0) { + return void 0; + } + return info2; + } + async getLoadConfig(stack) { + const loadConfig = await this.port.callRpc("getLoadConfig", { specifier: this.specifier }, { stack }); + return loadConfig; + } + }; + EmbeddingDynamicHandle = class extends DynamicHandle { + /** + * Don't construct this on your own. Use {@link EmbeddingNamespace#get} or + * {@link EmbeddingNamespace#load} + * instead. + * + * @internal + */ + constructor(port2, specifier, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) { + super(port2, specifier); + this.validator = validator2; + this.logger = logger2; + } + async embed(inputString) { + const stack = getCurrentStack(1); + inputString = this.validator.validateMethodParamOrThrow("client.embedding", "embed", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack); + if (Array.isArray(inputString)) { + return await Promise.all(inputString.map((s6) => this.port.callRpc("embedString", { inputString: s6, modelSpecifier: this.specifier }, { stack }))); + } else { + return await this.port.callRpc("embedString", { inputString, modelSpecifier: this.specifier }, { stack }); + } + } + async getContextLength() { + const stack = getCurrentStack(1); + const loadConfig = await this.getLoadConfig(stack); + return embeddingSharedLoadConfigSchematics.access(loadConfig, "contextLength"); + } + async getEvalBatchSize() { + const stack = getCurrentStack(1); + const loadConfig = await this.getLoadConfig(stack); + return globalConfigSchematics.access(loadConfig, "embedding.load.llama.evalBatchSize"); + } + async tokenize(inputString) { + const stack = getCurrentStack(1); + inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack); + if (Array.isArray(inputString)) { + return (await Promise.all(inputString.map((s6) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s6 }, { stack })))).map((r8) => r8.tokens); + } else { + return (await this.port.callRpc("tokenize", { + specifier: this.specifier, + inputString + }, { stack })).tokens; + } + } + async countTokens(inputString) { + const stack = getCurrentStack(1); + inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack); + return (await this.port.callRpc("countTokens", { + specifier: this.specifier, + inputString + }, { stack })).tokenCount; + } + }; + EmbeddingModel = class extends EmbeddingDynamicHandle { + /** @internal */ + constructor(embeddingPort, info2, validator2, logger2 = new SimpleLogger(`EmbeddingModel`)) { + const specifier = { + type: "instanceReference", + instanceReference: info2.instanceReference + }; + super(embeddingPort, specifier, validator2, logger2); + this.identifier = info2.identifier; + this.path = info2.path; + this.modelKey = info2.modelKey; + this.format = info2.format; + this.displayName = info2.displayName; + this.sizeBytes = info2.sizeBytes; + } + async unload() { + const stack = getCurrentStack(1); + await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack }); + } + async getModelInfo() { + const info2 = await super.getModelInfo(); + if (info2 === void 0) { + const stack = getCurrentStack(1); + throw makePrettyError("This model has already been unloaded", stack); + } + return info2; + } + }; + EmbeddingNamespace = class extends ModelNamespace { + constructor() { + super(...arguments); + this.namespace = "embedding"; + this.defaultLoadConfig = {}; + this.loadModelConfigSchema = embeddingLoadModelConfigSchema; + } + /** @internal */ + loadConfigToKVConfig(config) { + return embeddingLlamaLoadConfigSchematics.buildPartialConfig({ + "llama.acceleration.offloadRatio": config.gpu?.ratio, + "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu), + "contextLength": config.contextLength, + "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0), + "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0), + "llama.keepModelInMemory": config.keepModelInMemory, + "llama.tryMmap": config.tryMmap + }); + } + /** @internal */ + createDomainSpecificModel(port2, info2, validator2, logger2) { + return new EmbeddingModel(port2, info2, validator2, logger2); + } + /** @internal */ + createDomainDynamicHandle(port2, specifier, validator2, logger2) { + return new EmbeddingDynamicHandle(port2, specifier, validator2, logger2); + } + }; + parseDocumentOptsSchema = documentParsingOptsSchema.extend({ + onProgress: external_exports.function().optional(), + signal: external_exports.instanceof(AbortSignal).optional() + }); + retrievalCallbacksSchema = external_exports.object({ + onFileProcessList: external_exports.function().optional(), + onFileProcessingStart: external_exports.function().optional(), + onFileProcessingEnd: external_exports.function().optional(), + onFileProcessingStepStart: external_exports.function().optional(), + onFileProcessingStepProgress: external_exports.function().optional(), + onFileProcessingStepEnd: external_exports.function().optional(), + onSearchingStart: external_exports.function().optional(), + onSearchingEnd: external_exports.function().optional(), + verbose: external_exports.union([external_exports.boolean(), external_exports.string()]).optional() + }); + retrievalOptsSchema = external_exports.object({ + chunkingMethod: retrievalChunkingMethodSchema.optional(), + limit: external_exports.number().int().optional(), + embeddingModel: external_exports.instanceof(EmbeddingDynamicHandle).optional(), + databasePath: external_exports.string().optional(), + signal: external_exports.instanceof(AbortSignal).optional(), + ...retrievalCallbacksSchema.shape + }); + FilesNamespace = class { + /** @internal */ + constructor(filesPort, validator2, parentLogger) { + this.filesPort = filesPort; + this.validator = validator2; + this.logger = new SimpleLogger("File", parentLogger); + } + /** + * Gets the absolute path to a local file. + * + * @internal + */ + async getLocalFileAbsolutePath(fileName, stack) { + return await this.filesPort.callRpc("getLocalFileAbsolutePath", { fileName }, { stack }); + } + /** + * Creates a file handle from a chat message part file data. Used internally. + * + * @internal + */ + createFileHandleFromChatMessagePartFileData(data) { + return new FileHandle(this, data.identifier, data.fileType, data.sizeBytes, data.name); + } + /** + * Adds a temporary image to LM Studio, and returns a FileHandle that can be used to reference + * this image. This image will be deleted when the client disconnects. + * + * This method can only be used in environments that have file system access (such as Node.js). + */ + async prepareImage(path6) { + const result = await (0, import_lms_isomorphic.readFileAsBase64)(path6); + if (result.success === false) { + throw new Error(text` + Your current JavaScript environment does not support reading files. If you can read the file + using other methods, please use "prepareImageBase64". + `); + } + const fileName = path6.split(/[\\/]/).at(-1); + const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { + name: fileName, + contentBase64: result.base64 + }); + return new FileHandle(this, identifier, fileType, sizeBytes, fileName); + } + /** + * Adds a temporary image to LM Studio. The content of the file is specified using base64. If you + * are using Node.js and have a file laying around, consider using `prepareImage` instead. + */ + async prepareImageBase64(fileName, contentBase64) { + const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { + name: fileName, + contentBase64 + }); + return new FileHandle(this, identifier, fileType, sizeBytes, fileName); + } + /** + * Adds a temporary file to LM Studio, and returns a FileHandle that can be used to reference this + * file. This file will be deleted when the client disconnects. + * + * This method can only be used in environments that have file system access (such as Node.js). + * + * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for + * updates. + */ + async prepareFile(path6) { + const result = await (0, import_lms_isomorphic.readFileAsBase64)(path6); + if (result.success === false) { + throw new Error(text` + Your current JavaScript environment does not support reading files. If you can read the file + using other methods, please use "prepareFileBase64". + `); + } + const fileName = path6.split(/[\\/]/).at(-1); + const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { + name: fileName, + contentBase64: result.base64 + }); + return new FileHandle(this, identifier, fileType, sizeBytes, fileName); + } + /** + * Adds a temporary file to LM Studio. The content of the file is specified using base64. If you + * are using Node.js and have a file laying around, consider using `prepareFile` instead. + * + * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for + * updates. */ + async prepareFileBase64(fileName, contentBase64) { + const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { + name: fileName, + contentBase64 + }); + return new FileHandle(this, identifier, fileType, sizeBytes, fileName); + } + /** + * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for + * updates. */ + async retrieve(query, files, opts = {}) { + const logger2 = this.logger; + const stack = getCurrentStack(1); + this.validator.validateMethodParamsOrThrow("client.retrieval", "retrieve", ["query", "filePaths", "opts"], [external_exports.string(), external_exports.array(external_exports.instanceof(FileHandle)), retrievalOptsSchema], [query, files, opts], stack); + const { verbose = "info" } = opts; + const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; + const shouldLog = verbose && opts.onFileProcessList === void 0 && opts.onFileProcessingStart === void 0 && opts.onFileProcessingEnd === void 0 && opts.onFileProcessingStepStart === void 0 && opts.onFileProcessingStepProgress === void 0 && opts.onFileProcessingStepEnd === void 0 && opts.onSearchingStart === void 0 && opts.onSearchingEnd === void 0; + if (opts.embeddingModel === void 0) { + throw new Error("Embedding model currently is required."); + } + const resolveFileIndex = (index2) => { + const file = files[index2]; + if (file === void 0) { + throw new Error(`File not found: ${index2}`); + } + return file; + }; + const resolveFileIndices = (indices) => { + return indices.map(resolveFileIndex); + }; + const kvConfig = retrievalSchematics.buildPartialConfig({ + chunkingMethod: opts.chunkingMethod, + databaseFile: opts.databasePath, + embeddingModel: (await opts.embeddingModel.getModelInfo())?.identifier, + limit: opts.limit + }); + let filesToProcess; + const filesProcessingStartTimes = []; + let searchingStartTime = 0; + let lastVerboseCallTime = 0; + let lastVerboseLine = ""; + return await new Promise((resolve2, reject) => { + const channel = this.filesPort.createChannel("retrieve", { query, fileIdentifiers: files.map((file) => file.identifier), config: kvConfig }, (message) => { + switch (message.type) { + case "onFileProcessList": + filesToProcess = resolveFileIndices(message.indices); + safeCallCallback(logger2, "onFileProcessList", opts.onFileProcessList, [ + filesToProcess + ]); + if (shouldLog) { + logger2.logAtLevel(verboseLevel, text` + Found ${filesToProcess.length} files need processing: + ${filesToProcess.map((file) => file.name).join(", ")} + `); + } + break; + case "onFileProcessingStart": { + if (filesToProcess === null) { + throw new Error("onFileProcessList must be called before onFileProcessingStart"); + } + const file = resolveFileIndex(message.index); + safeCallCallback(logger2, "onFileProcessingStart", opts.onFileProcessingStart, [ + file, + filesToProcess.indexOf(file), + filesToProcess + ]); + if (shouldLog) { + filesProcessingStartTimes[message.index] = Date.now(); + logger2.logAtLevel(verboseLevel, text` + Start processing file: ${file.name} + (${message.index + 1}/${filesToProcess.length}) + `); + } + break; + } + case "onFileProcessingEnd": { + if (filesToProcess === null) { + throw new Error("onFileProcessList must be called before onFileProcessingEnd"); + } + const file = resolveFileIndex(message.index); + safeCallCallback(logger2, "onFileProcessingEnd", opts.onFileProcessingEnd, [ + file, + filesToProcess.indexOf(file), + filesToProcess + ]); + if (shouldLog) { + logger2.logAtLevel(verboseLevel, text` + File processed: ${file.name}. + Time took: ${Date.now() - filesProcessingStartTimes[message.index]}ms + `); + } + break; + } + case "onFileProcessingStepStart": + safeCallCallback(logger2, "onFileProcessingStepStart", opts.onFileProcessingStepStart, [resolveFileIndex(message.index), message.step]); + break; + case "onFileProcessingStepProgress": { + safeCallCallback(logger2, "onFileProcessingStepProgress", opts.onFileProcessingStepProgress, [resolveFileIndex(message.index), message.step, message.progress]); + const now = Date.now(); + if (shouldLog && (now - lastVerboseCallTime > 500 || message.progress === 1)) { + lastVerboseCallTime = now; + const line = text` + > ${getProcessingStepName(message.step)}: ${Math.round(message.progress * 100)}% + `; + if (lastVerboseLine !== line) { + lastVerboseLine = line; + logger2.logAtLevel(verboseLevel, line); + } + } + break; + } + case "onFileProcessingStepEnd": + safeCallCallback(logger2, "onFileProcessingStepEnd", opts.onFileProcessingStepEnd, [ + resolveFileIndex(message.index), + message.step + ]); + break; + case "onSearchingStart": + safeCallCallback(logger2, "onSearchingStart", opts.onSearchingStart, []); + if (shouldLog) { + searchingStartTime = Date.now(); + logger2.logAtLevel(verboseLevel, "Start searching in the vector database..."); + } + break; + case "onSearchingEnd": + safeCallCallback(logger2, "onSearchingEnd", opts.onSearchingEnd, []); + if (shouldLog) { + logger2.logAtLevel(verboseLevel, text` + Finished searching in the vector database. + Time took: ${Date.now() - searchingStartTime}ms + `); + } + break; + case "result": { + resolve2({ + entries: message.result.entries.map((entry) => ({ + content: entry.content, + score: entry.score, + source: files[entry.sourceIndex] + })) + }); + break; + } + } + }); + if (opts.signal !== void 0) { + if (opts.signal.aborted) { + reject(opts.signal.reason); + channel.send({ type: "stop" }); + } else { + opts.signal?.addEventListener("abort", () => { + reject(opts.signal.reason); + channel.send({ type: "stop" }); + }); + } + } + channel.onError.subscribeOnce(reject); + }); + } + /** + * Parse a document + * + * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for + * updates. + */ + async parseDocument(fileHandle, opts = {}) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamsOrThrow("client.files", "parseDocument", ["fileHandle", "opts"], [external_exports.instanceof(FileHandle), parseDocumentOptsSchema], [fileHandle, opts], stack); + const { onParserLoaded, onProgress, signal, ...config } = opts; + const { promise, resolve: resolve2, reject } = makePromise(); + opts.signal?.throwIfAborted(); + let finished2 = false; + const channel = this.filesPort.createChannel("parseDocument", { fileIdentifier: fileHandle.identifier, parseOpts: config }, (message) => { + const messageType = message.type; + switch (messageType) { + case "progress": { + safeCallCallback(this.logger, "onProgress", onProgress, [message.progress]); + break; + } + case "parserLoaded": { + safeCallCallback(this.logger, "onParserLoaded", onParserLoaded, [message.parser]); + break; + } + case "result": { + resolve2({ + content: message.content, + parser: message.parser + }); + finished2 = true; + break; + } + } + }, { stack }); + signal?.addEventListener("abort", () => { + if (finished2) { + return; + } + reject(signal.reason); + channel.send({ type: "cancel" }); + }); + channel.onError.subscribeOnce(reject); + channel.onClose.subscribeOnce(() => { + if (!finished2) { + reject(new Error("Channel closed before receiving a result.")); + } + }); + return await promise; + } + /** + * Get the parsing method for a document. + * + * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for + * updates. + */ + async getDocumentParsingLibrary(fileHandle) { + const stack = getCurrentStack(1); + return await this.filesPort.callRpc("getDocumentParsingLibrary", { fileIdentifier: fileHandle.identifier }, { stack }); + } + }; + errorDeserializersMap = /* @__PURE__ */ new Map(); + registerErrorDeserializer("generic.pathNotFound", ({ availablePathsSample, path: path6, totalModels }, stack) => { + return makeTitledPrettyError(`Cannot find a model with path "${import_chalk.default.yellowBright(path6)}"`, text` + Here are your available models: + + ${formatAvailableLLMs(availablePathsSample, totalModels)} + + Run + + ${import_chalk.default.yellowBright("lms ls")} + + to see a full list of loadable models + `, stack); + }); + registerErrorDeserializer("generic.identifierNotFound", ({ loadedModelsSample, identifier, totalLoadedModels }, stack) => { + return makeTitledPrettyError(`Cannot find a model with identifier "${import_chalk.default.yellowBright(identifier)}"`, text` + Here are your loaded models: + + ${formatLoadedModels(loadedModelsSample, totalLoadedModels)} + + Run + + ${import_chalk.default.yellowBright("lms ps")} + + to see a full list of loaded models + `, stack); + }); + registerErrorDeserializer("generic.specificModelUnloaded", (_3, stack) => { + return makePrettyError(import_chalk.default.bgRed.white(text` + This model has already been unloaded. + `), stack); + }); + registerErrorDeserializer("generic.noModelMatchingQuery", ({ loadedModelsSample, totalLoadedModels, query }, stack) => { + return makePrettyError(text` + ${import_chalk.default.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")} + + Loaded Models: + + ${formatLoadedModels(loadedModelsSample, totalLoadedModels)} + + Your query: + + ${formatQuery(query)} + + Run + + ${import_chalk.default.yellowBright("lms ps")} + + to see a full list of loaded models with details + `, stack); + }); + registerErrorDeserializer("generic.domainMismatch", ({ actualDomain, expectedDomain, path: path6 }, stack) => { + return makePrettyError(text` + ${import_chalk.default.bgRed.white(" Model has wrong domain. ")} + + Expecting ${import_chalk.default.greenBright(path6)} to be ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(expectedDomain))}, but it is actually ${import_chalk.default.yellowBright(getModelDomainTypeDisplayNameSingular(actualDomain))}. + `, stack); + }); + registerErrorDeserializer("generic.presetNotFound", ({ specifiedFuzzyPresetIdentifier, availablePresetsSample, totalAvailablePresets }) => { + return makeTitledPrettyError(`Cannot find a preset with identifier "${import_chalk.default.yellowBright(specifiedFuzzyPresetIdentifier)}"`, text` + Here are your available presets: + + ${formatAvailablePresets(availablePresetsSample, totalAvailablePresets)} + + Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You + can get a preset's identifier by right-clicking on it and then select "Copy Preset + Identifier". + `); + }); + ActResult = class { + constructor(rounds, totalExecutionTimeSeconds) { + this.rounds = rounds; + this.totalExecutionTimeSeconds = totalExecutionTimeSeconds; + } + }; + callIdGiver = new IdGiver(Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2 / 1e4)) * 1e4); + NoQueueQueue = class { + needsQueueing() { + return false; + } + async runInQueue(fn, signal) { + if (signal?.aborted) { + throw new Error("Operation aborted"); + } + return fn(); + } + }; + FIFOQueue = class { + constructor() { + this.queue = []; + this.executing = false; + this.poisoned = false; + this.poisonError = null; + } + needsQueueing() { + return this.executing || this.queue.length > 0; + } + async runInQueue(fn, signal) { + if (signal?.aborted) { + throw new Error("Operation aborted"); + } + if (this.poisoned) { + throw this.poisonError ?? new Error("Queue has been poisoned by a previous error"); + } + if (!this.needsQueueing()) { + this.executing = true; + try { + if (signal?.aborted) { + throw new Error("Operation aborted"); + } + return await fn(); + } catch (error) { + this.poisoned = true; + this.poisonError = error; + this.clearQueue(error); + throw error; + } finally { + this.executing = false; + this.processQueue(); + } + } + return new Promise((resolve2, reject) => { + if (signal) { + if (signal.aborted) { + return reject(new Error("Operation aborted")); + } + signal.addEventListener("abort", () => { + const index2 = this.queue.findIndex((item) => item.resolve === resolve2 && item.reject === reject); + if (index2 !== -1) { + this.queue.splice(index2, 1); + reject(new Error("Operation aborted")); + } + }, { once: true }); + } + this.queue.push({ + fn: async () => { + try { + if (signal?.aborted) { + throw new Error("Operation aborted"); + } + const result = await fn(); + resolve2(result); + return result; + } catch (error) { + reject(error); + throw error; + } + }, + resolve: resolve2, + reject, + signal + }); + }); + } + async processQueue() { + if (this.executing || this.queue.length === 0 || this.poisoned) { + return; + } + const nextItem = this.queue.shift(); + if (!nextItem) + return; + if (nextItem.signal?.aborted) { + nextItem.reject(new Error("Operation aborted")); + this.processQueue(); + return; + } + this.executing = true; + try { + await nextItem.fn(); + } catch (error) { + this.poisoned = true; + this.poisonError = error; + this.clearQueue(error); + } finally { + this.executing = false; + if (!this.poisoned) { + this.processQueue(); + } + } + } + clearQueue(error) { + for (const item of this.queue) { + item.reject(error); + } + this.queue = []; + } + }; + GuardToolCallController = class { + /** + * Don't construct this object yourself. + */ + constructor(toolCallRequest, tool, resultContainer) { + this.toolCallRequest = toolCallRequest; + this.tool = tool; + this.resultContainer = resultContainer; + this.allow = () => { + this.assertNoResultYet("allow", getCurrentStack(1)); + this.resultContainer[0] = { type: "allow" }; + }; + this.allowAndOverrideParameters = (newParameters) => { + this.assertNoResultYet("allowAndOverrideParameters", getCurrentStack(1)); + this.resultContainer[0] = { type: "allowAndOverrideParameters", parameters: newParameters }; + }; + this.deny = (reason) => { + this.assertNoResultYet("deny", getCurrentStack(1)); + this.resultContainer[0] = { type: "deny", reason }; + }; + } + assertNoResultYet(calledMethodName, stack) { + if (this.resultContainer[0] === null) { + return; + } + throw makeTitledPrettyError(`Cannot call ${calledMethodName} after a result has been set`, text` + This tool call guard has already set a result previously (${this.resultContainer[0].type}). + You cannot set a result more than once. + `, stack); + } + }; + llmActBaseOptsSchema = external_exports.object({ + onFirstToken: external_exports.function().optional(), + onPredictionFragment: external_exports.function().optional(), + onMessage: external_exports.function().optional(), + onRoundStart: external_exports.function().optional(), + onRoundEnd: external_exports.function().optional(), + onPredictionCompleted: external_exports.function().optional(), + onPromptProcessingProgress: external_exports.function().optional(), + onToolCallRequestStart: external_exports.function().optional(), + onToolCallRequestNameReceived: external_exports.function().optional(), + onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(), + onToolCallRequestEnd: external_exports.function().optional(), + onToolCallRequestFinalized: external_exports.function().optional(), + onToolCallRequestFailure: external_exports.function().optional(), + onToolCallRequestDequeued: external_exports.function().optional(), + guardToolCall: external_exports.function().optional(), + handleInvalidToolRequest: external_exports.function().optional(), + maxPredictionRounds: external_exports.number().int().min(1).optional(), + signal: external_exports.instanceof(AbortSignal).optional(), + allowParallelToolExecution: external_exports.boolean().optional() + }); + defaultHandleInvalidToolRequest = (error, request) => { + if (request) { + return error.message; + } + throw error; + }; + PredictionResult = class { + constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig) { + this.content = content; + this.reasoningContent = reasoningContent; + this.nonReasoningContent = nonReasoningContent; + this.stats = stats; + this.modelInfo = modelInfo; + this.roundIndex = roundIndex; + this.loadConfig = loadConfig; + this.predictionConfig = predictionConfig; + } + }; + StructuredPredictionResult = class extends PredictionResult { + constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig, parsed) { + super(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig); + this.parsed = parsed; + } + }; + OngoingPrediction = class _OngoingPrediction extends StreamablePromise { + async collect(fragments) { + const content = fragments.map(({ content: content2 }) => content2).join(""); + const reasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "reasoning").map(({ content: content2 }) => content2).join(""); + const nonReasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "none").map(({ content: content2 }) => content2).join(""); + if (this.stats === null) { + throw new Error("Stats should not be null"); + } + if (this.modelInfo === null) { + throw new Error("Model info should not be null"); + } + if (this.loadModelConfig === null) { + throw new Error("Load model config should not be null"); + } + if (this.predictionConfig === null) { + throw new Error("Prediction config should not be null"); + } + if (this.parser === null) { + return new PredictionResult( + content, + reasoningContent, + nonReasoningContent, + this.stats, + this.modelInfo, + // Currently, OngoingPrediction is only used with single round predictions. Thus always + // use roundIndex 0. + /* roundIndex */ + 0, + this.loadModelConfig, + this.predictionConfig + ); + } else { + return new StructuredPredictionResult( + content, + reasoningContent, + nonReasoningContent, + this.stats, + this.modelInfo, + // Currently, OngoingPrediction is only used with single round predictions. Thus always + // use roundIndex 0. + /* predictionIndex */ + 0, + this.loadModelConfig, + this.predictionConfig, + this.parser(content) + ); + } + } + constructor(onCancel, parser) { + super(); + this.onCancel = onCancel; + this.parser = parser; + this.stats = null; + this.modelInfo = null; + this.loadModelConfig = null; + this.predictionConfig = null; + } + /** @internal */ + static create(onCancel, parser) { + const ongoingPrediction = new _OngoingPrediction(onCancel, parser); + const finished2 = (stats, modelInfo, loadModelConfig, predictionConfig) => { + ongoingPrediction.stats = stats; + ongoingPrediction.modelInfo = modelInfo; + ongoingPrediction.loadModelConfig = loadModelConfig; + ongoingPrediction.predictionConfig = predictionConfig; + ongoingPrediction.finished(); + }; + const failed = (error) => ongoingPrediction.finished(error); + const push = (fragment2) => ongoingPrediction.push(fragment2); + return { ongoingPrediction, finished: finished2, failed, push }; + } + /** + * Get the final prediction results. If you have been streaming the results, awaiting on this + * method will take no extra effort, as the results are already available in the internal buffer. + * + * Example: + * + * ```typescript + * const prediction = model.complete("When will The Winds of Winter be released?"); + * for await (const { content } of prediction) { + * process.stdout.write(content); + * } + * const result = await prediction.result(); + * console.log(result.stats); + * ``` + * + * Technically, awaiting on this method is the same as awaiting on the instance itself: + * + * ```typescript + * await prediction.result(); + * + * // Is the same as: + * + * await prediction; + * ``` + */ + async result() { + return await this; + } + /** + * Cancels the prediction. This will stop the prediction with stop reason `userStopped`. See + * {@link LLMPredictionStopReason} for other reasons that a prediction might stop. + */ + async cancel() { + this.onCancel(); + } + }; + llmPredictionOptsSchema = llmPredictionConfigInputSchema.extend({ + onPromptProcessingProgress: external_exports.function().optional(), + onFirstToken: external_exports.function().optional(), + onPredictionFragment: external_exports.function().optional(), + onToolCallRequestStart: external_exports.function().optional(), + onToolCallRequestNameReceived: external_exports.function().optional(), + onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(), + onToolCallRequestEnd: external_exports.function().optional(), + onToolCallRequestFailure: external_exports.function().optional(), + signal: external_exports.instanceof(AbortSignal).optional(), + preset: external_exports.string().optional() + }); + llmRespondOptsSchema = llmPredictionOptsSchema.extend({ + onMessage: external_exports.function().optional(), + onToolCallRequestStart: external_exports.function().optional(), + onToolCallRequestNameReceived: external_exports.function().optional(), + onToolCallRequestArgumentFragmentGenerated: external_exports.function().optional(), + onToolCallRequestEnd: external_exports.function().optional(), + onToolCallRequestFailure: external_exports.function().optional() + }); + llmActionOptsSchema = llmPredictionConfigInputSchema.extend(llmActBaseOptsSchema.shape).extend({ + preset: external_exports.string().optional() + }); + noFormattingTemplate = text` + {% for message in messages %}{{ message['content'] }}{% endfor %} +`; + LLMDynamicHandle = class extends DynamicHandle { + /** + * Don't construct this on your own. Use {@link LLMNamespace#model} or + * {@link LLMNamespace#createDynamicHandle} instead. + * + * @internal + */ + constructor(port2, specifier, validator2, logger2 = new SimpleLogger(`LLMModel`)) { + super(port2, specifier); + this.validator = validator2; + this.logger = logger2; + this.internalKVConfigStack = { layers: [] }; + this.internalIgnoreServerSessionConfig = void 0; + } + /** @internal */ + internalPredict(history, predictionConfigStack, cancelEvent, extraOpts, onFragment, onFinished, onError) { + let finished2 = false; + let firstTokenTriggered = false; + let currentCallId = null; + let receivedEagerToolNameReporting = false; + let receivedToolArgumentsStreaming = false; + const channel = this.port.createChannel("predict", { + modelSpecifier: this.specifier, + history, + predictionConfigStack, + fuzzyPresetIdentifier: extraOpts.preset, + ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig + }, (message) => { + switch (message.type) { + case "fragment": { + if (!firstTokenTriggered) { + firstTokenTriggered = true; + safeCallCallback(this.logger, "onFirstToken", extraOpts.onFirstToken, []); + } + safeCallCallback(this.logger, "onFragment", extraOpts.onPredictionFragment, [ + message.fragment + ]); + onFragment(message.fragment); + break; + } + case "promptProcessingProgress": { + safeCallCallback(this.logger, "onPromptProcessingProgress", extraOpts.onPromptProcessingProgress, [message.progress]); + break; + } + case "toolCallGenerationStart": { + if (currentCallId === null) { + currentCallId = 0; + } else { + currentCallId++; + } + receivedEagerToolNameReporting = false; + receivedToolArgumentsStreaming = false; + safeCallCallback(this.logger, "onToolCallGenerationStart", extraOpts.onToolCallRequestStart, [currentCallId, { toolCallId: message.toolCallId }]); + break; + } + case "toolCallGenerationNameReceived": { + receivedEagerToolNameReporting = true; + safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.name]); + break; + } + case "toolCallGenerationArgumentFragmentGenerated": { + receivedToolArgumentsStreaming = true; + safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [currentCallId ?? -1, message.content]); + break; + } + case "toolCallGenerationEnd": { + if (!receivedEagerToolNameReporting) { + safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.toolCallRequest.name]); + } + if (!receivedToolArgumentsStreaming) { + safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [ + currentCallId ?? -1, + JSON.stringify(message.toolCallRequest.arguments ?? {}, null, 2) + ]); + } + safeCallCallback(this.logger, "onToolCallGenerationEnd", extraOpts.onToolCallRequestEnd, [ + currentCallId ?? -1, + { toolCallRequest: message.toolCallRequest, rawContent: message.rawContent } + ]); + break; + } + case "toolCallGenerationFailed": { + const toolCallRequestError = new ToolCallRequestError(fromSerializedError(message.error).message, message.rawContent); + safeCallCallback(this.logger, "onToolCallGenerationFailed", extraOpts.onToolCallRequestFailure, [currentCallId ?? -1, toolCallRequestError]); + break; + } + case "success": { + finished2 = true; + onFinished(message.stats, message.modelInfo, message.loadModelConfig, message.predictionConfig); + break; + } + } + }, { stack: getCurrentStack(2) }); + cancelEvent.subscribeOnce(() => { + if (finished2) { + return; + } + channel.send({ type: "cancel" }); + }); + channel.onError.subscribeOnce(onError); + } + predictionConfigInputToKVConfig(config) { + let structuredField = void 0; + if (typeof config.structured?.parse === "function") { + structuredField = { + type: "json", + jsonSchema: zodToJsonSchema(config.structured) + }; + } else { + structuredField = config.structured; + } + const convertedConfig = { + ...config, + structured: structuredField + }; + return llmPredictionConfigToKVConfig(convertedConfig); + } + createZodParser(zodSchema) { + return (content) => { + try { + return zodSchema.parse(JSON.parse(content)); + } catch (e9) { + throw new Error("Failed to parse structured output: " + JSON.stringify(content), { + cause: e9 + }); + } + }; + } + /** + * Use the loaded model to predict text. + * + * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a + * promise (if you only care about the final result) or as an async iterable (if you want to + * stream the results as they are being generated). + * + * Example usage as a promise (Resolves to a {@link PredictionResult}): + * + * ```typescript + * const result = await model.complete("When will The Winds of Winter be released?"); + * console.log(result.content); + * ``` + * + * Or + * + * ```typescript + * model.complete("When will The Winds of Winter be released?") + * .then(result =\> console.log(result.content)) + * .catch(error =\> console.error(error)); + * ``` + * + * Example usage as an async iterable (streaming): + * + * ```typescript + * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { + * process.stdout.write(content); + * } + * ``` + * + * If you wish to stream the result, but also getting the final prediction results (for example, + * you wish to get the prediction stats), you can use the following pattern: + * + * ```typescript + * const prediction = model.complete("When will The Winds of Winter be released?"); + * for await (const { content } of prediction) { + * process.stdout.write(content); + * } + * const result = await prediction.result(); + * console.log(result.stats); + * ``` + * + * @param prompt - The prompt to use for prediction. + * @param opts - Options for the prediction. + */ + complete(prompt, opts = {}) { + const stack = getCurrentStack(1); + [prompt, opts] = this.validator.validateMethodParamsOrThrow("model", "complete", ["prompt", "opts"], [external_exports.string(), llmPredictionOptsSchema], [prompt, opts], stack); + const [config, extraOpts] = splitPredictionOpts(opts); + const [cancelEvent, emitCancelEvent] = BufferedEvent.create(); + if (extraOpts.signal !== void 0) { + if (extraOpts.signal.aborted) { + emitCancelEvent(); + } else { + extraOpts.signal.addEventListener("abort", () => { + emitCancelEvent(); + }, { once: true }); + } + } + const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured); + const { ongoingPrediction, finished: finished2, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data)); + this.internalPredict(this.resolveCompletionContext(prompt), { + layers: [ + ...this.internalKVConfigStack.layers, + { + layerName: "apiOverride", + config: this.predictionConfigInputToKVConfig({ + // If the user did not specify `stopStrings`, we default to an empty array. This is to + // prevent the model from using the value set in the preset. + stopStrings: [], + ...config + }) + }, + { + layerName: "completeModeFormatting", + config: llmSharedPredictionConfigSchematics.buildPartialConfig({ + promptTemplate: { + type: "jinja", + jinjaPromptTemplate: { + template: noFormattingTemplate + }, + stopStrings: [] + } + }) + } + ] + }, cancelEvent, extraOpts, (fragment2) => push(fragment2), (stats, modelInfo, loadModelConfig, predictionConfig) => finished2(stats, modelInfo, loadModelConfig, predictionConfig), (error) => failed(error)); + return ongoingPrediction; + } + resolveCompletionContext(contextInput) { + return { + messages: [ + { + role: "user", + content: [{ type: "text", text: contextInput }] + } + ] + }; + } + /** + * Use the loaded model to generate a response based on the given history. + * + * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a + * promise (if you only care about the final result) or as an async iterable (if you want to + * stream the results as they are being generated). + * + * Example usage as a promise (Resolves to a {@link PredictionResult}): + * + * ```typescript + * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; + * const result = await model.respond(history); + * console.log(result.content); + * ``` + * + * Or + * + * ```typescript + * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; + * model.respond(history) + * .then(result => console.log(result.content)) + * .catch(error => console.error(error)); + * ``` + * + * Example usage as an async iterable (streaming): + * + * ```typescript + * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; + * for await (const { content } of model.respond(history)) { + * process.stdout.write(content); + * } + * ``` + * + * If you wish to stream the result, but also getting the final prediction results (for example, + * you wish to get the prediction stats), you can use the following pattern: + * + * ```typescript + * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; + * const prediction = model.respond(history); + * for await (const { content } of prediction) { + * process.stdout.write(content); + * } + * const result = await prediction; + * console.log(result.stats); + * ``` + * + * @param chat - The LLMChatHistory array to use for generating a response. + * @param opts - Options for the prediction. + */ + respond(chat, opts = {}) { + const stack = getCurrentStack(1); + [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmRespondOptsSchema], [chat, opts], stack); + const [cancelEvent, emitCancelEvent] = BufferedEvent.create(); + const [config, predictionOpts, respondOpts] = splitRespondOpts(opts); + if (predictionOpts.signal !== void 0) { + if (predictionOpts.signal.aborted) { + emitCancelEvent(); + } else { + predictionOpts.signal.addEventListener("abort", () => { + emitCancelEvent(); + }, { once: true }); + } + } + const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured); + const { ongoingPrediction, finished: finished2, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data)); + this.internalPredict(accessMaybeMutableInternals(Chat3.from(chat))._internalGetData(), addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig(config)), cancelEvent, predictionOpts, (fragment2) => push(fragment2), (stats, modelInfo, loadModelConfig, predictionConfig) => finished2(stats, modelInfo, loadModelConfig, predictionConfig), (error) => failed(error)); + ongoingPrediction.then((result) => { + safeCallCallback(this.logger, "onMessage", respondOpts.onMessage, [ + ChatMessage.create("assistant", result.content) + ]); + }, () => { + }); + return ongoingPrediction; + } + /** + * @param chat - The LLMChatHistory array to act from as the base + * @param tool - An array of tools that the model can use during the operation. You can create + * tools by using the `tool` function. + * @param opts - Additional options + * + * Example: + * + * ``` + * import { LMStudioClient, tool } from "@lmstudio/sdk"; + * import { z } from "zod"; + * + * const client = new LMStudioClient(); + * const model = await client.llm.model(); + * + * const additionTool = tool({ + * name: "add", + * description: "Add two numbers", + * parameters: { + * a: z.number(), + * b: z.number(), + * }, + * implementation: ({ a, b }) => a + b, + * }); + * + * await model.act("What is 1234 + 4321?", [additionTool], { + * onMessage: message => console.log(message.toString()), + * }); + * ``` + */ + async act(chat, tools, opts = {}) { + const startTime = performance.now(); + const stack = getCurrentStack(1); + [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmActionOptsSchema], [chat, opts], stack); + const [config, { preset, ...baseOpts }] = splitActOpts(opts); + if (config.structured !== void 0 && config.structured.type !== "none" && tools.length > 0) { + throw makePrettyError("Structured output is currently not supported in .act() when there are tools.", stack); + } + if (config.structured !== void 0 && config.structured.parse !== void 0) { + throw makePrettyError("zod schema is not supported in .act().", stack); + } + if (config.rawTools !== void 0) { + throw makePrettyError("`rawTools` is not supported in act. Use `tools` instead", stack); + } + let rawTools; + if (tools.length === 0) { + rawTools = { type: "none" }; + } else { + rawTools = { + type: "toolArray", + tools: tools.map(toolToLLMTool) + }; + } + const configWithTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({ + ...config, + rawTools + })); + const configWithoutTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({ + ...config, + rawTools: { type: "none" } + })); + return await internalAct( + chat, + tools, + baseOpts, + stack, + this.logger, + startTime, + // Implementation of the prediction function. This performs the prediction by creating a + // predict channel and redirect the messages to the appropriate handlers. + async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError }) => { + const channel = this.port.createChannel("predict", { + modelSpecifier: this.specifier, + history, + predictionConfigStack: allowTools ? configWithTools : configWithoutTools, + fuzzyPresetIdentifier: preset, + ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig + }, (message) => { + const messageType = message.type; + switch (messageType) { + case "fragment": { + handleFragment(message.fragment); + break; + } + case "promptProcessingProgress": { + handlePromptProcessingProgress(message.progress); + break; + } + case "toolCallGenerationStart": { + handleToolCallGenerationStart(message.toolCallId); + break; + } + case "toolCallGenerationNameReceived": { + handleToolCallGenerationNameReceived(message.name); + break; + } + case "toolCallGenerationArgumentFragmentGenerated": { + handleToolCallGenerationArgumentFragmentGenerated(message.content); + break; + } + case "toolCallGenerationEnd": { + handleToolCallGenerationEnd(message.toolCallRequest, message.rawContent); + break; + } + case "toolCallGenerationFailed": { + handleToolCallGenerationFailed(fromSerializedError(message.error), message.rawContent); + break; + } + case "success": { + handlePredictionEnd({ + stats: message.stats, + modelInfo: message.modelInfo, + loadModelConfig: message.loadModelConfig, + predictionConfig: message.predictionConfig + }); + break; + } + } + }, { stack }); + if (signal.aborted) { + channel.send({ type: "cancel" }); + } else { + signal.addEventListener("abort", () => { + channel.send({ type: "cancel" }); + }, { once: true }); + } + channel.onError.subscribeOnce(handleError); + }, + ({ endPacket, content, nonReasoningContent, reasoningContent, predictionsPerformed }) => { + return new PredictionResult(content, reasoningContent, nonReasoningContent, endPacket.stats, endPacket.modelInfo, predictionsPerformed, endPacket.loadModelConfig, endPacket.predictionConfig); + } + ); + } + async getContextLength() { + const stack = getCurrentStack(1); + const loadConfig = await this.getLoadConfig(stack); + return llmSharedLoadConfigSchematics.access(loadConfig, "contextLength"); + } + async applyPromptTemplate(history, opts = {}) { + const stack = getCurrentStack(1); + [history, opts] = this.validator.validateMethodParamsOrThrow("model", "applyPromptTemplate", ["history", "opts"], [chatHistoryLikeSchema, llmApplyPromptTemplateOptsSchema], [history, opts], stack); + return (await this.port.callRpc("applyPromptTemplate", { + specifier: this.specifier, + history: accessMaybeMutableInternals(Chat3.from(history))._internalGetData(), + predictionConfigStack: this.internalKVConfigStack, + opts + }, { + stack + })).formatted; + } + async tokenize(inputString) { + const stack = getCurrentStack(1); + inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", external_exports.string().or(external_exports.array(external_exports.string())), inputString, stack); + if (Array.isArray(inputString)) { + return (await Promise.all(inputString.map((s6) => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s6 }, { stack })))).map((r8) => r8.tokens); + } else { + return (await this.port.callRpc("tokenize", { + specifier: this.specifier, + inputString + }, { stack })).tokens; + } + } + async countTokens(inputString) { + const stack = getCurrentStack(1); + inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", external_exports.string(), inputString, stack); + return (await this.port.callRpc("countTokens", { + specifier: this.specifier, + inputString + }, { stack })).tokenCount; + } + /** + * Starts to eagerly preload a draft model. This is useful when you want a draft model to be ready + * for speculative decoding. + * + * Preloading is done on a best-effort basis and may not always succeed. It is not guaranteed that + * the draft model is actually loaded when this method returns. Thus, this method should only be + * used as an optimization. The actual draft model used only depends on the parameter set when + * performing the prediction. + */ + async unstable_preloadDraftModel(draftModelKey) { + const stack = getCurrentStack(1); + draftModelKey = this.validator.validateMethodParamOrThrow("model", "unstable_preloadDraftModel", "draftModelKey", external_exports.string(), draftModelKey, stack); + await this.port.callRpc("preloadDraftModel", { specifier: this.specifier, draftModelKey }, { stack }); + } + }; + LLM = class extends LLMDynamicHandle { + /** @internal */ + constructor(llmPort, info2, validator2, logger2 = new SimpleLogger(`LLM`)) { + const specifier = { + type: "instanceReference", + instanceReference: info2.instanceReference + }; + super(llmPort, specifier, validator2, logger2); + this.identifier = info2.identifier; + this.path = info2.path; + this.modelKey = info2.modelKey; + this.format = info2.format; + this.displayName = info2.displayName; + this.sizeBytes = info2.sizeBytes; + this.vision = info2.vision; + this.trainedForToolUse = info2.trainedForToolUse; + } + async unload() { + const stack = getCurrentStack(1); + await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack }); + } + async getModelInfo() { + const info2 = await super.getModelInfo(); + if (info2 === void 0) { + const stack = getCurrentStack(1); + throw makePrettyError("This model has already been unloaded", stack); + } + return info2; + } + }; + LLMNamespace = class extends ModelNamespace { + constructor() { + super(...arguments); + this.namespace = "llm"; + this.defaultLoadConfig = {}; + this.loadModelConfigSchema = llmLoadModelConfigSchema; + } + /** @internal */ + loadConfigToKVConfig(config) { + return llmLlamaMoeLoadConfigSchematics.buildPartialConfig({ + "contextLength": config.contextLength, + "llama.evalBatchSize": config.evalBatchSize, + "llama.acceleration.offloadRatio": config.gpu?.ratio, + "numCpuExpertLayersRatio": config.gpu?.numCpuExpertLayersRatio, + "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu), + "llama.flashAttention": config.flashAttention, + "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0), + "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0), + "llama.keepModelInMemory": config.keepModelInMemory, + "seed": numberToCheckboxNumeric(config.seed, -1, 0), + "llama.useFp16ForKVCache": config.useFp16ForKVCache, + "llama.tryMmap": config.tryMmap, + "numExperts": config.numExperts, + "llama.kCacheQuantizationType": cacheQuantizationTypeToCheckbox({ + value: config.llamaKCacheQuantizationType, + falseDefault: "f16" + }), + "llama.vCacheQuantizationType": cacheQuantizationTypeToCheckbox({ + value: config.llamaVCacheQuantizationType, + falseDefault: "f16" + }) + }); + } + /** @internal */ + createDomainSpecificModel(port2, info2, validator2, logger2) { + return new LLM(port2, info2, validator2, logger2); + } + /** @internal */ + createDomainDynamicHandle(port2, specifier, validator2, logger2) { + return new LLMDynamicHandle(port2, specifier, validator2, logger2); + } + }; + GeneratorPredictionResult = class { + constructor(content, reasoningContent, nonReasoningContent, pluginIdentifier) { + this.content = content; + this.reasoningContent = reasoningContent; + this.nonReasoningContent = nonReasoningContent; + this.pluginIdentifier = pluginIdentifier; + } + }; + OngoingGeneratorPrediction = class _OngoingGeneratorPrediction extends StreamablePromise { + async collect(fragments) { + const content = fragments.map(({ content: content2 }) => content2).join(""); + const reasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "reasoning").map(({ content: content2 }) => content2).join(""); + const nonReasoningContent = fragments.filter(({ isStructural }) => !isStructural).filter(({ reasoningType }) => reasoningType === "none").map(({ content: content2 }) => content2).join(""); + return new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier); + } + constructor(pluginIdentifier, onCancel) { + super(); + this.pluginIdentifier = pluginIdentifier; + this.onCancel = onCancel; + } + /** @internal */ + static create(pluginIdentifier, onCancel) { + const ongoingPrediction = new _OngoingGeneratorPrediction(pluginIdentifier, onCancel); + const finished2 = () => ongoingPrediction.finished(); + const failed = (error) => ongoingPrediction.finished(error); + const push = (fragment2) => ongoingPrediction.push(fragment2); + return { ongoingPrediction, finished: finished2, failed, push }; + } + /** + * Get the final prediction results. If you have been streaming the results, awaiting on this + * method will take no extra effort, as the results are already available in the internal buffer. + * + * Example: + * + * ```typescript + * const prediction = generator.complete("When will The Winds of Winter be released?"); + * for await (const { content } of prediction) { + * process.stdout.write(content); + * } + * const result = await prediction.result(); + * console.log(result.stats); + * ``` + * + * Technically, awaiting on this method is the same as awaiting on the instance itself: + * + * ```typescript + * await prediction.result(); + * + * // Is the same as: + * + * await prediction; + * ``` + */ + async result() { + return await this; + } + /** + * Cancels the prediction. + */ + async cancel() { + this.onCancel(); + } + }; + llmGeneratorPredictionOptsSchema = external_exports.object({ + onFirstToken: external_exports.function().optional(), + onPredictionFragment: external_exports.function().optional(), + onMessage: external_exports.function().optional(), + signal: external_exports.instanceof(AbortSignal).optional(), + pluginConfig: kvConfigSchema.optional(), + workingDirectory: external_exports.string().optional() + }); + llmGeneratorActOptsSchema = llmActBaseOptsSchema.extend({ + pluginConfig: kvConfigSchema.optional(), + workingDirectory: external_exports.string().optional() + }); + LLMGeneratorHandle = class { + /** + * Don't use this method directly, use {@link LLMNamespace#createGeneratorHandle} instead. + * + * @internal + */ + constructor(port2, pluginIdentifier, validator2, associatedPredictionProcess, logger2 = new SimpleLogger(`LLMGeneratorHandle`)) { + this.port = port2; + this.pluginIdentifier = pluginIdentifier; + this.validator = validator2; + this.associatedPredictionProcess = associatedPredictionProcess; + this.logger = logger2; + this.identifier = this.pluginIdentifier; + } + getPluginConfigSpecifier(userSuppliedPluginConfig, userSuppliedWorkingDirectory, stack) { + if (this.associatedPredictionProcess === null) { + return { + type: "direct", + config: userSuppliedPluginConfig ?? emptyKVConfig, + workingDirectoryPath: userSuppliedWorkingDirectory ?? void 0 + }; + } + if (userSuppliedPluginConfig !== void 0) { + throw makeTitledPrettyError("Cannot use plugin config with prediction process", text` + You cannot provide a plugin config to the generator handle when it is associated with a + prediction process. The plugin config that was configured for the prediction process will + be used instead. + + If you want to use a different plugin config, you will need to create a separate + GeneratorHandle instead. + `, stack); + } + if (userSuppliedWorkingDirectory !== void 0) { + throw makeTitledPrettyError("Cannot use working directory with prediction process", text` + You cannot provide a working directory to the generator handle when it is associated with + a prediction process. The working directory that was configured for the prediction process + will be used instead. + + If you want to use a different working directory, you will need to create a separate + GeneratorHandle instead. + `, stack); + } + return { + type: "predictionProcess", + pci: this.associatedPredictionProcess.pci, + token: this.associatedPredictionProcess.token + }; + } + /** + * Use the generator to produce a response based on the given history. + */ + respond(chat, opts = {}) { + const stack = getCurrentStack(1); + [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorPredictionOptsSchema], [chat, opts], stack); + const { onFirstToken, onPredictionFragment, onMessage, signal, pluginConfig, workingDirectory } = opts; + let resolved = false; + let firstTokenTriggered = false; + const cancelEvent = new CancelEvent(); + if (signal !== void 0) { + if (signal.aborted) { + cancelEvent.cancel(); + } else { + signal.addEventListener("abort", () => cancelEvent.cancel(), { once: true }); + } + } + const { ongoingPrediction, finished: finished2, failed, push } = OngoingGeneratorPrediction.create(this.pluginIdentifier, () => { + cancelEvent.cancel(); + }); + const channel = this.port.createChannel("generateWithGenerator", { + pluginIdentifier: this.pluginIdentifier, + pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack), + tools: [], + history: accessMaybeMutableInternals(Chat3.from(chat))._internalGetData() + }, (message) => { + const messageType = message.type; + switch (messageType) { + case "fragment": { + if (!firstTokenTriggered) { + firstTokenTriggered = true; + safeCallCallback(this.logger, "onFirstToken", onFirstToken, []); + } + safeCallCallback(this.logger, "onPredictionFragment", onPredictionFragment, [ + message.fragment + ]); + push(message.fragment); + break; + } + case "success": { + resolved = true; + finished2(); + break; + } + } + }, { stack }); + channel.onError.subscribeOnce((error) => { + if (resolved) { + return; + } + resolved = true; + failed(error); + }); + cancelEvent.subscribeOnce(() => { + if (resolved) { + return; + } + channel.send({ type: "cancel" }); + }); + ongoingPrediction.then((result) => { + safeCallCallback(this.logger, "onMessage", onMessage, [ + ChatMessage.create("assistant", result.content) + ]); + }, () => { + }); + return ongoingPrediction; + } + async act(chat, tools, opts = {}) { + const startTime = performance.now(); + const stack = getCurrentStack(1); + [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorActOptsSchema], [chat, opts], stack); + const { pluginConfig, workingDirectory, ...baseOpts } = opts; + const toolDefinitions = tools.map(toolToLLMTool); + return await internalAct( + chat, + tools, + baseOpts, + stack, + this.logger, + startTime, + // Implementation of the prediction function. This performs the prediction by creating a + // predict channel and redirect the messages to the appropriate handlers. + async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError }) => { + const channel = this.port.createChannel("generateWithGenerator", { + pluginIdentifier: this.pluginIdentifier, + pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack), + tools: allowTools ? toolDefinitions : [], + history + }, (message) => { + const messageType = message.type; + switch (messageType) { + case "fragment": { + handleFragment(message.fragment); + break; + } + case "promptProcessingProgress": { + handlePromptProcessingProgress(message.progress); + break; + } + case "toolCallGenerationStart": { + handleToolCallGenerationStart(message.toolCallId); + break; + } + case "toolCallGenerationNameReceived": { + handleToolCallGenerationNameReceived(message.name); + break; + } + case "toolCallGenerationArgumentFragmentGenerated": { + handleToolCallGenerationArgumentFragmentGenerated(message.content); + break; + } + case "toolCallGenerationEnd": { + handleToolCallGenerationEnd(message.toolCallRequest, void 0); + break; + } + case "toolCallGenerationFailed": { + handleToolCallGenerationFailed( + new Error("Tool call generation failed"), + // Placeholder error for now + void 0 + ); + break; + } + case "success": { + handlePredictionEnd(void 0); + break; + } + } + }, { stack }); + if (signal.aborted) { + channel.send({ type: "cancel" }); + } else { + signal.addEventListener("abort", () => { + channel.send({ type: "cancel" }); + }, { once: true }); + } + channel.onError.subscribeOnce(handleError); + }, + ({ content, nonReasoningContent, reasoningContent }) => new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier) + ); + } + }; + generatorSchema = external_exports.function(); + BaseController = class { + constructor(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath) { + this.client = client; + this.abortSignal = abortSignal; + this.pluginConfig = pluginConfig; + this.globalPluginConfig = globalPluginConfig; + this.workingDirectoryPath = workingDirectoryPath; + } + /** + * Gets the working directory for the current prediction. If your plugin produces files, you + * should aim to put them in this directory. + */ + getWorkingDirectory() { + if (this.workingDirectoryPath === null) { + throw new Error("This prediction process is not attached to a working directory."); + } + return this.workingDirectoryPath; + } + /** + * Get the per-chat config for the plugin. Takes in the configSchematics. You can get the + * values of fields like so: + * + * ```ts + * const config = ctl.getPluginConfig(configSchematics); + * const value = config.get("fieldKey"); + * ``` + * + * @remarks + * + * If you need to name the type of the returned value, use: + * + * `InferParsedConfig`. + * + * Example: + * + * ```ts + * function myFunction(config: InferParsedConfig) { + * // ... + * } + * + * myFunction(ctl.getPluginConfig(configSchematics)); + * ``` + */ + getPluginConfig(configSchematics) { + return configSchematics.parse(this.pluginConfig); + } + /** + * Get the application-wide config for the plugin. Takes in the globalConfigSchematics. You can + * get the values of fields like so: + * + * ```ts + * const config = ctl.getGlobalPluginConfig(globalConfigSchematics); + * const value = config.get("fieldKey"); + * ``` + * + * @remarks + * + * If you need to name the type of the returned value, use: + * + * `InferParsedConfig`. + * + * Example: + * + * ```ts + * function myFunction(config: InferParsedConfig) { + * // ... + * } + * + * myFunction(ctl.getGlobalPluginConfig(globalConfigSchematics)); + * ``` + */ + getGlobalPluginConfig(globalConfigSchematics2) { + return globalConfigSchematics2.parse(this.globalPluginConfig); + } + /** + * Provides a callback that will be called when the prediction is aborted. If the prediction is + * already aborted, the callback will be called immediately. + * + * You can also use {@link BaseController.abortSignal} if you are using an async function that + * supports abort signals. + * + * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about + * abort signals. + */ + onAborted(callback2) { + if (this.abortSignal.aborted) { + callback2(); + } else { + this.abortSignal.addEventListener("abort", callback2, { once: true }); + } + } + }; + GeneratorController = class extends BaseController { + /** + * @internal Do not construct this class yourself. + */ + constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, abortSignal, toolDefinitions, connector, validator2) { + super(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath); + this.toolDefinitions = toolDefinitions; + this.connector = connector; + this.validator = validator2; + } + /** + * Get the definitions of the tools available for this generation. + */ + getToolDefinitions() { + return this.toolDefinitions; + } + /** + * Use this function to report a text fragment has been generated. + * + * @param content - The content that has been generated. + * @param opts - Additional info about the generated content, such as how many tokens it contains. + * See {@link LLMPredictionFragmentInputOpts} for more info. All the fields are optional. + */ + fragmentGenerated(content, opts = {}) { + const stack = getCurrentStack(1); + [content, opts] = this.validator.validateMethodParamsOrThrow("GeneratorController", "fragmentGenerated", ["content", "opts"], [external_exports.string(), llmPredictionFragmentInputOptsSchema], [content, opts], stack); + this.connector.fragmentGenerated(content, opts); + } + /** + * Use this function to report that a tool call generation has started. Each + * `toolCallGenerationStarted` must be paired up with a `toolCallGenerationEnded` call for + * successfully generated tool calls, or a `toolCallGenerationFailed` call for + * failed tool calls. + */ + toolCallGenerationStarted({ toolCallId } = {}) { + this.connector.toolCallGenerationStarted(toolCallId); + } + /** + * Use this function to report that the name of the tool call has been generated. This function + * should only be called once for each `toolCallGenerationStarted`. + * + * @param toolName - The name of the tool that has been generated. + */ + toolCallGenerationNameReceived(toolName) { + const stack = getCurrentStack(1); + toolName = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationNameReceived", "toolName", external_exports.string(), toolName, stack); + this.connector.toolCallGenerationNameReceived(toolName); + } + /** + * Use this function to report that a new argument fragment has been generated for the tool call. + * This function can be called multiple times for each `toolCallGenerationStarted`. + * + * @param content - The new fragment that has been generated for the tool call. + */ + toolCallGenerationArgumentFragmentGenerated(content) { + const stack = getCurrentStack(1); + content = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationArgumentFragmentGenerated", "content", external_exports.string(), content, stack); + this.connector.toolCallGenerationArgumentFragmentGenerated(content); + } + /** + * Use this function to report that a tool call generation has successfully ended. This function + * should only be called after a `toolCallGenerationStarted` call. + */ + toolCallGenerationEnded(toolCallRequest) { + const stack = getCurrentStack(1); + toolCallRequest = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationEnded", "toolCallRequest", toolCallRequestSchema, toolCallRequest, stack); + this.connector.toolCallGenerationEnded(toolCallRequest); + } + /** + * Use this function to report that a tool call generation has failed. This function should only + * be called after a `toolCallGenerationStarted` call. + * + * @param error - The error that occurred during the tool call generation. + */ + toolCallGenerationFailed(error) { + const stack = getCurrentStack(1); + error = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationFailed", "error", external_exports.instanceof(Error), error, stack); + this.connector.toolCallGenerationFailed(error); + } + }; + __addDisposableResource$1 = globalThis && globalThis.__addDisposableResource || function(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner2; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner2 = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner2) dispose = function() { + try { + inner2.call(this); + } catch (e9) { + return Promise.reject(e9); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + __disposeResources$1 = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) { + return function(env) { + function fail(e9) { + env.error = env.hasError ? new SuppressedError2(e9, env.error, "An error was suppressed during disposal.") : e9; + env.hasError = true; + } + var r8, s6 = 0; + function next() { + while (r8 = env.stack.pop()) { + try { + if (!r8.async && s6 === 1) return s6 = 0, env.stack.push(r8), Promise.resolve().then(next); + if (r8.dispose) { + var result = r8.dispose.call(r8.value); + if (r8.async) return s6 |= 2, Promise.resolve(result).then(next, function(e9) { + fail(e9); + return next(); + }); + } else s6 |= 1; + } catch (e9) { + fail(e9); + } + } + if (s6 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e9 = new Error(message); + return e9.name = "SuppressedError", e9.error = error, e9.suppressed = suppressed, e9; + }); + ProcessingConnector = class { + constructor(pluginsPort, abortSignal, processingContextIdentifier, token, logger2) { + this.pluginsPort = pluginsPort; + this.abortSignal = abortSignal; + this.processingContextIdentifier = processingContextIdentifier; + this.token = token; + this.logger = logger2; + } + handleUpdate(update) { + this.pluginsPort.callRpc("processingHandleUpdate", { + pci: this.processingContextIdentifier, + token: this.token, + update + }).catch((error) => { + this.logger.error("Failed to send update", error); + }); + } + async handleRequest(request) { + const { response } = await this.pluginsPort.callRpc("processingHandleRequest", { + pci: this.processingContextIdentifier, + token: this.token, + request + }); + return response; + } + async pullHistory(includeCurrent) { + const chatHistoryData = await this.pluginsPort.callRpc("processingPullHistory", { + pci: this.processingContextIdentifier, + token: this.token, + includeCurrent + }); + return Chat3.createRaw( + chatHistoryData, + /* mutable */ + false + ).asMutableCopy(); + } + async getOrLoadTokenSource() { + const result = await this.pluginsPort.callRpc("processingGetOrLoadTokenSource", { + pci: this.processingContextIdentifier, + token: this.token + }); + return result.tokenSourceIdentifier; + } + async hasStatus() { + return await this.pluginsPort.callRpc("processingHasStatus", { + pci: this.processingContextIdentifier, + token: this.token + }); + } + async needsNaming() { + return await this.pluginsPort.callRpc("processingNeedsNaming", { + pci: this.processingContextIdentifier, + token: this.token + }); + } + async suggestName(name) { + await this.pluginsPort.callRpc("processingSuggestName", { + pci: this.processingContextIdentifier, + token: this.token, + name + }); + } + }; + ProcessingController = class extends BaseController { + /** @internal */ + constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, enabledPluginInfos, connector, config, shouldIncludeCurrentInHistory) { + super(client, connector.abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath); + this.enabledPluginInfos = enabledPluginInfos; + this.connector = connector; + this.config = config; + this.shouldIncludeCurrentInHistory = shouldIncludeCurrentInHistory; + this.processingControllerHandle = { + abortSignal: connector.abortSignal, + sendUpdate: (update) => { + connector.handleUpdate(update); + }, + sendRequest: async (request) => { + const type = request.type; + const response = await connector.handleRequest(request); + if (response.type !== type) { + throw new Error(`Expected response type ${type}, but got ${response.type}. This is a bug.`); + } + return response; + } + }; + } + sendUpdate(update) { + this.processingControllerHandle.sendUpdate(update); + } + /** + * Gets a mutable copy of the current history. The returned history is a copy, so mutating it will + * not affect the actual history. It is mutable for convenience reasons. + * + * - If you are a promptPreprocessor, this will not include the user message you are currently + * preprocessing. + * - If you are a prediction loop handler, this will include the user message, and can be fed into + * the {@link LLMDynamicHandle#respond} method directly. + */ + async pullHistory() { + return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory); + } + createStatus(initialState) { + const id = createId(); + this.sendUpdate({ + type: "status.create", + id, + state: initialState + }); + const statusController = new PredictionProcessStatusController(this.processingControllerHandle, initialState, id); + return statusController; + } + addCitations(arg) { + if (Array.isArray(arg)) { + for (const entry of arg) { + this.createCitationBlock(entry.content, { + fileName: entry.source.name, + fileIdentifier: entry.source.identifier + }); + } + } else { + for (const entry of arg.entries) { + this.createCitationBlock(entry.content, { + fileName: entry.source.name, + fileIdentifier: entry.source.identifier + }); + } + } + } + createCitationBlock(citedText, source) { + const id = createId(); + this.sendUpdate({ + type: "citationBlock.create", + id, + citedText, + ...source + }); + const citationBlockController = new PredictionProcessCitationBlockController(this.processingControllerHandle, id); + return citationBlockController; + } + /** + * @internal + */ + createDebugInfoBlock(debugInfo) { + const id = createId(); + this.sendUpdate({ + type: "debugInfoBlock.create", + id, + debugInfo + }); + const debugInfoBlockController = new PredictionProcessDebugInfoBlockController(this.processingControllerHandle, id); + return debugInfoBlockController; + } + createContentBlock({ roleOverride, includeInContext = true, style, prefix, suffix } = {}) { + const id = createId(); + this.sendUpdate({ + type: "contentBlock.create", + id, + roleOverride, + includeInContext, + style, + prefix, + suffix + }); + const contentBlockController = new PredictionProcessContentBlockController(this.processingControllerHandle, id, roleOverride ?? "assistant"); + return contentBlockController; + } + debug(...messages) { + this.createDebugInfoBlock(concatenateDebugMessages(...messages)); + } + /** + * Gets the token source associated with this prediction process (i.e. what the user has selected + * on the top navigation bar). + * + * The token source can either be a model or a generator plugin. In both cases, the returned + * object will contain a ".act" and a ".respond" method, which can be used to generate text. + * + * The token source is already pre-configured to use user's prediction config - you don't need to + * pass through any additional configuration. + */ + async tokenSource() { + const tokenSourceIdentifier = await this.connector.getOrLoadTokenSource(); + const tokenSourceIdentifierType = tokenSourceIdentifier.type; + switch (tokenSourceIdentifierType) { + case "model": { + const model = await this.client.llm.model(tokenSourceIdentifier.identifier); + model.internalIgnoreServerSessionConfig = true; + model.internalKVConfigStack = { + layers: [ + { + layerName: "conversationSpecific", + config: this.config + } + ] + }; + return model; + } + case "generator": { + const generator = this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(tokenSourceIdentifier.pluginIdentifier, this.connector.processingContextIdentifier, this.connector.token); + return generator; + } + } + } + /** + * Sets the sender name for this message. The sender name shown above the message in the chat. + */ + async setSenderName(name) { + this.sendUpdate({ + type: "setSenderName", + name + }); + } + /** + * Throws an error if the prediction process has been aborted. Sprinkle this throughout your code + * to ensure that the prediction process is aborted as soon as possible. + */ + guardAbort() { + this.abortSignal.throwIfAborted(); + } + /** + * Whether this prediction process has had any status. + */ + async hasStatus() { + return await this.connector.hasStatus(); + } + /** + * Returns whether this conversation needs a name. + */ + async needsNaming() { + return await this.connector.needsNaming(); + } + /** + * Suggests a name for this conversation. + */ + async suggestName(name) { + await this.connector.suggestName(name); + } + async requestConfirmToolCall({ callId, pluginIdentifier, name, parameters }) { + const { result } = await raceWithAbortSignal(this.processingControllerHandle.sendRequest({ + type: "confirmToolCall", + callId, + pluginIdentifier, + name, + parameters + }), this.abortSignal); + const resultType = result.type; + switch (resultType) { + case "allow": { + return { + type: "allow", + toolArgsOverride: result.toolArgsOverride + }; + } + case "deny": { + return { + type: "deny", + denyReason: result.denyReason + }; + } + default: { + const exhaustiveCheck = resultType; + throw new Error(`Unexpected result type ${exhaustiveCheck}. This is a bug. Please report it.`); + } + } + } + createToolStatus(callId, initialStatus) { + const id = createId(); + this.sendUpdate({ + type: "toolStatus.create", + id, + callId, + state: { + status: initialStatus, + customStatus: "", + customWarnings: [] + } + }); + const toolStatusController = new PredictionProcessToolStatusController(this.processingControllerHandle, id, initialStatus); + return toolStatusController; + } + /** + * Starts a tool use session with tools available in the prediction process. Note, this method + * should be used with "Explicit Resource Management". That is, you should use it like so: + * + * ```typescript + * using toolUseSession = await ctl.startToolUseSession(); + * // ^ Notice the `using` keyword here. + * ``` + * + * If you do not `using`, you should call `toolUseSession[Symbol.dispose]()` after you are done. + * + * If you don't, lmstudio-js will close the session upon the end of the prediction step + * automatically. However, it is not recommended. + * + * @public + * @deprecated WIP + */ + async startToolUseSession() { + const identifiersOfPluginsWithTools = this.enabledPluginInfos.filter(({ hasToolsProvider }) => hasToolsProvider).map(({ identifier }) => identifier); + return await this.client.plugins.startToolUseSessionUsingPredictionProcess( + // We start a tool use session with all the plugins that have tools available + identifiersOfPluginsWithTools, + this.connector.processingContextIdentifier, + this.connector.token + ); + } + }; + PredictionProcessStatusController = class _PredictionProcessStatusController { + /** @internal */ + constructor(handle, initialState, id, indentation = 0) { + this.handle = handle; + this.id = id; + this.indentation = indentation; + this.lastSubStatus = this; + this.lastState = initialState; + } + setText(text3) { + this.lastState.text = text3; + this.handle.sendUpdate({ + type: "status.update", + id: this.id, + state: this.lastState + }); + } + setState(state) { + this.lastState = state; + this.handle.sendUpdate({ + type: "status.update", + id: this.id, + state + }); + } + remove() { + this.handle.sendUpdate({ + type: "status.remove", + id: this.id + }); + } + getNestedLastSubStatusBlockId() { + let current2 = this.lastSubStatus; + while (current2 !== current2.lastSubStatus) { + current2 = current2.lastSubStatus; + } + return current2.id; + } + addSubStatus(initialState) { + const id = createId(); + this.handle.sendUpdate({ + type: "status.create", + id, + state: initialState, + location: { + type: "afterId", + id: this.getNestedLastSubStatusBlockId() + }, + indentation: this.indentation + 1 + }); + const controller = new _PredictionProcessStatusController(this.handle, initialState, id, this.indentation + 1); + this.lastSubStatus = controller; + return controller; + } + }; + PredictionProcessCitationBlockController = class { + /** @internal */ + constructor(handle, id) { + this.handle = handle; + this.id = id; + } + }; + PredictionProcessDebugInfoBlockController = class { + /** @internal */ + constructor(handle, id) { + this.handle = handle; + this.id = id; + } + }; + PredictionProcessContentBlockController = class { + /** @internal */ + constructor(handle, id, role) { + this.handle = handle; + this.id = id; + this.role = role; + } + appendText(text3, { tokensCount, fromDraftModel, isStructural } = {}) { + if (this.role === "tool") { + throw new Error("Text cannot be appended to tool blocks."); + } + this.handle.sendUpdate({ + type: "contentBlock.appendText", + id: this.id, + text: text3, + tokensCount, + fromDraftModel, + isStructural + }); + } + appendToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier }) { + if (this.role !== "assistant") { + throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`); + } + this.handle.sendUpdate({ + type: "contentBlock.appendToolRequest", + id: this.id, + callId, + toolCallRequestId, + name, + parameters, + pluginIdentifier + }); + } + replaceToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier }) { + if (this.role !== "assistant") { + throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`); + } + this.handle.sendUpdate({ + type: "contentBlock.replaceToolRequest", + id: this.id, + callId, + toolCallRequestId, + name, + parameters, + pluginIdentifier + }); + } + appendToolResult({ callId, toolCallRequestId, content }) { + if (this.role !== "tool") { + throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`); + } + this.handle.sendUpdate({ + type: "contentBlock.appendToolResult", + id: this.id, + callId, + toolCallRequestId, + content + }); + } + replaceText(text3) { + if (this.role === "tool") { + throw new Error("Text cannot be set in tool blocks."); + } + this.handle.sendUpdate({ + type: "contentBlock.replaceText", + id: this.id, + text: text3 + }); + } + setStyle(style) { + this.handle.sendUpdate({ + type: "contentBlock.setStyle", + id: this.id, + style + }); + } + setPrefix(prefix) { + this.handle.sendUpdate({ + type: "contentBlock.setPrefix", + id: this.id, + prefix + }); + } + setSuffix(suffix) { + this.handle.sendUpdate({ + type: "contentBlock.setSuffix", + id: this.id, + suffix + }); + } + attachGenInfo(genInfo) { + this.handle.sendUpdate({ + type: "contentBlock.attachGenInfo", + id: this.id, + genInfo + }); + } + async pipeFrom(prediction) { + const env_1 = { stack: [], error: void 0, hasError: false }; + try { + const cleaner = __addDisposableResource$1(env_1, new Cleaner(), false); + const abortListener = () => { + prediction.cancel(); + }; + this.handle.abortSignal.addEventListener("abort", abortListener); + cleaner.register(() => { + this.handle.abortSignal.removeEventListener("abort", abortListener); + }); + for await (const { content } of prediction) { + this.appendText(content); + } + const result = await prediction; + this.attachGenInfo({ + indexedModelIdentifier: result.modelInfo.path, + identifier: result.modelInfo.identifier, + loadModelConfig: result.loadConfig, + predictionConfig: result.predictionConfig, + stats: result.stats + }); + this.handle.abortSignal.throwIfAborted(); + return result; + } catch (e_1) { + env_1.error = e_1; + env_1.hasError = true; + } finally { + __disposeResources$1(env_1); + } + } + }; + PredictionProcessToolStatusController = class { + /** @internal */ + constructor(handle, id, initialStatus) { + this.handle = handle; + this.id = id; + this.customStatus = ""; + this.customWarnings = []; + this.status = initialStatus; + } + updateState() { + this.handle.sendUpdate({ + type: "toolStatus.update", + id: this.id, + state: { + status: this.status, + customStatus: this.customStatus, + customWarnings: this.customWarnings + } + }); + } + setCustomStatusText(status) { + this.customStatus = status; + this.updateState(); + } + addWarning(warning) { + this.customWarnings.push(warning); + this.updateState(); + } + setStatus(status) { + this.status = status; + this.updateState(); + } + appendArgumentFragment(content) { + this.handle.sendUpdate({ + type: "toolStatus.argumentFragment", + id: this.id, + content + }); + } + }; + ToolsProviderController = class extends BaseController { + /** + * @internal Do not construct this class yourself. + */ + constructor(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath) { + super(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath); + } + }; + GeneratorConnectorImpl = class { + constructor(channel, taskId) { + this.channel = channel; + this.taskId = taskId; + } + fragmentGenerated(content, opts) { + this.channel.send({ + type: "fragmentGenerated", + taskId: this.taskId, + content, + opts + }); + } + toolCallGenerationStarted(toolCallId) { + this.channel.send({ + type: "toolCallGenerationStarted", + taskId: this.taskId, + toolCallId + }); + } + toolCallGenerationNameReceived(toolName) { + this.channel.send({ + type: "toolCallGenerationNameReceived", + taskId: this.taskId, + toolName + }); + } + toolCallGenerationArgumentFragmentGenerated(content) { + this.channel.send({ + type: "toolCallGenerationArgumentFragmentGenerated", + taskId: this.taskId, + content + }); + } + toolCallGenerationEnded(toolCallRequest) { + this.channel.send({ + type: "toolCallGenerationEnded", + taskId: this.taskId, + toolCallRequest + }); + } + toolCallGenerationFailed(error) { + this.channel.send({ + type: "toolCallGenerationFailed", + taskId: this.taskId, + error: serializeError(error) + }); + } + }; + PluginSelfRegistrationHost = class { + constructor(port2, client, rootLogger, validator2) { + this.port = port2; + this.client = client; + this.rootLogger = rootLogger; + this.validator = validator2; + } + /** + * Sets the promptPreprocessor to be used by the plugin represented by this client. + * + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + setPromptPreprocessor(promptPreprocessor) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "registerPromptPreprocessor", "promptPreprocessor", external_exports.function(), promptPreprocessor, stack); + const logger2 = new SimpleLogger(`PromptPreprocessor`, this.rootLogger); + logger2.info("Register with LM Studio"); + const tasks = /* @__PURE__ */ new Map(); + const channel = this.port.createChannel("setPromptPreprocessor", void 0, (message) => { + switch (message.type) { + case "preprocess": { + const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2); + taskLogger.info(`New preprocess request received.`); + const abortController = new AbortController(); + const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger); + const input = ChatMessage.createRaw( + message.input, + /* mutable */ + false + ); + const controller = new ProcessingController( + this.client, + message.pluginConfig, + message.globalPluginConfig, + message.workingDirectoryPath, + message.enabledPluginInfos, + connector, + message.config, + /* shouldIncludeInputInHistory */ + false + ); + tasks.set(message.taskId, { + cancel: () => { + abortController.abort(); + }, + taskLogger + }); + promptPreprocessor(controller, input.asMutableCopy()).then((result) => { + taskLogger.info(`Preprocess request completed.`); + const parsedReturned = external_exports.union([external_exports.string(), external_exports.custom((v4) => v4 instanceof ChatMessage)]).safeParse(result); + if (!parsedReturned.success) { + throw new Error("PromptPreprocessor returned an invalid value:" + Validator.prettyPrintZod("result", parsedReturned.error)); + } + const returned = parsedReturned.data; + let processed; + if (typeof returned === "string") { + const messageCopy = input.asMutableCopy(); + messageCopy.replaceText(returned); + processed = messageCopy.getRaw(); + } else { + processed = returned.getRaw(); + } + channel.send({ + type: "complete", + taskId: message.taskId, + processed + }); + }).catch((error) => { + if (error.name === "AbortError") { + logger2.info(`Request successfully aborted.`); + channel.send({ + type: "aborted", + taskId: message.taskId + }); + return; + } + logger2.warn(`Preprocessing failed.`, error); + channel.send({ + type: "error", + taskId: message.taskId, + error: serializeError(error) + }); + }).finally(() => { + tasks.delete(message.taskId); + }); + break; + } + case "abort": { + const task = tasks.get(message.taskId); + if (task !== void 0) { + task.taskLogger.info(`Received abort request.`); + task.cancel(); + tasks.delete(message.taskId); + } + break; + } + } + }, { stack }); + } + /** + * Sets the prediction loop handler to be used by the plugin represented by this client. + * + * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in + * development. Stay tuned for updates. + */ + setPredictionLoopHandler(predictionLoopHandler) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "setPredictionLoopHandler", "predictionLoopHandler", external_exports.function(), predictionLoopHandler, stack); + const logger2 = new SimpleLogger(` PredictionLoopHandler`, this.rootLogger); + logger2.info("Register with LM Studio"); + const tasks = /* @__PURE__ */ new Map(); + const channel = this.port.createChannel("setPredictionLoopHandler", void 0, (message) => { + switch (message.type) { + case "handlePredictionLoop": { + const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2); + taskLogger.info(`New prediction loop handling request received.`); + const abortController = new AbortController(); + const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger); + const controller = new ProcessingController( + this.client, + message.pluginConfig, + message.globalPluginConfig, + message.workingDirectoryPath, + message.enabledPluginInfos, + connector, + message.config, + /* shouldIncludeInputInHistory */ + true + ); + tasks.set(message.taskId, { + cancel: () => { + abortController.abort(); + }, + taskLogger + }); + predictionLoopHandler(controller).then(() => { + channel.send({ + type: "complete", + taskId: message.taskId + }); + }).catch((error) => { + if (error.name === "AbortError") { + logger2.info(`Request successfully aborted.`); + channel.send({ + type: "aborted", + taskId: message.taskId + }); + return; + } + logger2.warn(`Generation failed.`, error); + channel.send({ + type: "error", + taskId: message.taskId, + error: serializeError(error) + }); + }).finally(() => { + tasks.delete(message.taskId); + }); + break; + } + case "abort": { + const task = tasks.get(message.taskId); + if (task !== void 0) { + task.taskLogger.info(`Received abort request.`); + task.cancel(); + tasks.delete(message.taskId); + } + break; + } + } + }, { stack }); + } + /** + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + async setConfigSchematics(configSchematics) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "setConfigSchematics", "configSchematics", external_exports.instanceof(KVConfigSchematics), configSchematics, stack); + await this.port.callRpc("setConfigSchematics", { + schematics: configSchematics.serialize() + }, { stack }); + } + /** + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + async setGlobalConfigSchematics(globalConfigSchematics2) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "setGlobalConfigSchematics", "globalConfigSchematics", external_exports.instanceof(KVConfigSchematics), globalConfigSchematics2, stack); + await this.port.callRpc("setGlobalConfigSchematics", { + schematics: globalConfigSchematics2.serialize() + }, { stack }); + } + /** + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + setToolsProvider(toolsProvider) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "setToolsProvider", "toolsProvider", external_exports.function(), toolsProvider, stack); + const logger2 = new SimpleLogger(`Tools Prvdr.`, this.rootLogger); + logger2.info("Register with LM Studio"); + const openSessions = /* @__PURE__ */ new Map(); + const channel = this.port.createChannel("setToolsProvider", void 0, (message) => { + const messageType = message.type; + switch (messageType) { + case "initSession": { + const sessionId = message.sessionId; + const sessionAbortController = new AbortController(); + const openSession = { + tools: null, + ongoingToolCalls: /* @__PURE__ */ new Map(), + discarded: false, + abortController: sessionAbortController + }; + openSessions.set(sessionId, openSession); + const controller = new ToolsProviderController(this.client, sessionAbortController.signal, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath); + toolsProvider(controller).then((tools) => { + const llmTools = tools.map(toolToLLMTool); + if (openSession.discarded) { + return; + } + channel.send({ + type: "sessionInitialized", + sessionId, + toolDefinitions: llmTools + }); + openSession.tools = new Map(tools.map((tool) => [tool.name, tool])); + }, (error) => { + if (openSession.discarded) { + return; + } + channel.send({ + type: "sessionInitializationFailed", + sessionId, + error: serializeError(error) + }); + openSession.discarded = true; + openSessions.delete(sessionId); + }); + break; + } + case "discardSession": { + const sessionId = message.sessionId; + const openSession = openSessions.get(sessionId); + if (openSession === void 0) { + return; + } + openSession.discarded = true; + openSession.abortController.abort(); + openSessions.delete(sessionId); + break; + } + case "callTool": { + const sessionId = message.sessionId; + const openSession = openSessions.get(sessionId); + if (openSession === void 0) { + return; + } + if (openSession.tools === null) { + throw new Error("Tool called before initialization completed. This is unexpected."); + } + const tool = openSession.tools.get(message.toolName); + if (tool === void 0) { + throw new Error(`Tool ${message.toolName} not found.`); + } + const callId = message.callId; + const ongoingToolCall = { + settled: false, + abortController: new AbortController() + }; + openSession.ongoingToolCalls.set(callId, ongoingToolCall); + new SimpleLogger(`Tool (${message.toolName})`, this.rootLogger); + const toolCallContext = { + status(text3) { + channel.send({ + type: "toolCallStatus", + sessionId, + callId, + statusText: text3 + }); + }, + warn(text3) { + channel.send({ + type: "toolCallWarn", + sessionId, + callId, + warnText: text3 + }); + }, + signal: ongoingToolCall.abortController.signal, + // Call ID is used to match up life cycle events of the same tool call. In this case, + // each call does not have different parts, thus call ID is useless. We can just use 0. + // If the user wants a "unique" ID, they can just have variable that goes up by one + // each time the function is called. + callId: 0 + }; + (async () => { + return await tool.implementation(message.parameters, toolCallContext); + })().then((result) => { + if (openSession.discarded) { + return; + } + if (ongoingToolCall.settled) { + return; + } + if (ongoingToolCall.abortController.signal.aborted) { + return; + } + if (result === void 0) { + result = "undefined"; + channel.send({ + type: "toolCallWarn", + sessionId, + callId, + warnText: text` + Tool call returned undefined. This is not expected as the model always expects + a result. If you don't want to return anything, you can just return a string + reporting that the tool call was successful. For example: "operation + successful." In this case, we will give the model string "${result}". + ` + }); + } + try { + JSON.stringify(result); + } catch (error) { + result = text` + Error: Tool call completed but returned a value that cannot be serialized to JSON + `; + channel.send({ + type: "toolCallWarn", + sessionId, + callId, + warnText: text` + Tool call succeeded, but returned a value that is not JSON serializable. In + order to provide the result to the model, return values of tools must be JSON + serializable. In this case, we will give the model string "${result}". + ` + }); + } + channel.send({ + type: "toolCallComplete", + sessionId, + callId, + result + }); + ongoingToolCall.settled = true; + openSession.ongoingToolCalls.delete(callId); + }, (error) => { + if (openSession.discarded) { + return; + } + if (ongoingToolCall.settled) { + return; + } + if (ongoingToolCall.abortController.signal.aborted) { + return; + } + channel.send({ + type: "toolCallError", + sessionId, + callId, + error: serializeError(error) + }); + ongoingToolCall.settled = true; + openSession.ongoingToolCalls.delete(callId); + }); + break; + } + case "abortToolCall": { + const sessionId = message.sessionId; + const callId = message.callId; + const openSession = openSessions.get(sessionId); + if (openSession === void 0) { + return; + } + const ongoingToolCall = openSession.ongoingToolCalls.get(callId); + if (ongoingToolCall === void 0) { + return; + } + ongoingToolCall.settled = true; + ongoingToolCall.abortController.abort(); + openSession.ongoingToolCalls.delete(callId); + break; + } + default: { + const exhaustiveCheck = messageType; + throw new Error(`Unexpected message type: ${exhaustiveCheck}`); + } + } + }); + } + /** + * Sets the generator to be used by the plugin represented by this client. + * + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + setGenerator(generator) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "setGenerator", "generator", generatorSchema, generator, stack); + const logger2 = new SimpleLogger(`Generator`, this.rootLogger); + logger2.info("Register with LM Studio"); + const tasks = /* @__PURE__ */ new Map(); + const channel = this.port.createChannel("setGenerator", void 0, (message) => { + const messageType = message.type; + switch (messageType) { + case "generate": { + const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger2); + taskLogger.info(`New generate request received.`); + const abortController = new AbortController(); + const connector = new GeneratorConnectorImpl(channel, message.taskId); + const controller = new GeneratorController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, abortController.signal, message.toolDefinitions, connector, this.validator); + tasks.set(message.taskId, { + cancel: () => { + abortController.abort(); + }, + taskLogger + }); + const history = Chat3.createRaw(message.input, false); + generator(controller, history).then((result) => { + if (result !== void 0) { + taskLogger.warnText` + The generator has returned a value. This it not expected. You should report + generated content using method on the controller. The returned value will be + ignored. + `; + } + channel.send({ + type: "complete", + taskId: message.taskId + }); + }, (error) => { + if (error.name === "AbortError") { + taskLogger.info(`Request successfully aborted.`); + channel.send({ + type: "aborted", + taskId: message.taskId + }); + } else { + channel.send({ + type: "error", + taskId: message.taskId, + error: serializeError(error) + }); + taskLogger.warn(`Generation failed.`, error); + } + }).finally(() => { + tasks.delete(message.taskId); + }); + break; + } + case "abort": { + const task = tasks.get(message.taskId); + if (task !== void 0) { + task.taskLogger.info(`Received abort request.`); + task.cancel(); + tasks.delete(message.taskId); + } + break; + } + default: { + const exhaustiveCheck = messageType; + throw new Error(`Unexpected message type: ${exhaustiveCheck}`); + } + } + }); + } + /** + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + async initCompleted() { + const stack = getCurrentStack(1); + await this.port.callRpc("pluginInitCompleted", void 0, { stack }); + } + }; + __addDisposableResource = globalThis && globalThis.__addDisposableResource || function(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner2; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner2 = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner2) dispose = function() { + try { + inner2.call(this); + } catch (e9) { + return Promise.reject(e9); + } + }; + env.stack.push({ value, dispose, async }); + } else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + __disposeResources = globalThis && globalThis.__disposeResources || /* @__PURE__ */ (function(SuppressedError2) { + return function(env) { + function fail(e9) { + env.error = env.hasError ? new SuppressedError2(e9, env.error, "An error was suppressed during disposal.") : e9; + env.hasError = true; + } + var r8, s6 = 0; + function next() { + while (r8 = env.stack.pop()) { + try { + if (!r8.async && s6 === 1) return s6 = 0, env.stack.push(r8), Promise.resolve().then(next); + if (r8.dispose) { + var result = r8.dispose.call(r8.value); + if (r8.async) return s6 |= 2, Promise.resolve(result).then(next, function(e9) { + fail(e9); + return next(); + }); + } else s6 |= 1; + } catch (e9) { + fail(e9); + } + } + if (s6 === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + })(typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) { + var e9 = new Error(message); + return e9.name = "SuppressedError", e9.error = error, e9.suppressed = suppressed, e9; + }); + SingleRemoteToolUseSession = class _SingleRemoteToolUseSession { + static async create(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2, stack) { + const session = new _SingleRemoteToolUseSession(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2); + await session.init(stack); + return session; + } + constructor(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger2) { + this.pluginsPort = pluginsPort; + this.pluginIdentifier = pluginIdentifier; + this.pluginConfigSpecifier = pluginConfigSpecifier; + this.logger = logger2; + this.status = "initializing"; + this.poison = null; + this.ongoingToolCalls = /* @__PURE__ */ new Map(); + this.callIdGiver = new IdGiver(0); + } + async init(stack) { + const { promise: initPromise, resolve: resolveInit, reject: rejectInit } = makePromise(); + const channel = this.pluginsPort.createChannel("startToolUseSession", { + pluginIdentifier: this.pluginIdentifier, + pluginConfigSpecifier: this.pluginConfigSpecifier + }, (message) => { + const messageType = message.type; + switch (messageType) { + // Upon receiving session ready, mark self as ready and resolve the promise. + case "sessionReady": { + if (this.status !== "initializing") { + this.logger.error("Received sessionReady message while not initializing"); + return; + } + this.status = "ready"; + resolveInit(); + this.tools = message.toolDefinitions.map((toolDefinition) => this.makeTool(toolDefinition)); + break; + } + case "toolCallComplete": { + const ongoingCall = this.ongoingToolCalls.get(message.callId); + if (ongoingCall === void 0) { + return; + } + ongoingCall.resolve(message.result); + break; + } + case "toolCallError": { + const ongoingCall = this.ongoingToolCalls.get(message.callId); + if (ongoingCall === void 0) { + return; + } + ongoingCall.reject(fromSerializedError(message.error)); + break; + } + case "toolCallStatus": { + const ongoingCall = this.ongoingToolCalls.get(message.callId); + if (ongoingCall === void 0) { + return; + } + ongoingCall.reportStatus(message.statusText); + break; + } + case "toolCallWarn": { + const ongoingCall = this.ongoingToolCalls.get(message.callId); + if (ongoingCall === void 0) { + return; + } + ongoingCall.reportWarning(message.warnText); + break; + } + default: { + const exhaustiveCheck = messageType; + this.logger.warn(`Received unexpected message type in tool use session: ${exhaustiveCheck}`); + } + } + }, { stack }); + channel.onError.subscribeOnce((error) => { + if (this.status === "initializing") { + rejectInit(error); + } else { + this.logger.error("Tool use session error.", error); + this.poison = error; + } + for (const ongoingCall of this.ongoingToolCalls.values()) { + ongoingCall.reject(error); + } + this.status = "disposed"; + }); + channel.onClose.subscribeOnce(() => { + let error; + if (this.status === "initializing") { + error = new Error("Tool use session channel closed unexpectedly during initialization."); + rejectInit(error); + } else { + error = new Error("Tool use session has already ended."); + this.poison = error; + } + for (const ongoingCall of this.ongoingToolCalls.values()) { + ongoingCall.reject(error); + } + this.status = "disposed"; + }); + this.channel = channel; + await initPromise; + } + [Symbol.dispose]() { + if (this.status !== "disposed") { + this.channel.send({ type: "discardSession" }); + this.status = "disposed"; + const error = new Error("Session disposed by client."); + for (const ongoingCall of this.ongoingToolCalls.values()) { + ongoingCall.reject(error); + } + this.poison = error; + } + } + makeTool(toolDefinition) { + return internalCreateRemoteTool({ + name: toolDefinition.function.name, + description: toolDefinition.function.description ?? "", + pluginIdentifier: this.pluginIdentifier, + parametersJsonSchema: toolDefinition.function.parameters ?? {}, + implementation: async (args, ctx) => { + const env_1 = { stack: [], error: void 0, hasError: false }; + try { + if (this.poison !== null) { + throw this.poison; + } + if (ctx.signal.aborted) { + throw ctx.signal.reason; + } + const callId = this.callIdGiver.next(); + const { promise, resolve: resolve2, reject } = makePromise(); + const cleaner = __addDisposableResource(env_1, new Cleaner(), false); + this.ongoingToolCalls.set(callId, { + callId, + resolve: resolve2, + reject, + reportStatus: (status) => ctx.status(status), + reportWarning: (warning) => ctx.warn(warning) + }); + cleaner.register(() => { + this.ongoingToolCalls.delete(callId); + }); + this.channel.send({ + type: "callTool", + callId, + name: toolDefinition.function.name, + arguments: args + }); + ctx.signal.addEventListener("abort", () => { + if (this.status === "disposed") { + return; + } + this.channel.send({ + type: "abortToolCall", + callId + }); + reject(ctx.signal.reason); + }, { once: true }); + return await promise; + } catch (e_1) { + env_1.error = e_1; + env_1.hasError = true; + } finally { + __disposeResources(env_1); + } + } + }); + } + }; + MultiRemoteToolUseSession = class _MultiRemoteToolUseSession { + static async createUsingPredictionProcess(pluginsPort, pluginIdentifiers, predictionContextIdentifier, token, logger2, stack) { + const results = await Promise.allSettled(pluginIdentifiers.map((pluginIdentifier) => SingleRemoteToolUseSession.create(pluginsPort, pluginIdentifier, { + type: "predictionProcess", + pci: predictionContextIdentifier, + token + }, logger2, stack))); + const failed = results.filter((result) => result.status === "rejected"); + if (failed.length > 0) { + for (const result of results) { + if (result.status === "fulfilled") { + try { + result.value[Symbol.dispose](); + } catch (error) { + logger2.error("Failed to dispose a session after initialization failure.", error); + } + } + } + throw new AggregateError(failed.map((result) => result.reason), "Failed to initialize some tool use sessions."); + } + return new _MultiRemoteToolUseSession(results.map((result) => result.value), logger2); + } + constructor(sessions, logger2) { + this.sessions = sessions; + this.logger = logger2; + this.tools = []; + this.tools = sessions.flatMap((session) => session.tools); + } + [Symbol.dispose]() { + for (const session of this.sessions) { + try { + session[Symbol.dispose](); + } catch (error) { + this.logger.error("Failed to dispose a session.", error); + } + } + } + }; + pluginToolsOptsSchema = external_exports.object({ + pluginConfig: kvConfigSchema.optional(), + workingDirectory: external_exports.string().optional() + }); + registerDevelopmentPluginOptsSchema = external_exports.object({ + manifest: pluginManifestSchema + }); + PluginsNamespace = class { + /** @internal */ + constructor(port2, client, validator2, parentLogger, rootLogger) { + this.port = port2; + this.client = client; + this.validator = validator2; + this.rootLogger = rootLogger; + this.logger = new SimpleLogger("Plugins", parentLogger); + } + /** + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + async registerDevelopmentPlugin(opts) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("plugins", "registerDevelopmentPlugin", "opts", registerDevelopmentPluginOptsSchema, opts, stack); + const { promise, resolve: resolve2 } = makePromise(); + const channel = this.port.createChannel("registerDevelopmentPlugin", opts, (message) => { + if (message.type === "ready") { + resolve2({ + clientIdentifier: message.clientIdentifier, + clientPasskey: message.clientPasskey + }); + } + }, { stack }); + let unregisterCalled = false; + const unregister = async () => { + if (unregisterCalled) { + return; + } + unregisterCalled = true; + channel.send({ type: "end" }); + const { promise: promise2, resolve: resolve3 } = makePromise(); + channel.onClose.subscribeOnce(resolve3); + await promise2; + }; + const base = await promise; + return { + ...base, + unregister + }; + } + /** + * Requests LM Studio to reindex all the plugins. + * + * CAVEAT: Currently, we do not wait for the reindex to complete before returning. In the future, + * we will change this behavior and only return after the reindex is completed. + * + * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the + * future without warning. + */ + async reindexPlugins() { + const stack = getCurrentStack(1); + await this.port.callRpc("reindexPlugins", void 0, { stack }); + } + /** + * If this client is currently running as a plugin, get the self registration host which can be + * used to register hooks. + * + * @deprecated This method is used by plugins internally to register hooks. Do not use directly. + */ + getSelfRegistrationHost() { + return new PluginSelfRegistrationHost(this.port, this.client, this.rootLogger, this.validator); + } + /** + * Starts a tool use session use any config specifier. + */ + async internalStartToolUseSession(pluginIdentifier, pluginConfigSpecifier, _stack) { + return await SingleRemoteToolUseSession.create(this.port, pluginIdentifier, pluginConfigSpecifier, this.logger); + } + /** + * Start a tool use session with a plugin. Note, this method must be used with "Explicit Resource + * Management". That is, you should use it like so: + * + * ```typescript + * using pluginTools = await client.plugins.pluginTools("owner/name", { ... }); + * // ^ Notice the `using` keyword here. + * ``` + * + * If you do not use `using`, you must call `pluginTools[Symbol.dispose]()` after you are done. + * Otherwise, there will be a memory leak and the plugins you requested tools from will be loaded + * indefinitely. + * + * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in + * development. This may change in the future without warning. + */ + async pluginTools(pluginIdentifier, opts = {}) { + const stack = getCurrentStack(1); + [pluginIdentifier, opts] = this.validator.validateMethodParamsOrThrow("plugins", "pluginTools", ["pluginIdentifier", "opts"], [artifactIdentifierSchema, pluginToolsOptsSchema], [pluginIdentifier, opts], stack); + return await this.internalStartToolUseSession(pluginIdentifier, { + type: "direct", + config: opts.pluginConfig ?? emptyKVConfig, + workingDirectoryPath: opts.workingDirectory + }); + } + /** + * Start a tool use session associated with a prediction process. + * + * This method is used internally by processing controllers and will be stripped by the internal + * tag. + * + * @internal + */ + async startToolUseSessionUsingPredictionProcess(pluginIdentifiers, predictionContextIdentifier, token, stack) { + return await MultiRemoteToolUseSession.createUsingPredictionProcess(this.port, pluginIdentifiers, predictionContextIdentifier, token, this.logger, stack); + } + /** + * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in + * development. This may change in the future without warning. + */ + createGeneratorHandle(pluginIdentifier) { + return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, null, this.logger); + } + /** + * Creates a generator handle that is already associated with a prediction process. + * + * This method is used internally by the processing controllers to create generator handles. It is + * marked as internal and will be stripped. + * + * @internal + */ + createGeneratorHandleAssociatedWithPredictionProcess(pluginIdentifier, predictionContextIdentifier, token) { + return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, { pci: predictionContextIdentifier, token }, this.logger); + } + }; + artifactDownloadPlannerDownloadOptsSchema = external_exports.object({ + onStartFinalizing: external_exports.function().optional(), + onProgress: external_exports.function().optional(), + signal: external_exports.instanceof(AbortSignal).optional() + }); + ArtifactDownloadPlanner = class { + /** + * @internal Do not construct this class yourself. + */ + constructor(owner, name, onPlanUpdated, channel, validator2, onDisposed) { + this.owner = owner; + this.name = name; + this.onPlanUpdated = onPlanUpdated; + this.channel = channel; + this.validator = validator2; + this.onDisposed = onDisposed; + this.readyDeferredPromise = makePromise(); + this.isReadyBoolean = false; + this.currentDownload = null; + this.errorReceivedBeforeDownloadStart = null; + this.logger = new SimpleLogger(`ArtifactDownloadPlanner(${owner}/${name})`); + this.readyDeferredPromise.promise.catch(() => { + }); + this.planValue = { + nodes: [ + { + type: "artifact", + owner, + name, + state: "pending", + dependencyNodes: [] + } + ], + downloadSizeBytes: 0 + }; + this.channel.onMessage.subscribe((message) => { + const messageType = message.type; + switch (messageType) { + case "planReady": { + this.isReadyBoolean = true; + this.readyDeferredPromise.resolve(); + this.planValue = message.plan; + break; + } + case "planUpdated": { + this.planValue = message.plan; + safeCallCallback(this.logger, "onPlanUpdated", this.onPlanUpdated, [message.plan]); + break; + } + case "success": { + if (this.currentDownload === null) { + throw new Error("Unexpected: received success message without a download."); + } + this.currentDownload.downloadFinished(); + break; + } + case "downloadProgress": { + if (this.currentDownload === null) { + throw new Error("Unexpected: received progress message without a download."); + } + this.currentDownload.progressUpdate(message.update); + break; + } + case "startFinalizing": { + if (this.currentDownload === null) { + throw new Error("Unexpected: received startFinalizing message without a download."); + } + this.currentDownload.startFinalizing(); + break; + } + } + }); + this.channel.onError.subscribeOnce((error) => { + if (this.currentDownload === null) { + this.errorReceivedBeforeDownloadStart = error; + this.readyDeferredPromise.reject(error); + } else { + this.currentDownload.downloadFailed(error); + } + }); + } + [Symbol.dispose]() { + this.channel.send({ type: "cancel" }); + this.onDisposed(); + } + isReady() { + return this.isReadyBoolean; + } + async untilReady() { + return await this.readyDeferredPromise.promise; + } + getPlan() { + return this.planValue; + } + /** + * Download this artifact. `download` can only be called once. + */ + async download(opts) { + const stack = getCurrentStack(1); + opts = this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner", "download", "opts", artifactDownloadPlannerDownloadOptsSchema, opts, stack); + const { onProgress, onStartFinalizing, signal = new AbortController().signal } = opts; + if (this.currentDownload !== null) { + throw new Error("You can only call `download` once for each planner."); + } + if (this.errorReceivedBeforeDownloadStart !== null) { + const error = this.errorReceivedBeforeDownloadStart; + this.errorReceivedBeforeDownloadStart = null; + throw error; + } + const { promise, resolve: resolve2, reject } = makePromise(); + this.currentDownload = { + downloadFinished: () => { + resolve2(); + }, + startFinalizing: () => { + safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []); + }, + progressUpdate: (update) => { + safeCallCallback(this.logger, "onProgress", onProgress, [update]); + }, + downloadFailed: (error) => { + reject(error); + } + }; + this.channel.send({ type: "commit" }); + if (signal.aborted) { + this.channel.send({ type: "cancel" }); + } else { + signal.addEventListener("abort", () => { + this.channel.send({ type: "cancel" }); + }); + } + return await promise.catch((error) => { + if (signal.aborted) { + throw signal.reason; + } else { + throw error; + } + }); + } + }; + downloadOptsSchema = external_exports.object({ + onProgress: external_exports.function().optional(), + onStartFinalizing: external_exports.function().optional(), + signal: external_exports.instanceof(AbortSignal).optional() + }); + ModelSearchResultDownloadOption = class { + /** @internal */ + constructor(repositoryPort, validator2, logger2, data) { + this.repositoryPort = repositoryPort; + this.validator = validator2; + this.logger = logger2; + this.data = data; + this.quantization = data.quantization; + this.name = data.name; + this.sizeBytes = data.sizeBytes; + this.fitEstimation = this.data.fitEstimation; + this.indexedModelIdentifier = this.data.indexedModelIdentifier; + } + isRecommended() { + return this.data.recommended ?? false; + } + /** + * Download the model. Returns the model key which can be used to load the model. + */ + async download(opts = {}) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption", "download", "opts", downloadOptsSchema, opts, stack); + const { promise, resolve: resolve2, reject } = makePromise(); + const channel = this.repositoryPort.createChannel("downloadModel", { + downloadIdentifier: this.data.downloadIdentifier + }, (message) => { + switch (message.type) { + case "downloadProgress": { + safeCallCallback(this.logger, "onProgress", opts.onProgress, [message.update]); + break; + } + case "startFinalizing": { + safeCallCallback(this.logger, "onStartFinalizing", opts.onStartFinalizing, []); + break; + } + case "success": { + resolve2(message.defaultIdentifier); + break; + } + default: { + const exhaustiveCheck = message; + throw new Error(`Unexpected message type: ${exhaustiveCheck}`); + } + } + }, { stack }); + channel.onError.subscribeOnce((error) => { + if (opts.signal?.aborted) { + reject(opts.signal.reason); + } else { + reject(error); + } + }); + channel.onClose.subscribeOnce(() => { + if (opts.signal?.aborted) { + reject(opts.signal.reason); + } else { + reject(new Error("Channel closed unexpectedly.")); + } + }); + const abortListener = () => { + channel.send({ type: "cancel" }); + }; + opts.signal?.addEventListener("abort", abortListener); + promise.finally(() => { + opts.signal?.removeEventListener("abort", abortListener); + }); + return await promise; + } + }; + ModelSearchResultEntry = class { + /** + * @internal + */ + constructor(repositoryPort, validator2, logger2, data) { + this.repositoryPort = repositoryPort; + this.validator = validator2; + this.logger = logger2; + this.data = data; + this.name = data.name; + } + isExactMatch() { + return this.data.exact ?? false; + } + isStaffPick() { + return this.data.staffPick ?? false; + } + async getDownloadOptions() { + const { results } = await this.repositoryPort.callRpc("getModelDownloadOptions", { + modelSearchResultIdentifier: this.data.identifier + }); + return results.map((data) => new ModelSearchResultDownloadOption(this.repositoryPort, this.validator, this.logger, data)); + } + }; + downloadArtifactOptsSchema = external_exports.object({ + owner: external_exports.string(), + name: external_exports.string(), + revisionNumber: external_exports.number(), + path: external_exports.string(), + onProgress: external_exports.function().optional(), + onStartFinalizing: external_exports.function().optional(), + signal: external_exports.instanceof(AbortSignal).optional() + }); + pushArtifactOptsSchema = external_exports.object({ + path: external_exports.string(), + description: external_exports.string().optional(), + makePrivate: external_exports.boolean().optional(), + writeRevision: external_exports.boolean().optional(), + overrides: jsonSerializableSchema.optional(), + onMessage: external_exports.function().optional() + }); + ensureAuthenticatedOptsSchema = external_exports.object({ + onAuthenticationUrl: external_exports.function() + }); + loginWithPreAuthenticatedKeysOptsSchema = external_exports.object({ + keyId: external_exports.string(), + publicKey: external_exports.string(), + privateKey: external_exports.string() + }); + external_exports.object({ + userName: external_exports.string() + }); + createArtifactDownloadPlannerOptsSchema = external_exports.object({ + owner: external_exports.string(), + name: external_exports.string(), + onPlanUpdated: external_exports.function().optional() + }); + RepositoryNamespace = class { + /** @internal */ + constructor(repositoryPort, validator2, parentLogger) { + this.repositoryPort = repositoryPort; + this.validator = validator2; + this.downloadPlanFinalizationRegistry = new FinalizationRegistry(({ owner, name }) => { + this.logger.warn(` + A download plan for artifact ${owner}/${name} has been garbage collected without being + disposed. Please make sure you are creating the download plan with the "using" keyword. + + This is a memory leak and needs to be fixed. + `); + }); + this.logger = new SimpleLogger("Repository", parentLogger); + } + async searchModels(opts) { + const stack = getCurrentStack(1); + opts = this.validator.validateMethodParamOrThrow("repository", "search", "opts", modelSearchOptsSchema, opts, stack); + const { results } = await this.repositoryPort.callRpc("searchModels", { opts }, { stack }); + return results.map((data) => new ModelSearchResultEntry(this.repositoryPort, this.validator, this.logger, data)); + } + /** + * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay + * tuned for updates. + */ + async installPluginDependencies(pluginFolder) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("repository", "installPluginDependencies", "pluginFolder", external_exports.string(), pluginFolder, stack); + await this.repositoryPort.callRpc("installPluginDependencies", { pluginFolder }, { stack }); + } + /** + * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay + * tuned for updates. + */ + async downloadArtifact(opts) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("client.repository", "downloadArtifact", "opts", downloadArtifactOptsSchema, opts, stack); + const { owner, name, revisionNumber, path: path6, onProgress, onStartFinalizing, signal } = opts; + const { promise, resolve: resolve2, reject } = makePromise(); + const channel = this.repositoryPort.createChannel("downloadArtifact", { artifactOwner: owner, artifactName: name, revisionNumber, path: path6 }, (message) => { + switch (message.type) { + case "downloadProgress": { + safeCallCallback(this.logger, "onProgress", onProgress, [message.update]); + break; + } + case "startFinalizing": { + safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []); + break; + } + case "success": { + resolve2(); + break; + } + default: { + const exhaustiveCheck = message; + throw new Error(`Unexpected message type: ${exhaustiveCheck}`); + } + } + }, { stack }); + channel.onError.subscribeOnce(reject); + channel.onClose.subscribeOnce(() => { + if (signal?.aborted) { + reject(signal.reason); + } else { + reject(new Error("Channel closed unexpectedly.")); + } + }); + const abortListener = () => { + channel.send({ type: "cancel" }); + }; + signal?.addEventListener("abort", abortListener); + promise.finally(() => { + signal?.removeEventListener("abort", abortListener); + }); + return await promise; + } + /** + * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay + * tuned for updates. + */ + async pushArtifact(opts) { + const stack = getCurrentStack(1); + const { path: path6, description, makePrivate, writeRevision, overrides: overrides2, onMessage } = this.validator.validateMethodParamOrThrow("repository", "pushArtifact", "opts", pushArtifactOptsSchema, opts, stack); + const channel = this.repositoryPort.createChannel("pushArtifact", { path: path6, description, makePrivate, writeRevision, overrides: overrides2 }, (message) => { + const type = message.type; + switch (type) { + case "message": { + safeCallCallback(this.logger, "onMessage", onMessage, [message.message]); + break; + } + default: { + const exhaustiveCheck = type; + throw new Error(`Unexpected message type: ${exhaustiveCheck}`); + } + } + }, { stack }); + const { promise, resolve: resolve2, reject } = makePromise(); + channel.onError.subscribeOnce(reject); + channel.onClose.subscribeOnce(resolve2); + await promise; + } + /** + * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay + * tuned for updates. + */ + async getLocalArtifactFileList(path6) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("repository", "getLocalArtifactFileList", "path", external_exports.string(), path6, stack); + const { fileList } = await this.repositoryPort.callRpc("getLocalArtifactFiles", { path: path6 }, { stack }); + return fileList; + } + /** + * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay + * tuned for updates. + */ + async ensureAuthenticated(opts) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("repository", "ensureAuthenticated", "opts", ensureAuthenticatedOptsSchema, opts, stack); + const { promise, resolve: resolve2, reject } = makePromise(); + const channel = this.repositoryPort.createChannel("ensureAuthenticated", void 0, (message) => { + const type = message.type; + switch (type) { + case "authenticationUrl": { + safeCallCallback(this.logger, "onAuthenticationUrl", opts.onAuthenticationUrl, [ + message.url + ]); + break; + } + case "authenticated": { + resolve2(); + break; + } + default: { + const exhaustiveCheck = type; + throw new Error(`Unexpected message type: ${exhaustiveCheck}`); + } + } + }); + channel.onError.subscribeOnce(reject); + await promise; + } + async loginWithPreAuthenticatedKeys(opts) { + const stack = getCurrentStack(1); + this.validator.validateMethodParamOrThrow("repository", "loginWithPreAuthenticatedKeys", "opts", loginWithPreAuthenticatedKeysOptsSchema, opts, stack); + const { keyId, publicKey, privateKey } = opts; + const { userName } = await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys", { keyId, publicKey, privateKey }, { stack }); + return { userName }; + } + /** + * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay + * tuned for updates. + */ + createArtifactDownloadPlanner(opts) { + const { owner, name, onPlanUpdated } = this.validator.validateMethodParamOrThrow("repository", "createArtifactDownloadPlanner", "opts", createArtifactDownloadPlannerOptsSchema, opts); + const stack = getCurrentStack(1); + const channel = this.repositoryPort.createChannel( + "createArtifactDownloadPlan", + { owner, name }, + void 0, + // Don't listen to the messages yet. + { stack } + ); + const planner = new ArtifactDownloadPlanner(owner, name, onPlanUpdated, channel, this.validator, () => { + this.downloadPlanFinalizationRegistry.unregister(planner); + }); + this.downloadPlanFinalizationRegistry.register(planner, { owner, name }, planner); + return planner; + } + }; + startHttpServerOptsSchema = external_exports.object({ + port: external_exports.number().int().min(1).max(65535).describe("Port to run the API server on. Must be between 1 and 65535."), + cors: external_exports.boolean().describe("Enable CORS on the API server. Allows any website to access the server.") + }); + SystemNamespace = class { + /** @internal */ + constructor(systemPort, validator2, parentLogger) { + this.systemPort = systemPort; + this.validator = validator2; + this.logger = new SimpleLogger("System", parentLogger); + } + async listDownloadedModels(domain) { + const stack = getCurrentStack(1); + domain = this.validator.validateMethodParamOrThrow("client.system", "listDownloadedModels", "domain", external_exports.union([external_exports.literal("llm"), external_exports.literal("embedding"), external_exports.undefined()]), domain, stack); + const models = await this.systemPort.callRpc("listDownloadedModels", void 0, { + stack: getCurrentStack(1) + }); + if (domain === void 0) { + return models; + } + return models.filter((model) => model.type === domain); + } + async whenDisconnected() { + const stack = getCurrentStack(1); + const channel = this.systemPort.createChannel("alive", void 0, void 0, { stack }); + const { promise, resolve: resolve2 } = makePromise(); + channel.onError.subscribeOnce(resolve2); + channel.onClose.subscribeOnce(resolve2); + await promise; + } + async notify(notification) { + const stack = getCurrentStack(1); + notification = this.validator.validateMethodParamOrThrow("client.system", "notify", "notification", backendNotificationSchema, notification, stack); + await this.systemPort.callRpc("notify", notification, { stack }); + } + async getLMStudioVersion() { + const stack = getCurrentStack(1); + return await this.systemPort.callRpc("version", void 0, { stack }); + } + /** + * Sets an experiment flags for LM Studio. This is an unstable API and may change without notice. + * + * @experimental + */ + async unstable_setExperimentFlag(flag, value) { + const stack = getCurrentStack(1); + [flag, value] = this.validator.validateMethodParamsOrThrow("client.system", "setExperimentFlag", ["flag", "value"], [external_exports.string(), external_exports.boolean()], [flag, value], stack); + await this.systemPort.callRpc("setExperimentFlag", { code: flag, value }, { stack }); + } + /** + * Gets all experiment flags for LM Studio. This is an unstable API and may change without notice. + * + * @experimental + */ + async unstable_getExperimentFlags() { + const stack = getCurrentStack(1); + return await this.systemPort.callRpc("getExperimentFlags", void 0, { stack }); + } + /** + * Starts the API server on the specified port. + * + * @experimental + */ + async startHttpServer(opts) { + const stack = getCurrentStack(1); + opts = this.validator.validateMethodParamOrThrow("client.system", "startHttpServer", "args", startHttpServerOptsSchema, opts); + return await this.systemPort.callRpc("startHttpServer", { port: opts.port, cors: opts.cors }, { + stack + }); + } + /** + * Stops the API server if it is running. + * + * @experimental + */ + async stopHttpServer() { + const stack = getCurrentStack(1); + return await this.systemPort.callRpc("stopHttpServer", void 0, { stack }); + } + }; + constructorOptsSchema = external_exports.object({ + logger: external_exports.any().optional(), + baseUrl: external_exports.string().optional(), + verboseErrorMessages: external_exports.boolean().optional(), + clientIdentifier: external_exports.string().optional(), + clientPasskey: external_exports.string().optional(), + // Internal testing options + disableConnection: external_exports.boolean().optional(), + llmPort: external_exports.any().optional(), + embeddingPort: external_exports.any().optional(), + systemPort: external_exports.any().optional(), + diagnosticsPort: external_exports.any().optional(), + retrievalPort: external_exports.any().optional(), + filesPort: external_exports.any().optional(), + repositoryPort: external_exports.any().optional(), + pluginsPort: external_exports.any().optional() + }).strict(); + LMStudioClient = class { + /** @internal */ + validateBaseUrlOrThrow(baseUrl) { + let url; + try { + url = new URL(baseUrl); + } catch (e9) { + this.logger.throw(text` + Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${baseUrl} + `); + } + if (!["ws:", "wss:"].includes(url.protocol)) { + this.logger.throw(text` + Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss". + Received: ${baseUrl} + `); + } + if (url.search !== "") { + this.logger.throw(text` + Failed to construct LMStudioClient. The baseUrl passed contains search parameters + ("${url.search}"). + `); + } + if (url.hash !== "") { + this.logger.throw(text` + Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${url.hash}"). + `); + } + if (url.username !== "" || url.password !== "") { + this.logger.throw(text` + Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We + do not support these in the baseUrl. Received: ${baseUrl} + `); + } + if (baseUrl.endsWith("/")) { + this.logger.throw(text` + Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you + are reverse-proxying, you should remove the trailing slash from the baseUrl. Received: + ${baseUrl} + `); + } + } + async isLocalhostWithGivenPortLMStudioServer(port2) { + const response = await fetch(`http://127.0.0.1:${port2}/lmstudio-greeting`); + if (response.status !== 200) { + throw new Error("Status is not 200."); + } + const json2 = await response.json(); + if (json2?.lmstudio !== true) { + throw new Error("Not an LM Studio server."); + } + return port2; + } + /** + * Guess the base URL of the LM Studio server by visiting localhost on various default ports. + */ + async guessBaseUrl(stack) { + if (getHostedEnv() !== null) { + return Promise.resolve("Using hosted env"); + } + if (process_shim_default.browser) { + try { + this.isLocalhostWithGivenPortLMStudioServer(1234); + return "ws://127.0.0.1:1234"; + } catch (error) { + text` + ${import_chalk.default.redBright("Failed to connect to LM Studio.")} + + Is LM Studio running? If not, please start it by running: + + ${import_chalk.default.yellow("lms server start --cors")} + + If you are attempting to connect to LM Studio on a separate machine, please provide the + baseUrl option when creating the LMStudioClient: + + ${import_chalk.default.blueBright(text` + const client = new LMStudioClient({ baseUrl: 'ws://:' }); + `)} + + ${import_chalk.default.white("(i) For more information, refer to the LM Studio documentation:")} + + ${import_chalk.default.gray("https://lmstudio.ai/docs/local-server")} + `; + } + } + return Promise.any(apiServerPorts.map(this.isLocalhostWithGivenPortLMStudioServer)).then((port2) => `ws://127.0.0.1:${port2}`, () => { + throw makePrettyError(text` + ${import_chalk.default.redBright("Failed to connect to LM Studio.")} + + Please make sure LM Studio is running on your machine. + + If you are attempting to connect to LM Studio on a separate machine, please provide the + baseUrl option when creating the LMStudioClient: + + ${import_chalk.default.blueBright(text` + const client = new LMStudioClient({ baseUrl: 'ws://:' }); + `)} + + ${import_chalk.default.white("(i) For more information, refer to the LM Studio documentation:")} + + ${import_chalk.default.gray("https://lmstudio.ai/docs/local-server")} + `, stack); + }); + } + createPort(namespace, name, backendInterface) { + return createAuthenticatedClientPort(backendInterface, this.resolvingBaseUrl, namespace, this.clientIdentifier, this.clientPasskey, new SimpleLogger(name, this.logger), { + errorDeserializer: friendlyErrorDeserializer, + verboseErrorMessage: this.verboseErrorMessages + }); + } + constructor(opts = {}) { + const { logger: logger2, baseUrl, verboseErrorMessages, clientIdentifier, clientPasskey, disableConnection, llmPort, embeddingPort, systemPort, diagnosticsPort, retrievalPort, filesPort, repositoryPort, pluginsPort } = new Validator().validateConstructorParamOrThrow("LMStudioClient", "opts", constructorOptsSchema, opts); + if (globalThis.__LMS_PLUGIN_CONTEXT && opts.baseUrl === void 0) { + throw new Error(text` + You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use + the "client" property attached to the Controllers. + + For example, instead of: + + ${"const client = new LMStudioClient(); // <-- Error\nexport async function generate(ctl: GeneratorController) {\n const model = await client.llm.model(...);\n}"} + + Do this: + + ${"export async function generate(ctl: GeneratorController) {\n const model = await ctl.client.llm.model(...);\n}"} + + If you need to connect to a remote LM Studio, you should pass in the \`baseUrl\` option to + the LMStudioClient constructor: + + ${"const client = new LMStudioClient({ baseUrl: 'ws://:' });"} + `); + } + this.logger = new SimpleLogger("LMStudioClient", logger2); + this.clientIdentifier = clientIdentifier ?? (0, import_lms_isomorphic.generateRandomBase64)(18); + this.clientPasskey = clientPasskey ?? (0, import_lms_isomorphic.generateRandomBase64)(18); + const stack = getCurrentStack(1); + if (disableConnection) { + this.resolvingBaseUrl = new Promise(() => void 0); + } else { + if (baseUrl === void 0) { + this.resolvingBaseUrl = this.guessBaseUrl(verboseErrorMessages ? stack : void 0); + } else { + this.validateBaseUrlOrThrow(baseUrl); + this.resolvingBaseUrl = baseUrl; + } + } + this.verboseErrorMessages = verboseErrorMessages ?? true; + this.llmPort = llmPort ?? this.createPort("llm", "LLM", createLlmBackendInterface()); + this.embeddingPort = embeddingPort ?? this.createPort("embedding", "Embedding", createEmbeddingBackendInterface()); + this.systemPort = systemPort ?? this.createPort("system", "System", createSystemBackendInterface()); + this.diagnosticsPort = diagnosticsPort ?? this.createPort("diagnostics", "Diagnostics", createDiagnosticsBackendInterface()); + this.filesPort = filesPort ?? this.createPort("files", "Files", createFilesBackendInterface()); + this.repositoryPort = repositoryPort ?? this.createPort("repository", "Repository", createRepositoryBackendInterface()); + this.pluginsPort = pluginsPort ?? this.createPort("plugins", "Plugins", createPluginsBackendInterface()); + const validator2 = new Validator(); + this.llm = new LLMNamespace(this, this.llmPort, new SimpleLogger("LLM", this.logger), validator2); + this.embedding = new EmbeddingNamespace(this, this.embeddingPort, new SimpleLogger("Embedding", this.logger), validator2); + this.system = new SystemNamespace(this.systemPort, validator2, this.logger); + this.diagnostics = new DiagnosticsNamespace(this.diagnosticsPort, validator2, this.logger); + this.files = new FilesNamespace(this.filesPort, validator2, this.logger); + this.repository = new RepositoryNamespace(this.repositoryPort, validator2, this.logger); + this.plugins = new PluginsNamespace(this.pluginsPort, this, validator2, this.logger, logger2); + } + async [Symbol.asyncDispose]() { + await Promise.all([ + this.llmPort[Symbol.asyncDispose](), + this.embeddingPort[Symbol.asyncDispose](), + this.systemPort[Symbol.asyncDispose](), + this.diagnosticsPort[Symbol.asyncDispose](), + this.filesPort[Symbol.asyncDispose](), + this.repositoryPort[Symbol.asyncDispose](), + this.pluginsPort[Symbol.asyncDispose]() + ]); + } + }; + } +}); + +// ../pi-mono/node_modules/whatwg-fetch/fetch.js +function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj); +} +function normalizeName(name) { + if (typeof name !== "string") { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === "") { + throw new TypeError('Invalid character in header field name: "' + name + '"'); + } + return name.toLowerCase(); +} +function normalizeValue(value) { + if (typeof value !== "string") { + value = String(value); + } + return value; +} +function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift(); + return { done: value === void 0, value }; + } + }; + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator; + }; + } + return iterator; +} +function Headers2(headers) { + this.map = {}; + if (headers instanceof Headers2) { + headers.forEach(function(value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + if (header.length != 2) { + throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + header.length); + } + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); + } +} +function consumed(body) { + if (body._noBody) return; + if (body.bodyUsed) { + return Promise.reject(new TypeError("Already read")); + } + body.bodyUsed = true; +} +function fileReaderReady(reader) { + return new Promise(function(resolve2, reject) { + reader.onload = function() { + resolve2(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }); +} +function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise; +} +function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + var match2 = /charset=([A-Za-z0-9_-]+)/.exec(blob.type); + var encoding = match2 ? match2[1] : "utf-8"; + reader.readAsText(blob, encoding); + return promise; +} +function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + for (var i7 = 0; i7 < view.length; i7++) { + chars[i7] = String.fromCharCode(view[i7]); + } + return chars.join(""); +} +function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0); + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer; + } +} +function Body() { + this.bodyUsed = false; + this._initBody = function(body) { + this.bodyUsed = this.bodyUsed; + this._bodyInit = body; + if (!body) { + this._noBody = true; + this._bodyText = ""; + } else if (typeof body === "string") { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + this._bodyText = body = Object.prototype.toString.call(body); + } + if (!this.headers.get("content-type")) { + if (typeof body === "string") { + this.headers.set("content-type", "text/plain;charset=UTF-8"); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set("content-type", this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"); + } + } + }; + if (support.blob) { + this.blob = function() { + var rejected = consumed(this); + if (rejected) { + return rejected; + } + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob); + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])); + } else if (this._bodyFormData) { + throw new Error("could not read FormData body as blob"); + } else { + return Promise.resolve(new Blob([this._bodyText])); + } + }; + } + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + var isConsumed = consumed(this); + if (isConsumed) { + return isConsumed; + } else if (ArrayBuffer.isView(this._bodyArrayBuffer)) { + return Promise.resolve( + this._bodyArrayBuffer.buffer.slice( + this._bodyArrayBuffer.byteOffset, + this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength + ) + ); + } else { + return Promise.resolve(this._bodyArrayBuffer); + } + } else if (support.blob) { + return this.blob().then(readBlobAsArrayBuffer); + } else { + throw new Error("could not read as ArrayBuffer"); + } + }; + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected; + } + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob); + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); + } else if (this._bodyFormData) { + throw new Error("could not read FormData body as text"); + } else { + return Promise.resolve(this._bodyText); + } + }; + if (support.formData) { + this.formData = function() { + return this.text().then(decode); + }; + } + this.json = function() { + return this.text().then(JSON.parse); + }; + return this; +} +function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method; +} +function Request2(input, options) { + if (!(this instanceof Request2)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.'); + } + options = options || {}; + var body = options.body; + if (input instanceof Request2) { + if (input.bodyUsed) { + throw new TypeError("Already read"); + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers2(input.headers); + } + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + this.credentials = options.credentials || this.credentials || "same-origin"; + if (options.headers || !this.headers) { + this.headers = new Headers2(options.headers); + } + this.method = normalizeMethod(options.method || this.method || "GET"); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal || (function() { + if ("AbortController" in g2) { + var ctrl = new AbortController(); + return ctrl.signal; + } + })(); + this.referrer = null; + if ((this.method === "GET" || this.method === "HEAD") && body) { + throw new TypeError("Body not allowed for GET or HEAD requests"); + } + this._initBody(body); + if (this.method === "GET" || this.method === "HEAD") { + if (options.cache === "no-store" || options.cache === "no-cache") { + var reParamSearch = /([?&])_=[^&]*/; + if (reParamSearch.test(this.url)) { + this.url = this.url.replace(reParamSearch, "$1_=" + (/* @__PURE__ */ new Date()).getTime()); + } else { + var reQueryString = /\?/; + this.url += (reQueryString.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime(); + } + } + } +} +function decode(body) { + var form = new FormData(); + body.trim().split("&").forEach(function(bytes) { + if (bytes) { + var split = bytes.split("="); + var name = split.shift().replace(/\+/g, " "); + var value = split.join("=").replace(/\+/g, " "); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form; +} +function parseHeaders(rawHeaders) { + var headers = new Headers2(); + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " "); + preProcessedHeaders.split("\r").map(function(header) { + return header.indexOf("\n") === 0 ? header.substr(1, header.length) : header; + }).forEach(function(line) { + var parts = line.split(":"); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(":").trim(); + try { + headers.append(key, value); + } catch (error) { + console.warn("Response " + error.message); + } + } + }); + return headers; +} +function Response2(bodyInit, options) { + if (!(this instanceof Response2)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.'); + } + if (!options) { + options = {}; + } + this.type = "default"; + this.status = options.status === void 0 ? 200 : options.status; + if (this.status < 200 || this.status > 599) { + throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599]."); + } + this.ok = this.status >= 200 && this.status < 300; + this.statusText = options.statusText === void 0 ? "" : "" + options.statusText; + this.headers = new Headers2(options.headers); + this.url = options.url || ""; + this._initBody(bodyInit); +} +function fetch2(input, init) { + return new Promise(function(resolve2, reject) { + var request = new Request2(input, init); + if (request.signal && request.signal.aborted) { + return reject(new DOMException("Aborted", "AbortError")); + } + var xhr = new XMLHttpRequest(); + function abortXhr() { + xhr.abort(); + } + xhr.onload = function() { + var options = { + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || "") + }; + if (request.url.indexOf("file://") === 0 && (xhr.status < 200 || xhr.status > 599)) { + options.status = 200; + } else { + options.status = xhr.status; + } + options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL"); + var body = "response" in xhr ? xhr.response : xhr.responseText; + setTimeout(function() { + resolve2(new Response2(body, options)); + }, 0); + }; + xhr.onerror = function() { + setTimeout(function() { + reject(new TypeError("Network request failed")); + }, 0); + }; + xhr.ontimeout = function() { + setTimeout(function() { + reject(new TypeError("Network request timed out")); + }, 0); + }; + xhr.onabort = function() { + setTimeout(function() { + reject(new DOMException("Aborted", "AbortError")); + }, 0); + }; + function fixUrl(url) { + try { + return url === "" && g2.location.href ? g2.location.href : url; + } catch (e9) { + return url; + } + } + xhr.open(request.method, fixUrl(request.url), true); + if (request.credentials === "include") { + xhr.withCredentials = true; + } else if (request.credentials === "omit") { + xhr.withCredentials = false; + } + if ("responseType" in xhr) { + if (support.blob) { + xhr.responseType = "blob"; + } else if (support.arrayBuffer) { + xhr.responseType = "arraybuffer"; + } + } + if (init && typeof init.headers === "object" && !(init.headers instanceof Headers2 || g2.Headers && init.headers instanceof g2.Headers)) { + var names2 = []; + Object.getOwnPropertyNames(init.headers).forEach(function(name) { + names2.push(normalizeName(name)); + xhr.setRequestHeader(name, normalizeValue(init.headers[name])); + }); + request.headers.forEach(function(value, name) { + if (names2.indexOf(name) === -1) { + xhr.setRequestHeader(name, value); + } + }); + } else { + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + } + if (request.signal) { + request.signal.addEventListener("abort", abortXhr); + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + request.signal.removeEventListener("abort", abortXhr); + } + }; + } + xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit); + }); +} +var g2, support, viewClasses, isArrayBufferView, methods, redirectStatuses, DOMException; +var init_fetch = __esm({ + "../pi-mono/node_modules/whatwg-fetch/fetch.js"() { + init_process_shim(); + g2 = typeof globalThis !== "undefined" && globalThis || typeof self !== "undefined" && self || // eslint-disable-next-line no-undef + typeof globalThis !== "undefined" && globalThis || {}; + support = { + searchParams: "URLSearchParams" in g2, + iterable: "Symbol" in g2 && "iterator" in Symbol, + blob: "FileReader" in g2 && "Blob" in g2 && (function() { + try { + new Blob(); + return true; + } catch (e9) { + return false; + } + })(), + formData: "FormData" in g2, + arrayBuffer: "ArrayBuffer" in g2 + }; + if (support.arrayBuffer) { + viewClasses = [ + "[object Int8Array]", + "[object Uint8Array]", + "[object Uint8ClampedArray]", + "[object Int16Array]", + "[object Uint16Array]", + "[object Int32Array]", + "[object Uint32Array]", + "[object Float32Array]", + "[object Float64Array]" + ]; + isArrayBufferView = ArrayBuffer.isView || function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1; + }; + } + Headers2.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ", " + value : value; + }; + Headers2.prototype["delete"] = function(name) { + delete this.map[normalizeName(name)]; + }; + Headers2.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null; + }; + Headers2.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)); + }; + Headers2.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; + Headers2.prototype.forEach = function(callback2, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback2.call(thisArg, this.map[name], name, this); + } + } + }; + Headers2.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items); + }; + Headers2.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items); + }; + Headers2.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items); + }; + if (support.iterable) { + Headers2.prototype[Symbol.iterator] = Headers2.prototype.entries; + } + methods = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"]; + Request2.prototype.clone = function() { + return new Request2(this, { body: this._bodyInit }); + }; + Body.call(Request2.prototype); + Body.call(Response2.prototype); + Response2.prototype.clone = function() { + return new Response2(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers2(this.headers), + url: this.url + }); + }; + Response2.error = function() { + var response = new Response2(null, { status: 200, statusText: "" }); + response.ok = false; + response.status = 0; + response.type = "error"; + return response; + }; + redirectStatuses = [301, 302, 303, 307, 308]; + Response2.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError("Invalid status code"); + } + return new Response2(null, { status, headers: { location: url } }); + }; + DOMException = g2.DOMException; + try { + new DOMException(); + } catch (err) { + DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + DOMException.prototype = Object.create(Error.prototype); + DOMException.prototype.constructor = DOMException; + } + fetch2.polyfill = true; + if (!g2.fetch) { + g2.fetch = fetch2; + g2.Headers = Headers2; + g2.Request = Request2; + g2.Response = Response2; + } + } +}); + +// ../pi-mono/node_modules/ollama/dist/browser.mjs +function getPlatform() { + if (typeof window !== "undefined" && window.navigator) { + const nav = navigator; + if ("userAgentData" in nav && nav.userAgentData?.platform) { + return `${nav.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`; + } + if (navigator.platform) { + return `${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`; + } + return `unknown Browser/${navigator.userAgent};`; + } else if (typeof process !== "undefined") { + return `${process.arch} ${process.platform} Node.js/${process.version}`; + } + return ""; +} +function normalizeHeaders(headers) { + if (headers instanceof Headers) { + const obj = {}; + headers.forEach((value, key) => { + obj[key] = value; + }); + return obj; + } else if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } else { + return headers || {}; + } +} +var defaultPort, defaultHost, version, __defProp$1, __defNormalProp$1, __publicField$1, ResponseError, AbortableAsyncIterator, checkOk, readEnvVar, fetchWithHeaders, get2, post, del, parseJSON2, formatHost, __defProp2, __defNormalProp, __publicField, Ollama$1, browser; +var init_browser = __esm({ + "../pi-mono/node_modules/ollama/dist/browser.mjs"() { + init_process_shim(); + init_fetch(); + defaultPort = "11434"; + defaultHost = `http://127.0.0.1:${defaultPort}`; + version = "0.6.3"; + __defProp$1 = Object.defineProperty; + __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + __publicField$1 = (obj, key, value) => { + __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + ResponseError = class _ResponseError extends Error { + constructor(error, status_code) { + super(error); + this.error = error; + this.status_code = status_code; + this.name = "ResponseError"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, _ResponseError); + } + } + }; + AbortableAsyncIterator = class { + constructor(abortController, itr, doneCallback) { + __publicField$1(this, "abortController"); + __publicField$1(this, "itr"); + __publicField$1(this, "doneCallback"); + this.abortController = abortController; + this.itr = itr; + this.doneCallback = doneCallback; + } + abort() { + this.abortController.abort(); + } + async *[Symbol.asyncIterator]() { + for await (const message of this.itr) { + if ("error" in message) { + throw new Error(message.error); + } + yield message; + if (message.done || message.status === "success") { + this.doneCallback(); + return; + } + } + throw new Error("Did not receive done or success response in stream."); + } + }; + checkOk = async (response) => { + if (response.ok) { + return; + } + let message = `Error ${response.status}: ${response.statusText}`; + let errorData = null; + if (response.headers.get("content-type")?.includes("application/json")) { + try { + errorData = await response.json(); + message = errorData.error || message; + } catch (error) { + console.log("Failed to parse error response as JSON"); + } + } else { + try { + console.log("Getting text from response"); + const textResponse = await response.text(); + message = textResponse || message; + } catch (error) { + console.log("Failed to get text from error response"); + } + } + throw new ResponseError(message, response.status); + }; + readEnvVar = (obj, key) => { + return obj[key]; + }; + fetchWithHeaders = async (fetch3, url, options = {}) => { + const defaultHeaders = { + "Content-Type": "application/json", + Accept: "application/json", + "User-Agent": `ollama-js/${version} (${getPlatform()})` + }; + options.headers = normalizeHeaders(options.headers); + try { + const parsed = new URL(url); + if (parsed.protocol === "https:" && parsed.hostname === "ollama.com") { + const apiKey = typeof process === "object" && process !== null && typeof process.env === "object" && process.env !== null ? readEnvVar(process.env, "OLLAMA_API_KEY") : void 0; + const authorization = options.headers["authorization"] || options.headers["Authorization"]; + if (!authorization && apiKey) { + options.headers["Authorization"] = `Bearer ${apiKey}`; + } + } + } catch (error) { + console.error("error parsing url", error); + } + const customHeaders = Object.fromEntries( + Object.entries(options.headers).filter( + ([key]) => !Object.keys(defaultHeaders).some( + (defaultKey) => defaultKey.toLowerCase() === key.toLowerCase() + ) + ) + ); + options.headers = { + ...defaultHeaders, + ...customHeaders + }; + return fetch3(url, options); + }; + get2 = async (fetch3, host, options) => { + const response = await fetchWithHeaders(fetch3, host, { + headers: options?.headers + }); + await checkOk(response); + return response; + }; + post = async (fetch3, host, data, options) => { + const isRecord = (input) => { + return input !== null && typeof input === "object" && !Array.isArray(input); + }; + const formattedData = isRecord(data) ? JSON.stringify(data) : data; + const response = await fetchWithHeaders(fetch3, host, { + method: "POST", + body: formattedData, + signal: options?.signal, + headers: options?.headers + }); + await checkOk(response); + return response; + }; + del = async (fetch3, host, data, options) => { + const response = await fetchWithHeaders(fetch3, host, { + method: "DELETE", + body: JSON.stringify(data), + headers: options?.headers + }); + await checkOk(response); + return response; + }; + parseJSON2 = async function* (itr) { + const decoder = new TextDecoder("utf-8"); + let buffer = ""; + const reader = itr.getReader(); + while (true) { + const { done, value: chunk } = await reader.read(); + if (done) { + break; + } + buffer += decoder.decode(chunk, { stream: true }); + const parts = buffer.split("\n"); + buffer = parts.pop() ?? ""; + for (const part of parts) { + try { + yield JSON.parse(part); + } catch (error) { + console.warn("invalid json: ", part); + } + } + } + buffer += decoder.decode(); + for (const part of buffer.split("\n").filter((p4) => p4 !== "")) { + try { + yield JSON.parse(part); + } catch (error) { + console.warn("invalid json: ", part); + } + } + }; + formatHost = (host) => { + if (!host) { + return defaultHost; + } + let isExplicitProtocol = host.includes("://"); + if (host.startsWith(":")) { + host = `http://127.0.0.1${host}`; + isExplicitProtocol = true; + } + if (!isExplicitProtocol) { + host = `http://${host}`; + } + const url = new URL(host); + let port2 = url.port; + if (!port2) { + if (!isExplicitProtocol) { + port2 = defaultPort; + } else { + port2 = url.protocol === "https:" ? "443" : "80"; + } + } + let auth = ""; + if (url.username) { + auth = url.username; + if (url.password) { + auth += `:${url.password}`; + } + auth += "@"; + } + let formattedHost = `${url.protocol}//${auth}${url.hostname}:${port2}${url.pathname}`; + if (formattedHost.endsWith("/")) { + formattedHost = formattedHost.slice(0, -1); + } + return formattedHost; + }; + __defProp2 = Object.defineProperty; + __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; + __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; + }; + Ollama$1 = class Ollama { + constructor(config) { + __publicField(this, "config"); + __publicField(this, "fetch"); + __publicField(this, "ongoingStreamedRequests", []); + this.config = { + host: "", + headers: config?.headers + }; + if (!config?.proxy) { + this.config.host = formatHost(config?.host ?? defaultHost); + } + this.fetch = config?.fetch ?? fetch; + } + // Abort any ongoing streamed requests to Ollama + abort() { + for (const request of this.ongoingStreamedRequests) { + request.abort(); + } + this.ongoingStreamedRequests.length = 0; + } + /** + * Processes a request to the Ollama server. If the request is streamable, it will return a + * AbortableAsyncIterator that yields the response messages. Otherwise, it will return the response + * object. + * @param endpoint {string} - The endpoint to send the request to. + * @param request {object} - The request object to send to the endpoint. + * @protected {T | AbortableAsyncIterator} - The response object or a AbortableAsyncIterator that yields + * response messages. + * @throws {Error} - If the response body is missing or if the response is an error. + * @returns {Promise>} - The response object or a AbortableAsyncIterator that yields the streamed response. + */ + async processStreamableRequest(endpoint, request) { + request.stream = request.stream ?? false; + const host = `${this.config.host}/api/${endpoint}`; + if (request.stream) { + const abortController = new AbortController(); + const response2 = await post(this.fetch, host, request, { + signal: abortController.signal, + headers: this.config.headers + }); + if (!response2.body) { + throw new Error("Missing body"); + } + const itr = parseJSON2(response2.body); + const abortableAsyncIterator = new AbortableAsyncIterator( + abortController, + itr, + () => { + const i7 = this.ongoingStreamedRequests.indexOf(abortableAsyncIterator); + if (i7 > -1) { + this.ongoingStreamedRequests.splice(i7, 1); + } + } + ); + this.ongoingStreamedRequests.push(abortableAsyncIterator); + return abortableAsyncIterator; + } + const response = await post(this.fetch, host, request, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Encodes an image to base64 if it is a Uint8Array. + * @param image {Uint8Array | string} - The image to encode. + * @returns {Promise} - The base64 encoded image. + */ + async encodeImage(image) { + if (typeof image !== "string") { + const uint8Array = new Uint8Array(image); + let byteString = ""; + const len = uint8Array.byteLength; + for (let i7 = 0; i7 < len; i7++) { + byteString += String.fromCharCode(uint8Array[i7]); + } + return btoa(byteString); + } + return image; + } + /** + * Generates a response from a text prompt. + * @param request {GenerateRequest} - The request object. + * @returns {Promise>} - The response object or + * an AbortableAsyncIterator that yields response messages. + */ + async generate(request) { + if (request.images) { + request.images = await Promise.all(request.images.map(this.encodeImage.bind(this))); + } + return this.processStreamableRequest("generate", request); + } + /** + * Chats with the model. The request object can contain messages with images that are either + * Uint8Arrays or base64 encoded strings. The images will be base64 encoded before sending the + * request. + * @param request {ChatRequest} - The request object. + * @returns {Promise>} - The response object or an + * AbortableAsyncIterator that yields response messages. + */ + async chat(request) { + if (request.messages) { + for (const message of request.messages) { + if (message.images) { + message.images = await Promise.all( + message.images.map(this.encodeImage.bind(this)) + ); + } + } + } + return this.processStreamableRequest("chat", request); + } + /** + * Creates a new model from a stream of data. + * @param request {CreateRequest} - The request object. + * @returns {Promise>} - The response object or a stream of progress responses. + */ + async create(request) { + return this.processStreamableRequest("create", { + ...request + }); + } + /** + * Pulls a model from the Ollama registry. The request object can contain a stream flag to indicate if the + * response should be streamed. + * @param request {PullRequest} - The request object. + * @returns {Promise>} - The response object or + * an AbortableAsyncIterator that yields response messages. + */ + async pull(request) { + return this.processStreamableRequest("pull", { + name: request.model, + stream: request.stream, + insecure: request.insecure + }); + } + /** + * Pushes a model to the Ollama registry. The request object can contain a stream flag to indicate if the + * response should be streamed. + * @param request {PushRequest} - The request object. + * @returns {Promise>} - The response object or + * an AbortableAsyncIterator that yields response messages. + */ + async push(request) { + return this.processStreamableRequest("push", { + name: request.model, + stream: request.stream, + insecure: request.insecure + }); + } + /** + * Deletes a model from the server. The request object should contain the name of the model to + * delete. + * @param request {DeleteRequest} - The request object. + * @returns {Promise} - The response object. + */ + async delete(request) { + await del( + this.fetch, + `${this.config.host}/api/delete`, + { name: request.model }, + { headers: this.config.headers } + ); + return { status: "success" }; + } + /** + * Copies a model from one name to another. The request object should contain the name of the + * model to copy and the new name. + * @param request {CopyRequest} - The request object. + * @returns {Promise} - The response object. + */ + async copy(request) { + await post(this.fetch, `${this.config.host}/api/copy`, { ...request }, { + headers: this.config.headers + }); + return { status: "success" }; + } + /** + * Lists the models on the server. + * @returns {Promise} - The response object. + * @throws {Error} - If the response body is missing. + */ + async list() { + const response = await get2(this.fetch, `${this.config.host}/api/tags`, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Shows the metadata of a model. The request object should contain the name of the model. + * @param request {ShowRequest} - The request object. + * @returns {Promise} - The response object. + */ + async show(request) { + const response = await post(this.fetch, `${this.config.host}/api/show`, { + ...request + }, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Embeds text input into vectors. + * @param request {EmbedRequest} - The request object. + * @returns {Promise} - The response object. + */ + async embed(request) { + const response = await post(this.fetch, `${this.config.host}/api/embed`, { + ...request + }, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Embeds a text prompt into a vector. + * @param request {EmbeddingsRequest} - The request object. + * @returns {Promise} - The response object. + */ + async embeddings(request) { + const response = await post(this.fetch, `${this.config.host}/api/embeddings`, { + ...request + }, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Lists the running models on the server + * @returns {Promise} - The response object. + * @throws {Error} - If the response body is missing. + */ + async ps() { + const response = await get2(this.fetch, `${this.config.host}/api/ps`, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Returns the Ollama server version. + * @returns {Promise} - The server version object. + */ + async version() { + const response = await get2(this.fetch, `${this.config.host}/api/version`, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Performs web search using the Ollama web search API + * @param request {WebSearchRequest} - The search request containing query and options + * @returns {Promise} - The search results + * @throws {Error} - If the request is invalid or the server returns an error + */ + async webSearch(request) { + if (!request.query || request.query.length === 0) { + throw new Error("Query is required"); + } + const response = await post(this.fetch, `https://ollama.com/api/web_search`, { ...request }, { + headers: this.config.headers + }); + return await response.json(); + } + /** + * Fetches a single page using the Ollama web fetch API + * @param request {WebFetchRequest} - The fetch request containing a URL + * @returns {Promise} - The fetch result + * @throws {Error} - If the request is invalid or the server returns an error + */ + async webFetch(request) { + if (!request.url || request.url.length === 0) { + throw new Error("URL is required"); + } + const response = await post(this.fetch, `https://ollama.com/api/web_fetch`, { ...request }, { headers: this.config.headers }); + return await response.json(); + } + }; + browser = new Ollama$1(); + } +}); + +// ../pi-mono/packages/web-ui/dist/utils/model-discovery.js +async function discoverOllamaModels(baseUrl, _apiKey) { + try { + const ollama = new Ollama$1({ host: baseUrl }); + const { models } = await ollama.list(); + const ollamaModelPromises = models.map(async (model) => { + try { + const details = await ollama.show({ + model: model.name + }); + const capabilities = details.capabilities || []; + if (!capabilities.includes("tools")) { + console.debug(`Skipping model ${model.name}: does not support tools`); + return null; + } + const modelInfo = details.model_info || {}; + const architecture = modelInfo["general.architecture"] || ""; + const contextKey = `${architecture}.context_length`; + const contextWindow = parseInt(modelInfo[contextKey] || "8192", 10); + const maxTokens = contextWindow * 10; + const ollamaModel = { + id: model.name, + name: model.name, + api: "openai-completions", + provider: "", + // Will be set by caller + baseUrl: `${baseUrl}/v1`, + reasoning: capabilities.includes("thinking"), + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow, + maxTokens + }; + return ollamaModel; + } catch (err) { + console.error(`Failed to fetch details for model ${model.name}:`, err); + return null; + } + }); + const results = await Promise.all(ollamaModelPromises); + return results.filter((m4) => m4 !== null); + } catch (err) { + console.error("Failed to discover Ollama models:", err); + throw new Error(`Ollama discovery failed: ${err instanceof Error ? err.message : String(err)}`); + } +} +async function discoverLlamaCppModels(baseUrl, apiKey) { + try { + const headers = { + "Content-Type": "application/json" + }; + if (apiKey) { + headers.Authorization = `Bearer ${apiKey}`; + } + const response = await fetch(`${baseUrl}/v1/models`, { + method: "GET", + headers + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + const data = await response.json(); + if (!data.data || !Array.isArray(data.data)) { + throw new Error("Invalid response format from llama.cpp server"); + } + return data.data.map((model) => { + const contextWindow = model.context_length || 8192; + const maxTokens = model.max_tokens || 4096; + const llamaModel = { + id: model.id, + name: model.id, + api: "openai-completions", + provider: "", + // Will be set by caller + baseUrl: `${baseUrl}/v1`, + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow, + maxTokens + }; + return llamaModel; + }); + } catch (err) { + console.error("Failed to discover llama.cpp models:", err); + throw new Error(`llama.cpp discovery failed: ${err instanceof Error ? err.message : String(err)}`); + } +} +async function discoverVLLMModels(baseUrl, apiKey) { + try { + const headers = { + "Content-Type": "application/json" + }; + if (apiKey) { + headers.Authorization = `Bearer ${apiKey}`; + } + const response = await fetch(`${baseUrl}/v1/models`, { + method: "GET", + headers + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + const data = await response.json(); + if (!data.data || !Array.isArray(data.data)) { + throw new Error("Invalid response format from vLLM server"); + } + return data.data.map((model) => { + const contextWindow = model.max_model_len || 8192; + const maxTokens = Math.min(contextWindow, 4096); + const vllmModel = { + id: model.id, + name: model.id, + api: "openai-completions", + provider: "", + // Will be set by caller + baseUrl: `${baseUrl}/v1`, + reasoning: false, + input: ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow, + maxTokens + }; + return vllmModel; + }); + } catch (err) { + console.error("Failed to discover vLLM models:", err); + throw new Error(`vLLM discovery failed: ${err instanceof Error ? err.message : String(err)}`); + } +} +async function discoverLMStudioModels(baseUrl, _apiKey) { + try { + const url = new URL(baseUrl); + const port2 = url.port ? parseInt(url.port, 10) : 1234; + const client = new LMStudioClient({ baseUrl: `ws://${url.hostname}:${port2}` }); + const models = await client.system.listDownloadedModels(); + return models.filter((model) => model.type === "llm").map((model) => { + const contextWindow = model.maxContextLength; + const maxTokens = contextWindow; + const lmStudioModel = { + id: model.path, + name: model.displayName || model.path, + api: "openai-completions", + provider: "", + // Will be set by caller + baseUrl: `${baseUrl}/v1`, + reasoning: model.trainedForToolUse || false, + input: model.vision ? ["text", "image"] : ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow, + maxTokens + }; + return lmStudioModel; + }); + } catch (err) { + console.error("Failed to discover LM Studio models:", err); + throw new Error(`LM Studio discovery failed: ${err instanceof Error ? err.message : String(err)}`); + } +} +function isAutoDiscoveryProviderType(type) { + return type === "ollama" || type === "llama.cpp" || type === "vllm" || type === "lmstudio" || type === "openai-compatible"; +} +function normalizeOpenAICompatibleBaseUrl(baseUrl) { + const trimmed = baseUrl.replace(/\/+$/, ""); + return trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`; +} +async function discoverOpenAICompatibleModels(baseUrl, apiKey) { + try { + const resolvedBaseUrl = normalizeOpenAICompatibleBaseUrl(baseUrl); + console.debug("[OpenAI-Compatible Discovery] Starting discovery", { + inputBaseUrl: baseUrl, + resolvedBaseUrl, + hasApiKey: !!apiKey + }); + const headers = { + "Content-Type": "application/json" + }; + if (apiKey) { + headers.Authorization = `Bearer ${apiKey}`; + } + const response = await fetch(`${resolvedBaseUrl}/models`, { + method: "GET", + headers + }); + console.debug("[OpenAI-Compatible Discovery] Response received", { + resolvedBaseUrl, + status: response.status, + ok: response.ok + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + const data = await response.json(); + console.debug("[OpenAI-Compatible Discovery] Payload shape", { + resolvedBaseUrl, + hasDataArray: Array.isArray(data?.data), + modelCount: Array.isArray(data?.data) ? data.data.length : 0, + firstModelId: Array.isArray(data?.data) && data.data.length > 0 ? data.data[0]?.id : null + }); + if (!data.data || !Array.isArray(data.data)) { + throw new Error("Invalid response format from OpenAI-compatible server"); + } + return data.data.map((model) => { + const contextWindow = model.context_length || model.context_window || model.max_context_length || model.max_model_len || 8192; + const maxTokens = model.max_output_tokens || model.max_completion_tokens || Math.min(contextWindow, 4096); + const supportsVision = Array.isArray(model.input_modalities) && model.input_modalities.includes("image") || Array.isArray(model.modalities) && model.modalities.includes("image"); + const reasoning = model.reasoning === true || model.supports_reasoning === true || Array.isArray(model.capabilities) && (model.capabilities.includes("reasoning") || model.capabilities.includes("thinking")); + return { + id: model.id, + name: model.name || model.id, + api: "openai-completions", + provider: "", + // Will be set by caller + baseUrl: resolvedBaseUrl, + reasoning, + input: supportsVision ? ["text", "image"] : ["text"], + cost: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0 + }, + contextWindow, + maxTokens + }; + }); + } catch (err) { + console.error("Failed to discover OpenAI-compatible models:", err); + throw new Error(`OpenAI-compatible discovery failed: ${err instanceof Error ? err.message : String(err)}`); + } +} +async function discoverModels(type, baseUrl, apiKey) { + switch (type) { + case "ollama": + return discoverOllamaModels(baseUrl, apiKey); + case "llama.cpp": + return discoverLlamaCppModels(baseUrl, apiKey); + case "vllm": + return discoverVLLMModels(baseUrl, apiKey); + case "lmstudio": + return discoverLMStudioModels(baseUrl, apiKey); + case "openai-compatible": + return discoverOpenAICompatibleModels(baseUrl, apiKey); + } +} +function parsePositiveInteger(value) { + if (value === null || value === void 0 || value === "") { + return void 0; + } + const parsed = Number(value); + if (!Number.isFinite(parsed) || parsed <= 0) { + return void 0; + } + return Math.round(parsed); +} +function normalizeModelInputs(input) { + const normalized = Array.isArray(input) ? Array.from(new Set(input.filter((item) => typeof item === "string" && item.length > 0))) : []; + if (!normalized.includes("text")) { + normalized.unshift("text"); + } + return normalized; +} +function getCustomProviderModelOverride(provider, modelId) { + if (!provider?.modelOverrides || !modelId) { + return {}; + } + return provider.modelOverrides[modelId] || {}; +} +function applyCustomProviderModelOverrides(provider, model) { + if (!provider || !model) { + return model; + } + const override = getCustomProviderModelOverride(provider, model.id); + const effectiveProvider = provider.name || model.provider || provider.type; + const input = normalizeModelInputs(model.input); + const overrideVision = typeof override.visionCapable === "boolean" ? override.visionCapable : void 0; + const supportsVision = overrideVision ?? input.includes("image"); + const effectiveInput = supportsVision ? input.includes("image") ? input : [...input, "image"] : input.filter((item) => item !== "image"); + const contextWindow = parsePositiveInteger(override.contextWindow) ?? parsePositiveInteger(model.contextWindow) ?? 8192; + let maxTokens = parsePositiveInteger(override.maxTokens) ?? parsePositiveInteger(model.maxTokens) ?? Math.min(contextWindow, 4096); + maxTokens = Math.min(maxTokens, contextWindow); + return { + ...model, + provider: effectiveProvider, + input: effectiveInput, + contextWindow, + maxTokens, + customProviderId: provider.id + }; +} +function applyCustomProviderModels(provider, models) { + return (models || []).map((model) => applyCustomProviderModelOverrides(provider, { + ...model, + provider: provider.name || model.provider || provider.type + })); +} +function resolveCustomProviderStoredModel(model, customProviders) { + if (!model || !Array.isArray(customProviders) || customProviders.length === 0) { + return model; + } + const provider = customProviders.find((entry) => model.customProviderId ? entry.id === model.customProviderId : entry.name === model.provider); + if (!provider) { + return model; + } + const storedModel = (provider.models || []).find((entry) => entry.id === model.id); + if (!storedModel) { + return { + ...model, + provider: provider.name || model.provider, + customProviderId: provider.id + }; + } + return applyCustomProviderModelOverrides(provider, storedModel); +} +var init_model_discovery = __esm({ + "../pi-mono/packages/web-ui/dist/utils/model-discovery.js"() { + "use strict"; + init_process_shim(); + init_dist3(); + init_browser(); + } +}); + +// ../pi-mono/packages/web-ui/dist/dialogs/ModelSelector.js +function subsequenceScore(query, text3) { + let qi = 0; + let ti = 0; + let gaps = 0; + let lastMatchIndex = -1; + while (qi < query.length && ti < text3.length) { + if (query[qi] === text3[ti]) { + if (lastMatchIndex >= 0) { + gaps += ti - lastMatchIndex - 1; + } + lastMatchIndex = ti; + qi++; + } + ti++; + } + if (qi < query.length) + return 0; + return query.length / (query.length + gaps); +} +var __decorate2, ModelSelector_1, ModelSelector; +var init_ModelSelector = __esm({ + "../pi-mono/packages/web-ui/dist/dialogs/ModelSelector.js"() { + "use strict"; + init_process_shim(); + init_dist(); + init_Badge(); + init_Button(); + init_Dialog(); + init_DialogBase(); + init_dist2(); + init_lit(); + init_decorators(); + init_ref2(); + init_lucide2(); + init_Input2(); + init_app_storage(); + init_format2(); + init_i18n2(); + init_model_discovery(); + __decorate2 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + ModelSelector = ModelSelector_1 = class ModelSelector2 extends DialogBase { + constructor() { + super(...arguments); + this.currentModel = null; + this.searchQuery = ""; + this.filterThinking = false; + this.filterVision = false; + this.customProvidersLoading = false; + this.selectedIndex = 0; + this.navigationMode = "mouse"; + this.customProviderModels = []; + this.scrollContainerRef = e5(); + this.searchInputRef = e5(); + this.lastMousePosition = { x: 0, y: 0 }; + this.modalWidth = "min(400px, 90vw)"; + } + static async open(currentModel, onSelect, allowedProviders) { + const selector = new ModelSelector_1(); + selector.currentModel = currentModel; + selector.onSelectCallback = onSelect; + if (allowedProviders) { + selector.allowedProviders = new Set(allowedProviders); + } + selector.open(); + selector.loadCustomProviders(); + } + async firstUpdated(changedProperties) { + super.firstUpdated(changedProperties); + await this.updateComplete; + this.searchInputRef.value?.focus(); + this.addEventListener("mousemove", (e9) => { + if (e9.clientX !== this.lastMousePosition.x || e9.clientY !== this.lastMousePosition.y) { + this.lastMousePosition = { x: e9.clientX, y: e9.clientY }; + if (this.navigationMode === "keyboard") { + this.navigationMode = "mouse"; + const target = e9.target; + const modelItem = target.closest("[data-model-item]"); + if (modelItem) { + const allItems = this.scrollContainerRef.value?.querySelectorAll("[data-model-item]"); + if (allItems) { + const index2 = Array.from(allItems).indexOf(modelItem); + if (index2 !== -1) { + this.selectedIndex = index2; + } + } + } + } + } + }); + this.addEventListener("keydown", (e9) => { + const filteredModels = this.getFilteredModels(); + if (e9.key === "ArrowDown") { + e9.preventDefault(); + this.navigationMode = "keyboard"; + this.selectedIndex = Math.min(this.selectedIndex + 1, filteredModels.length - 1); + this.scrollToSelected(); + } else if (e9.key === "ArrowUp") { + e9.preventDefault(); + this.navigationMode = "keyboard"; + this.selectedIndex = Math.max(this.selectedIndex - 1, 0); + this.scrollToSelected(); + } else if (e9.key === "Enter") { + e9.preventDefault(); + if (filteredModels[this.selectedIndex]) { + this.handleSelect(filteredModels[this.selectedIndex].model); + } + } + }); + } + async loadCustomProviders() { + this.customProvidersLoading = true; + const allCustomModels = []; + try { + const storage2 = getAppStorage(); + const customProviders = await storage2.customProviders.getAll(); + for (const provider of customProviders) { + const isAutoDiscovery = isAutoDiscoveryProviderType(provider.type); + if (isAutoDiscovery) { + try { + const models = await discoverModels(provider.type, provider.baseUrl, provider.apiKey); + const modelsWithProvider = applyCustomProviderModels(provider, models.map((model) => ({ + ...model, + provider: provider.name + }))); + allCustomModels.push(...modelsWithProvider); + } catch (error) { + console.debug(`Failed to load models from ${provider.name}:`, error); + } + } else if (provider.models) { + allCustomModels.push(...applyCustomProviderModels(provider, provider.models)); + } + } + } catch (error) { + console.error("Failed to load custom providers:", error); + } finally { + this.customProviderModels = allCustomModels; + this.customProvidersLoading = false; + this.requestUpdate(); + } + } + formatTokens(tokens) { + if (tokens >= 1e6) + return `${(tokens / 1e6).toFixed(0)}M`; + if (tokens >= 1e3) + return `${(tokens / 1e3).toFixed(0)}`; + return String(tokens); + } + handleSelect(model) { + if (model) { + this.onSelectCallback?.(model); + this.close(); + } + } + getFilteredModels() { + const allModels = []; + const knownProviders = getProviders(); + for (const provider of knownProviders) { + const models = getModels(provider); + for (const model of models) { + allModels.push({ provider, id: model.id, model }); + } + } + for (const model of this.customProviderModels) { + allModels.push({ provider: model.provider, id: model.id, model }); + } + if (this.allowedProviders) { + const allowed = this.allowedProviders; + allModels.splice(0, allModels.length, ...allModels.filter(({ provider }) => allowed.has(provider))); + } + let filteredModels = allModels; + if (this.searchQuery) { + const query = this.searchQuery.toLowerCase().replace(/\s+/g, ""); + if (query) { + const scored = []; + for (const entry of filteredModels) { + const searchText = `${entry.provider} ${entry.id} ${entry.model.name}`.toLowerCase(); + const score = subsequenceScore(query, searchText); + if (score > 0) { + scored.push({ item: entry, score }); + } + } + scored.sort((a3, b4) => b4.score - a3.score); + filteredModels = scored.map((s6) => s6.item); + } + } + if (this.filterThinking) { + filteredModels = filteredModels.filter(({ model }) => model.reasoning); + } + if (this.filterVision) { + filteredModels = filteredModels.filter(({ model }) => model.input.includes("image")); + } + if (!this.searchQuery) { + filteredModels.sort((a3, b4) => { + const aIsCurrent = modelsAreEqual(this.currentModel, a3.model); + const bIsCurrent = modelsAreEqual(this.currentModel, b4.model); + if (aIsCurrent && !bIsCurrent) + return -1; + if (!aIsCurrent && bIsCurrent) + return 1; + return a3.provider.localeCompare(b4.provider); + }); + } + return filteredModels; + } + scrollToSelected() { + requestAnimationFrame(() => { + const scrollContainer = this.scrollContainerRef.value; + const selectedElement = scrollContainer?.querySelectorAll("[data-model-item]")[this.selectedIndex]; + if (selectedElement) { + selectedElement.scrollIntoView({ block: "nearest", behavior: "smooth" }); + } + }); + } + renderContent() { + const filteredModels = this.getFilteredModels(); + return b2` + +
+ ${DialogHeader({ title: i18n("Select Model") })} + ${Input2({ + placeholder: i18n("Search models..."), + value: this.searchQuery, + inputRef: this.searchInputRef, + onInput: (e9) => { + this.searchQuery = e9.target.value; + this.selectedIndex = 0; + if (this.scrollContainerRef.value) { + this.scrollContainerRef.value.scrollTop = 0; + } + } + })} +
+ ${Button({ + variant: this.filterThinking ? "default" : "secondary", + size: "sm", + onClick: () => { + this.filterThinking = !this.filterThinking; + this.selectedIndex = 0; + if (this.scrollContainerRef.value) { + this.scrollContainerRef.value.scrollTop = 0; + } + }, + className: "rounded-full", + children: b2`${icon(Brain, "sm")} ${i18n("Thinking")}` + })} + ${Button({ + variant: this.filterVision ? "default" : "secondary", + size: "sm", + onClick: () => { + this.filterVision = !this.filterVision; + this.selectedIndex = 0; + if (this.scrollContainerRef.value) { + this.scrollContainerRef.value.scrollTop = 0; + } + }, + className: "rounded-full", + children: b2`${icon(Image2, "sm")} ${i18n("Vision")}` + })} +
+
+ + +
+ ${filteredModels.map(({ provider, id, model }, index2) => { + const isCurrent = modelsAreEqual(this.currentModel, model); + const isSelected = index2 === this.selectedIndex; + return b2` +
this.handleSelect(model)} + @mouseenter=${() => { + if (this.navigationMode === "mouse") { + this.selectedIndex = index2; + } + }} + > +
+
+ ${id} + ${isCurrent ? b2`` : ""} +
+ ${Badge(provider, "outline")} +
+
+
+ ${icon(Brain, "sm")} + ${icon(Image2, "sm")} + ${this.formatTokens(model.contextWindow)}K/${this.formatTokens(model.maxTokens)}K +
+ ${formatModelCost(model.cost)} +
+
+ `; + })} +
+ `; + } + }; + __decorate2([ + r7() + ], ModelSelector.prototype, "currentModel", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "searchQuery", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "filterThinking", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "filterVision", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "customProvidersLoading", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "selectedIndex", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "navigationMode", void 0); + __decorate2([ + r7() + ], ModelSelector.prototype, "customProviderModels", void 0); + ModelSelector = ModelSelector_1 = __decorate2([ + t5("agent-model-selector") + ], ModelSelector); + } +}); + +// ../mini-lit/dist/Select.js +function Select(props) { + const { value, placeholder = i18n("Select an option"), options, onChange, disabled = false, className = "", width = "180px", size = "md", variant = "default", fitContent = false } = props; + const triggerRef = e5(); + const state = { + isOpen: false, + focusedIndex: -1 + }; + const sizeClasses2 = { + sm: "h-8 px-2 text-xs", + md: "h-9 px-3 text-sm", + lg: "h-10 px-4 text-base" + }; + const variantClasses = { + default: "text-foreground border-input bg-transparent hover:bg-accent/50 shadow-xs", + ghost: "text-foreground border-transparent bg-transparent hover:bg-accent hover:text-accent-foreground", + outline: "text-foreground border-input bg-transparent hover:bg-accent hover:text-accent-foreground" + }; + const flatOptions = []; + const isGrouped = options.length > 0 && "options" in options[0]; + if (isGrouped) { + options.forEach((group) => { + flatOptions.push(...group.options.filter((opt) => !opt.disabled)); + }); + } else { + flatOptions.push(...options.filter((opt) => !opt.disabled)); + } + const selectedOption = flatOptions.find((opt) => opt.value === value); + let portalContainer = null; + const ensurePortalContainer = () => { + if (!portalContainer) { + portalContainer = document.createElement("div"); + portalContainer.className = "select-portal-container"; + portalContainer.style.cssText = "position: fixed; z-index: 50; pointer-events: none;"; + document.body.appendChild(portalContainer); + } + return portalContainer; + }; + const updatePosition = () => { + if (!triggerRef.value || !portalContainer) + return; + const rect = triggerRef.value.getBoundingClientRect(); + state.triggerRect = rect; + const spaceBelow = window.innerHeight - rect.bottom; + const spaceAbove = rect.top; + const dropdownHeight = 300; + const showAbove = spaceBelow < dropdownHeight && spaceAbove > spaceBelow; + portalContainer.style.cssText = ` + position: fixed; + left: ${rect.left}px; + ${showAbove ? `bottom: ${window.innerHeight - rect.top}px` : `top: ${rect.bottom}px`}; + min-width: ${rect.width}px; + width: max-content; + z-index: 50; + pointer-events: ${state.isOpen ? "auto" : "none"}; + `; + }; + const open2 = () => { + if (disabled || state.isOpen) + return; + if (activeSelect && activeSelect !== api) { + activeSelect.close(); + } + state.isOpen = true; + state.focusedIndex = selectedOption ? flatOptions.indexOf(selectedOption) : 0; + ensurePortalContainer(); + updatePosition(); + renderPortal(); + setTimeout(() => { + document.addEventListener("click", handleOutsideClick); + document.addEventListener("keydown", handleKeyDown); + window.addEventListener("scroll", updatePosition, true); + window.addEventListener("resize", updatePosition); + }, 0); + activeSelect = api; + if (triggerRef.value) { + triggerRef.value.setAttribute("aria-expanded", "true"); + } + }; + const close2 = () => { + if (!state.isOpen) + return; + state.isOpen = false; + state.focusedIndex = -1; + document.removeEventListener("click", handleOutsideClick); + document.removeEventListener("keydown", handleKeyDown); + window.removeEventListener("scroll", updatePosition, true); + window.removeEventListener("resize", updatePosition); + if (portalContainer) { + D(b2``, portalContainer); + } + if (activeSelect === api) { + activeSelect = null; + } + if (triggerRef.value) { + triggerRef.value.setAttribute("aria-expanded", "false"); + triggerRef.value.focus(); + } + }; + const handleOutsideClick = (e9) => { + const target = e9.target; + if (triggerRef.value?.contains(target) || portalContainer?.contains(target)) { + return; + } + close2(); + }; + const handleKeyDown = (e9) => { + if (!state.isOpen) + return; + switch (e9.key) { + case "Escape": + e9.preventDefault(); + close2(); + break; + case "ArrowDown": + e9.preventDefault(); + state.focusedIndex = Math.min(state.focusedIndex + 1, flatOptions.length - 1); + renderPortal(); + break; + case "ArrowUp": + e9.preventDefault(); + state.focusedIndex = Math.max(state.focusedIndex - 1, 0); + renderPortal(); + break; + case "Enter": + case " ": + e9.preventDefault(); + if (state.focusedIndex >= 0 && state.focusedIndex < flatOptions.length) { + selectOption(flatOptions[state.focusedIndex].value); + } + break; + case "Home": + e9.preventDefault(); + state.focusedIndex = 0; + renderPortal(); + break; + case "End": + e9.preventDefault(); + state.focusedIndex = flatOptions.length - 1; + renderPortal(); + break; + } + }; + const selectOption = (optionValue) => { + onChange(optionValue); + close2(); + }; + const renderPortal = () => { + if (!portalContainer || !state.isOpen) + return; + const dropdownContent = b2` +
+
+ ${isGrouped ? options.map((group, _groupIndex) => b2` +
+ ${group.label ? b2` +
+ ${group.label} +
+ ` : ""} + ${group.options.map((option, _optionIndex) => { + const globalIndex = flatOptions.indexOf(option); + const isFocused = globalIndex === state.focusedIndex; + const isSelected = option.value === value; + return b2` +
selectOption(option.value)} + @mouseenter=${() => { + if (!option.disabled) { + state.focusedIndex = globalIndex; + renderPortal(); + } + }} + > + + ${isSelected ? b2` + + + + ` : ""} + + ${option.icon ? b2`${option.icon}` : ""} + ${option.label} +
+ `; + })} +
+ `) : options.map((option, index2) => { + const isFocused = index2 === state.focusedIndex; + const isSelected = option.value === value; + return b2` +
selectOption(option.value)} + @mouseenter=${() => { + if (!option.disabled) { + state.focusedIndex = index2; + renderPortal(); + } + }} + > + + ${isSelected ? b2` + + + + ` : ""} + + ${option.icon ? b2`${option.icon}` : ""} + ${option.label} +
+ `; + })} +
+
+ `; + D(dropdownContent, portalContainer); + }; + const api = { close: close2 }; + const handleTriggerClick = (e9) => { + e9.preventDefault(); + e9.stopPropagation(); + if (state.isOpen) { + close2(); + } else { + open2(); + } + }; + const buttonWidth = fitContent ? "auto" : width; + const minWidth = fitContent ? width || "auto" : void 0; + return b2` + + `; +} +var activeSelect; +var init_Select = __esm({ + "../mini-lit/dist/Select.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_ref2(); + init_i18n(); + activeSelect = null; + } +}); + +// ../pi-mono/node_modules/jszip/dist/jszip.min.js +var require_jszip_min = __commonJS({ + "../pi-mono/node_modules/jszip/dist/jszip.min.js"(exports, module) { + init_process_shim(); + !(function(e9) { + if ("object" == typeof exports && "undefined" != typeof module) module.exports = e9(); + else if ("function" == typeof define && define.amd) define([], e9); + else { + ("undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : this).JSZip = e9(); + } + })(function() { + return (function s6(a3, o9, h7) { + function u5(r8, e10) { + if (!o9[r8]) { + if (!a3[r8]) { + var t6 = "function" == typeof __require && __require; + if (!e10 && t6) return t6(r8, true); + if (l5) return l5(r8, true); + var n7 = new Error("Cannot find module '" + r8 + "'"); + throw n7.code = "MODULE_NOT_FOUND", n7; + } + var i7 = o9[r8] = { exports: {} }; + a3[r8][0].call(i7.exports, function(e11) { + var t7 = a3[r8][1][e11]; + return u5(t7 || e11); + }, i7, i7.exports, s6, a3, o9, h7); + } + return o9[r8].exports; + } + for (var l5 = "function" == typeof __require && __require, e9 = 0; e9 < h7.length; e9++) u5(h7[e9]); + return u5; + })({ 1: [function(e9, t6, r8) { + "use strict"; + var d4 = e9("./utils"), c6 = e9("./support"), p4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + r8.encode = function(e10) { + for (var t7, r9, n7, i7, s6, a3, o9, h7 = [], u5 = 0, l5 = e10.length, f4 = l5, c7 = "string" !== d4.getTypeOf(e10); u5 < e10.length; ) f4 = l5 - u5, n7 = c7 ? (t7 = e10[u5++], r9 = u5 < l5 ? e10[u5++] : 0, u5 < l5 ? e10[u5++] : 0) : (t7 = e10.charCodeAt(u5++), r9 = u5 < l5 ? e10.charCodeAt(u5++) : 0, u5 < l5 ? e10.charCodeAt(u5++) : 0), i7 = t7 >> 2, s6 = (3 & t7) << 4 | r9 >> 4, a3 = 1 < f4 ? (15 & r9) << 2 | n7 >> 6 : 64, o9 = 2 < f4 ? 63 & n7 : 64, h7.push(p4.charAt(i7) + p4.charAt(s6) + p4.charAt(a3) + p4.charAt(o9)); + return h7.join(""); + }, r8.decode = function(e10) { + var t7, r9, n7, i7, s6, a3, o9 = 0, h7 = 0, u5 = "data:"; + if (e10.substr(0, u5.length) === u5) throw new Error("Invalid base64 input, it looks like a data url."); + var l5, f4 = 3 * (e10 = e10.replace(/[^A-Za-z0-9+/=]/g, "")).length / 4; + if (e10.charAt(e10.length - 1) === p4.charAt(64) && f4--, e10.charAt(e10.length - 2) === p4.charAt(64) && f4--, f4 % 1 != 0) throw new Error("Invalid base64 input, bad content length."); + for (l5 = c6.uint8array ? new Uint8Array(0 | f4) : new Array(0 | f4); o9 < e10.length; ) t7 = p4.indexOf(e10.charAt(o9++)) << 2 | (i7 = p4.indexOf(e10.charAt(o9++))) >> 4, r9 = (15 & i7) << 4 | (s6 = p4.indexOf(e10.charAt(o9++))) >> 2, n7 = (3 & s6) << 6 | (a3 = p4.indexOf(e10.charAt(o9++))), l5[h7++] = t7, 64 !== s6 && (l5[h7++] = r9), 64 !== a3 && (l5[h7++] = n7); + return l5; + }; + }, { "./support": 30, "./utils": 32 }], 2: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./external"), i7 = e9("./stream/DataWorker"), s6 = e9("./stream/Crc32Probe"), a3 = e9("./stream/DataLengthProbe"); + function o9(e10, t7, r9, n8, i8) { + this.compressedSize = e10, this.uncompressedSize = t7, this.crc32 = r9, this.compression = n8, this.compressedContent = i8; + } + o9.prototype = { getContentWorker: function() { + var e10 = new i7(n7.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a3("data_length")), t7 = this; + return e10.on("end", function() { + if (this.streamInfo.data_length !== t7.uncompressedSize) throw new Error("Bug : uncompressed data size mismatch"); + }), e10; + }, getCompressedWorker: function() { + return new i7(n7.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } }, o9.createWorkerFrom = function(e10, t7, r9) { + return e10.pipe(new s6()).pipe(new a3("uncompressedSize")).pipe(t7.compressWorker(r9)).pipe(new a3("compressedSize")).withStreamInfo("compression", t7); + }, t6.exports = o9; + }, { "./external": 6, "./stream/Crc32Probe": 25, "./stream/DataLengthProbe": 26, "./stream/DataWorker": 27 }], 3: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./stream/GenericWorker"); + r8.STORE = { magic: "\0\0", compressWorker: function() { + return new n7("STORE compression"); + }, uncompressWorker: function() { + return new n7("STORE decompression"); + } }, r8.DEFLATE = e9("./flate"); + }, { "./flate": 7, "./stream/GenericWorker": 28 }], 4: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./utils"); + var o9 = (function() { + for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) { + e10 = r9; + for (var n8 = 0; n8 < 8; n8++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1; + t7[r9] = e10; + } + return t7; + })(); + t6.exports = function(e10, t7) { + return void 0 !== e10 && e10.length ? "string" !== n7.getTypeOf(e10) ? (function(e11, t8, r9, n8) { + var i7 = o9, s6 = n8 + r9; + e11 ^= -1; + for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8[a3])]; + return -1 ^ e11; + })(0 | t7, e10, e10.length, 0) : (function(e11, t8, r9, n8) { + var i7 = o9, s6 = n8 + r9; + e11 ^= -1; + for (var a3 = n8; a3 < s6; a3++) e11 = e11 >>> 8 ^ i7[255 & (e11 ^ t8.charCodeAt(a3))]; + return -1 ^ e11; + })(0 | t7, e10, e10.length, 0) : 0; + }; + }, { "./utils": 32 }], 5: [function(e9, t6, r8) { + "use strict"; + r8.base64 = false, r8.binary = false, r8.dir = false, r8.createFolders = true, r8.date = null, r8.compression = null, r8.compressionOptions = null, r8.comment = null, r8.unixPermissions = null, r8.dosPermissions = null; + }, {}], 6: [function(e9, t6, r8) { + "use strict"; + var n7 = null; + n7 = "undefined" != typeof Promise ? Promise : e9("lie"), t6.exports = { Promise: n7 }; + }, { lie: 37 }], 7: [function(e9, t6, r8) { + "use strict"; + var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Uint32Array, i7 = e9("pako"), s6 = e9("./utils"), a3 = e9("./stream/GenericWorker"), o9 = n7 ? "uint8array" : "array"; + function h7(e10, t7) { + a3.call(this, "FlateWorker/" + e10), this._pako = null, this._pakoAction = e10, this._pakoOptions = t7, this.meta = {}; + } + r8.magic = "\b\0", s6.inherits(h7, a3), h7.prototype.processChunk = function(e10) { + this.meta = e10.meta, null === this._pako && this._createPako(), this._pako.push(s6.transformTo(o9, e10.data), false); + }, h7.prototype.flush = function() { + a3.prototype.flush.call(this), null === this._pako && this._createPako(), this._pako.push([], true); + }, h7.prototype.cleanUp = function() { + a3.prototype.cleanUp.call(this), this._pako = null; + }, h7.prototype._createPako = function() { + this._pako = new i7[this._pakoAction]({ raw: true, level: this._pakoOptions.level || -1 }); + var t7 = this; + this._pako.onData = function(e10) { + t7.push({ data: e10, meta: t7.meta }); + }; + }, r8.compressWorker = function(e10) { + return new h7("Deflate", e10); + }, r8.uncompressWorker = function() { + return new h7("Inflate", {}); + }; + }, { "./stream/GenericWorker": 28, "./utils": 32, pako: 38 }], 8: [function(e9, t6, r8) { + "use strict"; + function A2(e10, t7) { + var r9, n8 = ""; + for (r9 = 0; r9 < t7; r9++) n8 += String.fromCharCode(255 & e10), e10 >>>= 8; + return n8; + } + function n7(e10, t7, r9, n8, i8, s7) { + var a3, o9, h7 = e10.file, u5 = e10.compression, l5 = s7 !== O2.utf8encode, f4 = I3.transformTo("string", s7(h7.name)), c6 = I3.transformTo("string", O2.utf8encode(h7.name)), d4 = h7.comment, p4 = I3.transformTo("string", s7(d4)), m4 = I3.transformTo("string", O2.utf8encode(d4)), _3 = c6.length !== h7.name.length, g3 = m4.length !== d4.length, b4 = "", v4 = "", y4 = "", w3 = h7.dir, k2 = h7.date, x2 = { crc32: 0, compressedSize: 0, uncompressedSize: 0 }; + t7 && !r9 || (x2.crc32 = e10.crc32, x2.compressedSize = e10.compressedSize, x2.uncompressedSize = e10.uncompressedSize); + var S5 = 0; + t7 && (S5 |= 8), l5 || !_3 && !g3 || (S5 |= 2048); + var z3 = 0, C3 = 0; + w3 && (z3 |= 16), "UNIX" === i8 ? (C3 = 798, z3 |= (function(e11, t8) { + var r10 = e11; + return e11 || (r10 = t8 ? 16893 : 33204), (65535 & r10) << 16; + })(h7.unixPermissions, w3)) : (C3 = 20, z3 |= (function(e11) { + return 63 & (e11 || 0); + })(h7.dosPermissions)), a3 = k2.getUTCHours(), a3 <<= 6, a3 |= k2.getUTCMinutes(), a3 <<= 5, a3 |= k2.getUTCSeconds() / 2, o9 = k2.getUTCFullYear() - 1980, o9 <<= 4, o9 |= k2.getUTCMonth() + 1, o9 <<= 5, o9 |= k2.getUTCDate(), _3 && (v4 = A2(1, 1) + A2(B3(f4), 4) + c6, b4 += "up" + A2(v4.length, 2) + v4), g3 && (y4 = A2(1, 1) + A2(B3(p4), 4) + m4, b4 += "uc" + A2(y4.length, 2) + y4); + var E3 = ""; + return E3 += "\n\0", E3 += A2(S5, 2), E3 += u5.magic, E3 += A2(a3, 2), E3 += A2(o9, 2), E3 += A2(x2.crc32, 4), E3 += A2(x2.compressedSize, 4), E3 += A2(x2.uncompressedSize, 4), E3 += A2(f4.length, 2), E3 += A2(b4.length, 2), { fileRecord: R3.LOCAL_FILE_HEADER + E3 + f4 + b4, dirRecord: R3.CENTRAL_FILE_HEADER + A2(C3, 2) + E3 + A2(p4.length, 2) + "\0\0\0\0" + A2(z3, 4) + A2(n8, 4) + f4 + b4 + p4 }; + } + var I3 = e9("../utils"), i7 = e9("../stream/GenericWorker"), O2 = e9("../utf8"), B3 = e9("../crc32"), R3 = e9("../signature"); + function s6(e10, t7, r9, n8) { + i7.call(this, "ZipFileWorker"), this.bytesWritten = 0, this.zipComment = t7, this.zipPlatform = r9, this.encodeFileName = n8, this.streamFiles = e10, this.accumulate = false, this.contentBuffer = [], this.dirRecords = [], this.currentSourceOffset = 0, this.entriesCount = 0, this.currentFile = null, this._sources = []; + } + I3.inherits(s6, i7), s6.prototype.push = function(e10) { + var t7 = e10.meta.percent || 0, r9 = this.entriesCount, n8 = this._sources.length; + this.accumulate ? this.contentBuffer.push(e10) : (this.bytesWritten += e10.data.length, i7.prototype.push.call(this, { data: e10.data, meta: { currentFile: this.currentFile, percent: r9 ? (t7 + 100 * (r9 - n8 - 1)) / r9 : 100 } })); + }, s6.prototype.openedSource = function(e10) { + this.currentSourceOffset = this.bytesWritten, this.currentFile = e10.file.name; + var t7 = this.streamFiles && !e10.file.dir; + if (t7) { + var r9 = n7(e10, t7, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ data: r9.fileRecord, meta: { percent: 0 } }); + } else this.accumulate = true; + }, s6.prototype.closedSource = function(e10) { + this.accumulate = false; + var t7 = this.streamFiles && !e10.file.dir, r9 = n7(e10, t7, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + if (this.dirRecords.push(r9.dirRecord), t7) this.push({ data: (function(e11) { + return R3.DATA_DESCRIPTOR + A2(e11.crc32, 4) + A2(e11.compressedSize, 4) + A2(e11.uncompressedSize, 4); + })(e10), meta: { percent: 100 } }); + else for (this.push({ data: r9.fileRecord, meta: { percent: 0 } }); this.contentBuffer.length; ) this.push(this.contentBuffer.shift()); + this.currentFile = null; + }, s6.prototype.flush = function() { + for (var e10 = this.bytesWritten, t7 = 0; t7 < this.dirRecords.length; t7++) this.push({ data: this.dirRecords[t7], meta: { percent: 100 } }); + var r9 = this.bytesWritten - e10, n8 = (function(e11, t8, r10, n9, i8) { + var s7 = I3.transformTo("string", i8(n9)); + return R3.CENTRAL_DIRECTORY_END + "\0\0\0\0" + A2(e11, 2) + A2(e11, 2) + A2(t8, 4) + A2(r10, 4) + A2(s7.length, 2) + s7; + })(this.dirRecords.length, r9, e10, this.zipComment, this.encodeFileName); + this.push({ data: n8, meta: { percent: 100 } }); + }, s6.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(), this.openedSource(this.previous.streamInfo), this.isPaused ? this.previous.pause() : this.previous.resume(); + }, s6.prototype.registerPrevious = function(e10) { + this._sources.push(e10); + var t7 = this; + return e10.on("data", function(e11) { + t7.processChunk(e11); + }), e10.on("end", function() { + t7.closedSource(t7.previous.streamInfo), t7._sources.length ? t7.prepareNextSource() : t7.end(); + }), e10.on("error", function(e11) { + t7.error(e11); + }), this; + }, s6.prototype.resume = function() { + return !!i7.prototype.resume.call(this) && (!this.previous && this._sources.length ? (this.prepareNextSource(), true) : this.previous || this._sources.length || this.generatedError ? void 0 : (this.end(), true)); + }, s6.prototype.error = function(e10) { + var t7 = this._sources; + if (!i7.prototype.error.call(this, e10)) return false; + for (var r9 = 0; r9 < t7.length; r9++) try { + t7[r9].error(e10); + } catch (e11) { + } + return true; + }, s6.prototype.lock = function() { + i7.prototype.lock.call(this); + for (var e10 = this._sources, t7 = 0; t7 < e10.length; t7++) e10[t7].lock(); + }, t6.exports = s6; + }, { "../crc32": 4, "../signature": 23, "../stream/GenericWorker": 28, "../utf8": 31, "../utils": 32 }], 9: [function(e9, t6, r8) { + "use strict"; + var u5 = e9("../compressions"), n7 = e9("./ZipFileWorker"); + r8.generateWorker = function(e10, a3, t7) { + var o9 = new n7(a3.streamFiles, t7, a3.platform, a3.encodeFileName), h7 = 0; + try { + e10.forEach(function(e11, t8) { + h7++; + var r9 = (function(e12, t9) { + var r10 = e12 || t9, n9 = u5[r10]; + if (!n9) throw new Error(r10 + " is not a valid compression method !"); + return n9; + })(t8.options.compression, a3.compression), n8 = t8.options.compressionOptions || a3.compressionOptions || {}, i7 = t8.dir, s6 = t8.date; + t8._compressWorker(r9, n8).withStreamInfo("file", { name: e11, dir: i7, date: s6, comment: t8.comment || "", unixPermissions: t8.unixPermissions, dosPermissions: t8.dosPermissions }).pipe(o9); + }), o9.entriesCount = h7; + } catch (e11) { + o9.error(e11); + } + return o9; + }; + }, { "../compressions": 3, "./ZipFileWorker": 8 }], 10: [function(e9, t6, r8) { + "use strict"; + function n7() { + if (!(this instanceof n7)) return new n7(); + if (arguments.length) throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + this.files = /* @__PURE__ */ Object.create(null), this.comment = null, this.root = "", this.clone = function() { + var e10 = new n7(); + for (var t7 in this) "function" != typeof this[t7] && (e10[t7] = this[t7]); + return e10; + }; + } + (n7.prototype = e9("./object")).loadAsync = e9("./load"), n7.support = e9("./support"), n7.defaults = e9("./defaults"), n7.version = "3.10.1", n7.loadAsync = function(e10, t7) { + return new n7().loadAsync(e10, t7); + }, n7.external = e9("./external"), t6.exports = n7; + }, { "./defaults": 5, "./external": 6, "./load": 11, "./object": 15, "./support": 30 }], 11: [function(e9, t6, r8) { + "use strict"; + var u5 = e9("./utils"), i7 = e9("./external"), n7 = e9("./utf8"), s6 = e9("./zipEntries"), a3 = e9("./stream/Crc32Probe"), l5 = e9("./nodejsUtils"); + function f4(n8) { + return new i7.Promise(function(e10, t7) { + var r9 = n8.decompressed.getContentWorker().pipe(new a3()); + r9.on("error", function(e11) { + t7(e11); + }).on("end", function() { + r9.streamInfo.crc32 !== n8.decompressed.crc32 ? t7(new Error("Corrupted zip : CRC32 mismatch")) : e10(); + }).resume(); + }); + } + t6.exports = function(e10, o9) { + var h7 = this; + return o9 = u5.extend(o9 || {}, { base64: false, checkCRC32: false, optimizedBinaryString: false, createFolders: false, decodeFileName: n7.utf8decode }), l5.isNode && l5.isStream(e10) ? i7.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")) : u5.prepareContent("the loaded zip file", e10, true, o9.optimizedBinaryString, o9.base64).then(function(e11) { + var t7 = new s6(o9); + return t7.load(e11), t7; + }).then(function(e11) { + var t7 = [i7.Promise.resolve(e11)], r9 = e11.files; + if (o9.checkCRC32) for (var n8 = 0; n8 < r9.length; n8++) t7.push(f4(r9[n8])); + return i7.Promise.all(t7); + }).then(function(e11) { + for (var t7 = e11.shift(), r9 = t7.files, n8 = 0; n8 < r9.length; n8++) { + var i8 = r9[n8], s7 = i8.fileNameStr, a4 = u5.resolve(i8.fileNameStr); + h7.file(a4, i8.decompressed, { binary: true, optimizedBinaryString: true, date: i8.date, dir: i8.dir, comment: i8.fileCommentStr.length ? i8.fileCommentStr : null, unixPermissions: i8.unixPermissions, dosPermissions: i8.dosPermissions, createFolders: o9.createFolders }), i8.dir || (h7.file(a4).unsafeOriginalName = s7); + } + return t7.zipComment.length && (h7.comment = t7.zipComment), h7; + }); + }; + }, { "./external": 6, "./nodejsUtils": 14, "./stream/Crc32Probe": 25, "./utf8": 31, "./utils": 32, "./zipEntries": 33 }], 12: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("../stream/GenericWorker"); + function s6(e10, t7) { + i7.call(this, "Nodejs stream input adapter for " + e10), this._upstreamEnded = false, this._bindStream(t7); + } + n7.inherits(s6, i7), s6.prototype._bindStream = function(e10) { + var t7 = this; + (this._stream = e10).pause(), e10.on("data", function(e11) { + t7.push({ data: e11, meta: { percent: 0 } }); + }).on("error", function(e11) { + t7.isPaused ? this.generatedError = e11 : t7.error(e11); + }).on("end", function() { + t7.isPaused ? t7._upstreamEnded = true : t7.end(); + }); + }, s6.prototype.pause = function() { + return !!i7.prototype.pause.call(this) && (this._stream.pause(), true); + }, s6.prototype.resume = function() { + return !!i7.prototype.resume.call(this) && (this._upstreamEnded ? this.end() : this._stream.resume(), true); + }, t6.exports = s6; + }, { "../stream/GenericWorker": 28, "../utils": 32 }], 13: [function(e9, t6, r8) { + "use strict"; + var i7 = e9("readable-stream").Readable; + function n7(e10, t7, r9) { + i7.call(this, t7), this._helper = e10; + var n8 = this; + e10.on("data", function(e11, t8) { + n8.push(e11) || n8._helper.pause(), r9 && r9(t8); + }).on("error", function(e11) { + n8.emit("error", e11); + }).on("end", function() { + n8.push(null); + }); + } + e9("../utils").inherits(n7, i7), n7.prototype._read = function() { + this._helper.resume(); + }, t6.exports = n7; + }, { "../utils": 32, "readable-stream": 16 }], 14: [function(e9, t6, r8) { + "use strict"; + t6.exports = { isNode: "undefined" != typeof Buffer, newBufferFrom: function(e10, t7) { + if (Buffer.from && Buffer.from !== Uint8Array.from) return Buffer.from(e10, t7); + if ("number" == typeof e10) throw new Error('The "data" argument must not be a number'); + return new Buffer(e10, t7); + }, allocBuffer: function(e10) { + if (Buffer.alloc) return Buffer.alloc(e10); + var t7 = new Buffer(e10); + return t7.fill(0), t7; + }, isBuffer: function(e10) { + return Buffer.isBuffer(e10); + }, isStream: function(e10) { + return e10 && "function" == typeof e10.on && "function" == typeof e10.pause && "function" == typeof e10.resume; + } }; + }, {}], 15: [function(e9, t6, r8) { + "use strict"; + function s6(e10, t7, r9) { + var n8, i8 = u5.getTypeOf(t7), s7 = u5.extend(r9 || {}, f4); + s7.date = s7.date || /* @__PURE__ */ new Date(), null !== s7.compression && (s7.compression = s7.compression.toUpperCase()), "string" == typeof s7.unixPermissions && (s7.unixPermissions = parseInt(s7.unixPermissions, 8)), s7.unixPermissions && 16384 & s7.unixPermissions && (s7.dir = true), s7.dosPermissions && 16 & s7.dosPermissions && (s7.dir = true), s7.dir && (e10 = g3(e10)), s7.createFolders && (n8 = _3(e10)) && b4.call(this, n8, true); + var a4 = "string" === i8 && false === s7.binary && false === s7.base64; + r9 && void 0 !== r9.binary || (s7.binary = !a4), (t7 instanceof c6 && 0 === t7.uncompressedSize || s7.dir || !t7 || 0 === t7.length) && (s7.base64 = false, s7.binary = true, t7 = "", s7.compression = "STORE", i8 = "string"); + var o10 = null; + o10 = t7 instanceof c6 || t7 instanceof l5 ? t7 : p4.isNode && p4.isStream(t7) ? new m4(e10, t7) : u5.prepareContent(e10, t7, s7.binary, s7.optimizedBinaryString, s7.base64); + var h8 = new d4(e10, o10, s7); + this.files[e10] = h8; + } + var i7 = e9("./utf8"), u5 = e9("./utils"), l5 = e9("./stream/GenericWorker"), a3 = e9("./stream/StreamHelper"), f4 = e9("./defaults"), c6 = e9("./compressedObject"), d4 = e9("./zipObject"), o9 = e9("./generate"), p4 = e9("./nodejsUtils"), m4 = e9("./nodejs/NodejsStreamInputAdapter"), _3 = function(e10) { + "/" === e10.slice(-1) && (e10 = e10.substring(0, e10.length - 1)); + var t7 = e10.lastIndexOf("/"); + return 0 < t7 ? e10.substring(0, t7) : ""; + }, g3 = function(e10) { + return "/" !== e10.slice(-1) && (e10 += "/"), e10; + }, b4 = function(e10, t7) { + return t7 = void 0 !== t7 ? t7 : f4.createFolders, e10 = g3(e10), this.files[e10] || s6.call(this, e10, null, { dir: true, createFolders: t7 }), this.files[e10]; + }; + function h7(e10) { + return "[object RegExp]" === Object.prototype.toString.call(e10); + } + var n7 = { load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, forEach: function(e10) { + var t7, r9, n8; + for (t7 in this.files) n8 = this.files[t7], (r9 = t7.slice(this.root.length, t7.length)) && t7.slice(0, this.root.length) === this.root && e10(r9, n8); + }, filter: function(r9) { + var n8 = []; + return this.forEach(function(e10, t7) { + r9(e10, t7) && n8.push(t7); + }), n8; + }, file: function(e10, t7, r9) { + if (1 !== arguments.length) return e10 = this.root + e10, s6.call(this, e10, t7, r9), this; + if (h7(e10)) { + var n8 = e10; + return this.filter(function(e11, t8) { + return !t8.dir && n8.test(e11); + }); + } + var i8 = this.files[this.root + e10]; + return i8 && !i8.dir ? i8 : null; + }, folder: function(r9) { + if (!r9) return this; + if (h7(r9)) return this.filter(function(e11, t8) { + return t8.dir && r9.test(e11); + }); + var e10 = this.root + r9, t7 = b4.call(this, e10), n8 = this.clone(); + return n8.root = t7.name, n8; + }, remove: function(r9) { + r9 = this.root + r9; + var e10 = this.files[r9]; + if (e10 || ("/" !== r9.slice(-1) && (r9 += "/"), e10 = this.files[r9]), e10 && !e10.dir) delete this.files[r9]; + else for (var t7 = this.filter(function(e11, t8) { + return t8.name.slice(0, r9.length) === r9; + }), n8 = 0; n8 < t7.length; n8++) delete this.files[t7[n8].name]; + return this; + }, generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, generateInternalStream: function(e10) { + var t7, r9 = {}; + try { + if ((r9 = u5.extend(e10 || {}, { streamFiles: false, compression: "STORE", compressionOptions: null, type: "", platform: "DOS", comment: null, mimeType: "application/zip", encodeFileName: i7.utf8encode })).type = r9.type.toLowerCase(), r9.compression = r9.compression.toUpperCase(), "binarystring" === r9.type && (r9.type = "string"), !r9.type) throw new Error("No output type specified."); + u5.checkSupport(r9.type), "darwin" !== r9.platform && "freebsd" !== r9.platform && "linux" !== r9.platform && "sunos" !== r9.platform || (r9.platform = "UNIX"), "win32" === r9.platform && (r9.platform = "DOS"); + var n8 = r9.comment || this.comment || ""; + t7 = o9.generateWorker(this, r9, n8); + } catch (e11) { + (t7 = new l5("error")).error(e11); + } + return new a3(t7, r9.type || "string", r9.mimeType); + }, generateAsync: function(e10, t7) { + return this.generateInternalStream(e10).accumulate(t7); + }, generateNodeStream: function(e10, t7) { + return (e10 = e10 || {}).type || (e10.type = "nodebuffer"), this.generateInternalStream(e10).toNodejsStream(t7); + } }; + t6.exports = n7; + }, { "./compressedObject": 2, "./defaults": 5, "./generate": 9, "./nodejs/NodejsStreamInputAdapter": 12, "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31, "./utils": 32, "./zipObject": 35 }], 16: [function(e9, t6, r8) { + "use strict"; + t6.exports = e9("stream"); + }, { stream: void 0 }], 17: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./DataReader"); + function i7(e10) { + n7.call(this, e10); + for (var t7 = 0; t7 < this.data.length; t7++) e10[t7] = 255 & e10[t7]; + } + e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) { + return this.data[this.zero + e10]; + }, i7.prototype.lastIndexOfSignature = function(e10) { + for (var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.length - 4; 0 <= s6; --s6) if (this.data[s6] === t7 && this.data[s6 + 1] === r9 && this.data[s6 + 2] === n8 && this.data[s6 + 3] === i8) return s6 - this.zero; + return -1; + }, i7.prototype.readAndCheckSignature = function(e10) { + var t7 = e10.charCodeAt(0), r9 = e10.charCodeAt(1), n8 = e10.charCodeAt(2), i8 = e10.charCodeAt(3), s6 = this.readData(4); + return t7 === s6[0] && r9 === s6[1] && n8 === s6[2] && i8 === s6[3]; + }, i7.prototype.readData = function(e10) { + if (this.checkOffset(e10), 0 === e10) return []; + var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./DataReader": 18 }], 18: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"); + function i7(e10) { + this.data = e10, this.length = e10.length, this.index = 0, this.zero = 0; + } + i7.prototype = { checkOffset: function(e10) { + this.checkIndex(this.index + e10); + }, checkIndex: function(e10) { + if (this.length < this.zero + e10 || e10 < 0) throw new Error("End of data reached (data length = " + this.length + ", asked index = " + e10 + "). Corrupted zip ?"); + }, setIndex: function(e10) { + this.checkIndex(e10), this.index = e10; + }, skip: function(e10) { + this.setIndex(this.index + e10); + }, byteAt: function() { + }, readInt: function(e10) { + var t7, r9 = 0; + for (this.checkOffset(e10), t7 = this.index + e10 - 1; t7 >= this.index; t7--) r9 = (r9 << 8) + this.byteAt(t7); + return this.index += e10, r9; + }, readString: function(e10) { + return n7.transformTo("string", this.readData(e10)); + }, readData: function() { + }, lastIndexOfSignature: function() { + }, readAndCheckSignature: function() { + }, readDate: function() { + var e10 = this.readInt(4); + return new Date(Date.UTC(1980 + (e10 >> 25 & 127), (e10 >> 21 & 15) - 1, e10 >> 16 & 31, e10 >> 11 & 31, e10 >> 5 & 63, (31 & e10) << 1)); + } }, t6.exports = i7; + }, { "../utils": 32 }], 19: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./Uint8ArrayReader"); + function i7(e10) { + n7.call(this, e10); + } + e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) { + this.checkOffset(e10); + var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./Uint8ArrayReader": 21 }], 20: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./DataReader"); + function i7(e10) { + n7.call(this, e10); + } + e9("../utils").inherits(i7, n7), i7.prototype.byteAt = function(e10) { + return this.data.charCodeAt(this.zero + e10); + }, i7.prototype.lastIndexOfSignature = function(e10) { + return this.data.lastIndexOf(e10) - this.zero; + }, i7.prototype.readAndCheckSignature = function(e10) { + return e10 === this.readData(4); + }, i7.prototype.readData = function(e10) { + this.checkOffset(e10); + var t7 = this.data.slice(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./DataReader": 18 }], 21: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./ArrayReader"); + function i7(e10) { + n7.call(this, e10); + } + e9("../utils").inherits(i7, n7), i7.prototype.readData = function(e10) { + if (this.checkOffset(e10), 0 === e10) return new Uint8Array(0); + var t7 = this.data.subarray(this.zero + this.index, this.zero + this.index + e10); + return this.index += e10, t7; + }, t6.exports = i7; + }, { "../utils": 32, "./ArrayReader": 17 }], 22: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("../support"), s6 = e9("./ArrayReader"), a3 = e9("./StringReader"), o9 = e9("./NodeBufferReader"), h7 = e9("./Uint8ArrayReader"); + t6.exports = function(e10) { + var t7 = n7.getTypeOf(e10); + return n7.checkSupport(t7), "string" !== t7 || i7.uint8array ? "nodebuffer" === t7 ? new o9(e10) : i7.uint8array ? new h7(n7.transformTo("uint8array", e10)) : new s6(n7.transformTo("array", e10)) : new a3(e10); + }; + }, { "../support": 30, "../utils": 32, "./ArrayReader": 17, "./NodeBufferReader": 19, "./StringReader": 20, "./Uint8ArrayReader": 21 }], 23: [function(e9, t6, r8) { + "use strict"; + r8.LOCAL_FILE_HEADER = "PK", r8.CENTRAL_FILE_HEADER = "PK", r8.CENTRAL_DIRECTORY_END = "PK", r8.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x07", r8.ZIP64_CENTRAL_DIRECTORY_END = "PK", r8.DATA_DESCRIPTOR = "PK\x07\b"; + }, {}], 24: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./GenericWorker"), i7 = e9("../utils"); + function s6(e10) { + n7.call(this, "ConvertWorker to " + e10), this.destType = e10; + } + i7.inherits(s6, n7), s6.prototype.processChunk = function(e10) { + this.push({ data: i7.transformTo(this.destType, e10.data), meta: e10.meta }); + }, t6.exports = s6; + }, { "../utils": 32, "./GenericWorker": 28 }], 25: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./GenericWorker"), i7 = e9("../crc32"); + function s6() { + n7.call(this, "Crc32Probe"), this.withStreamInfo("crc32", 0); + } + e9("../utils").inherits(s6, n7), s6.prototype.processChunk = function(e10) { + this.streamInfo.crc32 = i7(e10.data, this.streamInfo.crc32 || 0), this.push(e10); + }, t6.exports = s6; + }, { "../crc32": 4, "../utils": 32, "./GenericWorker": 28 }], 26: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("./GenericWorker"); + function s6(e10) { + i7.call(this, "DataLengthProbe for " + e10), this.propName = e10, this.withStreamInfo(e10, 0); + } + n7.inherits(s6, i7), s6.prototype.processChunk = function(e10) { + if (e10) { + var t7 = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = t7 + e10.data.length; + } + i7.prototype.processChunk.call(this, e10); + }, t6.exports = s6; + }, { "../utils": 32, "./GenericWorker": 28 }], 27: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("../utils"), i7 = e9("./GenericWorker"); + function s6(e10) { + i7.call(this, "DataWorker"); + var t7 = this; + this.dataIsReady = false, this.index = 0, this.max = 0, this.data = null, this.type = "", this._tickScheduled = false, e10.then(function(e11) { + t7.dataIsReady = true, t7.data = e11, t7.max = e11 && e11.length || 0, t7.type = n7.getTypeOf(e11), t7.isPaused || t7._tickAndRepeat(); + }, function(e11) { + t7.error(e11); + }); + } + n7.inherits(s6, i7), s6.prototype.cleanUp = function() { + i7.prototype.cleanUp.call(this), this.data = null; + }, s6.prototype.resume = function() { + return !!i7.prototype.resume.call(this) && (!this._tickScheduled && this.dataIsReady && (this._tickScheduled = true, n7.delay(this._tickAndRepeat, [], this)), true); + }, s6.prototype._tickAndRepeat = function() { + this._tickScheduled = false, this.isPaused || this.isFinished || (this._tick(), this.isFinished || (n7.delay(this._tickAndRepeat, [], this), this._tickScheduled = true)); + }, s6.prototype._tick = function() { + if (this.isPaused || this.isFinished) return false; + var e10 = null, t7 = Math.min(this.max, this.index + 16384); + if (this.index >= this.max) return this.end(); + switch (this.type) { + case "string": + e10 = this.data.substring(this.index, t7); + break; + case "uint8array": + e10 = this.data.subarray(this.index, t7); + break; + case "array": + case "nodebuffer": + e10 = this.data.slice(this.index, t7); + } + return this.index = t7, this.push({ data: e10, meta: { percent: this.max ? this.index / this.max * 100 : 0 } }); + }, t6.exports = s6; + }, { "../utils": 32, "./GenericWorker": 28 }], 28: [function(e9, t6, r8) { + "use strict"; + function n7(e10) { + this.name = e10 || "default", this.streamInfo = {}, this.generatedError = null, this.extraStreamInfo = {}, this.isPaused = true, this.isFinished = false, this.isLocked = false, this._listeners = { data: [], end: [], error: [] }, this.previous = null; + } + n7.prototype = { push: function(e10) { + this.emit("data", e10); + }, end: function() { + if (this.isFinished) return false; + this.flush(); + try { + this.emit("end"), this.cleanUp(), this.isFinished = true; + } catch (e10) { + this.emit("error", e10); + } + return true; + }, error: function(e10) { + return !this.isFinished && (this.isPaused ? this.generatedError = e10 : (this.isFinished = true, this.emit("error", e10), this.previous && this.previous.error(e10), this.cleanUp()), true); + }, on: function(e10, t7) { + return this._listeners[e10].push(t7), this; + }, cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null, this._listeners = []; + }, emit: function(e10, t7) { + if (this._listeners[e10]) for (var r9 = 0; r9 < this._listeners[e10].length; r9++) this._listeners[e10][r9].call(this, t7); + }, pipe: function(e10) { + return e10.registerPrevious(this); + }, registerPrevious: function(e10) { + if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); + this.streamInfo = e10.streamInfo, this.mergeStreamInfo(), this.previous = e10; + var t7 = this; + return e10.on("data", function(e11) { + t7.processChunk(e11); + }), e10.on("end", function() { + t7.end(); + }), e10.on("error", function(e11) { + t7.error(e11); + }), this; + }, pause: function() { + return !this.isPaused && !this.isFinished && (this.isPaused = true, this.previous && this.previous.pause(), true); + }, resume: function() { + if (!this.isPaused || this.isFinished) return false; + var e10 = this.isPaused = false; + return this.generatedError && (this.error(this.generatedError), e10 = true), this.previous && this.previous.resume(), !e10; + }, flush: function() { + }, processChunk: function(e10) { + this.push(e10); + }, withStreamInfo: function(e10, t7) { + return this.extraStreamInfo[e10] = t7, this.mergeStreamInfo(), this; + }, mergeStreamInfo: function() { + for (var e10 in this.extraStreamInfo) Object.prototype.hasOwnProperty.call(this.extraStreamInfo, e10) && (this.streamInfo[e10] = this.extraStreamInfo[e10]); + }, lock: function() { + if (this.isLocked) throw new Error("The stream '" + this + "' has already been used."); + this.isLocked = true, this.previous && this.previous.lock(); + }, toString: function() { + var e10 = "Worker " + this.name; + return this.previous ? this.previous + " -> " + e10 : e10; + } }, t6.exports = n7; + }, {}], 29: [function(e9, t6, r8) { + "use strict"; + var h7 = e9("../utils"), i7 = e9("./ConvertWorker"), s6 = e9("./GenericWorker"), u5 = e9("../base64"), n7 = e9("../support"), a3 = e9("../external"), o9 = null; + if (n7.nodestream) try { + o9 = e9("../nodejs/NodejsStreamOutputAdapter"); + } catch (e10) { + } + function l5(e10, o10) { + return new a3.Promise(function(t7, r9) { + var n8 = [], i8 = e10._internalType, s7 = e10._outputType, a4 = e10._mimeType; + e10.on("data", function(e11, t8) { + n8.push(e11), o10 && o10(t8); + }).on("error", function(e11) { + n8 = [], r9(e11); + }).on("end", function() { + try { + var e11 = (function(e12, t8, r10) { + switch (e12) { + case "blob": + return h7.newBlob(h7.transformTo("arraybuffer", t8), r10); + case "base64": + return u5.encode(t8); + default: + return h7.transformTo(e12, t8); + } + })(s7, (function(e12, t8) { + var r10, n9 = 0, i9 = null, s8 = 0; + for (r10 = 0; r10 < t8.length; r10++) s8 += t8[r10].length; + switch (e12) { + case "string": + return t8.join(""); + case "array": + return Array.prototype.concat.apply([], t8); + case "uint8array": + for (i9 = new Uint8Array(s8), r10 = 0; r10 < t8.length; r10++) i9.set(t8[r10], n9), n9 += t8[r10].length; + return i9; + case "nodebuffer": + return Buffer.concat(t8); + default: + throw new Error("concat : unsupported type '" + e12 + "'"); + } + })(i8, n8), a4); + t7(e11); + } catch (e12) { + r9(e12); + } + n8 = []; + }).resume(); + }); + } + function f4(e10, t7, r9) { + var n8 = t7; + switch (t7) { + case "blob": + case "arraybuffer": + n8 = "uint8array"; + break; + case "base64": + n8 = "string"; + } + try { + this._internalType = n8, this._outputType = t7, this._mimeType = r9, h7.checkSupport(n8), this._worker = e10.pipe(new i7(n8)), e10.lock(); + } catch (e11) { + this._worker = new s6("error"), this._worker.error(e11); + } + } + f4.prototype = { accumulate: function(e10) { + return l5(this, e10); + }, on: function(e10, t7) { + var r9 = this; + return "data" === e10 ? this._worker.on(e10, function(e11) { + t7.call(r9, e11.data, e11.meta); + }) : this._worker.on(e10, function() { + h7.delay(t7, arguments, r9); + }), this; + }, resume: function() { + return h7.delay(this._worker.resume, [], this._worker), this; + }, pause: function() { + return this._worker.pause(), this; + }, toNodejsStream: function(e10) { + if (h7.checkSupport("nodestream"), "nodebuffer" !== this._outputType) throw new Error(this._outputType + " is not supported by this method"); + return new o9(this, { objectMode: "nodebuffer" !== this._outputType }, e10); + } }, t6.exports = f4; + }, { "../base64": 1, "../external": 6, "../nodejs/NodejsStreamOutputAdapter": 13, "../support": 30, "../utils": 32, "./ConvertWorker": 24, "./GenericWorker": 28 }], 30: [function(e9, t6, r8) { + "use strict"; + if (r8.base64 = true, r8.array = true, r8.string = true, r8.arraybuffer = "undefined" != typeof ArrayBuffer && "undefined" != typeof Uint8Array, r8.nodebuffer = "undefined" != typeof Buffer, r8.uint8array = "undefined" != typeof Uint8Array, "undefined" == typeof ArrayBuffer) r8.blob = false; + else { + var n7 = new ArrayBuffer(0); + try { + r8.blob = 0 === new Blob([n7], { type: "application/zip" }).size; + } catch (e10) { + try { + var i7 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); + i7.append(n7), r8.blob = 0 === i7.getBlob("application/zip").size; + } catch (e11) { + r8.blob = false; + } + } + } + try { + r8.nodestream = !!e9("readable-stream").Readable; + } catch (e10) { + r8.nodestream = false; + } + }, { "readable-stream": 16 }], 31: [function(e9, t6, s6) { + "use strict"; + for (var o9 = e9("./utils"), h7 = e9("./support"), r8 = e9("./nodejsUtils"), n7 = e9("./stream/GenericWorker"), u5 = new Array(256), i7 = 0; i7 < 256; i7++) u5[i7] = 252 <= i7 ? 6 : 248 <= i7 ? 5 : 240 <= i7 ? 4 : 224 <= i7 ? 3 : 192 <= i7 ? 2 : 1; + u5[254] = u5[254] = 1; + function a3() { + n7.call(this, "utf-8 decode"), this.leftOver = null; + } + function l5() { + n7.call(this, "utf-8 encode"); + } + s6.utf8encode = function(e10) { + return h7.nodebuffer ? r8.newBufferFrom(e10, "utf-8") : (function(e11) { + var t7, r9, n8, i8, s7, a4 = e11.length, o10 = 0; + for (i8 = 0; i8 < a4; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o10 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4; + for (t7 = h7.uint8array ? new Uint8Array(o10) : new Array(o10), i8 = s7 = 0; s7 < o10; i8++) 55296 == (64512 & (r9 = e11.charCodeAt(i8))) && i8 + 1 < a4 && 56320 == (64512 & (n8 = e11.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9); + return t7; + })(e10); + }, s6.utf8decode = function(e10) { + return h7.nodebuffer ? o9.transformTo("nodebuffer", e10).toString("utf-8") : (function(e11) { + var t7, r9, n8, i8, s7 = e11.length, a4 = new Array(2 * s7); + for (t7 = r9 = 0; t7 < s7; ) if ((n8 = e11[t7++]) < 128) a4[r9++] = n8; + else if (4 < (i8 = u5[n8])) a4[r9++] = 65533, t7 += i8 - 1; + else { + for (n8 &= 2 === i8 ? 31 : 3 === i8 ? 15 : 7; 1 < i8 && t7 < s7; ) n8 = n8 << 6 | 63 & e11[t7++], i8--; + 1 < i8 ? a4[r9++] = 65533 : n8 < 65536 ? a4[r9++] = n8 : (n8 -= 65536, a4[r9++] = 55296 | n8 >> 10 & 1023, a4[r9++] = 56320 | 1023 & n8); + } + return a4.length !== r9 && (a4.subarray ? a4 = a4.subarray(0, r9) : a4.length = r9), o9.applyFromCharCode(a4); + })(e10 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10)); + }, o9.inherits(a3, n7), a3.prototype.processChunk = function(e10) { + var t7 = o9.transformTo(h7.uint8array ? "uint8array" : "array", e10.data); + if (this.leftOver && this.leftOver.length) { + if (h7.uint8array) { + var r9 = t7; + (t7 = new Uint8Array(r9.length + this.leftOver.length)).set(this.leftOver, 0), t7.set(r9, this.leftOver.length); + } else t7 = this.leftOver.concat(t7); + this.leftOver = null; + } + var n8 = (function(e11, t8) { + var r10; + for ((t8 = t8 || e11.length) > e11.length && (t8 = e11.length), r10 = t8 - 1; 0 <= r10 && 128 == (192 & e11[r10]); ) r10--; + return r10 < 0 ? t8 : 0 === r10 ? t8 : r10 + u5[e11[r10]] > t8 ? r10 : t8; + })(t7), i8 = t7; + n8 !== t7.length && (h7.uint8array ? (i8 = t7.subarray(0, n8), this.leftOver = t7.subarray(n8, t7.length)) : (i8 = t7.slice(0, n8), this.leftOver = t7.slice(n8, t7.length))), this.push({ data: s6.utf8decode(i8), meta: e10.meta }); + }, a3.prototype.flush = function() { + this.leftOver && this.leftOver.length && (this.push({ data: s6.utf8decode(this.leftOver), meta: {} }), this.leftOver = null); + }, s6.Utf8DecodeWorker = a3, o9.inherits(l5, n7), l5.prototype.processChunk = function(e10) { + this.push({ data: s6.utf8encode(e10.data), meta: e10.meta }); + }, s6.Utf8EncodeWorker = l5; + }, { "./nodejsUtils": 14, "./stream/GenericWorker": 28, "./support": 30, "./utils": 32 }], 32: [function(e9, t6, a3) { + "use strict"; + var o9 = e9("./support"), h7 = e9("./base64"), r8 = e9("./nodejsUtils"), u5 = e9("./external"); + function n7(e10) { + return e10; + } + function l5(e10, t7) { + for (var r9 = 0; r9 < e10.length; ++r9) t7[r9] = 255 & e10.charCodeAt(r9); + return t7; + } + e9("setimmediate"), a3.newBlob = function(t7, r9) { + a3.checkSupport("blob"); + try { + return new Blob([t7], { type: r9 }); + } catch (e10) { + try { + var n8 = new (self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder)(); + return n8.append(t7), n8.getBlob(r9); + } catch (e11) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + var i7 = { stringifyByChunk: function(e10, t7, r9) { + var n8 = [], i8 = 0, s7 = e10.length; + if (s7 <= r9) return String.fromCharCode.apply(null, e10); + for (; i8 < s7; ) "array" === t7 || "nodebuffer" === t7 ? n8.push(String.fromCharCode.apply(null, e10.slice(i8, Math.min(i8 + r9, s7)))) : n8.push(String.fromCharCode.apply(null, e10.subarray(i8, Math.min(i8 + r9, s7)))), i8 += r9; + return n8.join(""); + }, stringifyByChar: function(e10) { + for (var t7 = "", r9 = 0; r9 < e10.length; r9++) t7 += String.fromCharCode(e10[r9]); + return t7; + }, applyCanBeUsed: { uint8array: (function() { + try { + return o9.uint8array && 1 === String.fromCharCode.apply(null, new Uint8Array(1)).length; + } catch (e10) { + return false; + } + })(), nodebuffer: (function() { + try { + return o9.nodebuffer && 1 === String.fromCharCode.apply(null, r8.allocBuffer(1)).length; + } catch (e10) { + return false; + } + })() } }; + function s6(e10) { + var t7 = 65536, r9 = a3.getTypeOf(e10), n8 = true; + if ("uint8array" === r9 ? n8 = i7.applyCanBeUsed.uint8array : "nodebuffer" === r9 && (n8 = i7.applyCanBeUsed.nodebuffer), n8) for (; 1 < t7; ) try { + return i7.stringifyByChunk(e10, r9, t7); + } catch (e11) { + t7 = Math.floor(t7 / 2); + } + return i7.stringifyByChar(e10); + } + function f4(e10, t7) { + for (var r9 = 0; r9 < e10.length; r9++) t7[r9] = e10[r9]; + return t7; + } + a3.applyFromCharCode = s6; + var c6 = {}; + c6.string = { string: n7, array: function(e10) { + return l5(e10, new Array(e10.length)); + }, arraybuffer: function(e10) { + return c6.string.uint8array(e10).buffer; + }, uint8array: function(e10) { + return l5(e10, new Uint8Array(e10.length)); + }, nodebuffer: function(e10) { + return l5(e10, r8.allocBuffer(e10.length)); + } }, c6.array = { string: s6, array: n7, arraybuffer: function(e10) { + return new Uint8Array(e10).buffer; + }, uint8array: function(e10) { + return new Uint8Array(e10); + }, nodebuffer: function(e10) { + return r8.newBufferFrom(e10); + } }, c6.arraybuffer = { string: function(e10) { + return s6(new Uint8Array(e10)); + }, array: function(e10) { + return f4(new Uint8Array(e10), new Array(e10.byteLength)); + }, arraybuffer: n7, uint8array: function(e10) { + return new Uint8Array(e10); + }, nodebuffer: function(e10) { + return r8.newBufferFrom(new Uint8Array(e10)); + } }, c6.uint8array = { string: s6, array: function(e10) { + return f4(e10, new Array(e10.length)); + }, arraybuffer: function(e10) { + return e10.buffer; + }, uint8array: n7, nodebuffer: function(e10) { + return r8.newBufferFrom(e10); + } }, c6.nodebuffer = { string: s6, array: function(e10) { + return f4(e10, new Array(e10.length)); + }, arraybuffer: function(e10) { + return c6.nodebuffer.uint8array(e10).buffer; + }, uint8array: function(e10) { + return f4(e10, new Uint8Array(e10.length)); + }, nodebuffer: n7 }, a3.transformTo = function(e10, t7) { + if (t7 = t7 || "", !e10) return t7; + a3.checkSupport(e10); + var r9 = a3.getTypeOf(t7); + return c6[r9][e10](t7); + }, a3.resolve = function(e10) { + for (var t7 = e10.split("/"), r9 = [], n8 = 0; n8 < t7.length; n8++) { + var i8 = t7[n8]; + "." === i8 || "" === i8 && 0 !== n8 && n8 !== t7.length - 1 || (".." === i8 ? r9.pop() : r9.push(i8)); + } + return r9.join("/"); + }, a3.getTypeOf = function(e10) { + return "string" == typeof e10 ? "string" : "[object Array]" === Object.prototype.toString.call(e10) ? "array" : o9.nodebuffer && r8.isBuffer(e10) ? "nodebuffer" : o9.uint8array && e10 instanceof Uint8Array ? "uint8array" : o9.arraybuffer && e10 instanceof ArrayBuffer ? "arraybuffer" : void 0; + }, a3.checkSupport = function(e10) { + if (!o9[e10.toLowerCase()]) throw new Error(e10 + " is not supported by this platform"); + }, a3.MAX_VALUE_16BITS = 65535, a3.MAX_VALUE_32BITS = -1, a3.pretty = function(e10) { + var t7, r9, n8 = ""; + for (r9 = 0; r9 < (e10 || "").length; r9++) n8 += "\\x" + ((t7 = e10.charCodeAt(r9)) < 16 ? "0" : "") + t7.toString(16).toUpperCase(); + return n8; + }, a3.delay = function(e10, t7, r9) { + setImmediate(function() { + e10.apply(r9 || null, t7 || []); + }); + }, a3.inherits = function(e10, t7) { + function r9() { + } + r9.prototype = t7.prototype, e10.prototype = new r9(); + }, a3.extend = function() { + var e10, t7, r9 = {}; + for (e10 = 0; e10 < arguments.length; e10++) for (t7 in arguments[e10]) Object.prototype.hasOwnProperty.call(arguments[e10], t7) && void 0 === r9[t7] && (r9[t7] = arguments[e10][t7]); + return r9; + }, a3.prepareContent = function(r9, e10, n8, i8, s7) { + return u5.Promise.resolve(e10).then(function(n9) { + return o9.blob && (n9 instanceof Blob || -1 !== ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(n9))) && "undefined" != typeof FileReader ? new u5.Promise(function(t7, r10) { + var e11 = new FileReader(); + e11.onload = function(e12) { + t7(e12.target.result); + }, e11.onerror = function(e12) { + r10(e12.target.error); + }, e11.readAsArrayBuffer(n9); + }) : n9; + }).then(function(e11) { + var t7 = a3.getTypeOf(e11); + return t7 ? ("arraybuffer" === t7 ? e11 = a3.transformTo("uint8array", e11) : "string" === t7 && (s7 ? e11 = h7.decode(e11) : n8 && true !== i8 && (e11 = (function(e12) { + return l5(e12, o9.uint8array ? new Uint8Array(e12.length) : new Array(e12.length)); + })(e11))), e11) : u5.Promise.reject(new Error("Can't read the data of '" + r9 + "'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); + }); + }; + }, { "./base64": 1, "./external": 6, "./nodejsUtils": 14, "./support": 30, setimmediate: 54 }], 33: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./reader/readerFor"), i7 = e9("./utils"), s6 = e9("./signature"), a3 = e9("./zipEntry"), o9 = e9("./support"); + function h7(e10) { + this.files = [], this.loadOptions = e10; + } + h7.prototype = { checkSignature: function(e10) { + if (!this.reader.readAndCheckSignature(e10)) { + this.reader.index -= 4; + var t7 = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature (" + i7.pretty(t7) + ", expected " + i7.pretty(e10) + ")"); + } + }, isSignature: function(e10, t7) { + var r9 = this.reader.index; + this.reader.setIndex(e10); + var n8 = this.reader.readString(4) === t7; + return this.reader.setIndex(r9), n8; + }, readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2), this.diskWithCentralDirStart = this.reader.readInt(2), this.centralDirRecordsOnThisDisk = this.reader.readInt(2), this.centralDirRecords = this.reader.readInt(2), this.centralDirSize = this.reader.readInt(4), this.centralDirOffset = this.reader.readInt(4), this.zipCommentLength = this.reader.readInt(2); + var e10 = this.reader.readData(this.zipCommentLength), t7 = o9.uint8array ? "uint8array" : "array", r9 = i7.transformTo(t7, e10); + this.zipComment = this.loadOptions.decodeFileName(r9); + }, readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8), this.reader.skip(4), this.diskNumber = this.reader.readInt(4), this.diskWithCentralDirStart = this.reader.readInt(4), this.centralDirRecordsOnThisDisk = this.reader.readInt(8), this.centralDirRecords = this.reader.readInt(8), this.centralDirSize = this.reader.readInt(8), this.centralDirOffset = this.reader.readInt(8), this.zip64ExtensibleData = {}; + for (var e10, t7, r9, n8 = this.zip64EndOfCentralSize - 44; 0 < n8; ) e10 = this.reader.readInt(2), t7 = this.reader.readInt(4), r9 = this.reader.readData(t7), this.zip64ExtensibleData[e10] = { id: e10, length: t7, value: r9 }; + }, readBlockZip64EndOfCentralLocator: function() { + if (this.diskWithZip64CentralDirStart = this.reader.readInt(4), this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8), this.disksCount = this.reader.readInt(4), 1 < this.disksCount) throw new Error("Multi-volumes zip are not supported"); + }, readLocalFiles: function() { + var e10, t7; + for (e10 = 0; e10 < this.files.length; e10++) t7 = this.files[e10], this.reader.setIndex(t7.localHeaderOffset), this.checkSignature(s6.LOCAL_FILE_HEADER), t7.readLocalPart(this.reader), t7.handleUTF8(), t7.processAttributes(); + }, readCentralDir: function() { + var e10; + for (this.reader.setIndex(this.centralDirOffset); this.reader.readAndCheckSignature(s6.CENTRAL_FILE_HEADER); ) (e10 = new a3({ zip64: this.zip64 }, this.loadOptions)).readCentralPart(this.reader), this.files.push(e10); + if (this.centralDirRecords !== this.files.length && 0 !== this.centralDirRecords && 0 === this.files.length) throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + }, readEndOfCentral: function() { + var e10 = this.reader.lastIndexOfSignature(s6.CENTRAL_DIRECTORY_END); + if (e10 < 0) throw !this.isSignature(0, s6.LOCAL_FILE_HEADER) ? new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html") : new Error("Corrupted zip: can't find end of central directory"); + this.reader.setIndex(e10); + var t7 = e10; + if (this.checkSignature(s6.CENTRAL_DIRECTORY_END), this.readBlockEndOfCentral(), this.diskNumber === i7.MAX_VALUE_16BITS || this.diskWithCentralDirStart === i7.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === i7.MAX_VALUE_16BITS || this.centralDirRecords === i7.MAX_VALUE_16BITS || this.centralDirSize === i7.MAX_VALUE_32BITS || this.centralDirOffset === i7.MAX_VALUE_32BITS) { + if (this.zip64 = true, (e10 = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR)) < 0) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + if (this.reader.setIndex(e10), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_LOCATOR), this.readBlockZip64EndOfCentralLocator(), !this.isSignature(this.relativeOffsetEndOfZip64CentralDir, s6.ZIP64_CENTRAL_DIRECTORY_END) && (this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.relativeOffsetEndOfZip64CentralDir < 0)) throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir), this.checkSignature(s6.ZIP64_CENTRAL_DIRECTORY_END), this.readBlockZip64EndOfCentral(); + } + var r9 = this.centralDirOffset + this.centralDirSize; + this.zip64 && (r9 += 20, r9 += 12 + this.zip64EndOfCentralSize); + var n8 = t7 - r9; + if (0 < n8) this.isSignature(t7, s6.CENTRAL_FILE_HEADER) || (this.reader.zero = n8); + else if (n8 < 0) throw new Error("Corrupted zip: missing " + Math.abs(n8) + " bytes."); + }, prepareReader: function(e10) { + this.reader = n7(e10); + }, load: function(e10) { + this.prepareReader(e10), this.readEndOfCentral(), this.readCentralDir(), this.readLocalFiles(); + } }, t6.exports = h7; + }, { "./reader/readerFor": 22, "./signature": 23, "./support": 30, "./utils": 32, "./zipEntry": 34 }], 34: [function(e9, t6, r8) { + "use strict"; + var n7 = e9("./reader/readerFor"), s6 = e9("./utils"), i7 = e9("./compressedObject"), a3 = e9("./crc32"), o9 = e9("./utf8"), h7 = e9("./compressions"), u5 = e9("./support"); + function l5(e10, t7) { + this.options = e10, this.loadOptions = t7; + } + l5.prototype = { isEncrypted: function() { + return 1 == (1 & this.bitFlag); + }, useUTF8: function() { + return 2048 == (2048 & this.bitFlag); + }, readLocalPart: function(e10) { + var t7, r9; + if (e10.skip(22), this.fileNameLength = e10.readInt(2), r9 = e10.readInt(2), this.fileName = e10.readData(this.fileNameLength), e10.skip(r9), -1 === this.compressedSize || -1 === this.uncompressedSize) throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)"); + if (null === (t7 = (function(e11) { + for (var t8 in h7) if (Object.prototype.hasOwnProperty.call(h7, t8) && h7[t8].magic === e11) return h7[t8]; + return null; + })(this.compressionMethod))) throw new Error("Corrupted zip : compression " + s6.pretty(this.compressionMethod) + " unknown (inner file : " + s6.transformTo("string", this.fileName) + ")"); + this.decompressed = new i7(this.compressedSize, this.uncompressedSize, this.crc32, t7, e10.readData(this.compressedSize)); + }, readCentralPart: function(e10) { + this.versionMadeBy = e10.readInt(2), e10.skip(2), this.bitFlag = e10.readInt(2), this.compressionMethod = e10.readString(2), this.date = e10.readDate(), this.crc32 = e10.readInt(4), this.compressedSize = e10.readInt(4), this.uncompressedSize = e10.readInt(4); + var t7 = e10.readInt(2); + if (this.extraFieldsLength = e10.readInt(2), this.fileCommentLength = e10.readInt(2), this.diskNumberStart = e10.readInt(2), this.internalFileAttributes = e10.readInt(2), this.externalFileAttributes = e10.readInt(4), this.localHeaderOffset = e10.readInt(4), this.isEncrypted()) throw new Error("Encrypted zip are not supported"); + e10.skip(t7), this.readExtraFields(e10), this.parseZIP64ExtraField(e10), this.fileComment = e10.readData(this.fileCommentLength); + }, processAttributes: function() { + this.unixPermissions = null, this.dosPermissions = null; + var e10 = this.versionMadeBy >> 8; + this.dir = !!(16 & this.externalFileAttributes), 0 == e10 && (this.dosPermissions = 63 & this.externalFileAttributes), 3 == e10 && (this.unixPermissions = this.externalFileAttributes >> 16 & 65535), this.dir || "/" !== this.fileNameStr.slice(-1) || (this.dir = true); + }, parseZIP64ExtraField: function() { + if (this.extraFields[1]) { + var e10 = n7(this.extraFields[1].value); + this.uncompressedSize === s6.MAX_VALUE_32BITS && (this.uncompressedSize = e10.readInt(8)), this.compressedSize === s6.MAX_VALUE_32BITS && (this.compressedSize = e10.readInt(8)), this.localHeaderOffset === s6.MAX_VALUE_32BITS && (this.localHeaderOffset = e10.readInt(8)), this.diskNumberStart === s6.MAX_VALUE_32BITS && (this.diskNumberStart = e10.readInt(4)); + } + }, readExtraFields: function(e10) { + var t7, r9, n8, i8 = e10.index + this.extraFieldsLength; + for (this.extraFields || (this.extraFields = {}); e10.index + 4 < i8; ) t7 = e10.readInt(2), r9 = e10.readInt(2), n8 = e10.readData(r9), this.extraFields[t7] = { id: t7, length: r9, value: n8 }; + e10.setIndex(i8); + }, handleUTF8: function() { + var e10 = u5.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) this.fileNameStr = o9.utf8decode(this.fileName), this.fileCommentStr = o9.utf8decode(this.fileComment); + else { + var t7 = this.findExtraFieldUnicodePath(); + if (null !== t7) this.fileNameStr = t7; + else { + var r9 = s6.transformTo(e10, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(r9); + } + var n8 = this.findExtraFieldUnicodeComment(); + if (null !== n8) this.fileCommentStr = n8; + else { + var i8 = s6.transformTo(e10, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(i8); + } + } + }, findExtraFieldUnicodePath: function() { + var e10 = this.extraFields[28789]; + if (e10) { + var t7 = n7(e10.value); + return 1 !== t7.readInt(1) ? null : a3(this.fileName) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5)); + } + return null; + }, findExtraFieldUnicodeComment: function() { + var e10 = this.extraFields[25461]; + if (e10) { + var t7 = n7(e10.value); + return 1 !== t7.readInt(1) ? null : a3(this.fileComment) !== t7.readInt(4) ? null : o9.utf8decode(t7.readData(e10.length - 5)); + } + return null; + } }, t6.exports = l5; + }, { "./compressedObject": 2, "./compressions": 3, "./crc32": 4, "./reader/readerFor": 22, "./support": 30, "./utf8": 31, "./utils": 32 }], 35: [function(e9, t6, r8) { + "use strict"; + function n7(e10, t7, r9) { + this.name = e10, this.dir = r9.dir, this.date = r9.date, this.comment = r9.comment, this.unixPermissions = r9.unixPermissions, this.dosPermissions = r9.dosPermissions, this._data = t7, this._dataBinary = r9.binary, this.options = { compression: r9.compression, compressionOptions: r9.compressionOptions }; + } + var s6 = e9("./stream/StreamHelper"), i7 = e9("./stream/DataWorker"), a3 = e9("./utf8"), o9 = e9("./compressedObject"), h7 = e9("./stream/GenericWorker"); + n7.prototype = { internalStream: function(e10) { + var t7 = null, r9 = "string"; + try { + if (!e10) throw new Error("No output type specified."); + var n8 = "string" === (r9 = e10.toLowerCase()) || "text" === r9; + "binarystring" !== r9 && "text" !== r9 || (r9 = "string"), t7 = this._decompressWorker(); + var i8 = !this._dataBinary; + i8 && !n8 && (t7 = t7.pipe(new a3.Utf8EncodeWorker())), !i8 && n8 && (t7 = t7.pipe(new a3.Utf8DecodeWorker())); + } catch (e11) { + (t7 = new h7("error")).error(e11); + } + return new s6(t7, r9, ""); + }, async: function(e10, t7) { + return this.internalStream(e10).accumulate(t7); + }, nodeStream: function(e10, t7) { + return this.internalStream(e10 || "nodebuffer").toNodejsStream(t7); + }, _compressWorker: function(e10, t7) { + if (this._data instanceof o9 && this._data.compression.magic === e10.magic) return this._data.getCompressedWorker(); + var r9 = this._decompressWorker(); + return this._dataBinary || (r9 = r9.pipe(new a3.Utf8EncodeWorker())), o9.createWorkerFrom(r9, e10, t7); + }, _decompressWorker: function() { + return this._data instanceof o9 ? this._data.getContentWorker() : this._data instanceof h7 ? this._data : new i7(this._data); + } }; + for (var u5 = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"], l5 = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, f4 = 0; f4 < u5.length; f4++) n7.prototype[u5[f4]] = l5; + t6.exports = n7; + }, { "./compressedObject": 2, "./stream/DataWorker": 27, "./stream/GenericWorker": 28, "./stream/StreamHelper": 29, "./utf8": 31 }], 36: [function(e9, l5, t6) { + (function(t7) { + "use strict"; + var r8, n7, e10 = t7.MutationObserver || t7.WebKitMutationObserver; + if (e10) { + var i7 = 0, s6 = new e10(u5), a3 = t7.document.createTextNode(""); + s6.observe(a3, { characterData: true }), r8 = function() { + a3.data = i7 = ++i7 % 2; + }; + } else if (t7.setImmediate || void 0 === t7.MessageChannel) r8 = "document" in t7 && "onreadystatechange" in t7.document.createElement("script") ? function() { + var e11 = t7.document.createElement("script"); + e11.onreadystatechange = function() { + u5(), e11.onreadystatechange = null, e11.parentNode.removeChild(e11), e11 = null; + }, t7.document.documentElement.appendChild(e11); + } : function() { + setTimeout(u5, 0); + }; + else { + var o9 = new t7.MessageChannel(); + o9.port1.onmessage = u5, r8 = function() { + o9.port2.postMessage(0); + }; + } + var h7 = []; + function u5() { + var e11, t8; + n7 = true; + for (var r9 = h7.length; r9; ) { + for (t8 = h7, h7 = [], e11 = -1; ++e11 < r9; ) t8[e11](); + r9 = h7.length; + } + n7 = false; + } + l5.exports = function(e11) { + 1 !== h7.push(e11) || n7 || r8(); + }; + }).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); + }, {}], 37: [function(e9, t6, r8) { + "use strict"; + var i7 = e9("immediate"); + function u5() { + } + var l5 = {}, s6 = ["REJECTED"], a3 = ["FULFILLED"], n7 = ["PENDING"]; + function o9(e10) { + if ("function" != typeof e10) throw new TypeError("resolver must be a function"); + this.state = n7, this.queue = [], this.outcome = void 0, e10 !== u5 && d4(this, e10); + } + function h7(e10, t7, r9) { + this.promise = e10, "function" == typeof t7 && (this.onFulfilled = t7, this.callFulfilled = this.otherCallFulfilled), "function" == typeof r9 && (this.onRejected = r9, this.callRejected = this.otherCallRejected); + } + function f4(t7, r9, n8) { + i7(function() { + var e10; + try { + e10 = r9(n8); + } catch (e11) { + return l5.reject(t7, e11); + } + e10 === t7 ? l5.reject(t7, new TypeError("Cannot resolve promise with itself")) : l5.resolve(t7, e10); + }); + } + function c6(e10) { + var t7 = e10 && e10.then; + if (e10 && ("object" == typeof e10 || "function" == typeof e10) && "function" == typeof t7) return function() { + t7.apply(e10, arguments); + }; + } + function d4(t7, e10) { + var r9 = false; + function n8(e11) { + r9 || (r9 = true, l5.reject(t7, e11)); + } + function i8(e11) { + r9 || (r9 = true, l5.resolve(t7, e11)); + } + var s7 = p4(function() { + e10(i8, n8); + }); + "error" === s7.status && n8(s7.value); + } + function p4(e10, t7) { + var r9 = {}; + try { + r9.value = e10(t7), r9.status = "success"; + } catch (e11) { + r9.status = "error", r9.value = e11; + } + return r9; + } + (t6.exports = o9).prototype.finally = function(t7) { + if ("function" != typeof t7) return this; + var r9 = this.constructor; + return this.then(function(e10) { + return r9.resolve(t7()).then(function() { + return e10; + }); + }, function(e10) { + return r9.resolve(t7()).then(function() { + throw e10; + }); + }); + }, o9.prototype.catch = function(e10) { + return this.then(null, e10); + }, o9.prototype.then = function(e10, t7) { + if ("function" != typeof e10 && this.state === a3 || "function" != typeof t7 && this.state === s6) return this; + var r9 = new this.constructor(u5); + this.state !== n7 ? f4(r9, this.state === a3 ? e10 : t7, this.outcome) : this.queue.push(new h7(r9, e10, t7)); + return r9; + }, h7.prototype.callFulfilled = function(e10) { + l5.resolve(this.promise, e10); + }, h7.prototype.otherCallFulfilled = function(e10) { + f4(this.promise, this.onFulfilled, e10); + }, h7.prototype.callRejected = function(e10) { + l5.reject(this.promise, e10); + }, h7.prototype.otherCallRejected = function(e10) { + f4(this.promise, this.onRejected, e10); + }, l5.resolve = function(e10, t7) { + var r9 = p4(c6, t7); + if ("error" === r9.status) return l5.reject(e10, r9.value); + var n8 = r9.value; + if (n8) d4(e10, n8); + else { + e10.state = a3, e10.outcome = t7; + for (var i8 = -1, s7 = e10.queue.length; ++i8 < s7; ) e10.queue[i8].callFulfilled(t7); + } + return e10; + }, l5.reject = function(e10, t7) { + e10.state = s6, e10.outcome = t7; + for (var r9 = -1, n8 = e10.queue.length; ++r9 < n8; ) e10.queue[r9].callRejected(t7); + return e10; + }, o9.resolve = function(e10) { + if (e10 instanceof this) return e10; + return l5.resolve(new this(u5), e10); + }, o9.reject = function(e10) { + var t7 = new this(u5); + return l5.reject(t7, e10); + }, o9.all = function(e10) { + var r9 = this; + if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array")); + var n8 = e10.length, i8 = false; + if (!n8) return this.resolve([]); + var s7 = new Array(n8), a4 = 0, t7 = -1, o10 = new this(u5); + for (; ++t7 < n8; ) h8(e10[t7], t7); + return o10; + function h8(e11, t8) { + r9.resolve(e11).then(function(e12) { + s7[t8] = e12, ++a4 !== n8 || i8 || (i8 = true, l5.resolve(o10, s7)); + }, function(e12) { + i8 || (i8 = true, l5.reject(o10, e12)); + }); + } + }, o9.race = function(e10) { + var t7 = this; + if ("[object Array]" !== Object.prototype.toString.call(e10)) return this.reject(new TypeError("must be an array")); + var r9 = e10.length, n8 = false; + if (!r9) return this.resolve([]); + var i8 = -1, s7 = new this(u5); + for (; ++i8 < r9; ) a4 = e10[i8], t7.resolve(a4).then(function(e11) { + n8 || (n8 = true, l5.resolve(s7, e11)); + }, function(e11) { + n8 || (n8 = true, l5.reject(s7, e11)); + }); + var a4; + return s7; + }; + }, { immediate: 36 }], 38: [function(e9, t6, r8) { + "use strict"; + var n7 = {}; + (0, e9("./lib/utils/common").assign)(n7, e9("./lib/deflate"), e9("./lib/inflate"), e9("./lib/zlib/constants")), t6.exports = n7; + }, { "./lib/deflate": 39, "./lib/inflate": 40, "./lib/utils/common": 41, "./lib/zlib/constants": 44 }], 39: [function(e9, t6, r8) { + "use strict"; + var a3 = e9("./zlib/deflate"), o9 = e9("./utils/common"), h7 = e9("./utils/strings"), i7 = e9("./zlib/messages"), s6 = e9("./zlib/zstream"), u5 = Object.prototype.toString, l5 = 0, f4 = -1, c6 = 0, d4 = 8; + function p4(e10) { + if (!(this instanceof p4)) return new p4(e10); + this.options = o9.assign({ level: f4, method: d4, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: c6, to: "" }, e10 || {}); + var t7 = this.options; + t7.raw && 0 < t7.windowBits ? t7.windowBits = -t7.windowBits : t7.gzip && 0 < t7.windowBits && t7.windowBits < 16 && (t7.windowBits += 16), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new s6(), this.strm.avail_out = 0; + var r9 = a3.deflateInit2(this.strm, t7.level, t7.method, t7.windowBits, t7.memLevel, t7.strategy); + if (r9 !== l5) throw new Error(i7[r9]); + if (t7.header && a3.deflateSetHeader(this.strm, t7.header), t7.dictionary) { + var n8; + if (n8 = "string" == typeof t7.dictionary ? h7.string2buf(t7.dictionary) : "[object ArrayBuffer]" === u5.call(t7.dictionary) ? new Uint8Array(t7.dictionary) : t7.dictionary, (r9 = a3.deflateSetDictionary(this.strm, n8)) !== l5) throw new Error(i7[r9]); + this._dict_set = true; + } + } + function n7(e10, t7) { + var r9 = new p4(t7); + if (r9.push(e10, true), r9.err) throw r9.msg || i7[r9.err]; + return r9.result; + } + p4.prototype.push = function(e10, t7) { + var r9, n8, i8 = this.strm, s7 = this.options.chunkSize; + if (this.ended) return false; + n8 = t7 === ~~t7 ? t7 : true === t7 ? 4 : 0, "string" == typeof e10 ? i8.input = h7.string2buf(e10) : "[object ArrayBuffer]" === u5.call(e10) ? i8.input = new Uint8Array(e10) : i8.input = e10, i8.next_in = 0, i8.avail_in = i8.input.length; + do { + if (0 === i8.avail_out && (i8.output = new o9.Buf8(s7), i8.next_out = 0, i8.avail_out = s7), 1 !== (r9 = a3.deflate(i8, n8)) && r9 !== l5) return this.onEnd(r9), !(this.ended = true); + 0 !== i8.avail_out && (0 !== i8.avail_in || 4 !== n8 && 2 !== n8) || ("string" === this.options.to ? this.onData(h7.buf2binstring(o9.shrinkBuf(i8.output, i8.next_out))) : this.onData(o9.shrinkBuf(i8.output, i8.next_out))); + } while ((0 < i8.avail_in || 0 === i8.avail_out) && 1 !== r9); + return 4 === n8 ? (r9 = a3.deflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === l5) : 2 !== n8 || (this.onEnd(l5), !(i8.avail_out = 0)); + }, p4.prototype.onData = function(e10) { + this.chunks.push(e10); + }, p4.prototype.onEnd = function(e10) { + e10 === l5 && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = o9.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg; + }, r8.Deflate = p4, r8.deflate = n7, r8.deflateRaw = function(e10, t7) { + return (t7 = t7 || {}).raw = true, n7(e10, t7); + }, r8.gzip = function(e10, t7) { + return (t7 = t7 || {}).gzip = true, n7(e10, t7); + }; + }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/deflate": 46, "./zlib/messages": 51, "./zlib/zstream": 53 }], 40: [function(e9, t6, r8) { + "use strict"; + var c6 = e9("./zlib/inflate"), d4 = e9("./utils/common"), p4 = e9("./utils/strings"), m4 = e9("./zlib/constants"), n7 = e9("./zlib/messages"), i7 = e9("./zlib/zstream"), s6 = e9("./zlib/gzheader"), _3 = Object.prototype.toString; + function a3(e10) { + if (!(this instanceof a3)) return new a3(e10); + this.options = d4.assign({ chunkSize: 16384, windowBits: 0, to: "" }, e10 || {}); + var t7 = this.options; + t7.raw && 0 <= t7.windowBits && t7.windowBits < 16 && (t7.windowBits = -t7.windowBits, 0 === t7.windowBits && (t7.windowBits = -15)), !(0 <= t7.windowBits && t7.windowBits < 16) || e10 && e10.windowBits || (t7.windowBits += 32), 15 < t7.windowBits && t7.windowBits < 48 && 0 == (15 & t7.windowBits) && (t7.windowBits |= 15), this.err = 0, this.msg = "", this.ended = false, this.chunks = [], this.strm = new i7(), this.strm.avail_out = 0; + var r9 = c6.inflateInit2(this.strm, t7.windowBits); + if (r9 !== m4.Z_OK) throw new Error(n7[r9]); + this.header = new s6(), c6.inflateGetHeader(this.strm, this.header); + } + function o9(e10, t7) { + var r9 = new a3(t7); + if (r9.push(e10, true), r9.err) throw r9.msg || n7[r9.err]; + return r9.result; + } + a3.prototype.push = function(e10, t7) { + var r9, n8, i8, s7, a4, o10, h7 = this.strm, u5 = this.options.chunkSize, l5 = this.options.dictionary, f4 = false; + if (this.ended) return false; + n8 = t7 === ~~t7 ? t7 : true === t7 ? m4.Z_FINISH : m4.Z_NO_FLUSH, "string" == typeof e10 ? h7.input = p4.binstring2buf(e10) : "[object ArrayBuffer]" === _3.call(e10) ? h7.input = new Uint8Array(e10) : h7.input = e10, h7.next_in = 0, h7.avail_in = h7.input.length; + do { + if (0 === h7.avail_out && (h7.output = new d4.Buf8(u5), h7.next_out = 0, h7.avail_out = u5), (r9 = c6.inflate(h7, m4.Z_NO_FLUSH)) === m4.Z_NEED_DICT && l5 && (o10 = "string" == typeof l5 ? p4.string2buf(l5) : "[object ArrayBuffer]" === _3.call(l5) ? new Uint8Array(l5) : l5, r9 = c6.inflateSetDictionary(this.strm, o10)), r9 === m4.Z_BUF_ERROR && true === f4 && (r9 = m4.Z_OK, f4 = false), r9 !== m4.Z_STREAM_END && r9 !== m4.Z_OK) return this.onEnd(r9), !(this.ended = true); + h7.next_out && (0 !== h7.avail_out && r9 !== m4.Z_STREAM_END && (0 !== h7.avail_in || n8 !== m4.Z_FINISH && n8 !== m4.Z_SYNC_FLUSH) || ("string" === this.options.to ? (i8 = p4.utf8border(h7.output, h7.next_out), s7 = h7.next_out - i8, a4 = p4.buf2string(h7.output, i8), h7.next_out = s7, h7.avail_out = u5 - s7, s7 && d4.arraySet(h7.output, h7.output, i8, s7, 0), this.onData(a4)) : this.onData(d4.shrinkBuf(h7.output, h7.next_out)))), 0 === h7.avail_in && 0 === h7.avail_out && (f4 = true); + } while ((0 < h7.avail_in || 0 === h7.avail_out) && r9 !== m4.Z_STREAM_END); + return r9 === m4.Z_STREAM_END && (n8 = m4.Z_FINISH), n8 === m4.Z_FINISH ? (r9 = c6.inflateEnd(this.strm), this.onEnd(r9), this.ended = true, r9 === m4.Z_OK) : n8 !== m4.Z_SYNC_FLUSH || (this.onEnd(m4.Z_OK), !(h7.avail_out = 0)); + }, a3.prototype.onData = function(e10) { + this.chunks.push(e10); + }, a3.prototype.onEnd = function(e10) { + e10 === m4.Z_OK && ("string" === this.options.to ? this.result = this.chunks.join("") : this.result = d4.flattenChunks(this.chunks)), this.chunks = [], this.err = e10, this.msg = this.strm.msg; + }, r8.Inflate = a3, r8.inflate = o9, r8.inflateRaw = function(e10, t7) { + return (t7 = t7 || {}).raw = true, o9(e10, t7); + }, r8.ungzip = o9; + }, { "./utils/common": 41, "./utils/strings": 42, "./zlib/constants": 44, "./zlib/gzheader": 47, "./zlib/inflate": 49, "./zlib/messages": 51, "./zlib/zstream": 53 }], 41: [function(e9, t6, r8) { + "use strict"; + var n7 = "undefined" != typeof Uint8Array && "undefined" != typeof Uint16Array && "undefined" != typeof Int32Array; + r8.assign = function(e10) { + for (var t7 = Array.prototype.slice.call(arguments, 1); t7.length; ) { + var r9 = t7.shift(); + if (r9) { + if ("object" != typeof r9) throw new TypeError(r9 + "must be non-object"); + for (var n8 in r9) r9.hasOwnProperty(n8) && (e10[n8] = r9[n8]); + } + } + return e10; + }, r8.shrinkBuf = function(e10, t7) { + return e10.length === t7 ? e10 : e10.subarray ? e10.subarray(0, t7) : (e10.length = t7, e10); + }; + var i7 = { arraySet: function(e10, t7, r9, n8, i8) { + if (t7.subarray && e10.subarray) e10.set(t7.subarray(r9, r9 + n8), i8); + else for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7]; + }, flattenChunks: function(e10) { + var t7, r9, n8, i8, s7, a3; + for (t7 = n8 = 0, r9 = e10.length; t7 < r9; t7++) n8 += e10[t7].length; + for (a3 = new Uint8Array(n8), t7 = i8 = 0, r9 = e10.length; t7 < r9; t7++) s7 = e10[t7], a3.set(s7, i8), i8 += s7.length; + return a3; + } }, s6 = { arraySet: function(e10, t7, r9, n8, i8) { + for (var s7 = 0; s7 < n8; s7++) e10[i8 + s7] = t7[r9 + s7]; + }, flattenChunks: function(e10) { + return [].concat.apply([], e10); + } }; + r8.setTyped = function(e10) { + e10 ? (r8.Buf8 = Uint8Array, r8.Buf16 = Uint16Array, r8.Buf32 = Int32Array, r8.assign(r8, i7)) : (r8.Buf8 = Array, r8.Buf16 = Array, r8.Buf32 = Array, r8.assign(r8, s6)); + }, r8.setTyped(n7); + }, {}], 42: [function(e9, t6, r8) { + "use strict"; + var h7 = e9("./common"), i7 = true, s6 = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (e10) { + i7 = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (e10) { + s6 = false; + } + for (var u5 = new h7.Buf8(256), n7 = 0; n7 < 256; n7++) u5[n7] = 252 <= n7 ? 6 : 248 <= n7 ? 5 : 240 <= n7 ? 4 : 224 <= n7 ? 3 : 192 <= n7 ? 2 : 1; + function l5(e10, t7) { + if (t7 < 65537 && (e10.subarray && s6 || !e10.subarray && i7)) return String.fromCharCode.apply(null, h7.shrinkBuf(e10, t7)); + for (var r9 = "", n8 = 0; n8 < t7; n8++) r9 += String.fromCharCode(e10[n8]); + return r9; + } + u5[254] = u5[254] = 1, r8.string2buf = function(e10) { + var t7, r9, n8, i8, s7, a3 = e10.length, o9 = 0; + for (i8 = 0; i8 < a3; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), o9 += r9 < 128 ? 1 : r9 < 2048 ? 2 : r9 < 65536 ? 3 : 4; + for (t7 = new h7.Buf8(o9), i8 = s7 = 0; s7 < o9; i8++) 55296 == (64512 & (r9 = e10.charCodeAt(i8))) && i8 + 1 < a3 && 56320 == (64512 & (n8 = e10.charCodeAt(i8 + 1))) && (r9 = 65536 + (r9 - 55296 << 10) + (n8 - 56320), i8++), r9 < 128 ? t7[s7++] = r9 : (r9 < 2048 ? t7[s7++] = 192 | r9 >>> 6 : (r9 < 65536 ? t7[s7++] = 224 | r9 >>> 12 : (t7[s7++] = 240 | r9 >>> 18, t7[s7++] = 128 | r9 >>> 12 & 63), t7[s7++] = 128 | r9 >>> 6 & 63), t7[s7++] = 128 | 63 & r9); + return t7; + }, r8.buf2binstring = function(e10) { + return l5(e10, e10.length); + }, r8.binstring2buf = function(e10) { + for (var t7 = new h7.Buf8(e10.length), r9 = 0, n8 = t7.length; r9 < n8; r9++) t7[r9] = e10.charCodeAt(r9); + return t7; + }, r8.buf2string = function(e10, t7) { + var r9, n8, i8, s7, a3 = t7 || e10.length, o9 = new Array(2 * a3); + for (r9 = n8 = 0; r9 < a3; ) if ((i8 = e10[r9++]) < 128) o9[n8++] = i8; + else if (4 < (s7 = u5[i8])) o9[n8++] = 65533, r9 += s7 - 1; + else { + for (i8 &= 2 === s7 ? 31 : 3 === s7 ? 15 : 7; 1 < s7 && r9 < a3; ) i8 = i8 << 6 | 63 & e10[r9++], s7--; + 1 < s7 ? o9[n8++] = 65533 : i8 < 65536 ? o9[n8++] = i8 : (i8 -= 65536, o9[n8++] = 55296 | i8 >> 10 & 1023, o9[n8++] = 56320 | 1023 & i8); + } + return l5(o9, n8); + }, r8.utf8border = function(e10, t7) { + var r9; + for ((t7 = t7 || e10.length) > e10.length && (t7 = e10.length), r9 = t7 - 1; 0 <= r9 && 128 == (192 & e10[r9]); ) r9--; + return r9 < 0 ? t7 : 0 === r9 ? t7 : r9 + u5[e10[r9]] > t7 ? r9 : t7; + }; + }, { "./common": 41 }], 43: [function(e9, t6, r8) { + "use strict"; + t6.exports = function(e10, t7, r9, n7) { + for (var i7 = 65535 & e10 | 0, s6 = e10 >>> 16 & 65535 | 0, a3 = 0; 0 !== r9; ) { + for (r9 -= a3 = 2e3 < r9 ? 2e3 : r9; s6 = s6 + (i7 = i7 + t7[n7++] | 0) | 0, --a3; ) ; + i7 %= 65521, s6 %= 65521; + } + return i7 | s6 << 16 | 0; + }; + }, {}], 44: [function(e9, t6, r8) { + "use strict"; + t6.exports = { Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_BUF_ERROR: -5, Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, Z_BINARY: 0, Z_TEXT: 1, Z_UNKNOWN: 2, Z_DEFLATED: 8 }; + }, {}], 45: [function(e9, t6, r8) { + "use strict"; + var o9 = (function() { + for (var e10, t7 = [], r9 = 0; r9 < 256; r9++) { + e10 = r9; + for (var n7 = 0; n7 < 8; n7++) e10 = 1 & e10 ? 3988292384 ^ e10 >>> 1 : e10 >>> 1; + t7[r9] = e10; + } + return t7; + })(); + t6.exports = function(e10, t7, r9, n7) { + var i7 = o9, s6 = n7 + r9; + e10 ^= -1; + for (var a3 = n7; a3 < s6; a3++) e10 = e10 >>> 8 ^ i7[255 & (e10 ^ t7[a3])]; + return -1 ^ e10; + }; + }, {}], 46: [function(e9, t6, r8) { + "use strict"; + var h7, c6 = e9("../utils/common"), u5 = e9("./trees"), d4 = e9("./adler32"), p4 = e9("./crc32"), n7 = e9("./messages"), l5 = 0, f4 = 4, m4 = 0, _3 = -2, g3 = -1, b4 = 4, i7 = 2, v4 = 8, y4 = 9, s6 = 286, a3 = 30, o9 = 19, w3 = 2 * s6 + 1, k2 = 15, x2 = 3, S5 = 258, z3 = S5 + x2 + 1, C3 = 42, E3 = 113, A2 = 1, I3 = 2, O2 = 3, B3 = 4; + function R3(e10, t7) { + return e10.msg = n7[t7], t7; + } + function T3(e10) { + return (e10 << 1) - (4 < e10 ? 9 : 0); + } + function D4(e10) { + for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0; + } + function F2(e10) { + var t7 = e10.state, r9 = t7.pending; + r9 > e10.avail_out && (r9 = e10.avail_out), 0 !== r9 && (c6.arraySet(e10.output, t7.pending_buf, t7.pending_out, r9, e10.next_out), e10.next_out += r9, t7.pending_out += r9, e10.total_out += r9, e10.avail_out -= r9, t7.pending -= r9, 0 === t7.pending && (t7.pending_out = 0)); + } + function N3(e10, t7) { + u5._tr_flush_block(e10, 0 <= e10.block_start ? e10.block_start : -1, e10.strstart - e10.block_start, t7), e10.block_start = e10.strstart, F2(e10.strm); + } + function U2(e10, t7) { + e10.pending_buf[e10.pending++] = t7; + } + function P3(e10, t7) { + e10.pending_buf[e10.pending++] = t7 >>> 8 & 255, e10.pending_buf[e10.pending++] = 255 & t7; + } + function L3(e10, t7) { + var r9, n8, i8 = e10.max_chain_length, s7 = e10.strstart, a4 = e10.prev_length, o10 = e10.nice_match, h8 = e10.strstart > e10.w_size - z3 ? e10.strstart - (e10.w_size - z3) : 0, u6 = e10.window, l6 = e10.w_mask, f5 = e10.prev, c7 = e10.strstart + S5, d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4]; + e10.prev_length >= e10.good_match && (i8 >>= 2), o10 > e10.lookahead && (o10 = e10.lookahead); + do { + if (u6[(r9 = t7) + a4] === p5 && u6[r9 + a4 - 1] === d5 && u6[r9] === u6[s7] && u6[++r9] === u6[s7 + 1]) { + s7 += 2, r9++; + do { + } while (u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && u6[++s7] === u6[++r9] && s7 < c7); + if (n8 = S5 - (c7 - s7), s7 = c7 - S5, a4 < n8) { + if (e10.match_start = t7, o10 <= (a4 = n8)) break; + d5 = u6[s7 + a4 - 1], p5 = u6[s7 + a4]; + } + } + } while ((t7 = f5[t7 & l6]) > h8 && 0 != --i8); + return a4 <= e10.lookahead ? a4 : e10.lookahead; + } + function j3(e10) { + var t7, r9, n8, i8, s7, a4, o10, h8, u6, l6, f5 = e10.w_size; + do { + if (i8 = e10.window_size - e10.lookahead - e10.strstart, e10.strstart >= f5 + (f5 - z3)) { + for (c6.arraySet(e10.window, e10.window, f5, f5, 0), e10.match_start -= f5, e10.strstart -= f5, e10.block_start -= f5, t7 = r9 = e10.hash_size; n8 = e10.head[--t7], e10.head[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ; + for (t7 = r9 = f5; n8 = e10.prev[--t7], e10.prev[t7] = f5 <= n8 ? n8 - f5 : 0, --r9; ) ; + i8 += f5; + } + if (0 === e10.strm.avail_in) break; + if (a4 = e10.strm, o10 = e10.window, h8 = e10.strstart + e10.lookahead, u6 = i8, l6 = void 0, l6 = a4.avail_in, u6 < l6 && (l6 = u6), r9 = 0 === l6 ? 0 : (a4.avail_in -= l6, c6.arraySet(o10, a4.input, a4.next_in, l6, h8), 1 === a4.state.wrap ? a4.adler = d4(a4.adler, o10, l6, h8) : 2 === a4.state.wrap && (a4.adler = p4(a4.adler, o10, l6, h8)), a4.next_in += l6, a4.total_in += l6, l6), e10.lookahead += r9, e10.lookahead + e10.insert >= x2) for (s7 = e10.strstart - e10.insert, e10.ins_h = e10.window[s7], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + 1]) & e10.hash_mask; e10.insert && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[s7 + x2 - 1]) & e10.hash_mask, e10.prev[s7 & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = s7, s7++, e10.insert--, !(e10.lookahead + e10.insert < x2)); ) ; + } while (e10.lookahead < z3 && 0 !== e10.strm.avail_in); + } + function Z2(e10, t7) { + for (var r9, n8; ; ) { + if (e10.lookahead < z3) { + if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2; + if (0 === e10.lookahead) break; + } + if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 !== r9 && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9)), e10.match_length >= x2) if (n8 = u5._tr_tally(e10, e10.strstart - e10.match_start, e10.match_length - x2), e10.lookahead -= e10.match_length, e10.match_length <= e10.max_lazy_match && e10.lookahead >= x2) { + for (e10.match_length--; e10.strstart++, e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart, 0 != --e10.match_length; ) ; + e10.strstart++; + } else e10.strstart += e10.match_length, e10.match_length = 0, e10.ins_h = e10.window[e10.strstart], e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + 1]) & e10.hash_mask; + else n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart]), e10.lookahead--, e10.strstart++; + if (n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2; + } + return e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3; + } + function W2(e10, t7) { + for (var r9, n8, i8; ; ) { + if (e10.lookahead < z3) { + if (j3(e10), e10.lookahead < z3 && t7 === l5) return A2; + if (0 === e10.lookahead) break; + } + if (r9 = 0, e10.lookahead >= x2 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), e10.prev_length = e10.match_length, e10.prev_match = e10.match_start, e10.match_length = x2 - 1, 0 !== r9 && e10.prev_length < e10.max_lazy_match && e10.strstart - r9 <= e10.w_size - z3 && (e10.match_length = L3(e10, r9), e10.match_length <= 5 && (1 === e10.strategy || e10.match_length === x2 && 4096 < e10.strstart - e10.match_start) && (e10.match_length = x2 - 1)), e10.prev_length >= x2 && e10.match_length <= e10.prev_length) { + for (i8 = e10.strstart + e10.lookahead - x2, n8 = u5._tr_tally(e10, e10.strstart - 1 - e10.prev_match, e10.prev_length - x2), e10.lookahead -= e10.prev_length - 1, e10.prev_length -= 2; ++e10.strstart <= i8 && (e10.ins_h = (e10.ins_h << e10.hash_shift ^ e10.window[e10.strstart + x2 - 1]) & e10.hash_mask, r9 = e10.prev[e10.strstart & e10.w_mask] = e10.head[e10.ins_h], e10.head[e10.ins_h] = e10.strstart), 0 != --e10.prev_length; ) ; + if (e10.match_available = 0, e10.match_length = x2 - 1, e10.strstart++, n8 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2; + } else if (e10.match_available) { + if ((n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1])) && N3(e10, false), e10.strstart++, e10.lookahead--, 0 === e10.strm.avail_out) return A2; + } else e10.match_available = 1, e10.strstart++, e10.lookahead--; + } + return e10.match_available && (n8 = u5._tr_tally(e10, 0, e10.window[e10.strstart - 1]), e10.match_available = 0), e10.insert = e10.strstart < x2 - 1 ? e10.strstart : x2 - 1, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : e10.last_lit && (N3(e10, false), 0 === e10.strm.avail_out) ? A2 : I3; + } + function M4(e10, t7, r9, n8, i8) { + this.good_length = e10, this.max_lazy = t7, this.nice_length = r9, this.max_chain = n8, this.func = i8; + } + function H2() { + this.strm = null, this.status = 0, this.pending_buf = null, this.pending_buf_size = 0, this.pending_out = 0, this.pending = 0, this.wrap = 0, this.gzhead = null, this.gzindex = 0, this.method = v4, this.last_flush = -1, this.w_size = 0, this.w_bits = 0, this.w_mask = 0, this.window = null, this.window_size = 0, this.prev = null, this.head = null, this.ins_h = 0, this.hash_size = 0, this.hash_bits = 0, this.hash_mask = 0, this.hash_shift = 0, this.block_start = 0, this.match_length = 0, this.prev_match = 0, this.match_available = 0, this.strstart = 0, this.match_start = 0, this.lookahead = 0, this.prev_length = 0, this.max_chain_length = 0, this.max_lazy_match = 0, this.level = 0, this.strategy = 0, this.good_match = 0, this.nice_match = 0, this.dyn_ltree = new c6.Buf16(2 * w3), this.dyn_dtree = new c6.Buf16(2 * (2 * a3 + 1)), this.bl_tree = new c6.Buf16(2 * (2 * o9 + 1)), D4(this.dyn_ltree), D4(this.dyn_dtree), D4(this.bl_tree), this.l_desc = null, this.d_desc = null, this.bl_desc = null, this.bl_count = new c6.Buf16(k2 + 1), this.heap = new c6.Buf16(2 * s6 + 1), D4(this.heap), this.heap_len = 0, this.heap_max = 0, this.depth = new c6.Buf16(2 * s6 + 1), D4(this.depth), this.l_buf = 0, this.lit_bufsize = 0, this.last_lit = 0, this.d_buf = 0, this.opt_len = 0, this.static_len = 0, this.matches = 0, this.insert = 0, this.bi_buf = 0, this.bi_valid = 0; + } + function G2(e10) { + var t7; + return e10 && e10.state ? (e10.total_in = e10.total_out = 0, e10.data_type = i7, (t7 = e10.state).pending = 0, t7.pending_out = 0, t7.wrap < 0 && (t7.wrap = -t7.wrap), t7.status = t7.wrap ? C3 : E3, e10.adler = 2 === t7.wrap ? 0 : 1, t7.last_flush = l5, u5._tr_init(t7), m4) : R3(e10, _3); + } + function K2(e10) { + var t7 = G2(e10); + return t7 === m4 && (function(e11) { + e11.window_size = 2 * e11.w_size, D4(e11.head), e11.max_lazy_match = h7[e11.level].max_lazy, e11.good_match = h7[e11.level].good_length, e11.nice_match = h7[e11.level].nice_length, e11.max_chain_length = h7[e11.level].max_chain, e11.strstart = 0, e11.block_start = 0, e11.lookahead = 0, e11.insert = 0, e11.match_length = e11.prev_length = x2 - 1, e11.match_available = 0, e11.ins_h = 0; + })(e10.state), t7; + } + function Y(e10, t7, r9, n8, i8, s7) { + if (!e10) return _3; + var a4 = 1; + if (t7 === g3 && (t7 = 6), n8 < 0 ? (a4 = 0, n8 = -n8) : 15 < n8 && (a4 = 2, n8 -= 16), i8 < 1 || y4 < i8 || r9 !== v4 || n8 < 8 || 15 < n8 || t7 < 0 || 9 < t7 || s7 < 0 || b4 < s7) return R3(e10, _3); + 8 === n8 && (n8 = 9); + var o10 = new H2(); + return (e10.state = o10).strm = e10, o10.wrap = a4, o10.gzhead = null, o10.w_bits = n8, o10.w_size = 1 << o10.w_bits, o10.w_mask = o10.w_size - 1, o10.hash_bits = i8 + 7, o10.hash_size = 1 << o10.hash_bits, o10.hash_mask = o10.hash_size - 1, o10.hash_shift = ~~((o10.hash_bits + x2 - 1) / x2), o10.window = new c6.Buf8(2 * o10.w_size), o10.head = new c6.Buf16(o10.hash_size), o10.prev = new c6.Buf16(o10.w_size), o10.lit_bufsize = 1 << i8 + 6, o10.pending_buf_size = 4 * o10.lit_bufsize, o10.pending_buf = new c6.Buf8(o10.pending_buf_size), o10.d_buf = 1 * o10.lit_bufsize, o10.l_buf = 3 * o10.lit_bufsize, o10.level = t7, o10.strategy = s7, o10.method = r9, K2(e10); + } + h7 = [new M4(0, 0, 0, 0, function(e10, t7) { + var r9 = 65535; + for (r9 > e10.pending_buf_size - 5 && (r9 = e10.pending_buf_size - 5); ; ) { + if (e10.lookahead <= 1) { + if (j3(e10), 0 === e10.lookahead && t7 === l5) return A2; + if (0 === e10.lookahead) break; + } + e10.strstart += e10.lookahead, e10.lookahead = 0; + var n8 = e10.block_start + r9; + if ((0 === e10.strstart || e10.strstart >= n8) && (e10.lookahead = e10.strstart - n8, e10.strstart = n8, N3(e10, false), 0 === e10.strm.avail_out)) return A2; + if (e10.strstart - e10.block_start >= e10.w_size - z3 && (N3(e10, false), 0 === e10.strm.avail_out)) return A2; + } + return e10.insert = 0, t7 === f4 ? (N3(e10, true), 0 === e10.strm.avail_out ? O2 : B3) : (e10.strstart > e10.block_start && (N3(e10, false), e10.strm.avail_out), A2); + }), new M4(4, 4, 8, 4, Z2), new M4(4, 5, 16, 8, Z2), new M4(4, 6, 32, 32, Z2), new M4(4, 4, 16, 16, W2), new M4(8, 16, 32, 32, W2), new M4(8, 16, 128, 128, W2), new M4(8, 32, 128, 256, W2), new M4(32, 128, 258, 1024, W2), new M4(32, 258, 258, 4096, W2)], r8.deflateInit = function(e10, t7) { + return Y(e10, t7, v4, 15, 8, 0); + }, r8.deflateInit2 = Y, r8.deflateReset = K2, r8.deflateResetKeep = G2, r8.deflateSetHeader = function(e10, t7) { + return e10 && e10.state ? 2 !== e10.state.wrap ? _3 : (e10.state.gzhead = t7, m4) : _3; + }, r8.deflate = function(e10, t7) { + var r9, n8, i8, s7; + if (!e10 || !e10.state || 5 < t7 || t7 < 0) return e10 ? R3(e10, _3) : _3; + if (n8 = e10.state, !e10.output || !e10.input && 0 !== e10.avail_in || 666 === n8.status && t7 !== f4) return R3(e10, 0 === e10.avail_out ? -5 : _3); + if (n8.strm = e10, r9 = n8.last_flush, n8.last_flush = t7, n8.status === C3) if (2 === n8.wrap) e10.adler = 0, U2(n8, 31), U2(n8, 139), U2(n8, 8), n8.gzhead ? (U2(n8, (n8.gzhead.text ? 1 : 0) + (n8.gzhead.hcrc ? 2 : 0) + (n8.gzhead.extra ? 4 : 0) + (n8.gzhead.name ? 8 : 0) + (n8.gzhead.comment ? 16 : 0)), U2(n8, 255 & n8.gzhead.time), U2(n8, n8.gzhead.time >> 8 & 255), U2(n8, n8.gzhead.time >> 16 & 255), U2(n8, n8.gzhead.time >> 24 & 255), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 255 & n8.gzhead.os), n8.gzhead.extra && n8.gzhead.extra.length && (U2(n8, 255 & n8.gzhead.extra.length), U2(n8, n8.gzhead.extra.length >> 8 & 255)), n8.gzhead.hcrc && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending, 0)), n8.gzindex = 0, n8.status = 69) : (U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 0), U2(n8, 9 === n8.level ? 2 : 2 <= n8.strategy || n8.level < 2 ? 4 : 0), U2(n8, 3), n8.status = E3); + else { + var a4 = v4 + (n8.w_bits - 8 << 4) << 8; + a4 |= (2 <= n8.strategy || n8.level < 2 ? 0 : n8.level < 6 ? 1 : 6 === n8.level ? 2 : 3) << 6, 0 !== n8.strstart && (a4 |= 32), a4 += 31 - a4 % 31, n8.status = E3, P3(n8, a4), 0 !== n8.strstart && (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), e10.adler = 1; + } + if (69 === n8.status) if (n8.gzhead.extra) { + for (i8 = n8.pending; n8.gzindex < (65535 & n8.gzhead.extra.length) && (n8.pending !== n8.pending_buf_size || (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending !== n8.pending_buf_size)); ) U2(n8, 255 & n8.gzhead.extra[n8.gzindex]), n8.gzindex++; + n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), n8.gzindex === n8.gzhead.extra.length && (n8.gzindex = 0, n8.status = 73); + } else n8.status = 73; + if (73 === n8.status) if (n8.gzhead.name) { + i8 = n8.pending; + do { + if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) { + s7 = 1; + break; + } + s7 = n8.gzindex < n8.gzhead.name.length ? 255 & n8.gzhead.name.charCodeAt(n8.gzindex++) : 0, U2(n8, s7); + } while (0 !== s7); + n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.gzindex = 0, n8.status = 91); + } else n8.status = 91; + if (91 === n8.status) if (n8.gzhead.comment) { + i8 = n8.pending; + do { + if (n8.pending === n8.pending_buf_size && (n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), F2(e10), i8 = n8.pending, n8.pending === n8.pending_buf_size)) { + s7 = 1; + break; + } + s7 = n8.gzindex < n8.gzhead.comment.length ? 255 & n8.gzhead.comment.charCodeAt(n8.gzindex++) : 0, U2(n8, s7); + } while (0 !== s7); + n8.gzhead.hcrc && n8.pending > i8 && (e10.adler = p4(e10.adler, n8.pending_buf, n8.pending - i8, i8)), 0 === s7 && (n8.status = 103); + } else n8.status = 103; + if (103 === n8.status && (n8.gzhead.hcrc ? (n8.pending + 2 > n8.pending_buf_size && F2(e10), n8.pending + 2 <= n8.pending_buf_size && (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), e10.adler = 0, n8.status = E3)) : n8.status = E3), 0 !== n8.pending) { + if (F2(e10), 0 === e10.avail_out) return n8.last_flush = -1, m4; + } else if (0 === e10.avail_in && T3(t7) <= T3(r9) && t7 !== f4) return R3(e10, -5); + if (666 === n8.status && 0 !== e10.avail_in) return R3(e10, -5); + if (0 !== e10.avail_in || 0 !== n8.lookahead || t7 !== l5 && 666 !== n8.status) { + var o10 = 2 === n8.strategy ? (function(e11, t8) { + for (var r10; ; ) { + if (0 === e11.lookahead && (j3(e11), 0 === e11.lookahead)) { + if (t8 === l5) return A2; + break; + } + if (e11.match_length = 0, r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++, r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2; + } + return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3; + })(n8, t7) : 3 === n8.strategy ? (function(e11, t8) { + for (var r10, n9, i9, s8, a5 = e11.window; ; ) { + if (e11.lookahead <= S5) { + if (j3(e11), e11.lookahead <= S5 && t8 === l5) return A2; + if (0 === e11.lookahead) break; + } + if (e11.match_length = 0, e11.lookahead >= x2 && 0 < e11.strstart && (n9 = a5[i9 = e11.strstart - 1]) === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9]) { + s8 = e11.strstart + S5; + do { + } while (n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && n9 === a5[++i9] && i9 < s8); + e11.match_length = S5 - (s8 - i9), e11.match_length > e11.lookahead && (e11.match_length = e11.lookahead); + } + if (e11.match_length >= x2 ? (r10 = u5._tr_tally(e11, 1, e11.match_length - x2), e11.lookahead -= e11.match_length, e11.strstart += e11.match_length, e11.match_length = 0) : (r10 = u5._tr_tally(e11, 0, e11.window[e11.strstart]), e11.lookahead--, e11.strstart++), r10 && (N3(e11, false), 0 === e11.strm.avail_out)) return A2; + } + return e11.insert = 0, t8 === f4 ? (N3(e11, true), 0 === e11.strm.avail_out ? O2 : B3) : e11.last_lit && (N3(e11, false), 0 === e11.strm.avail_out) ? A2 : I3; + })(n8, t7) : h7[n8.level].func(n8, t7); + if (o10 !== O2 && o10 !== B3 || (n8.status = 666), o10 === A2 || o10 === O2) return 0 === e10.avail_out && (n8.last_flush = -1), m4; + if (o10 === I3 && (1 === t7 ? u5._tr_align(n8) : 5 !== t7 && (u5._tr_stored_block(n8, 0, 0, false), 3 === t7 && (D4(n8.head), 0 === n8.lookahead && (n8.strstart = 0, n8.block_start = 0, n8.insert = 0))), F2(e10), 0 === e10.avail_out)) return n8.last_flush = -1, m4; + } + return t7 !== f4 ? m4 : n8.wrap <= 0 ? 1 : (2 === n8.wrap ? (U2(n8, 255 & e10.adler), U2(n8, e10.adler >> 8 & 255), U2(n8, e10.adler >> 16 & 255), U2(n8, e10.adler >> 24 & 255), U2(n8, 255 & e10.total_in), U2(n8, e10.total_in >> 8 & 255), U2(n8, e10.total_in >> 16 & 255), U2(n8, e10.total_in >> 24 & 255)) : (P3(n8, e10.adler >>> 16), P3(n8, 65535 & e10.adler)), F2(e10), 0 < n8.wrap && (n8.wrap = -n8.wrap), 0 !== n8.pending ? m4 : 1); + }, r8.deflateEnd = function(e10) { + var t7; + return e10 && e10.state ? (t7 = e10.state.status) !== C3 && 69 !== t7 && 73 !== t7 && 91 !== t7 && 103 !== t7 && t7 !== E3 && 666 !== t7 ? R3(e10, _3) : (e10.state = null, t7 === E3 ? R3(e10, -3) : m4) : _3; + }, r8.deflateSetDictionary = function(e10, t7) { + var r9, n8, i8, s7, a4, o10, h8, u6, l6 = t7.length; + if (!e10 || !e10.state) return _3; + if (2 === (s7 = (r9 = e10.state).wrap) || 1 === s7 && r9.status !== C3 || r9.lookahead) return _3; + for (1 === s7 && (e10.adler = d4(e10.adler, t7, l6, 0)), r9.wrap = 0, l6 >= r9.w_size && (0 === s7 && (D4(r9.head), r9.strstart = 0, r9.block_start = 0, r9.insert = 0), u6 = new c6.Buf8(r9.w_size), c6.arraySet(u6, t7, l6 - r9.w_size, r9.w_size, 0), t7 = u6, l6 = r9.w_size), a4 = e10.avail_in, o10 = e10.next_in, h8 = e10.input, e10.avail_in = l6, e10.next_in = 0, e10.input = t7, j3(r9); r9.lookahead >= x2; ) { + for (n8 = r9.strstart, i8 = r9.lookahead - (x2 - 1); r9.ins_h = (r9.ins_h << r9.hash_shift ^ r9.window[n8 + x2 - 1]) & r9.hash_mask, r9.prev[n8 & r9.w_mask] = r9.head[r9.ins_h], r9.head[r9.ins_h] = n8, n8++, --i8; ) ; + r9.strstart = n8, r9.lookahead = x2 - 1, j3(r9); + } + return r9.strstart += r9.lookahead, r9.block_start = r9.strstart, r9.insert = r9.lookahead, r9.lookahead = 0, r9.match_length = r9.prev_length = x2 - 1, r9.match_available = 0, e10.next_in = o10, e10.input = h8, e10.avail_in = a4, r9.wrap = s7, m4; + }, r8.deflateInfo = "pako deflate (from Nodeca project)"; + }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./messages": 51, "./trees": 52 }], 47: [function(e9, t6, r8) { + "use strict"; + t6.exports = function() { + this.text = 0, this.time = 0, this.xflags = 0, this.os = 0, this.extra = null, this.extra_len = 0, this.name = "", this.comment = "", this.hcrc = 0, this.done = false; + }; + }, {}], 48: [function(e9, t6, r8) { + "use strict"; + t6.exports = function(e10, t7) { + var r9, n7, i7, s6, a3, o9, h7, u5, l5, f4, c6, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3; + r9 = e10.state, n7 = e10.next_in, z3 = e10.input, i7 = n7 + (e10.avail_in - 5), s6 = e10.next_out, C3 = e10.output, a3 = s6 - (t7 - e10.avail_out), o9 = s6 + (e10.avail_out - 257), h7 = r9.dmax, u5 = r9.wsize, l5 = r9.whave, f4 = r9.wnext, c6 = r9.window, d4 = r9.hold, p4 = r9.bits, m4 = r9.lencode, _3 = r9.distcode, g3 = (1 << r9.lenbits) - 1, b4 = (1 << r9.distbits) - 1; + e: do { + p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = m4[d4 & g3]; + t: for (; ; ) { + if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, 0 === (y4 = v4 >>> 16 & 255)) C3[s6++] = 65535 & v4; + else { + if (!(16 & y4)) { + if (0 == (64 & y4)) { + v4 = m4[(65535 & v4) + (d4 & (1 << y4) - 1)]; + continue t; + } + if (32 & y4) { + r9.mode = 12; + break e; + } + e10.msg = "invalid literal/length code", r9.mode = 30; + break e; + } + w3 = 65535 & v4, (y4 &= 15) && (p4 < y4 && (d4 += z3[n7++] << p4, p4 += 8), w3 += d4 & (1 << y4) - 1, d4 >>>= y4, p4 -= y4), p4 < 15 && (d4 += z3[n7++] << p4, p4 += 8, d4 += z3[n7++] << p4, p4 += 8), v4 = _3[d4 & b4]; + r: for (; ; ) { + if (d4 >>>= y4 = v4 >>> 24, p4 -= y4, !(16 & (y4 = v4 >>> 16 & 255))) { + if (0 == (64 & y4)) { + v4 = _3[(65535 & v4) + (d4 & (1 << y4) - 1)]; + continue r; + } + e10.msg = "invalid distance code", r9.mode = 30; + break e; + } + if (k2 = 65535 & v4, p4 < (y4 &= 15) && (d4 += z3[n7++] << p4, (p4 += 8) < y4 && (d4 += z3[n7++] << p4, p4 += 8)), h7 < (k2 += d4 & (1 << y4) - 1)) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break e; + } + if (d4 >>>= y4, p4 -= y4, (y4 = s6 - a3) < k2) { + if (l5 < (y4 = k2 - y4) && r9.sane) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break e; + } + if (S5 = c6, (x2 = 0) === f4) { + if (x2 += u5 - y4, y4 < w3) { + for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ; + x2 = s6 - k2, S5 = C3; + } + } else if (f4 < y4) { + if (x2 += u5 + f4 - y4, (y4 -= f4) < w3) { + for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ; + if (x2 = 0, f4 < w3) { + for (w3 -= y4 = f4; C3[s6++] = c6[x2++], --y4; ) ; + x2 = s6 - k2, S5 = C3; + } + } + } else if (x2 += f4 - y4, y4 < w3) { + for (w3 -= y4; C3[s6++] = c6[x2++], --y4; ) ; + x2 = s6 - k2, S5 = C3; + } + for (; 2 < w3; ) C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], C3[s6++] = S5[x2++], w3 -= 3; + w3 && (C3[s6++] = S5[x2++], 1 < w3 && (C3[s6++] = S5[x2++])); + } else { + for (x2 = s6 - k2; C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], C3[s6++] = C3[x2++], 2 < (w3 -= 3); ) ; + w3 && (C3[s6++] = C3[x2++], 1 < w3 && (C3[s6++] = C3[x2++])); + } + break; + } + } + break; + } + } while (n7 < i7 && s6 < o9); + n7 -= w3 = p4 >> 3, d4 &= (1 << (p4 -= w3 << 3)) - 1, e10.next_in = n7, e10.next_out = s6, e10.avail_in = n7 < i7 ? i7 - n7 + 5 : 5 - (n7 - i7), e10.avail_out = s6 < o9 ? o9 - s6 + 257 : 257 - (s6 - o9), r9.hold = d4, r9.bits = p4; + }; + }, {}], 49: [function(e9, t6, r8) { + "use strict"; + var I3 = e9("../utils/common"), O2 = e9("./adler32"), B3 = e9("./crc32"), R3 = e9("./inffast"), T3 = e9("./inftrees"), D4 = 1, F2 = 2, N3 = 0, U2 = -2, P3 = 1, n7 = 852, i7 = 592; + function L3(e10) { + return (e10 >>> 24 & 255) + (e10 >>> 8 & 65280) + ((65280 & e10) << 8) + ((255 & e10) << 24); + } + function s6() { + this.mode = 0, this.last = false, this.wrap = 0, this.havedict = false, this.flags = 0, this.dmax = 0, this.check = 0, this.total = 0, this.head = null, this.wbits = 0, this.wsize = 0, this.whave = 0, this.wnext = 0, this.window = null, this.hold = 0, this.bits = 0, this.length = 0, this.offset = 0, this.extra = 0, this.lencode = null, this.distcode = null, this.lenbits = 0, this.distbits = 0, this.ncode = 0, this.nlen = 0, this.ndist = 0, this.have = 0, this.next = null, this.lens = new I3.Buf16(320), this.work = new I3.Buf16(288), this.lendyn = null, this.distdyn = null, this.sane = 0, this.back = 0, this.was = 0; + } + function a3(e10) { + var t7; + return e10 && e10.state ? (t7 = e10.state, e10.total_in = e10.total_out = t7.total = 0, e10.msg = "", t7.wrap && (e10.adler = 1 & t7.wrap), t7.mode = P3, t7.last = 0, t7.havedict = 0, t7.dmax = 32768, t7.head = null, t7.hold = 0, t7.bits = 0, t7.lencode = t7.lendyn = new I3.Buf32(n7), t7.distcode = t7.distdyn = new I3.Buf32(i7), t7.sane = 1, t7.back = -1, N3) : U2; + } + function o9(e10) { + var t7; + return e10 && e10.state ? ((t7 = e10.state).wsize = 0, t7.whave = 0, t7.wnext = 0, a3(e10)) : U2; + } + function h7(e10, t7) { + var r9, n8; + return e10 && e10.state ? (n8 = e10.state, t7 < 0 ? (r9 = 0, t7 = -t7) : (r9 = 1 + (t7 >> 4), t7 < 48 && (t7 &= 15)), t7 && (t7 < 8 || 15 < t7) ? U2 : (null !== n8.window && n8.wbits !== t7 && (n8.window = null), n8.wrap = r9, n8.wbits = t7, o9(e10))) : U2; + } + function u5(e10, t7) { + var r9, n8; + return e10 ? (n8 = new s6(), (e10.state = n8).window = null, (r9 = h7(e10, t7)) !== N3 && (e10.state = null), r9) : U2; + } + var l5, f4, c6 = true; + function j3(e10) { + if (c6) { + var t7; + for (l5 = new I3.Buf32(512), f4 = new I3.Buf32(32), t7 = 0; t7 < 144; ) e10.lens[t7++] = 8; + for (; t7 < 256; ) e10.lens[t7++] = 9; + for (; t7 < 280; ) e10.lens[t7++] = 7; + for (; t7 < 288; ) e10.lens[t7++] = 8; + for (T3(D4, e10.lens, 0, 288, l5, 0, e10.work, { bits: 9 }), t7 = 0; t7 < 32; ) e10.lens[t7++] = 5; + T3(F2, e10.lens, 0, 32, f4, 0, e10.work, { bits: 5 }), c6 = false; + } + e10.lencode = l5, e10.lenbits = 9, e10.distcode = f4, e10.distbits = 5; + } + function Z2(e10, t7, r9, n8) { + var i8, s7 = e10.state; + return null === s7.window && (s7.wsize = 1 << s7.wbits, s7.wnext = 0, s7.whave = 0, s7.window = new I3.Buf8(s7.wsize)), n8 >= s7.wsize ? (I3.arraySet(s7.window, t7, r9 - s7.wsize, s7.wsize, 0), s7.wnext = 0, s7.whave = s7.wsize) : (n8 < (i8 = s7.wsize - s7.wnext) && (i8 = n8), I3.arraySet(s7.window, t7, r9 - n8, i8, s7.wnext), (n8 -= i8) ? (I3.arraySet(s7.window, t7, r9 - n8, n8, 0), s7.wnext = n8, s7.whave = s7.wsize) : (s7.wnext += i8, s7.wnext === s7.wsize && (s7.wnext = 0), s7.whave < s7.wsize && (s7.whave += i8))), 0; + } + r8.inflateReset = o9, r8.inflateReset2 = h7, r8.inflateResetKeep = a3, r8.inflateInit = function(e10) { + return u5(e10, 15); + }, r8.inflateInit2 = u5, r8.inflate = function(e10, t7) { + var r9, n8, i8, s7, a4, o10, h8, u6, l6, f5, c7, d4, p4, m4, _3, g3, b4, v4, y4, w3, k2, x2, S5, z3, C3 = 0, E3 = new I3.Buf8(4), A2 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + if (!e10 || !e10.state || !e10.output || !e10.input && 0 !== e10.avail_in) return U2; + 12 === (r9 = e10.state).mode && (r9.mode = 13), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, f5 = o10, c7 = h8, x2 = N3; + e: for (; ; ) switch (r9.mode) { + case P3: + if (0 === r9.wrap) { + r9.mode = 13; + break; + } + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (2 & r9.wrap && 35615 === u6) { + E3[r9.check = 0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0), l6 = u6 = 0, r9.mode = 2; + break; + } + if (r9.flags = 0, r9.head && (r9.head.done = false), !(1 & r9.wrap) || (((255 & u6) << 8) + (u6 >> 8)) % 31) { + e10.msg = "incorrect header check", r9.mode = 30; + break; + } + if (8 != (15 & u6)) { + e10.msg = "unknown compression method", r9.mode = 30; + break; + } + if (l6 -= 4, k2 = 8 + (15 & (u6 >>>= 4)), 0 === r9.wbits) r9.wbits = k2; + else if (k2 > r9.wbits) { + e10.msg = "invalid window size", r9.mode = 30; + break; + } + r9.dmax = 1 << k2, e10.adler = r9.check = 1, r9.mode = 512 & u6 ? 10 : 12, l6 = u6 = 0; + break; + case 2: + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (r9.flags = u6, 8 != (255 & r9.flags)) { + e10.msg = "unknown compression method", r9.mode = 30; + break; + } + if (57344 & r9.flags) { + e10.msg = "unknown header flags set", r9.mode = 30; + break; + } + r9.head && (r9.head.text = u6 >> 8 & 1), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 3; + case 3: + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.head && (r9.head.time = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, E3[2] = u6 >>> 16 & 255, E3[3] = u6 >>> 24 & 255, r9.check = B3(r9.check, E3, 4, 0)), l6 = u6 = 0, r9.mode = 4; + case 4: + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.head && (r9.head.xflags = 255 & u6, r9.head.os = u6 >> 8), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0, r9.mode = 5; + case 5: + if (1024 & r9.flags) { + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.length = u6, r9.head && (r9.head.extra_len = u6), 512 & r9.flags && (E3[0] = 255 & u6, E3[1] = u6 >>> 8 & 255, r9.check = B3(r9.check, E3, 2, 0)), l6 = u6 = 0; + } else r9.head && (r9.head.extra = null); + r9.mode = 6; + case 6: + if (1024 & r9.flags && (o10 < (d4 = r9.length) && (d4 = o10), d4 && (r9.head && (k2 = r9.head.extra_len - r9.length, r9.head.extra || (r9.head.extra = new Array(r9.head.extra_len)), I3.arraySet(r9.head.extra, n8, s7, d4, k2)), 512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, r9.length -= d4), r9.length)) break e; + r9.length = 0, r9.mode = 7; + case 7: + if (2048 & r9.flags) { + if (0 === o10) break e; + for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.name += String.fromCharCode(k2)), k2 && d4 < o10; ) ; + if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e; + } else r9.head && (r9.head.name = null); + r9.length = 0, r9.mode = 8; + case 8: + if (4096 & r9.flags) { + if (0 === o10) break e; + for (d4 = 0; k2 = n8[s7 + d4++], r9.head && k2 && r9.length < 65536 && (r9.head.comment += String.fromCharCode(k2)), k2 && d4 < o10; ) ; + if (512 & r9.flags && (r9.check = B3(r9.check, n8, d4, s7)), o10 -= d4, s7 += d4, k2) break e; + } else r9.head && (r9.head.comment = null); + r9.mode = 9; + case 9: + if (512 & r9.flags) { + for (; l6 < 16; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (u6 !== (65535 & r9.check)) { + e10.msg = "header crc mismatch", r9.mode = 30; + break; + } + l6 = u6 = 0; + } + r9.head && (r9.head.hcrc = r9.flags >> 9 & 1, r9.head.done = true), e10.adler = r9.check = 0, r9.mode = 12; + break; + case 10: + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + e10.adler = r9.check = L3(u6), l6 = u6 = 0, r9.mode = 11; + case 11: + if (0 === r9.havedict) return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, 2; + e10.adler = r9.check = 1, r9.mode = 12; + case 12: + if (5 === t7 || 6 === t7) break e; + case 13: + if (r9.last) { + u6 >>>= 7 & l6, l6 -= 7 & l6, r9.mode = 27; + break; + } + for (; l6 < 3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + switch (r9.last = 1 & u6, l6 -= 1, 3 & (u6 >>>= 1)) { + case 0: + r9.mode = 14; + break; + case 1: + if (j3(r9), r9.mode = 20, 6 !== t7) break; + u6 >>>= 2, l6 -= 2; + break e; + case 2: + r9.mode = 17; + break; + case 3: + e10.msg = "invalid block type", r9.mode = 30; + } + u6 >>>= 2, l6 -= 2; + break; + case 14: + for (u6 >>>= 7 & l6, l6 -= 7 & l6; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if ((65535 & u6) != (u6 >>> 16 ^ 65535)) { + e10.msg = "invalid stored block lengths", r9.mode = 30; + break; + } + if (r9.length = 65535 & u6, l6 = u6 = 0, r9.mode = 15, 6 === t7) break e; + case 15: + r9.mode = 16; + case 16: + if (d4 = r9.length) { + if (o10 < d4 && (d4 = o10), h8 < d4 && (d4 = h8), 0 === d4) break e; + I3.arraySet(i8, n8, s7, d4, a4), o10 -= d4, s7 += d4, h8 -= d4, a4 += d4, r9.length -= d4; + break; + } + r9.mode = 12; + break; + case 17: + for (; l6 < 14; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (r9.nlen = 257 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ndist = 1 + (31 & u6), u6 >>>= 5, l6 -= 5, r9.ncode = 4 + (15 & u6), u6 >>>= 4, l6 -= 4, 286 < r9.nlen || 30 < r9.ndist) { + e10.msg = "too many length or distance symbols", r9.mode = 30; + break; + } + r9.have = 0, r9.mode = 18; + case 18: + for (; r9.have < r9.ncode; ) { + for (; l6 < 3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.lens[A2[r9.have++]] = 7 & u6, u6 >>>= 3, l6 -= 3; + } + for (; r9.have < 19; ) r9.lens[A2[r9.have++]] = 0; + if (r9.lencode = r9.lendyn, r9.lenbits = 7, S5 = { bits: r9.lenbits }, x2 = T3(0, r9.lens, 0, 19, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) { + e10.msg = "invalid code lengths set", r9.mode = 30; + break; + } + r9.have = 0, r9.mode = 19; + case 19: + for (; r9.have < r9.nlen + r9.ndist; ) { + for (; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (b4 < 16) u6 >>>= _3, l6 -= _3, r9.lens[r9.have++] = b4; + else { + if (16 === b4) { + for (z3 = _3 + 2; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (u6 >>>= _3, l6 -= _3, 0 === r9.have) { + e10.msg = "invalid bit length repeat", r9.mode = 30; + break; + } + k2 = r9.lens[r9.have - 1], d4 = 3 + (3 & u6), u6 >>>= 2, l6 -= 2; + } else if (17 === b4) { + for (z3 = _3 + 3; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + l6 -= _3, k2 = 0, d4 = 3 + (7 & (u6 >>>= _3)), u6 >>>= 3, l6 -= 3; + } else { + for (z3 = _3 + 7; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + l6 -= _3, k2 = 0, d4 = 11 + (127 & (u6 >>>= _3)), u6 >>>= 7, l6 -= 7; + } + if (r9.have + d4 > r9.nlen + r9.ndist) { + e10.msg = "invalid bit length repeat", r9.mode = 30; + break; + } + for (; d4--; ) r9.lens[r9.have++] = k2; + } + } + if (30 === r9.mode) break; + if (0 === r9.lens[256]) { + e10.msg = "invalid code -- missing end-of-block", r9.mode = 30; + break; + } + if (r9.lenbits = 9, S5 = { bits: r9.lenbits }, x2 = T3(D4, r9.lens, 0, r9.nlen, r9.lencode, 0, r9.work, S5), r9.lenbits = S5.bits, x2) { + e10.msg = "invalid literal/lengths set", r9.mode = 30; + break; + } + if (r9.distbits = 6, r9.distcode = r9.distdyn, S5 = { bits: r9.distbits }, x2 = T3(F2, r9.lens, r9.nlen, r9.ndist, r9.distcode, 0, r9.work, S5), r9.distbits = S5.bits, x2) { + e10.msg = "invalid distances set", r9.mode = 30; + break; + } + if (r9.mode = 20, 6 === t7) break e; + case 20: + r9.mode = 21; + case 21: + if (6 <= o10 && 258 <= h8) { + e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, R3(e10, c7), a4 = e10.next_out, i8 = e10.output, h8 = e10.avail_out, s7 = e10.next_in, n8 = e10.input, o10 = e10.avail_in, u6 = r9.hold, l6 = r9.bits, 12 === r9.mode && (r9.back = -1); + break; + } + for (r9.back = 0; g3 = (C3 = r9.lencode[u6 & (1 << r9.lenbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (g3 && 0 == (240 & g3)) { + for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.lencode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + u6 >>>= v4, l6 -= v4, r9.back += v4; + } + if (u6 >>>= _3, l6 -= _3, r9.back += _3, r9.length = b4, 0 === g3) { + r9.mode = 26; + break; + } + if (32 & g3) { + r9.back = -1, r9.mode = 12; + break; + } + if (64 & g3) { + e10.msg = "invalid literal/length code", r9.mode = 30; + break; + } + r9.extra = 15 & g3, r9.mode = 22; + case 22: + if (r9.extra) { + for (z3 = r9.extra; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.length += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra; + } + r9.was = r9.length, r9.mode = 23; + case 23: + for (; g3 = (C3 = r9.distcode[u6 & (1 << r9.distbits) - 1]) >>> 16 & 255, b4 = 65535 & C3, !((_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (0 == (240 & g3)) { + for (v4 = _3, y4 = g3, w3 = b4; g3 = (C3 = r9.distcode[w3 + ((u6 & (1 << v4 + y4) - 1) >> v4)]) >>> 16 & 255, b4 = 65535 & C3, !(v4 + (_3 = C3 >>> 24) <= l6); ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + u6 >>>= v4, l6 -= v4, r9.back += v4; + } + if (u6 >>>= _3, l6 -= _3, r9.back += _3, 64 & g3) { + e10.msg = "invalid distance code", r9.mode = 30; + break; + } + r9.offset = b4, r9.extra = 15 & g3, r9.mode = 24; + case 24: + if (r9.extra) { + for (z3 = r9.extra; l6 < z3; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + r9.offset += u6 & (1 << r9.extra) - 1, u6 >>>= r9.extra, l6 -= r9.extra, r9.back += r9.extra; + } + if (r9.offset > r9.dmax) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break; + } + r9.mode = 25; + case 25: + if (0 === h8) break e; + if (d4 = c7 - h8, r9.offset > d4) { + if ((d4 = r9.offset - d4) > r9.whave && r9.sane) { + e10.msg = "invalid distance too far back", r9.mode = 30; + break; + } + p4 = d4 > r9.wnext ? (d4 -= r9.wnext, r9.wsize - d4) : r9.wnext - d4, d4 > r9.length && (d4 = r9.length), m4 = r9.window; + } else m4 = i8, p4 = a4 - r9.offset, d4 = r9.length; + for (h8 < d4 && (d4 = h8), h8 -= d4, r9.length -= d4; i8[a4++] = m4[p4++], --d4; ) ; + 0 === r9.length && (r9.mode = 21); + break; + case 26: + if (0 === h8) break e; + i8[a4++] = r9.length, h8--, r9.mode = 21; + break; + case 27: + if (r9.wrap) { + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 |= n8[s7++] << l6, l6 += 8; + } + if (c7 -= h8, e10.total_out += c7, r9.total += c7, c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, a4 - c7) : O2(r9.check, i8, c7, a4 - c7)), c7 = h8, (r9.flags ? u6 : L3(u6)) !== r9.check) { + e10.msg = "incorrect data check", r9.mode = 30; + break; + } + l6 = u6 = 0; + } + r9.mode = 28; + case 28: + if (r9.wrap && r9.flags) { + for (; l6 < 32; ) { + if (0 === o10) break e; + o10--, u6 += n8[s7++] << l6, l6 += 8; + } + if (u6 !== (4294967295 & r9.total)) { + e10.msg = "incorrect length check", r9.mode = 30; + break; + } + l6 = u6 = 0; + } + r9.mode = 29; + case 29: + x2 = 1; + break e; + case 30: + x2 = -3; + break e; + case 31: + return -4; + case 32: + default: + return U2; + } + return e10.next_out = a4, e10.avail_out = h8, e10.next_in = s7, e10.avail_in = o10, r9.hold = u6, r9.bits = l6, (r9.wsize || c7 !== e10.avail_out && r9.mode < 30 && (r9.mode < 27 || 4 !== t7)) && Z2(e10, e10.output, e10.next_out, c7 - e10.avail_out) ? (r9.mode = 31, -4) : (f5 -= e10.avail_in, c7 -= e10.avail_out, e10.total_in += f5, e10.total_out += c7, r9.total += c7, r9.wrap && c7 && (e10.adler = r9.check = r9.flags ? B3(r9.check, i8, c7, e10.next_out - c7) : O2(r9.check, i8, c7, e10.next_out - c7)), e10.data_type = r9.bits + (r9.last ? 64 : 0) + (12 === r9.mode ? 128 : 0) + (20 === r9.mode || 15 === r9.mode ? 256 : 0), (0 == f5 && 0 === c7 || 4 === t7) && x2 === N3 && (x2 = -5), x2); + }, r8.inflateEnd = function(e10) { + if (!e10 || !e10.state) return U2; + var t7 = e10.state; + return t7.window && (t7.window = null), e10.state = null, N3; + }, r8.inflateGetHeader = function(e10, t7) { + var r9; + return e10 && e10.state ? 0 == (2 & (r9 = e10.state).wrap) ? U2 : ((r9.head = t7).done = false, N3) : U2; + }, r8.inflateSetDictionary = function(e10, t7) { + var r9, n8 = t7.length; + return e10 && e10.state ? 0 !== (r9 = e10.state).wrap && 11 !== r9.mode ? U2 : 11 === r9.mode && O2(1, t7, n8, 0) !== r9.check ? -3 : Z2(e10, t7, n8, n8) ? (r9.mode = 31, -4) : (r9.havedict = 1, N3) : U2; + }, r8.inflateInfo = "pako inflate (from Nodeca project)"; + }, { "../utils/common": 41, "./adler32": 43, "./crc32": 45, "./inffast": 48, "./inftrees": 50 }], 50: [function(e9, t6, r8) { + "use strict"; + var D4 = e9("../utils/common"), F2 = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0], N3 = [16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78], U2 = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0], P3 = [16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64]; + t6.exports = function(e10, t7, r9, n7, i7, s6, a3, o9) { + var h7, u5, l5, f4, c6, d4, p4, m4, _3, g3 = o9.bits, b4 = 0, v4 = 0, y4 = 0, w3 = 0, k2 = 0, x2 = 0, S5 = 0, z3 = 0, C3 = 0, E3 = 0, A2 = null, I3 = 0, O2 = new D4.Buf16(16), B3 = new D4.Buf16(16), R3 = null, T3 = 0; + for (b4 = 0; b4 <= 15; b4++) O2[b4] = 0; + for (v4 = 0; v4 < n7; v4++) O2[t7[r9 + v4]]++; + for (k2 = g3, w3 = 15; 1 <= w3 && 0 === O2[w3]; w3--) ; + if (w3 < k2 && (k2 = w3), 0 === w3) return i7[s6++] = 20971520, i7[s6++] = 20971520, o9.bits = 1, 0; + for (y4 = 1; y4 < w3 && 0 === O2[y4]; y4++) ; + for (k2 < y4 && (k2 = y4), b4 = z3 = 1; b4 <= 15; b4++) if (z3 <<= 1, (z3 -= O2[b4]) < 0) return -1; + if (0 < z3 && (0 === e10 || 1 !== w3)) return -1; + for (B3[1] = 0, b4 = 1; b4 < 15; b4++) B3[b4 + 1] = B3[b4] + O2[b4]; + for (v4 = 0; v4 < n7; v4++) 0 !== t7[r9 + v4] && (a3[B3[t7[r9 + v4]]++] = v4); + if (d4 = 0 === e10 ? (A2 = R3 = a3, 19) : 1 === e10 ? (A2 = F2, I3 -= 257, R3 = N3, T3 -= 257, 256) : (A2 = U2, R3 = P3, -1), b4 = y4, c6 = s6, S5 = v4 = E3 = 0, l5 = -1, f4 = (C3 = 1 << (x2 = k2)) - 1, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1; + for (; ; ) { + for (p4 = b4 - S5, _3 = a3[v4] < d4 ? (m4 = 0, a3[v4]) : a3[v4] > d4 ? (m4 = R3[T3 + a3[v4]], A2[I3 + a3[v4]]) : (m4 = 96, 0), h7 = 1 << b4 - S5, y4 = u5 = 1 << x2; i7[c6 + (E3 >> S5) + (u5 -= h7)] = p4 << 24 | m4 << 16 | _3 | 0, 0 !== u5; ) ; + for (h7 = 1 << b4 - 1; E3 & h7; ) h7 >>= 1; + if (0 !== h7 ? (E3 &= h7 - 1, E3 += h7) : E3 = 0, v4++, 0 == --O2[b4]) { + if (b4 === w3) break; + b4 = t7[r9 + a3[v4]]; + } + if (k2 < b4 && (E3 & f4) !== l5) { + for (0 === S5 && (S5 = k2), c6 += y4, z3 = 1 << (x2 = b4 - S5); x2 + S5 < w3 && !((z3 -= O2[x2 + S5]) <= 0); ) x2++, z3 <<= 1; + if (C3 += 1 << x2, 1 === e10 && 852 < C3 || 2 === e10 && 592 < C3) return 1; + i7[l5 = E3 & f4] = k2 << 24 | x2 << 16 | c6 - s6 | 0; + } + } + return 0 !== E3 && (i7[c6 + E3] = b4 - S5 << 24 | 64 << 16 | 0), o9.bits = k2, 0; + }; + }, { "../utils/common": 41 }], 51: [function(e9, t6, r8) { + "use strict"; + t6.exports = { 2: "need dictionary", 1: "stream end", 0: "", "-1": "file error", "-2": "stream error", "-3": "data error", "-4": "insufficient memory", "-5": "buffer error", "-6": "incompatible version" }; + }, {}], 52: [function(e9, t6, r8) { + "use strict"; + var i7 = e9("../utils/common"), o9 = 0, h7 = 1; + function n7(e10) { + for (var t7 = e10.length; 0 <= --t7; ) e10[t7] = 0; + } + var s6 = 0, a3 = 29, u5 = 256, l5 = u5 + 1 + a3, f4 = 30, c6 = 19, _3 = 2 * l5 + 1, g3 = 15, d4 = 16, p4 = 7, m4 = 256, b4 = 16, v4 = 17, y4 = 18, w3 = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0], k2 = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13], x2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7], S5 = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], z3 = new Array(2 * (l5 + 2)); + n7(z3); + var C3 = new Array(2 * f4); + n7(C3); + var E3 = new Array(512); + n7(E3); + var A2 = new Array(256); + n7(A2); + var I3 = new Array(a3); + n7(I3); + var O2, B3, R3, T3 = new Array(f4); + function D4(e10, t7, r9, n8, i8) { + this.static_tree = e10, this.extra_bits = t7, this.extra_base = r9, this.elems = n8, this.max_length = i8, this.has_stree = e10 && e10.length; + } + function F2(e10, t7) { + this.dyn_tree = e10, this.max_code = 0, this.stat_desc = t7; + } + function N3(e10) { + return e10 < 256 ? E3[e10] : E3[256 + (e10 >>> 7)]; + } + function U2(e10, t7) { + e10.pending_buf[e10.pending++] = 255 & t7, e10.pending_buf[e10.pending++] = t7 >>> 8 & 255; + } + function P3(e10, t7, r9) { + e10.bi_valid > d4 - r9 ? (e10.bi_buf |= t7 << e10.bi_valid & 65535, U2(e10, e10.bi_buf), e10.bi_buf = t7 >> d4 - e10.bi_valid, e10.bi_valid += r9 - d4) : (e10.bi_buf |= t7 << e10.bi_valid & 65535, e10.bi_valid += r9); + } + function L3(e10, t7, r9) { + P3(e10, r9[2 * t7], r9[2 * t7 + 1]); + } + function j3(e10, t7) { + for (var r9 = 0; r9 |= 1 & e10, e10 >>>= 1, r9 <<= 1, 0 < --t7; ) ; + return r9 >>> 1; + } + function Z2(e10, t7, r9) { + var n8, i8, s7 = new Array(g3 + 1), a4 = 0; + for (n8 = 1; n8 <= g3; n8++) s7[n8] = a4 = a4 + r9[n8 - 1] << 1; + for (i8 = 0; i8 <= t7; i8++) { + var o10 = e10[2 * i8 + 1]; + 0 !== o10 && (e10[2 * i8] = j3(s7[o10]++, o10)); + } + } + function W2(e10) { + var t7; + for (t7 = 0; t7 < l5; t7++) e10.dyn_ltree[2 * t7] = 0; + for (t7 = 0; t7 < f4; t7++) e10.dyn_dtree[2 * t7] = 0; + for (t7 = 0; t7 < c6; t7++) e10.bl_tree[2 * t7] = 0; + e10.dyn_ltree[2 * m4] = 1, e10.opt_len = e10.static_len = 0, e10.last_lit = e10.matches = 0; + } + function M4(e10) { + 8 < e10.bi_valid ? U2(e10, e10.bi_buf) : 0 < e10.bi_valid && (e10.pending_buf[e10.pending++] = e10.bi_buf), e10.bi_buf = 0, e10.bi_valid = 0; + } + function H2(e10, t7, r9, n8) { + var i8 = 2 * t7, s7 = 2 * r9; + return e10[i8] < e10[s7] || e10[i8] === e10[s7] && n8[t7] <= n8[r9]; + } + function G2(e10, t7, r9) { + for (var n8 = e10.heap[r9], i8 = r9 << 1; i8 <= e10.heap_len && (i8 < e10.heap_len && H2(t7, e10.heap[i8 + 1], e10.heap[i8], e10.depth) && i8++, !H2(t7, n8, e10.heap[i8], e10.depth)); ) e10.heap[r9] = e10.heap[i8], r9 = i8, i8 <<= 1; + e10.heap[r9] = n8; + } + function K2(e10, t7, r9) { + var n8, i8, s7, a4, o10 = 0; + if (0 !== e10.last_lit) for (; n8 = e10.pending_buf[e10.d_buf + 2 * o10] << 8 | e10.pending_buf[e10.d_buf + 2 * o10 + 1], i8 = e10.pending_buf[e10.l_buf + o10], o10++, 0 === n8 ? L3(e10, i8, t7) : (L3(e10, (s7 = A2[i8]) + u5 + 1, t7), 0 !== (a4 = w3[s7]) && P3(e10, i8 -= I3[s7], a4), L3(e10, s7 = N3(--n8), r9), 0 !== (a4 = k2[s7]) && P3(e10, n8 -= T3[s7], a4)), o10 < e10.last_lit; ) ; + L3(e10, m4, t7); + } + function Y(e10, t7) { + var r9, n8, i8, s7 = t7.dyn_tree, a4 = t7.stat_desc.static_tree, o10 = t7.stat_desc.has_stree, h8 = t7.stat_desc.elems, u6 = -1; + for (e10.heap_len = 0, e10.heap_max = _3, r9 = 0; r9 < h8; r9++) 0 !== s7[2 * r9] ? (e10.heap[++e10.heap_len] = u6 = r9, e10.depth[r9] = 0) : s7[2 * r9 + 1] = 0; + for (; e10.heap_len < 2; ) s7[2 * (i8 = e10.heap[++e10.heap_len] = u6 < 2 ? ++u6 : 0)] = 1, e10.depth[i8] = 0, e10.opt_len--, o10 && (e10.static_len -= a4[2 * i8 + 1]); + for (t7.max_code = u6, r9 = e10.heap_len >> 1; 1 <= r9; r9--) G2(e10, s7, r9); + for (i8 = h8; r9 = e10.heap[1], e10.heap[1] = e10.heap[e10.heap_len--], G2(e10, s7, 1), n8 = e10.heap[1], e10.heap[--e10.heap_max] = r9, e10.heap[--e10.heap_max] = n8, s7[2 * i8] = s7[2 * r9] + s7[2 * n8], e10.depth[i8] = (e10.depth[r9] >= e10.depth[n8] ? e10.depth[r9] : e10.depth[n8]) + 1, s7[2 * r9 + 1] = s7[2 * n8 + 1] = i8, e10.heap[1] = i8++, G2(e10, s7, 1), 2 <= e10.heap_len; ) ; + e10.heap[--e10.heap_max] = e10.heap[1], (function(e11, t8) { + var r10, n9, i9, s8, a5, o11, h9 = t8.dyn_tree, u7 = t8.max_code, l6 = t8.stat_desc.static_tree, f5 = t8.stat_desc.has_stree, c7 = t8.stat_desc.extra_bits, d5 = t8.stat_desc.extra_base, p5 = t8.stat_desc.max_length, m5 = 0; + for (s8 = 0; s8 <= g3; s8++) e11.bl_count[s8] = 0; + for (h9[2 * e11.heap[e11.heap_max] + 1] = 0, r10 = e11.heap_max + 1; r10 < _3; r10++) p5 < (s8 = h9[2 * h9[2 * (n9 = e11.heap[r10]) + 1] + 1] + 1) && (s8 = p5, m5++), h9[2 * n9 + 1] = s8, u7 < n9 || (e11.bl_count[s8]++, a5 = 0, d5 <= n9 && (a5 = c7[n9 - d5]), o11 = h9[2 * n9], e11.opt_len += o11 * (s8 + a5), f5 && (e11.static_len += o11 * (l6[2 * n9 + 1] + a5))); + if (0 !== m5) { + do { + for (s8 = p5 - 1; 0 === e11.bl_count[s8]; ) s8--; + e11.bl_count[s8]--, e11.bl_count[s8 + 1] += 2, e11.bl_count[p5]--, m5 -= 2; + } while (0 < m5); + for (s8 = p5; 0 !== s8; s8--) for (n9 = e11.bl_count[s8]; 0 !== n9; ) u7 < (i9 = e11.heap[--r10]) || (h9[2 * i9 + 1] !== s8 && (e11.opt_len += (s8 - h9[2 * i9 + 1]) * h9[2 * i9], h9[2 * i9 + 1] = s8), n9--); + } + })(e10, t7), Z2(s7, u6, e10.bl_count); + } + function X4(e10, t7, r9) { + var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4; + for (0 === a4 && (h8 = 138, u6 = 3), t7[2 * (r9 + 1) + 1] = 65535, n8 = 0; n8 <= r9; n8++) i8 = a4, a4 = t7[2 * (n8 + 1) + 1], ++o10 < h8 && i8 === a4 || (o10 < u6 ? e10.bl_tree[2 * i8] += o10 : 0 !== i8 ? (i8 !== s7 && e10.bl_tree[2 * i8]++, e10.bl_tree[2 * b4]++) : o10 <= 10 ? e10.bl_tree[2 * v4]++ : e10.bl_tree[2 * y4]++, s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4)); + } + function V3(e10, t7, r9) { + var n8, i8, s7 = -1, a4 = t7[1], o10 = 0, h8 = 7, u6 = 4; + for (0 === a4 && (h8 = 138, u6 = 3), n8 = 0; n8 <= r9; n8++) if (i8 = a4, a4 = t7[2 * (n8 + 1) + 1], !(++o10 < h8 && i8 === a4)) { + if (o10 < u6) for (; L3(e10, i8, e10.bl_tree), 0 != --o10; ) ; + else 0 !== i8 ? (i8 !== s7 && (L3(e10, i8, e10.bl_tree), o10--), L3(e10, b4, e10.bl_tree), P3(e10, o10 - 3, 2)) : o10 <= 10 ? (L3(e10, v4, e10.bl_tree), P3(e10, o10 - 3, 3)) : (L3(e10, y4, e10.bl_tree), P3(e10, o10 - 11, 7)); + s7 = i8, u6 = (o10 = 0) === a4 ? (h8 = 138, 3) : i8 === a4 ? (h8 = 6, 3) : (h8 = 7, 4); + } + } + n7(T3); + var q2 = false; + function J2(e10, t7, r9, n8) { + P3(e10, (s6 << 1) + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) { + M4(e11), n9 && (U2(e11, r10), U2(e11, ~r10)), i7.arraySet(e11.pending_buf, e11.window, t8, r10, e11.pending), e11.pending += r10; + })(e10, t7, r9, true); + } + r8._tr_init = function(e10) { + q2 || ((function() { + var e11, t7, r9, n8, i8, s7 = new Array(g3 + 1); + for (n8 = r9 = 0; n8 < a3 - 1; n8++) for (I3[n8] = r9, e11 = 0; e11 < 1 << w3[n8]; e11++) A2[r9++] = n8; + for (A2[r9 - 1] = n8, n8 = i8 = 0; n8 < 16; n8++) for (T3[n8] = i8, e11 = 0; e11 < 1 << k2[n8]; e11++) E3[i8++] = n8; + for (i8 >>= 7; n8 < f4; n8++) for (T3[n8] = i8 << 7, e11 = 0; e11 < 1 << k2[n8] - 7; e11++) E3[256 + i8++] = n8; + for (t7 = 0; t7 <= g3; t7++) s7[t7] = 0; + for (e11 = 0; e11 <= 143; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++; + for (; e11 <= 255; ) z3[2 * e11 + 1] = 9, e11++, s7[9]++; + for (; e11 <= 279; ) z3[2 * e11 + 1] = 7, e11++, s7[7]++; + for (; e11 <= 287; ) z3[2 * e11 + 1] = 8, e11++, s7[8]++; + for (Z2(z3, l5 + 1, s7), e11 = 0; e11 < f4; e11++) C3[2 * e11 + 1] = 5, C3[2 * e11] = j3(e11, 5); + O2 = new D4(z3, w3, u5 + 1, l5, g3), B3 = new D4(C3, k2, 0, f4, g3), R3 = new D4(new Array(0), x2, 0, c6, p4); + })(), q2 = true), e10.l_desc = new F2(e10.dyn_ltree, O2), e10.d_desc = new F2(e10.dyn_dtree, B3), e10.bl_desc = new F2(e10.bl_tree, R3), e10.bi_buf = 0, e10.bi_valid = 0, W2(e10); + }, r8._tr_stored_block = J2, r8._tr_flush_block = function(e10, t7, r9, n8) { + var i8, s7, a4 = 0; + 0 < e10.level ? (2 === e10.strm.data_type && (e10.strm.data_type = (function(e11) { + var t8, r10 = 4093624447; + for (t8 = 0; t8 <= 31; t8++, r10 >>>= 1) if (1 & r10 && 0 !== e11.dyn_ltree[2 * t8]) return o9; + if (0 !== e11.dyn_ltree[18] || 0 !== e11.dyn_ltree[20] || 0 !== e11.dyn_ltree[26]) return h7; + for (t8 = 32; t8 < u5; t8++) if (0 !== e11.dyn_ltree[2 * t8]) return h7; + return o9; + })(e10)), Y(e10, e10.l_desc), Y(e10, e10.d_desc), a4 = (function(e11) { + var t8; + for (X4(e11, e11.dyn_ltree, e11.l_desc.max_code), X4(e11, e11.dyn_dtree, e11.d_desc.max_code), Y(e11, e11.bl_desc), t8 = c6 - 1; 3 <= t8 && 0 === e11.bl_tree[2 * S5[t8] + 1]; t8--) ; + return e11.opt_len += 3 * (t8 + 1) + 5 + 5 + 4, t8; + })(e10), i8 = e10.opt_len + 3 + 7 >>> 3, (s7 = e10.static_len + 3 + 7 >>> 3) <= i8 && (i8 = s7)) : i8 = s7 = r9 + 5, r9 + 4 <= i8 && -1 !== t7 ? J2(e10, t7, r9, n8) : 4 === e10.strategy || s7 === i8 ? (P3(e10, 2 + (n8 ? 1 : 0), 3), K2(e10, z3, C3)) : (P3(e10, 4 + (n8 ? 1 : 0), 3), (function(e11, t8, r10, n9) { + var i9; + for (P3(e11, t8 - 257, 5), P3(e11, r10 - 1, 5), P3(e11, n9 - 4, 4), i9 = 0; i9 < n9; i9++) P3(e11, e11.bl_tree[2 * S5[i9] + 1], 3); + V3(e11, e11.dyn_ltree, t8 - 1), V3(e11, e11.dyn_dtree, r10 - 1); + })(e10, e10.l_desc.max_code + 1, e10.d_desc.max_code + 1, a4 + 1), K2(e10, e10.dyn_ltree, e10.dyn_dtree)), W2(e10), n8 && M4(e10); + }, r8._tr_tally = function(e10, t7, r9) { + return e10.pending_buf[e10.d_buf + 2 * e10.last_lit] = t7 >>> 8 & 255, e10.pending_buf[e10.d_buf + 2 * e10.last_lit + 1] = 255 & t7, e10.pending_buf[e10.l_buf + e10.last_lit] = 255 & r9, e10.last_lit++, 0 === t7 ? e10.dyn_ltree[2 * r9]++ : (e10.matches++, t7--, e10.dyn_ltree[2 * (A2[r9] + u5 + 1)]++, e10.dyn_dtree[2 * N3(t7)]++), e10.last_lit === e10.lit_bufsize - 1; + }, r8._tr_align = function(e10) { + P3(e10, 2, 3), L3(e10, m4, z3), (function(e11) { + 16 === e11.bi_valid ? (U2(e11, e11.bi_buf), e11.bi_buf = 0, e11.bi_valid = 0) : 8 <= e11.bi_valid && (e11.pending_buf[e11.pending++] = 255 & e11.bi_buf, e11.bi_buf >>= 8, e11.bi_valid -= 8); + })(e10); + }; + }, { "../utils/common": 41 }], 53: [function(e9, t6, r8) { + "use strict"; + t6.exports = function() { + this.input = null, this.next_in = 0, this.avail_in = 0, this.total_in = 0, this.output = null, this.next_out = 0, this.avail_out = 0, this.total_out = 0, this.msg = "", this.state = null, this.data_type = 2, this.adler = 0; + }; + }, {}], 54: [function(e9, t6, r8) { + (function(e10) { + !(function(r9, n7) { + "use strict"; + if (!r9.setImmediate) { + var i7, s6, t7, a3, o9 = 1, h7 = {}, u5 = false, l5 = r9.document, e11 = Object.getPrototypeOf && Object.getPrototypeOf(r9); + e11 = e11 && e11.setTimeout ? e11 : r9, i7 = "[object process]" === {}.toString.call(r9.process) ? function(e12) { + process.nextTick(function() { + c6(e12); + }); + } : (function() { + if (r9.postMessage && !r9.importScripts) { + var e12 = true, t8 = r9.onmessage; + return r9.onmessage = function() { + e12 = false; + }, r9.postMessage("", "*"), r9.onmessage = t8, e12; + } + })() ? (a3 = "setImmediate$" + Math.random() + "$", r9.addEventListener ? r9.addEventListener("message", d4, false) : r9.attachEvent("onmessage", d4), function(e12) { + r9.postMessage(a3 + e12, "*"); + }) : r9.MessageChannel ? ((t7 = new MessageChannel()).port1.onmessage = function(e12) { + c6(e12.data); + }, function(e12) { + t7.port2.postMessage(e12); + }) : l5 && "onreadystatechange" in l5.createElement("script") ? (s6 = l5.documentElement, function(e12) { + var t8 = l5.createElement("script"); + t8.onreadystatechange = function() { + c6(e12), t8.onreadystatechange = null, s6.removeChild(t8), t8 = null; + }, s6.appendChild(t8); + }) : function(e12) { + setTimeout(c6, 0, e12); + }, e11.setImmediate = function(e12) { + "function" != typeof e12 && (e12 = new Function("" + e12)); + for (var t8 = new Array(arguments.length - 1), r10 = 0; r10 < t8.length; r10++) t8[r10] = arguments[r10 + 1]; + var n8 = { callback: e12, args: t8 }; + return h7[o9] = n8, i7(o9), o9++; + }, e11.clearImmediate = f4; + } + function f4(e12) { + delete h7[e12]; + } + function c6(e12) { + if (u5) setTimeout(c6, 0, e12); + else { + var t8 = h7[e12]; + if (t8) { + u5 = true; + try { + !(function(e13) { + var t9 = e13.callback, r10 = e13.args; + switch (r10.length) { + case 0: + t9(); + break; + case 1: + t9(r10[0]); + break; + case 2: + t9(r10[0], r10[1]); + break; + case 3: + t9(r10[0], r10[1], r10[2]); + break; + default: + t9.apply(n7, r10); + } + })(t8); + } finally { + f4(e12), u5 = false; + } + } + } + } + function d4(e12) { + e12.source === r9 && "string" == typeof e12.data && 0 === e12.data.indexOf(a3) && c6(+e12.data.slice(a3.length)); + } + })("undefined" == typeof self ? void 0 === e10 ? this : e10 : self); + }).call(this, "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}); + }, {}] }, {}, [10])(10); + }); + } +}); + +// ../pi-mono/node_modules/docx-preview/dist/docx-preview.mjs +function parseRelationships(root, xml2) { + return xml2.elements(root).map((e9) => ({ + id: xml2.attr(e9, "Id"), + type: xml2.attr(e9, "Type"), + target: xml2.attr(e9, "Target"), + targetMode: xml2.attr(e9, "TargetMode") + })); +} +function escapeClassName(className) { + return className?.replace(/[ .]+/g, "-").replace(/[&]+/g, "and").toLowerCase(); +} +function encloseFontFamily(fontFamily) { + return /^[^"'].*\s.*[^"']$/.test(fontFamily) ? `'${fontFamily}'` : fontFamily; +} +function splitPath(path6) { + let si = path6.lastIndexOf("/") + 1; + let folder = si == 0 ? "" : path6.substring(0, si); + let fileName = si == 0 ? path6 : path6.substring(si); + return [folder, fileName]; +} +function resolvePath(path6, base) { + try { + const prefix = "http://docx/"; + const url = new URL(path6, prefix + base).toString(); + return url.substring(prefix.length); + } catch { + return `${base}${path6}`; + } +} +function keyBy(array, by) { + return array.reduce((a3, x2) => { + a3[by(x2)] = x2; + return a3; + }, {}); +} +function blobToBase64(blob) { + return new Promise((resolve2, reject) => { + const reader = new FileReader(); + reader.onloadend = () => resolve2(reader.result); + reader.onerror = () => reject(); + reader.readAsDataURL(blob); + }); +} +function isObject(item) { + return item && typeof item === "object" && !Array.isArray(item); +} +function isString2(item) { + return typeof item === "string" || item instanceof String; +} +function mergeDeep(target, ...sources) { + if (!sources.length) + return target; + const source = sources.shift(); + if (isObject(target) && isObject(source)) { + for (const key in source) { + if (isObject(source[key])) { + const val2 = target[key] ?? (target[key] = {}); + mergeDeep(val2, source[key]); + } else { + target[key] = source[key]; + } + } + } + return mergeDeep(target, ...sources); +} +function asArray(val2) { + return Array.isArray(val2) ? val2 : [val2]; +} +function clamp(val2, min, max) { + return min > val2 ? min : max < val2 ? max : val2; +} +function convertLength(val2, usage = LengthUsage.Dxa) { + if (val2 == null || /.+(p[xt]|[%])$/.test(val2)) { + return val2; + } + var num = parseInt(val2) * usage.mul; + if (usage.min && usage.max) + num = clamp(num, usage.min, usage.max); + return `${num.toFixed(2)}${usage.unit}`; +} +function convertBoolean(v4, defaultValue = false) { + switch (v4) { + case "1": + return true; + case "0": + return false; + case "on": + return true; + case "off": + return false; + case "true": + return true; + case "false": + return false; + default: + return defaultValue; + } +} +function parseCommonProperty(elem, props, xml2) { + if (elem.namespaceURI != ns$1.wordml) + return false; + switch (elem.localName) { + case "color": + props.color = xml2.attr(elem, "val"); + break; + case "sz": + props.fontSize = xml2.lengthAttr(elem, "val", LengthUsage.FontSize); + break; + default: + return false; + } + return true; +} +function parseXmlString(xmlString, trimXmlDeclaration = false) { + if (trimXmlDeclaration) + xmlString = xmlString.replace(/<[?].*[?]>/, ""); + xmlString = removeUTF8BOM(xmlString); + const result = new DOMParser().parseFromString(xmlString, "application/xml"); + const errorText = hasXmlParserError(result); + if (errorText) + throw new Error(errorText); + return result; +} +function hasXmlParserError(doc) { + return doc.getElementsByTagName("parsererror")[0]?.textContent; +} +function removeUTF8BOM(data) { + return data.charCodeAt(0) === 65279 ? data.substring(1) : data; +} +function serializeXmlString(elem) { + return new XMLSerializer().serializeToString(elem); +} +function parseFonts(root, xml2) { + return xml2.elements(root).map((el) => parseFont(el, xml2)); +} +function parseFont(elem, xml2) { + let result = { + name: xml2.attr(elem, "name"), + embedFontRefs: [] + }; + for (let el of xml2.elements(elem)) { + switch (el.localName) { + case "family": + result.family = xml2.attr(el, "val"); + break; + case "altName": + result.altName = xml2.attr(el, "val"); + break; + case "embedRegular": + case "embedBold": + case "embedItalic": + case "embedBoldItalic": + result.embedFontRefs.push(parseEmbedFontRef(el, xml2)); + break; + } + } + return result; +} +function parseEmbedFontRef(elem, xml2) { + return { + id: xml2.attr(elem, "id"), + key: xml2.attr(elem, "fontKey"), + type: embedFontTypeMap[elem.localName] + }; +} +function normalizePath(path6) { + return path6.startsWith("/") ? path6.substr(1) : path6; +} +function parseBorder(elem, xml2) { + return { + type: xml2.attr(elem, "val"), + color: xml2.attr(elem, "color"), + size: xml2.lengthAttr(elem, "sz", LengthUsage.Border), + offset: xml2.lengthAttr(elem, "space", LengthUsage.Point), + frame: xml2.boolAttr(elem, "frame"), + shadow: xml2.boolAttr(elem, "shadow") + }; +} +function parseBorders(elem, xml2) { + var result = {}; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "left": + result.left = parseBorder(e9, xml2); + break; + case "top": + result.top = parseBorder(e9, xml2); + break; + case "right": + result.right = parseBorder(e9, xml2); + break; + case "bottom": + result.bottom = parseBorder(e9, xml2); + break; + } + } + return result; +} +function parseSectionProperties(elem, xml2 = globalXmlParser) { + var section = {}; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "pgSz": + section.pageSize = { + width: xml2.lengthAttr(e9, "w"), + height: xml2.lengthAttr(e9, "h"), + orientation: xml2.attr(e9, "orient") + }; + break; + case "type": + section.type = xml2.attr(e9, "val"); + break; + case "pgMar": + section.pageMargins = { + left: xml2.lengthAttr(e9, "left"), + right: xml2.lengthAttr(e9, "right"), + top: xml2.lengthAttr(e9, "top"), + bottom: xml2.lengthAttr(e9, "bottom"), + header: xml2.lengthAttr(e9, "header"), + footer: xml2.lengthAttr(e9, "footer"), + gutter: xml2.lengthAttr(e9, "gutter") + }; + break; + case "cols": + section.columns = parseColumns(e9, xml2); + break; + case "headerReference": + (section.headerRefs ?? (section.headerRefs = [])).push(parseFooterHeaderReference(e9, xml2)); + break; + case "footerReference": + (section.footerRefs ?? (section.footerRefs = [])).push(parseFooterHeaderReference(e9, xml2)); + break; + case "titlePg": + section.titlePage = xml2.boolAttr(e9, "val", true); + break; + case "pgBorders": + section.pageBorders = parseBorders(e9, xml2); + break; + case "pgNumType": + section.pageNumber = parsePageNumber(e9, xml2); + break; + } + } + return section; +} +function parseColumns(elem, xml2) { + return { + numberOfColumns: xml2.intAttr(elem, "num"), + space: xml2.lengthAttr(elem, "space"), + separator: xml2.boolAttr(elem, "sep"), + equalWidth: xml2.boolAttr(elem, "equalWidth", true), + columns: xml2.elements(elem, "col").map((e9) => ({ + width: xml2.lengthAttr(e9, "w"), + space: xml2.lengthAttr(e9, "space") + })) + }; +} +function parsePageNumber(elem, xml2) { + return { + chapSep: xml2.attr(elem, "chapSep"), + chapStyle: xml2.attr(elem, "chapStyle"), + format: xml2.attr(elem, "fmt"), + start: xml2.intAttr(elem, "start") + }; +} +function parseFooterHeaderReference(elem, xml2) { + return { + id: xml2.attr(elem, "id"), + type: xml2.attr(elem, "type") + }; +} +function parseLineSpacing(elem, xml2) { + return { + before: xml2.lengthAttr(elem, "before"), + after: xml2.lengthAttr(elem, "after"), + line: xml2.intAttr(elem, "line"), + lineRule: xml2.attr(elem, "lineRule") + }; +} +function parseRunProperties(elem, xml2) { + let result = {}; + for (let el of xml2.elements(elem)) { + parseRunProperty(el, result, xml2); + } + return result; +} +function parseRunProperty(elem, props, xml2) { + if (parseCommonProperty(elem, props, xml2)) + return true; + return false; +} +function parseParagraphProperties(elem, xml2) { + let result = {}; + for (let el of xml2.elements(elem)) { + parseParagraphProperty(el, result, xml2); + } + return result; +} +function parseParagraphProperty(elem, props, xml2) { + if (elem.namespaceURI != ns$1.wordml) + return false; + if (parseCommonProperty(elem, props, xml2)) + return true; + switch (elem.localName) { + case "tabs": + props.tabs = parseTabs(elem, xml2); + break; + case "sectPr": + props.sectionProps = parseSectionProperties(elem, xml2); + break; + case "numPr": + props.numbering = parseNumbering$1(elem, xml2); + break; + case "spacing": + props.lineSpacing = parseLineSpacing(elem, xml2); + return false; + case "textAlignment": + props.textAlignment = xml2.attr(elem, "val"); + return false; + case "keepLines": + props.keepLines = xml2.boolAttr(elem, "val", true); + break; + case "keepNext": + props.keepNext = xml2.boolAttr(elem, "val", true); + break; + case "pageBreakBefore": + props.pageBreakBefore = xml2.boolAttr(elem, "val", true); + break; + case "outlineLvl": + props.outlineLevel = xml2.intAttr(elem, "val"); + break; + case "pStyle": + props.styleName = xml2.attr(elem, "val"); + break; + case "rPr": + props.runProps = parseRunProperties(elem, xml2); + break; + default: + return false; + } + return true; +} +function parseTabs(elem, xml2) { + return xml2.elements(elem, "tab").map((e9) => ({ + position: xml2.lengthAttr(e9, "pos"), + leader: xml2.attr(e9, "leader"), + style: xml2.attr(e9, "val") + })); +} +function parseNumbering$1(elem, xml2) { + var result = {}; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "numId": + result.id = xml2.attr(e9, "val"); + break; + case "ilvl": + result.level = xml2.intAttr(e9, "val"); + break; + } + } + return result; +} +function parseNumberingPart(elem, xml2) { + let result = { + numberings: [], + abstractNumberings: [], + bulletPictures: [] + }; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "num": + result.numberings.push(parseNumbering(e9, xml2)); + break; + case "abstractNum": + result.abstractNumberings.push(parseAbstractNumbering(e9, xml2)); + break; + case "numPicBullet": + result.bulletPictures.push(parseNumberingBulletPicture(e9, xml2)); + break; + } + } + return result; +} +function parseNumbering(elem, xml2) { + let result = { + id: xml2.attr(elem, "numId"), + overrides: [] + }; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "abstractNumId": + result.abstractId = xml2.attr(e9, "val"); + break; + case "lvlOverride": + result.overrides.push(parseNumberingLevelOverrride(e9, xml2)); + break; + } + } + return result; +} +function parseAbstractNumbering(elem, xml2) { + let result = { + id: xml2.attr(elem, "abstractNumId"), + levels: [] + }; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "name": + result.name = xml2.attr(e9, "val"); + break; + case "multiLevelType": + result.multiLevelType = xml2.attr(e9, "val"); + break; + case "numStyleLink": + result.numberingStyleLink = xml2.attr(e9, "val"); + break; + case "styleLink": + result.styleLink = xml2.attr(e9, "val"); + break; + case "lvl": + result.levels.push(parseNumberingLevel(e9, xml2)); + break; + } + } + return result; +} +function parseNumberingLevel(elem, xml2) { + let result = { + level: xml2.intAttr(elem, "ilvl") + }; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "start": + result.start = xml2.attr(e9, "val"); + break; + case "lvlRestart": + result.restart = xml2.intAttr(e9, "val"); + break; + case "numFmt": + result.format = xml2.attr(e9, "val"); + break; + case "lvlText": + result.text = xml2.attr(e9, "val"); + break; + case "lvlJc": + result.justification = xml2.attr(e9, "val"); + break; + case "lvlPicBulletId": + result.bulletPictureId = xml2.attr(e9, "val"); + break; + case "pStyle": + result.paragraphStyle = xml2.attr(e9, "val"); + break; + case "pPr": + result.paragraphProps = parseParagraphProperties(e9, xml2); + break; + case "rPr": + result.runProps = parseRunProperties(e9, xml2); + break; + } + } + return result; +} +function parseNumberingLevelOverrride(elem, xml2) { + let result = { + level: xml2.intAttr(elem, "ilvl") + }; + for (let e9 of xml2.elements(elem)) { + switch (e9.localName) { + case "startOverride": + result.start = xml2.intAttr(e9, "val"); + break; + case "lvl": + result.numberingLevel = parseNumberingLevel(e9, xml2); + break; + } + } + return result; +} +function parseNumberingBulletPicture(elem, xml2) { + var pict = xml2.element(elem, "pict"); + var shape = pict && xml2.element(pict, "shape"); + var imagedata = shape && xml2.element(shape, "imagedata"); + return imagedata ? { + id: xml2.attr(elem, "numPicBulletId"), + referenceId: xml2.attr(imagedata, "id"), + style: xml2.attr(shape, "style") + } : null; +} +function parseExtendedProps(root, xmlParser) { + const result = {}; + for (let el of xmlParser.elements(root)) { + switch (el.localName) { + case "Template": + result.template = el.textContent; + break; + case "Pages": + result.pages = safeParseToInt(el.textContent); + break; + case "Words": + result.words = safeParseToInt(el.textContent); + break; + case "Characters": + result.characters = safeParseToInt(el.textContent); + break; + case "Application": + result.application = el.textContent; + break; + case "Lines": + result.lines = safeParseToInt(el.textContent); + break; + case "Paragraphs": + result.paragraphs = safeParseToInt(el.textContent); + break; + case "Company": + result.company = el.textContent; + break; + case "AppVersion": + result.appVersion = el.textContent; + break; + } + } + return result; +} +function safeParseToInt(value) { + if (typeof value === "undefined") + return; + return parseInt(value); +} +function parseCoreProps(root, xmlParser) { + const result = {}; + for (let el of xmlParser.elements(root)) { + switch (el.localName) { + case "title": + result.title = el.textContent; + break; + case "description": + result.description = el.textContent; + break; + case "subject": + result.subject = el.textContent; + break; + case "creator": + result.creator = el.textContent; + break; + case "keywords": + result.keywords = el.textContent; + break; + case "language": + result.language = el.textContent; + break; + case "lastModifiedBy": + result.lastModifiedBy = el.textContent; + break; + case "revision": + el.textContent && (result.revision = parseInt(el.textContent)); + break; + } + } + return result; +} +function parseTheme(elem, xml2) { + var result = new DmlTheme(); + var themeElements = xml2.element(elem, "themeElements"); + for (let el of xml2.elements(themeElements)) { + switch (el.localName) { + case "clrScheme": + result.colorScheme = parseColorScheme(el, xml2); + break; + case "fontScheme": + result.fontScheme = parseFontScheme(el, xml2); + break; + } + } + return result; +} +function parseColorScheme(elem, xml2) { + var result = { + name: xml2.attr(elem, "name"), + colors: {} + }; + for (let el of xml2.elements(elem)) { + var srgbClr = xml2.element(el, "srgbClr"); + var sysClr = xml2.element(el, "sysClr"); + if (srgbClr) { + result.colors[el.localName] = xml2.attr(srgbClr, "val"); + } else if (sysClr) { + result.colors[el.localName] = xml2.attr(sysClr, "lastClr"); + } + } + return result; +} +function parseFontScheme(elem, xml2) { + var result = { + name: xml2.attr(elem, "name") + }; + for (let el of xml2.elements(elem)) { + switch (el.localName) { + case "majorFont": + result.majorFont = parseFontInfo(el, xml2); + break; + case "minorFont": + result.minorFont = parseFontInfo(el, xml2); + break; + } + } + return result; +} +function parseFontInfo(elem, xml2) { + return { + latinTypeface: xml2.elementAttr(elem, "latin", "typeface"), + eaTypeface: xml2.elementAttr(elem, "ea", "typeface"), + csTypeface: xml2.elementAttr(elem, "cs", "typeface") + }; +} +function parseSettings(elem, xml2) { + var result = {}; + for (let el of xml2.elements(elem)) { + switch (el.localName) { + case "defaultTabStop": + result.defaultTabStop = xml2.lengthAttr(el, "val"); + break; + case "footnotePr": + result.footnoteProps = parseNoteProperties(el, xml2); + break; + case "endnotePr": + result.endnoteProps = parseNoteProperties(el, xml2); + break; + case "autoHyphenation": + result.autoHyphenation = xml2.boolAttr(el, "val"); + break; + } + } + return result; +} +function parseNoteProperties(elem, xml2) { + var result = { + defaultNoteIds: [] + }; + for (let el of xml2.elements(elem)) { + switch (el.localName) { + case "numFmt": + result.nummeringFormat = xml2.attr(el, "val"); + break; + case "footnote": + case "endnote": + result.defaultNoteIds.push(xml2.attr(el, "id")); + break; + } + } + return result; +} +function parseCustomProps(root, xml2) { + return xml2.elements(root, "property").map((e9) => { + const firstChild = e9.firstChild; + return { + formatId: xml2.attr(e9, "fmtid"), + name: xml2.attr(e9, "name"), + type: firstChild.nodeName, + value: firstChild.textContent + }; + }); +} +function deobfuscate(data, guidKey) { + const len = 16; + const trimmed = guidKey.replace(/{|}|-/g, ""); + const numbers2 = new Array(len); + for (let i7 = 0; i7 < len; i7++) + numbers2[len - i7 - 1] = parseInt(trimmed.substring(i7 * 2, i7 * 2 + 2), 16); + for (let i7 = 0; i7 < 32; i7++) + data[i7] = data[i7] ^ numbers2[i7 % len]; + return data; +} +function parseBookmarkStart(elem, xml2) { + return { + type: DomType.BookmarkStart, + id: xml2.attr(elem, "id"), + name: xml2.attr(elem, "name"), + colFirst: xml2.intAttr(elem, "colFirst"), + colLast: xml2.intAttr(elem, "colLast") + }; +} +function parseBookmarkEnd(elem, xml2) { + return { + type: DomType.BookmarkEnd, + id: xml2.attr(elem, "id") + }; +} +function parseVmlElement(elem, parser) { + var result = new VmlElement(); + switch (elem.localName) { + case "rect": + result.tagName = "rect"; + Object.assign(result.attrs, { width: "100%", height: "100%" }); + break; + case "oval": + result.tagName = "ellipse"; + Object.assign(result.attrs, { cx: "50%", cy: "50%", rx: "50%", ry: "50%" }); + break; + case "line": + result.tagName = "line"; + break; + case "shape": + result.tagName = "g"; + break; + case "textbox": + result.tagName = "foreignObject"; + Object.assign(result.attrs, { width: "100%", height: "100%" }); + break; + default: + return null; + } + for (const at of globalXmlParser.attrs(elem)) { + switch (at.localName) { + case "style": + result.cssStyleText = at.value; + break; + case "fillcolor": + result.attrs.fill = at.value; + break; + case "from": + const [x1, y1] = parsePoint(at.value); + Object.assign(result.attrs, { x1, y1 }); + break; + case "to": + const [x2, y22] = parsePoint(at.value); + Object.assign(result.attrs, { x2, y2: y22 }); + break; + } + } + for (const el of globalXmlParser.elements(elem)) { + switch (el.localName) { + case "stroke": + Object.assign(result.attrs, parseStroke(el)); + break; + case "fill": + Object.assign(result.attrs, parseFill()); + break; + case "imagedata": + result.tagName = "image"; + Object.assign(result.attrs, { width: "100%", height: "100%" }); + result.imageHref = { + id: globalXmlParser.attr(el, "id"), + title: globalXmlParser.attr(el, "title") + }; + break; + case "txbxContent": + result.children.push(...parser.parseBodyElements(el)); + break; + default: + const child = parseVmlElement(el, parser); + child && result.children.push(child); + break; + } + } + return result; +} +function parseStroke(el) { + return { + "stroke": globalXmlParser.attr(el, "color"), + "stroke-width": globalXmlParser.lengthAttr(el, "weight", LengthUsage.Emu) ?? "1px" + }; +} +function parseFill(el) { + return {}; +} +function parsePoint(val2) { + return val2.split(","); +} +function computePixelToPoint(container = document.body) { + const temp = document.createElement("div"); + temp.style.width = "100pt"; + container.appendChild(temp); + const result = 100 / temp.offsetWidth; + container.removeChild(temp); + return result; +} +function updateTabStop(elem, tabs, defaultTabSize, pixelToPoint = 72 / 96) { + const p4 = elem.closest("p"); + const ebb = elem.getBoundingClientRect(); + const pbb = p4.getBoundingClientRect(); + const pcs = getComputedStyle(p4); + const tabStops = tabs?.length > 0 ? tabs.map((t6) => ({ + pos: lengthToPoint(t6.position), + leader: t6.leader, + style: t6.style + })).sort((a3, b4) => a3.pos - b4.pos) : [defaultTab]; + const lastTab = tabStops[tabStops.length - 1]; + const pWidthPt = pbb.width * pixelToPoint; + const size = lengthToPoint(defaultTabSize); + let pos = lastTab.pos + size; + if (pos < pWidthPt) { + for (; pos < pWidthPt && tabStops.length < maxTabs; pos += size) { + tabStops.push({ ...defaultTab, pos }); + } + } + const marginLeft = parseFloat(pcs.marginLeft); + const pOffset = pbb.left + marginLeft; + const left = (ebb.left - pOffset) * pixelToPoint; + const tab = tabStops.find((t6) => t6.style != "clear" && t6.pos > left); + if (tab == null) + return; + let width = 1; + if (tab.style == "right" || tab.style == "center") { + const tabStops2 = Array.from(p4.querySelectorAll(`.${elem.className}`)); + const nextIdx = tabStops2.indexOf(elem) + 1; + const range2 = document.createRange(); + range2.setStart(elem, 1); + if (nextIdx < tabStops2.length) { + range2.setEndBefore(tabStops2[nextIdx]); + } else { + range2.setEndAfter(p4); + } + const mul = tab.style == "center" ? 0.5 : 1; + const nextBB = range2.getBoundingClientRect(); + const offset = nextBB.left + mul * nextBB.width - (pbb.left - marginLeft); + width = tab.pos - offset * pixelToPoint; + } else { + width = tab.pos - left; + } + elem.innerHTML = " "; + elem.style.textDecoration = "inherit"; + elem.style.wordSpacing = `${width.toFixed(0)}pt`; + switch (tab.leader) { + case "dot": + case "middleDot": + elem.style.textDecoration = "underline"; + elem.style.textDecorationStyle = "dotted"; + break; + case "hyphen": + case "heavy": + case "underscore": + elem.style.textDecoration = "underline"; + break; + } +} +function lengthToPoint(length) { + return parseFloat(length); +} +function removeAllElements(elem) { + elem.innerHTML = ""; +} +function appendChildren(elem, children) { + children.forEach((c6) => elem.appendChild(isString2(c6) ? document.createTextNode(c6) : c6)); +} +function findParent(elem, type) { + var parent = elem.parent; + while (parent != null && parent.type != type) + parent = parent.parent; + return parent; +} +function parseAsync(data, userOptions) { + const ops = { ...defaultOptions2, ...userOptions }; + return WordDocument.load(data, new DocumentParser(ops), ops); +} +async function renderDocument(document2, bodyContainer, styleContainer, userOptions) { + const ops = { ...defaultOptions2, ...userOptions }; + const renderer = new HtmlRenderer(window.document); + return await renderer.render(document2, bodyContainer, styleContainer, ops); +} +async function renderAsync(data, bodyContainer, styleContainer, userOptions) { + const doc = await parseAsync(data, userOptions); + await renderDocument(doc, bodyContainer, styleContainer, userOptions); + return doc; +} +var import_jszip, RelationshipTypes, ns$1, LengthUsage, XmlParser, globalXmlParser, Part, embedFontTypeMap, FontTablePart, OpenXmlPackage, DocumentPart, SectionType, NumberingPart, StylesPart, DomType, OpenXmlElementBase, WmlHeader, WmlFooter, BaseHeaderFooterPart, HeaderPart, FooterPart, ExtendedPropsPart, CorePropsPart, DmlTheme, ThemePart, WmlBaseNote, WmlFootnote, WmlEndnote, BaseNotePart, FootnotesPart, EndnotesPart, SettingsPart, CustomPropsPart, CommentsPart, CommentsExtendedPart, topLevelRels, WordDocument, VmlElement, WmlComment, WmlCommentReference, WmlCommentRangeStart, WmlCommentRangeEnd, autos, supportedNamespaceURIs, mmlTagMap, DocumentParser, knownColors, xmlUtil, values, defaultTab, maxTabs, ns, HtmlRenderer, defaultOptions2; +var init_docx_preview = __esm({ + "../pi-mono/node_modules/docx-preview/dist/docx-preview.mjs"() { + init_process_shim(); + import_jszip = __toESM(require_jszip_min(), 1); + (function(RelationshipTypes2) { + RelationshipTypes2["OfficeDocument"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; + RelationshipTypes2["FontTable"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable"; + RelationshipTypes2["Image"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; + RelationshipTypes2["Numbering"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"; + RelationshipTypes2["Styles"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; + RelationshipTypes2["StylesWithEffects"] = "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects"; + RelationshipTypes2["Theme"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"; + RelationshipTypes2["Settings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings"; + RelationshipTypes2["WebSettings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings"; + RelationshipTypes2["Hyperlink"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; + RelationshipTypes2["Footnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"; + RelationshipTypes2["Endnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes"; + RelationshipTypes2["Footer"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"; + RelationshipTypes2["Header"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"; + RelationshipTypes2["ExtendedProperties"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; + RelationshipTypes2["CoreProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; + RelationshipTypes2["CustomProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties"; + RelationshipTypes2["Comments"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; + RelationshipTypes2["CommentsExtended"] = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended"; + RelationshipTypes2["AltChunk"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk"; + })(RelationshipTypes || (RelationshipTypes = {})); + ns$1 = { + wordml: "http://schemas.openxmlformats.org/wordprocessingml/2006/main" + }; + LengthUsage = { + Dxa: { mul: 0.05, unit: "pt" }, + Emu: { mul: 1 / 12700, unit: "pt" }, + FontSize: { mul: 0.5, unit: "pt" }, + Border: { mul: 0.125, unit: "pt", min: 0.25, max: 12 }, + Point: { mul: 1, unit: "pt" }, + Percent: { mul: 0.02, unit: "%" } + }; + XmlParser = class { + elements(elem, localName = null) { + const result = []; + for (let i7 = 0, l5 = elem.childNodes.length; i7 < l5; i7++) { + let c6 = elem.childNodes.item(i7); + if (c6.nodeType == Node.ELEMENT_NODE && (localName == null || c6.localName == localName)) + result.push(c6); + } + return result; + } + element(elem, localName) { + for (let i7 = 0, l5 = elem.childNodes.length; i7 < l5; i7++) { + let c6 = elem.childNodes.item(i7); + if (c6.nodeType == 1 && c6.localName == localName) + return c6; + } + return null; + } + elementAttr(elem, localName, attrLocalName) { + var el = this.element(elem, localName); + return el ? this.attr(el, attrLocalName) : void 0; + } + attrs(elem) { + return Array.from(elem.attributes); + } + attr(elem, localName) { + for (let i7 = 0, l5 = elem.attributes.length; i7 < l5; i7++) { + let a3 = elem.attributes.item(i7); + if (a3.localName == localName) + return a3.value; + } + return null; + } + intAttr(node, attrName, defaultValue = null) { + var val2 = this.attr(node, attrName); + return val2 ? parseInt(val2) : defaultValue; + } + hexAttr(node, attrName, defaultValue = null) { + var val2 = this.attr(node, attrName); + return val2 ? parseInt(val2, 16) : defaultValue; + } + floatAttr(node, attrName, defaultValue = null) { + var val2 = this.attr(node, attrName); + return val2 ? parseFloat(val2) : defaultValue; + } + boolAttr(node, attrName, defaultValue = null) { + return convertBoolean(this.attr(node, attrName), defaultValue); + } + lengthAttr(node, attrName, usage = LengthUsage.Dxa) { + return convertLength(this.attr(node, attrName), usage); + } + }; + globalXmlParser = new XmlParser(); + Part = class { + constructor(_package, path6) { + this._package = _package; + this.path = path6; + } + async load() { + this.rels = await this._package.loadRelationships(this.path); + const xmlText = await this._package.load(this.path); + const xmlDoc = this._package.parseXmlDocument(xmlText); + if (this._package.options.keepOrigin) { + this._xmlDocument = xmlDoc; + } + this.parseXml(xmlDoc.firstElementChild); + } + save() { + this._package.update(this.path, serializeXmlString(this._xmlDocument)); + } + parseXml(root) { + } + }; + embedFontTypeMap = { + embedRegular: "regular", + embedBold: "bold", + embedItalic: "italic", + embedBoldItalic: "boldItalic" + }; + FontTablePart = class extends Part { + parseXml(root) { + this.fonts = parseFonts(root, this._package.xmlParser); + } + }; + OpenXmlPackage = class _OpenXmlPackage { + constructor(_zip, options) { + this._zip = _zip; + this.options = options; + this.xmlParser = new XmlParser(); + } + get(path6) { + const p4 = normalizePath(path6); + return this._zip.files[p4] ?? this._zip.files[p4.replace(/\//g, "\\")]; + } + update(path6, content) { + this._zip.file(path6, content); + } + static async load(input, options) { + const zip = await import_jszip.default.loadAsync(input); + return new _OpenXmlPackage(zip, options); + } + save(type = "blob") { + return this._zip.generateAsync({ type }); + } + load(path6, type = "string") { + return this.get(path6)?.async(type) ?? Promise.resolve(null); + } + async loadRelationships(path6 = null) { + let relsPath = `_rels/.rels`; + if (path6 != null) { + const [f4, fn] = splitPath(path6); + relsPath = `${f4}_rels/${fn}.rels`; + } + const txt = await this.load(relsPath); + return txt ? parseRelationships(this.parseXmlDocument(txt).firstElementChild, this.xmlParser) : null; + } + parseXmlDocument(txt) { + return parseXmlString(txt, this.options.trimXmlDeclaration); + } + }; + DocumentPart = class extends Part { + constructor(pkg, path6, parser) { + super(pkg, path6); + this._documentParser = parser; + } + parseXml(root) { + this.body = this._documentParser.parseDocumentFile(root); + } + }; + (function(SectionType2) { + SectionType2["Continuous"] = "continuous"; + SectionType2["NextPage"] = "nextPage"; + SectionType2["NextColumn"] = "nextColumn"; + SectionType2["EvenPage"] = "evenPage"; + SectionType2["OddPage"] = "oddPage"; + })(SectionType || (SectionType = {})); + NumberingPart = class extends Part { + constructor(pkg, path6, parser) { + super(pkg, path6); + this._documentParser = parser; + } + parseXml(root) { + Object.assign(this, parseNumberingPart(root, this._package.xmlParser)); + this.domNumberings = this._documentParser.parseNumberingFile(root); + } + }; + StylesPart = class extends Part { + constructor(pkg, path6, parser) { + super(pkg, path6); + this._documentParser = parser; + } + parseXml(root) { + this.styles = this._documentParser.parseStylesFile(root); + } + }; + (function(DomType2) { + DomType2["Document"] = "document"; + DomType2["Paragraph"] = "paragraph"; + DomType2["Run"] = "run"; + DomType2["Break"] = "break"; + DomType2["NoBreakHyphen"] = "noBreakHyphen"; + DomType2["Table"] = "table"; + DomType2["Row"] = "row"; + DomType2["Cell"] = "cell"; + DomType2["Hyperlink"] = "hyperlink"; + DomType2["SmartTag"] = "smartTag"; + DomType2["Drawing"] = "drawing"; + DomType2["Image"] = "image"; + DomType2["Text"] = "text"; + DomType2["Tab"] = "tab"; + DomType2["Symbol"] = "symbol"; + DomType2["BookmarkStart"] = "bookmarkStart"; + DomType2["BookmarkEnd"] = "bookmarkEnd"; + DomType2["Footer"] = "footer"; + DomType2["Header"] = "header"; + DomType2["FootnoteReference"] = "footnoteReference"; + DomType2["EndnoteReference"] = "endnoteReference"; + DomType2["Footnote"] = "footnote"; + DomType2["Endnote"] = "endnote"; + DomType2["SimpleField"] = "simpleField"; + DomType2["ComplexField"] = "complexField"; + DomType2["Instruction"] = "instruction"; + DomType2["VmlPicture"] = "vmlPicture"; + DomType2["MmlMath"] = "mmlMath"; + DomType2["MmlMathParagraph"] = "mmlMathParagraph"; + DomType2["MmlFraction"] = "mmlFraction"; + DomType2["MmlFunction"] = "mmlFunction"; + DomType2["MmlFunctionName"] = "mmlFunctionName"; + DomType2["MmlNumerator"] = "mmlNumerator"; + DomType2["MmlDenominator"] = "mmlDenominator"; + DomType2["MmlRadical"] = "mmlRadical"; + DomType2["MmlBase"] = "mmlBase"; + DomType2["MmlDegree"] = "mmlDegree"; + DomType2["MmlSuperscript"] = "mmlSuperscript"; + DomType2["MmlSubscript"] = "mmlSubscript"; + DomType2["MmlPreSubSuper"] = "mmlPreSubSuper"; + DomType2["MmlSubArgument"] = "mmlSubArgument"; + DomType2["MmlSuperArgument"] = "mmlSuperArgument"; + DomType2["MmlNary"] = "mmlNary"; + DomType2["MmlDelimiter"] = "mmlDelimiter"; + DomType2["MmlRun"] = "mmlRun"; + DomType2["MmlEquationArray"] = "mmlEquationArray"; + DomType2["MmlLimit"] = "mmlLimit"; + DomType2["MmlLimitLower"] = "mmlLimitLower"; + DomType2["MmlMatrix"] = "mmlMatrix"; + DomType2["MmlMatrixRow"] = "mmlMatrixRow"; + DomType2["MmlBox"] = "mmlBox"; + DomType2["MmlBar"] = "mmlBar"; + DomType2["MmlGroupChar"] = "mmlGroupChar"; + DomType2["VmlElement"] = "vmlElement"; + DomType2["Inserted"] = "inserted"; + DomType2["Deleted"] = "deleted"; + DomType2["DeletedText"] = "deletedText"; + DomType2["Comment"] = "comment"; + DomType2["CommentReference"] = "commentReference"; + DomType2["CommentRangeStart"] = "commentRangeStart"; + DomType2["CommentRangeEnd"] = "commentRangeEnd"; + DomType2["AltChunk"] = "altChunk"; + })(DomType || (DomType = {})); + OpenXmlElementBase = class { + constructor() { + this.children = []; + this.cssStyle = {}; + } + }; + WmlHeader = class extends OpenXmlElementBase { + constructor() { + super(...arguments); + this.type = DomType.Header; + } + }; + WmlFooter = class extends OpenXmlElementBase { + constructor() { + super(...arguments); + this.type = DomType.Footer; + } + }; + BaseHeaderFooterPart = class extends Part { + constructor(pkg, path6, parser) { + super(pkg, path6); + this._documentParser = parser; + } + parseXml(root) { + this.rootElement = this.createRootElement(); + this.rootElement.children = this._documentParser.parseBodyElements(root); + } + }; + HeaderPart = class extends BaseHeaderFooterPart { + createRootElement() { + return new WmlHeader(); + } + }; + FooterPart = class extends BaseHeaderFooterPart { + createRootElement() { + return new WmlFooter(); + } + }; + ExtendedPropsPart = class extends Part { + parseXml(root) { + this.props = parseExtendedProps(root, this._package.xmlParser); + } + }; + CorePropsPart = class extends Part { + parseXml(root) { + this.props = parseCoreProps(root, this._package.xmlParser); + } + }; + DmlTheme = class { + }; + ThemePart = class extends Part { + constructor(pkg, path6) { + super(pkg, path6); + } + parseXml(root) { + this.theme = parseTheme(root, this._package.xmlParser); + } + }; + WmlBaseNote = class { + }; + WmlFootnote = class extends WmlBaseNote { + constructor() { + super(...arguments); + this.type = DomType.Footnote; + } + }; + WmlEndnote = class extends WmlBaseNote { + constructor() { + super(...arguments); + this.type = DomType.Endnote; + } + }; + BaseNotePart = class extends Part { + constructor(pkg, path6, parser) { + super(pkg, path6); + this._documentParser = parser; + } + }; + FootnotesPart = class extends BaseNotePart { + constructor(pkg, path6, parser) { + super(pkg, path6, parser); + } + parseXml(root) { + this.notes = this._documentParser.parseNotes(root, "footnote", WmlFootnote); + } + }; + EndnotesPart = class extends BaseNotePart { + constructor(pkg, path6, parser) { + super(pkg, path6, parser); + } + parseXml(root) { + this.notes = this._documentParser.parseNotes(root, "endnote", WmlEndnote); + } + }; + SettingsPart = class extends Part { + constructor(pkg, path6) { + super(pkg, path6); + } + parseXml(root) { + this.settings = parseSettings(root, this._package.xmlParser); + } + }; + CustomPropsPart = class extends Part { + parseXml(root) { + this.props = parseCustomProps(root, this._package.xmlParser); + } + }; + CommentsPart = class extends Part { + constructor(pkg, path6, parser) { + super(pkg, path6); + this._documentParser = parser; + } + parseXml(root) { + this.comments = this._documentParser.parseComments(root); + this.commentMap = keyBy(this.comments, (x2) => x2.id); + } + }; + CommentsExtendedPart = class extends Part { + constructor(pkg, path6) { + super(pkg, path6); + this.comments = []; + } + parseXml(root) { + const xml2 = this._package.xmlParser; + for (let el of xml2.elements(root, "commentEx")) { + this.comments.push({ + paraId: xml2.attr(el, "paraId"), + paraIdParent: xml2.attr(el, "paraIdParent"), + done: xml2.boolAttr(el, "done") + }); + } + this.commentMap = keyBy(this.comments, (x2) => x2.paraId); + } + }; + topLevelRels = [ + { type: RelationshipTypes.OfficeDocument, target: "word/document.xml" }, + { type: RelationshipTypes.ExtendedProperties, target: "docProps/app.xml" }, + { type: RelationshipTypes.CoreProperties, target: "docProps/core.xml" }, + { type: RelationshipTypes.CustomProperties, target: "docProps/custom.xml" } + ]; + WordDocument = class _WordDocument { + constructor() { + this.parts = []; + this.partsMap = {}; + } + static async load(blob, parser, options) { + var d4 = new _WordDocument(); + d4._options = options; + d4._parser = parser; + d4._package = await OpenXmlPackage.load(blob, options); + d4.rels = await d4._package.loadRelationships(); + await Promise.all(topLevelRels.map((rel2) => { + const r8 = d4.rels.find((x2) => x2.type === rel2.type) ?? rel2; + return d4.loadRelationshipPart(r8.target, r8.type); + })); + return d4; + } + save(type = "blob") { + return this._package.save(type); + } + async loadRelationshipPart(path6, type) { + if (this.partsMap[path6]) + return this.partsMap[path6]; + if (!this._package.get(path6)) + return null; + let part = null; + switch (type) { + case RelationshipTypes.OfficeDocument: + this.documentPart = part = new DocumentPart(this._package, path6, this._parser); + break; + case RelationshipTypes.FontTable: + this.fontTablePart = part = new FontTablePart(this._package, path6); + break; + case RelationshipTypes.Numbering: + this.numberingPart = part = new NumberingPart(this._package, path6, this._parser); + break; + case RelationshipTypes.Styles: + this.stylesPart = part = new StylesPart(this._package, path6, this._parser); + break; + case RelationshipTypes.Theme: + this.themePart = part = new ThemePart(this._package, path6); + break; + case RelationshipTypes.Footnotes: + this.footnotesPart = part = new FootnotesPart(this._package, path6, this._parser); + break; + case RelationshipTypes.Endnotes: + this.endnotesPart = part = new EndnotesPart(this._package, path6, this._parser); + break; + case RelationshipTypes.Footer: + part = new FooterPart(this._package, path6, this._parser); + break; + case RelationshipTypes.Header: + part = new HeaderPart(this._package, path6, this._parser); + break; + case RelationshipTypes.CoreProperties: + this.corePropsPart = part = new CorePropsPart(this._package, path6); + break; + case RelationshipTypes.ExtendedProperties: + this.extendedPropsPart = part = new ExtendedPropsPart(this._package, path6); + break; + case RelationshipTypes.CustomProperties: + part = new CustomPropsPart(this._package, path6); + break; + case RelationshipTypes.Settings: + this.settingsPart = part = new SettingsPart(this._package, path6); + break; + case RelationshipTypes.Comments: + this.commentsPart = part = new CommentsPart(this._package, path6, this._parser); + break; + case RelationshipTypes.CommentsExtended: + this.commentsExtendedPart = part = new CommentsExtendedPart(this._package, path6); + break; + } + if (part == null) + return Promise.resolve(null); + this.partsMap[path6] = part; + this.parts.push(part); + await part.load(); + if (part.rels?.length > 0) { + const [folder] = splitPath(part.path); + await Promise.all(part.rels.map((rel2) => this.loadRelationshipPart(resolvePath(rel2.target, folder), rel2.type))); + } + return part; + } + async loadDocumentImage(id, part) { + const x2 = await this.loadResource(part ?? this.documentPart, id, "blob"); + return this.blobToURL(x2); + } + async loadNumberingImage(id) { + const x2 = await this.loadResource(this.numberingPart, id, "blob"); + return this.blobToURL(x2); + } + async loadFont(id, key) { + const x2 = await this.loadResource(this.fontTablePart, id, "uint8array"); + return x2 ? this.blobToURL(new Blob([deobfuscate(x2, key)])) : x2; + } + async loadAltChunk(id, part) { + return await this.loadResource(part ?? this.documentPart, id, "string"); + } + blobToURL(blob) { + if (!blob) + return null; + if (this._options.useBase64URL) { + return blobToBase64(blob); + } + return URL.createObjectURL(blob); + } + findPartByRelId(id, basePart = null) { + var rel2 = (basePart.rels ?? this.rels).find((r8) => r8.id == id); + const folder = basePart ? splitPath(basePart.path)[0] : ""; + return rel2 ? this.partsMap[resolvePath(rel2.target, folder)] : null; + } + getPathById(part, id) { + const rel2 = part.rels.find((x2) => x2.id == id); + const [folder] = splitPath(part.path); + return rel2 ? resolvePath(rel2.target, folder) : null; + } + loadResource(part, id, outputType) { + const path6 = this.getPathById(part, id); + return path6 ? this._package.load(path6, outputType) : Promise.resolve(null); + } + }; + VmlElement = class extends OpenXmlElementBase { + constructor() { + super(...arguments); + this.type = DomType.VmlElement; + this.attrs = {}; + } + }; + WmlComment = class extends OpenXmlElementBase { + constructor() { + super(...arguments); + this.type = DomType.Comment; + } + }; + WmlCommentReference = class extends OpenXmlElementBase { + constructor(id) { + super(); + this.id = id; + this.type = DomType.CommentReference; + } + }; + WmlCommentRangeStart = class extends OpenXmlElementBase { + constructor(id) { + super(); + this.id = id; + this.type = DomType.CommentRangeStart; + } + }; + WmlCommentRangeEnd = class extends OpenXmlElementBase { + constructor(id) { + super(); + this.id = id; + this.type = DomType.CommentRangeEnd; + } + }; + autos = { + shd: "inherit", + color: "black", + borderColor: "black", + highlight: "transparent" + }; + supportedNamespaceURIs = []; + mmlTagMap = { + "oMath": DomType.MmlMath, + "oMathPara": DomType.MmlMathParagraph, + "f": DomType.MmlFraction, + "func": DomType.MmlFunction, + "fName": DomType.MmlFunctionName, + "num": DomType.MmlNumerator, + "den": DomType.MmlDenominator, + "rad": DomType.MmlRadical, + "deg": DomType.MmlDegree, + "e": DomType.MmlBase, + "sSup": DomType.MmlSuperscript, + "sSub": DomType.MmlSubscript, + "sPre": DomType.MmlPreSubSuper, + "sup": DomType.MmlSuperArgument, + "sub": DomType.MmlSubArgument, + "d": DomType.MmlDelimiter, + "nary": DomType.MmlNary, + "eqArr": DomType.MmlEquationArray, + "lim": DomType.MmlLimit, + "limLow": DomType.MmlLimitLower, + "m": DomType.MmlMatrix, + "mr": DomType.MmlMatrixRow, + "box": DomType.MmlBox, + "bar": DomType.MmlBar, + "groupChr": DomType.MmlGroupChar + }; + DocumentParser = class { + constructor(options) { + this.options = { + ignoreWidth: false, + debug: false, + ...options + }; + } + parseNotes(xmlDoc, elemName, elemClass) { + var result = []; + for (let el of globalXmlParser.elements(xmlDoc, elemName)) { + const node = new elemClass(); + node.id = globalXmlParser.attr(el, "id"); + node.noteType = globalXmlParser.attr(el, "type"); + node.children = this.parseBodyElements(el); + result.push(node); + } + return result; + } + parseComments(xmlDoc) { + var result = []; + for (let el of globalXmlParser.elements(xmlDoc, "comment")) { + const item = new WmlComment(); + item.id = globalXmlParser.attr(el, "id"); + item.author = globalXmlParser.attr(el, "author"); + item.initials = globalXmlParser.attr(el, "initials"); + item.date = globalXmlParser.attr(el, "date"); + item.children = this.parseBodyElements(el); + result.push(item); + } + return result; + } + parseDocumentFile(xmlDoc) { + var xbody = globalXmlParser.element(xmlDoc, "body"); + var background = globalXmlParser.element(xmlDoc, "background"); + var sectPr = globalXmlParser.element(xbody, "sectPr"); + return { + type: DomType.Document, + children: this.parseBodyElements(xbody), + props: sectPr ? parseSectionProperties(sectPr, globalXmlParser) : {}, + cssStyle: background ? this.parseBackground(background) : {} + }; + } + parseBackground(elem) { + var result = {}; + var color2 = xmlUtil.colorAttr(elem, "color"); + if (color2) { + result["background-color"] = color2; + } + return result; + } + parseBodyElements(element) { + var children = []; + for (const elem of globalXmlParser.elements(element)) { + switch (elem.localName) { + case "p": + children.push(this.parseParagraph(elem)); + break; + case "altChunk": + children.push(this.parseAltChunk(elem)); + break; + case "tbl": + children.push(this.parseTable(elem)); + break; + case "sdt": + children.push(...this.parseSdt(elem, (e9) => this.parseBodyElements(e9))); + break; + } + } + return children; + } + parseStylesFile(xstyles) { + var result = []; + for (const n7 of globalXmlParser.elements(xstyles)) { + switch (n7.localName) { + case "style": + result.push(this.parseStyle(n7)); + break; + case "docDefaults": + result.push(this.parseDefaultStyles(n7)); + break; + } + } + return result; + } + parseDefaultStyles(node) { + var result = { + id: null, + name: null, + target: null, + basedOn: null, + styles: [] + }; + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "rPrDefault": + var rPr = globalXmlParser.element(c6, "rPr"); + if (rPr) + result.styles.push({ + target: "span", + values: this.parseDefaultProperties(rPr, {}) + }); + break; + case "pPrDefault": + var pPr = globalXmlParser.element(c6, "pPr"); + if (pPr) + result.styles.push({ + target: "p", + values: this.parseDefaultProperties(pPr, {}) + }); + break; + } + } + return result; + } + parseStyle(node) { + var result = { + id: globalXmlParser.attr(node, "styleId"), + isDefault: globalXmlParser.boolAttr(node, "default"), + name: null, + target: null, + basedOn: null, + styles: [], + linked: null + }; + switch (globalXmlParser.attr(node, "type")) { + case "paragraph": + result.target = "p"; + break; + case "table": + result.target = "table"; + break; + case "character": + result.target = "span"; + break; + } + for (const n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "basedOn": + result.basedOn = globalXmlParser.attr(n7, "val"); + break; + case "name": + result.name = globalXmlParser.attr(n7, "val"); + break; + case "link": + result.linked = globalXmlParser.attr(n7, "val"); + break; + case "next": + result.next = globalXmlParser.attr(n7, "val"); + break; + case "aliases": + result.aliases = globalXmlParser.attr(n7, "val").split(","); + break; + case "pPr": + result.styles.push({ + target: "p", + values: this.parseDefaultProperties(n7, {}) + }); + result.paragraphProps = parseParagraphProperties(n7, globalXmlParser); + break; + case "rPr": + result.styles.push({ + target: "span", + values: this.parseDefaultProperties(n7, {}) + }); + result.runProps = parseRunProperties(n7, globalXmlParser); + break; + case "tblPr": + case "tcPr": + result.styles.push({ + target: "td", + values: this.parseDefaultProperties(n7, {}) + }); + break; + case "tblStylePr": + for (let s6 of this.parseTableStyle(n7)) + result.styles.push(s6); + break; + case "rsid": + case "qFormat": + case "hidden": + case "semiHidden": + case "unhideWhenUsed": + case "autoRedefine": + case "uiPriority": + break; + default: + this.options.debug && console.warn(`DOCX: Unknown style element: ${n7.localName}`); + } + } + return result; + } + parseTableStyle(node) { + var result = []; + var type = globalXmlParser.attr(node, "type"); + var selector = ""; + var modificator = ""; + switch (type) { + case "firstRow": + modificator = ".first-row"; + selector = "tr.first-row td"; + break; + case "lastRow": + modificator = ".last-row"; + selector = "tr.last-row td"; + break; + case "firstCol": + modificator = ".first-col"; + selector = "td.first-col"; + break; + case "lastCol": + modificator = ".last-col"; + selector = "td.last-col"; + break; + case "band1Vert": + modificator = ":not(.no-vband)"; + selector = "td.odd-col"; + break; + case "band2Vert": + modificator = ":not(.no-vband)"; + selector = "td.even-col"; + break; + case "band1Horz": + modificator = ":not(.no-hband)"; + selector = "tr.odd-row"; + break; + case "band2Horz": + modificator = ":not(.no-hband)"; + selector = "tr.even-row"; + break; + default: + return []; + } + for (const n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "pPr": + result.push({ + target: `${selector} p`, + mod: modificator, + values: this.parseDefaultProperties(n7, {}) + }); + break; + case "rPr": + result.push({ + target: `${selector} span`, + mod: modificator, + values: this.parseDefaultProperties(n7, {}) + }); + break; + case "tblPr": + case "tcPr": + result.push({ + target: selector, + mod: modificator, + values: this.parseDefaultProperties(n7, {}) + }); + break; + } + } + return result; + } + parseNumberingFile(node) { + var result = []; + var mapping = {}; + var bullets = []; + for (const n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "abstractNum": + this.parseAbstractNumbering(n7, bullets).forEach((x2) => result.push(x2)); + break; + case "numPicBullet": + bullets.push(this.parseNumberingPicBullet(n7)); + break; + case "num": + var numId = globalXmlParser.attr(n7, "numId"); + var abstractNumId = globalXmlParser.elementAttr(n7, "abstractNumId", "val"); + mapping[abstractNumId] = numId; + break; + } + } + result.forEach((x2) => x2.id = mapping[x2.id]); + return result; + } + parseNumberingPicBullet(elem) { + var pict = globalXmlParser.element(elem, "pict"); + var shape = pict && globalXmlParser.element(pict, "shape"); + var imagedata = shape && globalXmlParser.element(shape, "imagedata"); + return imagedata ? { + id: globalXmlParser.intAttr(elem, "numPicBulletId"), + src: globalXmlParser.attr(imagedata, "id"), + style: globalXmlParser.attr(shape, "style") + } : null; + } + parseAbstractNumbering(node, bullets) { + var result = []; + var id = globalXmlParser.attr(node, "abstractNumId"); + for (const n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "lvl": + result.push(this.parseNumberingLevel(id, n7, bullets)); + break; + } + } + return result; + } + parseNumberingLevel(id, node, bullets) { + var result = { + id, + level: globalXmlParser.intAttr(node, "ilvl"), + start: 1, + pStyleName: void 0, + pStyle: {}, + rStyle: {}, + suff: "tab" + }; + for (const n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "start": + result.start = globalXmlParser.intAttr(n7, "val"); + break; + case "pPr": + this.parseDefaultProperties(n7, result.pStyle); + break; + case "rPr": + this.parseDefaultProperties(n7, result.rStyle); + break; + case "lvlPicBulletId": + var bulletId = globalXmlParser.intAttr(n7, "val"); + result.bullet = bullets.find((x2) => x2?.id == bulletId); + break; + case "lvlText": + result.levelText = globalXmlParser.attr(n7, "val"); + break; + case "pStyle": + result.pStyleName = globalXmlParser.attr(n7, "val"); + break; + case "numFmt": + result.format = globalXmlParser.attr(n7, "val"); + break; + case "suff": + result.suff = globalXmlParser.attr(n7, "val"); + break; + } + } + return result; + } + parseSdt(node, parser) { + const sdtContent = globalXmlParser.element(node, "sdtContent"); + return sdtContent ? parser(sdtContent) : []; + } + parseInserted(node, parentParser) { + return { + type: DomType.Inserted, + children: parentParser(node)?.children ?? [] + }; + } + parseDeleted(node, parentParser) { + return { + type: DomType.Deleted, + children: parentParser(node)?.children ?? [] + }; + } + parseAltChunk(node) { + return { type: DomType.AltChunk, children: [], id: globalXmlParser.attr(node, "id") }; + } + parseParagraph(node) { + var result = { type: DomType.Paragraph, children: [] }; + for (let el of globalXmlParser.elements(node)) { + switch (el.localName) { + case "pPr": + this.parseParagraphProperties(el, result); + break; + case "r": + result.children.push(this.parseRun(el, result)); + break; + case "hyperlink": + result.children.push(this.parseHyperlink(el, result)); + break; + case "smartTag": + result.children.push(this.parseSmartTag(el, result)); + break; + case "bookmarkStart": + result.children.push(parseBookmarkStart(el, globalXmlParser)); + break; + case "bookmarkEnd": + result.children.push(parseBookmarkEnd(el, globalXmlParser)); + break; + case "commentRangeStart": + result.children.push(new WmlCommentRangeStart(globalXmlParser.attr(el, "id"))); + break; + case "commentRangeEnd": + result.children.push(new WmlCommentRangeEnd(globalXmlParser.attr(el, "id"))); + break; + case "oMath": + case "oMathPara": + result.children.push(this.parseMathElement(el)); + break; + case "sdt": + result.children.push(...this.parseSdt(el, (e9) => this.parseParagraph(e9).children)); + break; + case "ins": + result.children.push(this.parseInserted(el, (e9) => this.parseParagraph(e9))); + break; + case "del": + result.children.push(this.parseDeleted(el, (e9) => this.parseParagraph(e9))); + break; + } + } + return result; + } + parseParagraphProperties(elem, paragraph) { + this.parseDefaultProperties(elem, paragraph.cssStyle = {}, null, (c6) => { + if (parseParagraphProperty(c6, paragraph, globalXmlParser)) + return true; + switch (c6.localName) { + case "pStyle": + paragraph.styleName = globalXmlParser.attr(c6, "val"); + break; + case "cnfStyle": + paragraph.className = values.classNameOfCnfStyle(c6); + break; + case "framePr": + this.parseFrame(c6, paragraph); + break; + case "rPr": + break; + default: + return false; + } + return true; + }); + } + parseFrame(node, paragraph) { + var dropCap = globalXmlParser.attr(node, "dropCap"); + if (dropCap == "drop") + paragraph.cssStyle["float"] = "left"; + } + parseHyperlink(node, parent) { + var result = { type: DomType.Hyperlink, parent, children: [] }; + result.anchor = globalXmlParser.attr(node, "anchor"); + result.id = globalXmlParser.attr(node, "id"); + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "r": + result.children.push(this.parseRun(c6, result)); + break; + } + } + return result; + } + parseSmartTag(node, parent) { + var result = { type: DomType.SmartTag, parent, children: [] }; + var uri = globalXmlParser.attr(node, "uri"); + var element = globalXmlParser.attr(node, "element"); + if (uri) + result.uri = uri; + if (element) + result.element = element; + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "r": + result.children.push(this.parseRun(c6, result)); + break; + } + } + return result; + } + parseRun(node, parent) { + var result = { type: DomType.Run, parent, children: [] }; + for (let c6 of globalXmlParser.elements(node)) { + c6 = this.checkAlternateContent(c6); + switch (c6.localName) { + case "t": + result.children.push({ + type: DomType.Text, + text: c6.textContent + }); + break; + case "delText": + result.children.push({ + type: DomType.DeletedText, + text: c6.textContent + }); + break; + case "commentReference": + result.children.push(new WmlCommentReference(globalXmlParser.attr(c6, "id"))); + break; + case "fldSimple": + result.children.push({ + type: DomType.SimpleField, + instruction: globalXmlParser.attr(c6, "instr"), + lock: globalXmlParser.boolAttr(c6, "lock", false), + dirty: globalXmlParser.boolAttr(c6, "dirty", false) + }); + break; + case "instrText": + result.fieldRun = true; + result.children.push({ + type: DomType.Instruction, + text: c6.textContent + }); + break; + case "fldChar": + result.fieldRun = true; + result.children.push({ + type: DomType.ComplexField, + charType: globalXmlParser.attr(c6, "fldCharType"), + lock: globalXmlParser.boolAttr(c6, "lock", false), + dirty: globalXmlParser.boolAttr(c6, "dirty", false) + }); + break; + case "noBreakHyphen": + result.children.push({ type: DomType.NoBreakHyphen }); + break; + case "br": + result.children.push({ + type: DomType.Break, + break: globalXmlParser.attr(c6, "type") || "textWrapping" + }); + break; + case "lastRenderedPageBreak": + result.children.push({ + type: DomType.Break, + break: "lastRenderedPageBreak" + }); + break; + case "sym": + result.children.push({ + type: DomType.Symbol, + font: encloseFontFamily(globalXmlParser.attr(c6, "font")), + char: globalXmlParser.attr(c6, "char") + }); + break; + case "tab": + result.children.push({ type: DomType.Tab }); + break; + case "footnoteReference": + result.children.push({ + type: DomType.FootnoteReference, + id: globalXmlParser.attr(c6, "id") + }); + break; + case "endnoteReference": + result.children.push({ + type: DomType.EndnoteReference, + id: globalXmlParser.attr(c6, "id") + }); + break; + case "drawing": + let d4 = this.parseDrawing(c6); + if (d4) + result.children = [d4]; + break; + case "pict": + result.children.push(this.parseVmlPicture(c6)); + break; + case "rPr": + this.parseRunProperties(c6, result); + break; + } + } + return result; + } + parseMathElement(elem) { + const propsTag = `${elem.localName}Pr`; + const result = { type: mmlTagMap[elem.localName], children: [] }; + for (const el of globalXmlParser.elements(elem)) { + const childType = mmlTagMap[el.localName]; + if (childType) { + result.children.push(this.parseMathElement(el)); + } else if (el.localName == "r") { + var run = this.parseRun(el); + run.type = DomType.MmlRun; + result.children.push(run); + } else if (el.localName == propsTag) { + result.props = this.parseMathProperies(el); + } + } + return result; + } + parseMathProperies(elem) { + const result = {}; + for (const el of globalXmlParser.elements(elem)) { + switch (el.localName) { + case "chr": + result.char = globalXmlParser.attr(el, "val"); + break; + case "vertJc": + result.verticalJustification = globalXmlParser.attr(el, "val"); + break; + case "pos": + result.position = globalXmlParser.attr(el, "val"); + break; + case "degHide": + result.hideDegree = globalXmlParser.boolAttr(el, "val"); + break; + case "begChr": + result.beginChar = globalXmlParser.attr(el, "val"); + break; + case "endChr": + result.endChar = globalXmlParser.attr(el, "val"); + break; + } + } + return result; + } + parseRunProperties(elem, run) { + this.parseDefaultProperties(elem, run.cssStyle = {}, null, (c6) => { + switch (c6.localName) { + case "rStyle": + run.styleName = globalXmlParser.attr(c6, "val"); + break; + case "vertAlign": + run.verticalAlign = values.valueOfVertAlign(c6, true); + break; + default: + return false; + } + return true; + }); + } + parseVmlPicture(elem) { + const result = { type: DomType.VmlPicture, children: [] }; + for (const el of globalXmlParser.elements(elem)) { + const child = parseVmlElement(el, this); + child && result.children.push(child); + } + return result; + } + checkAlternateContent(elem) { + if (elem.localName != "AlternateContent") + return elem; + var choice = globalXmlParser.element(elem, "Choice"); + if (choice) { + var requires = globalXmlParser.attr(choice, "Requires"); + var namespaceURI = elem.lookupNamespaceURI(requires); + if (supportedNamespaceURIs.includes(namespaceURI)) + return choice.firstElementChild; + } + return globalXmlParser.element(elem, "Fallback")?.firstElementChild; + } + parseDrawing(node) { + for (var n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "inline": + case "anchor": + return this.parseDrawingWrapper(n7); + } + } + } + parseDrawingWrapper(node) { + var result = { type: DomType.Drawing, children: [], cssStyle: {} }; + var isAnchor = node.localName == "anchor"; + let wrapType = null; + let simplePos = globalXmlParser.boolAttr(node, "simplePos"); + globalXmlParser.boolAttr(node, "behindDoc"); + let posX = { relative: "page", align: "left", offset: "0" }; + let posY = { relative: "page", align: "top", offset: "0" }; + for (var n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "simplePos": + if (simplePos) { + posX.offset = globalXmlParser.lengthAttr(n7, "x", LengthUsage.Emu); + posY.offset = globalXmlParser.lengthAttr(n7, "y", LengthUsage.Emu); + } + break; + case "extent": + result.cssStyle["width"] = globalXmlParser.lengthAttr(n7, "cx", LengthUsage.Emu); + result.cssStyle["height"] = globalXmlParser.lengthAttr(n7, "cy", LengthUsage.Emu); + break; + case "positionH": + case "positionV": + if (!simplePos) { + let pos = n7.localName == "positionH" ? posX : posY; + var alignNode = globalXmlParser.element(n7, "align"); + var offsetNode = globalXmlParser.element(n7, "posOffset"); + pos.relative = globalXmlParser.attr(n7, "relativeFrom") ?? pos.relative; + if (alignNode) + pos.align = alignNode.textContent; + if (offsetNode) + pos.offset = convertLength(offsetNode.textContent, LengthUsage.Emu); + } + break; + case "wrapTopAndBottom": + wrapType = "wrapTopAndBottom"; + break; + case "wrapNone": + wrapType = "wrapNone"; + break; + case "graphic": + var g3 = this.parseGraphic(n7); + if (g3) + result.children.push(g3); + break; + } + } + if (wrapType == "wrapTopAndBottom") { + result.cssStyle["display"] = "block"; + if (posX.align) { + result.cssStyle["text-align"] = posX.align; + result.cssStyle["width"] = "100%"; + } + } else if (wrapType == "wrapNone") { + result.cssStyle["display"] = "block"; + result.cssStyle["position"] = "relative"; + result.cssStyle["width"] = "0px"; + result.cssStyle["height"] = "0px"; + if (posX.offset) + result.cssStyle["left"] = posX.offset; + if (posY.offset) + result.cssStyle["top"] = posY.offset; + } else if (isAnchor && (posX.align == "left" || posX.align == "right")) { + result.cssStyle["float"] = posX.align; + } + return result; + } + parseGraphic(elem) { + var graphicData = globalXmlParser.element(elem, "graphicData"); + for (let n7 of globalXmlParser.elements(graphicData)) { + switch (n7.localName) { + case "pic": + return this.parsePicture(n7); + } + } + return null; + } + parsePicture(elem) { + var result = { type: DomType.Image, src: "", cssStyle: {} }; + var blipFill = globalXmlParser.element(elem, "blipFill"); + var blip = globalXmlParser.element(blipFill, "blip"); + var srcRect = globalXmlParser.element(blipFill, "srcRect"); + result.src = globalXmlParser.attr(blip, "embed"); + if (srcRect) { + result.srcRect = [ + globalXmlParser.intAttr(srcRect, "l", 0) / 1e5, + globalXmlParser.intAttr(srcRect, "t", 0) / 1e5, + globalXmlParser.intAttr(srcRect, "r", 0) / 1e5, + globalXmlParser.intAttr(srcRect, "b", 0) / 1e5 + ]; + } + var spPr = globalXmlParser.element(elem, "spPr"); + var xfrm = globalXmlParser.element(spPr, "xfrm"); + result.cssStyle["position"] = "relative"; + if (xfrm) { + result.rotation = globalXmlParser.intAttr(xfrm, "rot", 0) / 6e4; + for (var n7 of globalXmlParser.elements(xfrm)) { + switch (n7.localName) { + case "ext": + result.cssStyle["width"] = globalXmlParser.lengthAttr(n7, "cx", LengthUsage.Emu); + result.cssStyle["height"] = globalXmlParser.lengthAttr(n7, "cy", LengthUsage.Emu); + break; + case "off": + result.cssStyle["left"] = globalXmlParser.lengthAttr(n7, "x", LengthUsage.Emu); + result.cssStyle["top"] = globalXmlParser.lengthAttr(n7, "y", LengthUsage.Emu); + break; + } + } + } + return result; + } + parseTable(node) { + var result = { type: DomType.Table, children: [] }; + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "tr": + result.children.push(this.parseTableRow(c6)); + break; + case "tblGrid": + result.columns = this.parseTableColumns(c6); + break; + case "tblPr": + this.parseTableProperties(c6, result); + break; + } + } + return result; + } + parseTableColumns(node) { + var result = []; + for (const n7 of globalXmlParser.elements(node)) { + switch (n7.localName) { + case "gridCol": + result.push({ width: globalXmlParser.lengthAttr(n7, "w") }); + break; + } + } + return result; + } + parseTableProperties(elem, table) { + table.cssStyle = {}; + table.cellStyle = {}; + this.parseDefaultProperties(elem, table.cssStyle, table.cellStyle, (c6) => { + switch (c6.localName) { + case "tblStyle": + table.styleName = globalXmlParser.attr(c6, "val"); + break; + case "tblLook": + table.className = values.classNameOftblLook(c6); + break; + case "tblpPr": + this.parseTablePosition(c6, table); + break; + case "tblStyleColBandSize": + table.colBandSize = globalXmlParser.intAttr(c6, "val"); + break; + case "tblStyleRowBandSize": + table.rowBandSize = globalXmlParser.intAttr(c6, "val"); + break; + case "hidden": + table.cssStyle["display"] = "none"; + break; + default: + return false; + } + return true; + }); + switch (table.cssStyle["text-align"]) { + case "center": + delete table.cssStyle["text-align"]; + table.cssStyle["margin-left"] = "auto"; + table.cssStyle["margin-right"] = "auto"; + break; + case "right": + delete table.cssStyle["text-align"]; + table.cssStyle["margin-left"] = "auto"; + break; + } + } + parseTablePosition(node, table) { + var topFromText = globalXmlParser.lengthAttr(node, "topFromText"); + var bottomFromText = globalXmlParser.lengthAttr(node, "bottomFromText"); + var rightFromText = globalXmlParser.lengthAttr(node, "rightFromText"); + var leftFromText = globalXmlParser.lengthAttr(node, "leftFromText"); + table.cssStyle["float"] = "left"; + table.cssStyle["margin-bottom"] = values.addSize(table.cssStyle["margin-bottom"], bottomFromText); + table.cssStyle["margin-left"] = values.addSize(table.cssStyle["margin-left"], leftFromText); + table.cssStyle["margin-right"] = values.addSize(table.cssStyle["margin-right"], rightFromText); + table.cssStyle["margin-top"] = values.addSize(table.cssStyle["margin-top"], topFromText); + } + parseTableRow(node) { + var result = { type: DomType.Row, children: [] }; + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "tc": + result.children.push(this.parseTableCell(c6)); + break; + case "trPr": + case "tblPrEx": + this.parseTableRowProperties(c6, result); + break; + } + } + return result; + } + parseTableRowProperties(elem, row) { + row.cssStyle = this.parseDefaultProperties(elem, {}, null, (c6) => { + switch (c6.localName) { + case "cnfStyle": + row.className = values.classNameOfCnfStyle(c6); + break; + case "tblHeader": + row.isHeader = globalXmlParser.boolAttr(c6, "val"); + break; + case "gridBefore": + row.gridBefore = globalXmlParser.intAttr(c6, "val"); + break; + case "gridAfter": + row.gridAfter = globalXmlParser.intAttr(c6, "val"); + break; + default: + return false; + } + return true; + }); + } + parseTableCell(node) { + var result = { type: DomType.Cell, children: [] }; + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "tbl": + result.children.push(this.parseTable(c6)); + break; + case "p": + result.children.push(this.parseParagraph(c6)); + break; + case "tcPr": + this.parseTableCellProperties(c6, result); + break; + } + } + return result; + } + parseTableCellProperties(elem, cell) { + cell.cssStyle = this.parseDefaultProperties(elem, {}, null, (c6) => { + switch (c6.localName) { + case "gridSpan": + cell.span = globalXmlParser.intAttr(c6, "val", null); + break; + case "vMerge": + cell.verticalMerge = globalXmlParser.attr(c6, "val") ?? "continue"; + break; + case "cnfStyle": + cell.className = values.classNameOfCnfStyle(c6); + break; + default: + return false; + } + return true; + }); + this.parseTableCellVerticalText(elem, cell); + } + parseTableCellVerticalText(elem, cell) { + const directionMap = { + "btLr": { + writingMode: "vertical-rl", + transform: "rotate(180deg)" + }, + "lrTb": { + writingMode: "vertical-lr", + transform: "none" + }, + "tbRl": { + writingMode: "vertical-rl", + transform: "none" + } + }; + for (const c6 of globalXmlParser.elements(elem)) { + if (c6.localName === "textDirection") { + const direction = globalXmlParser.attr(c6, "val"); + const style = directionMap[direction] || { writingMode: "horizontal-tb" }; + cell.cssStyle["writing-mode"] = style.writingMode; + cell.cssStyle["transform"] = style.transform; + } + } + } + parseDefaultProperties(elem, style = null, childStyle = null, handler = null) { + style = style || {}; + for (const c6 of globalXmlParser.elements(elem)) { + if (handler?.(c6)) + continue; + switch (c6.localName) { + case "jc": + style["text-align"] = values.valueOfJc(c6); + break; + case "textAlignment": + style["vertical-align"] = values.valueOfTextAlignment(c6); + break; + case "color": + style["color"] = xmlUtil.colorAttr(c6, "val", null, autos.color); + break; + case "sz": + style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c6, "val", LengthUsage.FontSize); + break; + case "shd": + style["background-color"] = xmlUtil.colorAttr(c6, "fill", null, autos.shd); + break; + case "highlight": + style["background-color"] = xmlUtil.colorAttr(c6, "val", null, autos.highlight); + break; + case "vertAlign": + break; + case "position": + style.verticalAlign = globalXmlParser.lengthAttr(c6, "val", LengthUsage.FontSize); + break; + case "tcW": + if (this.options.ignoreWidth) + break; + case "tblW": + style["width"] = values.valueOfSize(c6, "w"); + break; + case "trHeight": + this.parseTrHeight(c6, style); + break; + case "strike": + style["text-decoration"] = globalXmlParser.boolAttr(c6, "val", true) ? "line-through" : "none"; + break; + case "b": + style["font-weight"] = globalXmlParser.boolAttr(c6, "val", true) ? "bold" : "normal"; + break; + case "i": + style["font-style"] = globalXmlParser.boolAttr(c6, "val", true) ? "italic" : "normal"; + break; + case "caps": + style["text-transform"] = globalXmlParser.boolAttr(c6, "val", true) ? "uppercase" : "none"; + break; + case "smallCaps": + style["font-variant"] = globalXmlParser.boolAttr(c6, "val", true) ? "small-caps" : "none"; + break; + case "u": + this.parseUnderline(c6, style); + break; + case "ind": + case "tblInd": + this.parseIndentation(c6, style); + break; + case "rFonts": + this.parseFont(c6, style); + break; + case "tblBorders": + this.parseBorderProperties(c6, childStyle || style); + break; + case "tblCellSpacing": + style["border-spacing"] = values.valueOfMargin(c6); + style["border-collapse"] = "separate"; + break; + case "pBdr": + this.parseBorderProperties(c6, style); + break; + case "bdr": + style["border"] = values.valueOfBorder(c6); + break; + case "tcBorders": + this.parseBorderProperties(c6, style); + break; + case "vanish": + if (globalXmlParser.boolAttr(c6, "val", true)) + style["display"] = "none"; + break; + case "kern": + break; + case "noWrap": + break; + case "tblCellMar": + case "tcMar": + this.parseMarginProperties(c6, childStyle || style); + break; + case "tblLayout": + style["table-layout"] = values.valueOfTblLayout(c6); + break; + case "vAlign": + style["vertical-align"] = values.valueOfTextAlignment(c6); + break; + case "spacing": + if (elem.localName == "pPr") + this.parseSpacing(c6, style); + break; + case "wordWrap": + if (globalXmlParser.boolAttr(c6, "val")) + style["overflow-wrap"] = "break-word"; + break; + case "suppressAutoHyphens": + style["hyphens"] = globalXmlParser.boolAttr(c6, "val", true) ? "none" : "auto"; + break; + case "lang": + style["$lang"] = globalXmlParser.attr(c6, "val"); + break; + case "rtl": + case "bidi": + if (globalXmlParser.boolAttr(c6, "val", true)) + style["direction"] = "rtl"; + break; + case "bCs": + case "iCs": + case "szCs": + case "tabs": + case "outlineLvl": + case "contextualSpacing": + case "tblStyleColBandSize": + case "tblStyleRowBandSize": + case "webHidden": + case "pageBreakBefore": + case "suppressLineNumbers": + case "keepLines": + case "keepNext": + case "widowControl": + case "bidi": + case "rtl": + case "noProof": + break; + default: + if (this.options.debug) + console.warn(`DOCX: Unknown document element: ${elem.localName}.${c6.localName}`); + break; + } + } + return style; + } + parseUnderline(node, style) { + var val2 = globalXmlParser.attr(node, "val"); + if (val2 == null) + return; + switch (val2) { + case "dash": + case "dashDotDotHeavy": + case "dashDotHeavy": + case "dashedHeavy": + case "dashLong": + case "dashLongHeavy": + case "dotDash": + case "dotDotDash": + style["text-decoration"] = "underline dashed"; + break; + case "dotted": + case "dottedHeavy": + style["text-decoration"] = "underline dotted"; + break; + case "double": + style["text-decoration"] = "underline double"; + break; + case "single": + case "thick": + style["text-decoration"] = "underline"; + break; + case "wave": + case "wavyDouble": + case "wavyHeavy": + style["text-decoration"] = "underline wavy"; + break; + case "words": + style["text-decoration"] = "underline"; + break; + case "none": + style["text-decoration"] = "none"; + break; + } + var col = xmlUtil.colorAttr(node, "color"); + if (col) + style["text-decoration-color"] = col; + } + parseFont(node, style) { + var ascii = globalXmlParser.attr(node, "ascii"); + var asciiTheme = values.themeValue(node, "asciiTheme"); + var eastAsia = globalXmlParser.attr(node, "eastAsia"); + var fonts = [ascii, asciiTheme, eastAsia].filter((x2) => x2).map((x2) => encloseFontFamily(x2)); + if (fonts.length > 0) + style["font-family"] = [...new Set(fonts)].join(", "); + } + parseIndentation(node, style) { + var firstLine = globalXmlParser.lengthAttr(node, "firstLine"); + var hanging = globalXmlParser.lengthAttr(node, "hanging"); + var left = globalXmlParser.lengthAttr(node, "left"); + var start = globalXmlParser.lengthAttr(node, "start"); + var right = globalXmlParser.lengthAttr(node, "right"); + var end = globalXmlParser.lengthAttr(node, "end"); + if (firstLine) + style["text-indent"] = firstLine; + if (hanging) + style["text-indent"] = `-${hanging}`; + if (left || start) + style["margin-inline-start"] = left || start; + if (right || end) + style["margin-inline-end"] = right || end; + } + parseSpacing(node, style) { + var before = globalXmlParser.lengthAttr(node, "before"); + var after = globalXmlParser.lengthAttr(node, "after"); + var line = globalXmlParser.intAttr(node, "line", null); + var lineRule = globalXmlParser.attr(node, "lineRule"); + if (before) + style["margin-top"] = before; + if (after) + style["margin-bottom"] = after; + if (line !== null) { + switch (lineRule) { + case "auto": + style["line-height"] = `${(line / 240).toFixed(2)}`; + break; + case "atLeast": + style["line-height"] = `calc(100% + ${line / 20}pt)`; + break; + default: + style["line-height"] = style["min-height"] = `${line / 20}pt`; + break; + } + } + } + parseMarginProperties(node, output) { + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "left": + output["padding-left"] = values.valueOfMargin(c6); + break; + case "right": + output["padding-right"] = values.valueOfMargin(c6); + break; + case "top": + output["padding-top"] = values.valueOfMargin(c6); + break; + case "bottom": + output["padding-bottom"] = values.valueOfMargin(c6); + break; + } + } + } + parseTrHeight(node, output) { + switch (globalXmlParser.attr(node, "hRule")) { + case "exact": + output["height"] = globalXmlParser.lengthAttr(node, "val"); + break; + case "atLeast": + default: + output["height"] = globalXmlParser.lengthAttr(node, "val"); + break; + } + } + parseBorderProperties(node, output) { + for (const c6 of globalXmlParser.elements(node)) { + switch (c6.localName) { + case "start": + case "left": + output["border-left"] = values.valueOfBorder(c6); + break; + case "end": + case "right": + output["border-right"] = values.valueOfBorder(c6); + break; + case "top": + output["border-top"] = values.valueOfBorder(c6); + break; + case "bottom": + output["border-bottom"] = values.valueOfBorder(c6); + break; + } + } + } + }; + knownColors = ["black", "blue", "cyan", "darkBlue", "darkCyan", "darkGray", "darkGreen", "darkMagenta", "darkRed", "darkYellow", "green", "lightGray", "magenta", "none", "red", "white", "yellow"]; + xmlUtil = class { + static colorAttr(node, attrName, defValue = null, autoColor = "black") { + var v4 = globalXmlParser.attr(node, attrName); + if (v4) { + if (v4 == "auto") { + return autoColor; + } else if (knownColors.includes(v4)) { + return v4; + } + return `#${v4}`; + } + var themeColor = globalXmlParser.attr(node, "themeColor"); + return themeColor ? `var(--docx-${themeColor}-color)` : defValue; + } + }; + values = class _values { + static themeValue(c6, attr) { + var val2 = globalXmlParser.attr(c6, attr); + return val2 ? `var(--docx-${val2}-font)` : null; + } + static valueOfSize(c6, attr) { + var type = LengthUsage.Dxa; + switch (globalXmlParser.attr(c6, "type")) { + case "dxa": + break; + case "pct": + type = LengthUsage.Percent; + break; + case "auto": + return "auto"; + } + return globalXmlParser.lengthAttr(c6, attr, type); + } + static valueOfMargin(c6) { + return globalXmlParser.lengthAttr(c6, "w"); + } + static valueOfBorder(c6) { + var type = _values.parseBorderType(globalXmlParser.attr(c6, "val")); + if (type == "none") + return "none"; + var color2 = xmlUtil.colorAttr(c6, "color"); + var size = globalXmlParser.lengthAttr(c6, "sz", LengthUsage.Border); + return `${size} ${type} ${color2 == "auto" ? autos.borderColor : color2}`; + } + static parseBorderType(type) { + switch (type) { + case "single": + return "solid"; + case "dashDotStroked": + return "solid"; + case "dashed": + return "dashed"; + case "dashSmallGap": + return "dashed"; + case "dotDash": + return "dotted"; + case "dotDotDash": + return "dotted"; + case "dotted": + return "dotted"; + case "double": + return "double"; + case "doubleWave": + return "double"; + case "inset": + return "inset"; + case "nil": + return "none"; + case "none": + return "none"; + case "outset": + return "outset"; + case "thick": + return "solid"; + case "thickThinLargeGap": + return "solid"; + case "thickThinMediumGap": + return "solid"; + case "thickThinSmallGap": + return "solid"; + case "thinThickLargeGap": + return "solid"; + case "thinThickMediumGap": + return "solid"; + case "thinThickSmallGap": + return "solid"; + case "thinThickThinLargeGap": + return "solid"; + case "thinThickThinMediumGap": + return "solid"; + case "thinThickThinSmallGap": + return "solid"; + case "threeDEmboss": + return "solid"; + case "threeDEngrave": + return "solid"; + case "triple": + return "double"; + case "wave": + return "solid"; + } + return "solid"; + } + static valueOfTblLayout(c6) { + var type = globalXmlParser.attr(c6, "val"); + return type == "fixed" ? "fixed" : "auto"; + } + static classNameOfCnfStyle(c6) { + const val2 = globalXmlParser.attr(c6, "val"); + const classes = [ + "first-row", + "last-row", + "first-col", + "last-col", + "odd-col", + "even-col", + "odd-row", + "even-row", + "ne-cell", + "nw-cell", + "se-cell", + "sw-cell" + ]; + return classes.filter((_3, i7) => val2[i7] == "1").join(" "); + } + static valueOfJc(c6) { + var type = globalXmlParser.attr(c6, "val"); + switch (type) { + case "start": + case "left": + return "left"; + case "center": + return "center"; + case "end": + case "right": + return "right"; + case "both": + return "justify"; + } + return type; + } + static valueOfVertAlign(c6, asTagName = false) { + var type = globalXmlParser.attr(c6, "val"); + switch (type) { + case "subscript": + return "sub"; + case "superscript": + return asTagName ? "sup" : "super"; + } + return asTagName ? null : type; + } + static valueOfTextAlignment(c6) { + var type = globalXmlParser.attr(c6, "val"); + switch (type) { + case "auto": + case "baseline": + return "baseline"; + case "top": + return "top"; + case "center": + return "middle"; + case "bottom": + return "bottom"; + } + return type; + } + static addSize(a3, b4) { + if (a3 == null) + return b4; + if (b4 == null) + return a3; + return `calc(${a3} + ${b4})`; + } + static classNameOftblLook(c6) { + const val2 = globalXmlParser.hexAttr(c6, "val", 0); + let className = ""; + if (globalXmlParser.boolAttr(c6, "firstRow") || val2 & 32) + className += " first-row"; + if (globalXmlParser.boolAttr(c6, "lastRow") || val2 & 64) + className += " last-row"; + if (globalXmlParser.boolAttr(c6, "firstColumn") || val2 & 128) + className += " first-col"; + if (globalXmlParser.boolAttr(c6, "lastColumn") || val2 & 256) + className += " last-col"; + if (globalXmlParser.boolAttr(c6, "noHBand") || val2 & 512) + className += " no-hband"; + if (globalXmlParser.boolAttr(c6, "noVBand") || val2 & 1024) + className += " no-vband"; + return className.trim(); + } + }; + defaultTab = { pos: 0, leader: "none", style: "left" }; + maxTabs = 50; + ns = { + svg: "http://www.w3.org/2000/svg", + mathML: "http://www.w3.org/1998/Math/MathML" + }; + HtmlRenderer = class { + constructor(htmlDocument) { + this.htmlDocument = htmlDocument; + this.className = "docx"; + this.styleMap = {}; + this.currentPart = null; + this.tableVerticalMerges = []; + this.currentVerticalMerge = null; + this.tableCellPositions = []; + this.currentCellPosition = null; + this.footnoteMap = {}; + this.endnoteMap = {}; + this.currentEndnoteIds = []; + this.usedHederFooterParts = []; + this.currentTabs = []; + this.commentMap = {}; + this.tasks = []; + this.postRenderTasks = []; + } + async render(document2, bodyContainer, styleContainer = null, options) { + this.document = document2; + this.options = options; + this.className = options.className; + this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ":root"; + this.styleMap = null; + this.tasks = []; + if (this.options.renderComments && globalThis.Highlight) { + this.commentHighlight = new Highlight(); + } + styleContainer = styleContainer || bodyContainer; + removeAllElements(styleContainer); + removeAllElements(bodyContainer); + styleContainer.appendChild(this.createComment("docxjs library predefined styles")); + styleContainer.appendChild(this.renderDefaultStyle()); + if (document2.themePart) { + styleContainer.appendChild(this.createComment("docxjs document theme values")); + this.renderTheme(document2.themePart, styleContainer); + } + if (document2.stylesPart != null) { + this.styleMap = this.processStyles(document2.stylesPart.styles); + styleContainer.appendChild(this.createComment("docxjs document styles")); + styleContainer.appendChild(this.renderStyles(document2.stylesPart.styles)); + } + if (document2.numberingPart) { + this.prodessNumberings(document2.numberingPart.domNumberings); + styleContainer.appendChild(this.createComment("docxjs document numbering styles")); + styleContainer.appendChild(this.renderNumbering(document2.numberingPart.domNumberings, styleContainer)); + } + if (document2.footnotesPart) { + this.footnoteMap = keyBy(document2.footnotesPart.notes, (x2) => x2.id); + } + if (document2.endnotesPart) { + this.endnoteMap = keyBy(document2.endnotesPart.notes, (x2) => x2.id); + } + if (document2.settingsPart) { + this.defaultTabSize = document2.settingsPart.settings?.defaultTabStop; + } + if (!options.ignoreFonts && document2.fontTablePart) + this.renderFontTable(document2.fontTablePart, styleContainer); + var sectionElements = this.renderSections(document2.documentPart.body); + if (this.options.inWrapper) { + bodyContainer.appendChild(this.renderWrapper(sectionElements)); + } else { + appendChildren(bodyContainer, sectionElements); + } + if (this.commentHighlight && options.renderComments) { + CSS.highlights.set(`${this.className}-comments`, this.commentHighlight); + } + this.postRenderTasks.forEach((t6) => t6()); + await Promise.allSettled(this.tasks); + this.refreshTabStops(); + } + renderTheme(themePart, styleContainer) { + const variables = {}; + const fontScheme = themePart.theme?.fontScheme; + if (fontScheme) { + if (fontScheme.majorFont) { + variables["--docx-majorHAnsi-font"] = fontScheme.majorFont.latinTypeface; + } + if (fontScheme.minorFont) { + variables["--docx-minorHAnsi-font"] = fontScheme.minorFont.latinTypeface; + } + } + const colorScheme = themePart.theme?.colorScheme; + if (colorScheme) { + for (let [k2, v4] of Object.entries(colorScheme.colors)) { + variables[`--docx-${k2}-color`] = `#${v4}`; + } + } + const cssText = this.styleToString(`.${this.className}`, variables); + styleContainer.appendChild(this.createStyleElement(cssText)); + } + renderFontTable(fontsPart, styleContainer) { + for (let f4 of fontsPart.fonts) { + for (let ref of f4.embedFontRefs) { + this.tasks.push(this.document.loadFont(ref.id, ref.key).then((fontData) => { + const cssValues = { + "font-family": encloseFontFamily(f4.name), + "src": `url(${fontData})` + }; + if (ref.type == "bold" || ref.type == "boldItalic") { + cssValues["font-weight"] = "bold"; + } + if (ref.type == "italic" || ref.type == "boldItalic") { + cssValues["font-style"] = "italic"; + } + const cssText = this.styleToString("@font-face", cssValues); + styleContainer.appendChild(this.createComment(`docxjs ${f4.name} font`)); + styleContainer.appendChild(this.createStyleElement(cssText)); + })); + } + } + } + processStyleName(className) { + return className ? `${this.className}_${escapeClassName(className)}` : this.className; + } + processStyles(styles2) { + const stylesMap = keyBy(styles2.filter((x2) => x2.id != null), (x2) => x2.id); + for (const style of styles2.filter((x2) => x2.basedOn)) { + var baseStyle = stylesMap[style.basedOn]; + if (baseStyle) { + style.paragraphProps = mergeDeep(style.paragraphProps, baseStyle.paragraphProps); + style.runProps = mergeDeep(style.runProps, baseStyle.runProps); + for (const baseValues of baseStyle.styles) { + const styleValues = style.styles.find((x2) => x2.target == baseValues.target); + if (styleValues) { + this.copyStyleProperties(baseValues.values, styleValues.values); + } else { + style.styles.push({ ...baseValues, values: { ...baseValues.values } }); + } + } + } else if (this.options.debug) + console.warn(`Can't find base style ${style.basedOn}`); + } + for (let style of styles2) { + style.cssName = this.processStyleName(style.id); + } + return stylesMap; + } + prodessNumberings(numberings) { + for (let num of numberings.filter((n7) => n7.pStyleName)) { + const style = this.findStyle(num.pStyleName); + if (style?.paragraphProps?.numbering) { + style.paragraphProps.numbering.level = num.level; + } + } + } + processElement(element) { + if (element.children) { + for (var e9 of element.children) { + e9.parent = element; + if (e9.type == DomType.Table) { + this.processTable(e9); + } else { + this.processElement(e9); + } + } + } + } + processTable(table) { + for (var r8 of table.children) { + for (var c6 of r8.children) { + c6.cssStyle = this.copyStyleProperties(table.cellStyle, c6.cssStyle, [ + "border-left", + "border-right", + "border-top", + "border-bottom", + "padding-left", + "padding-right", + "padding-top", + "padding-bottom" + ]); + this.processElement(c6); + } + } + } + copyStyleProperties(input, output, attrs = null) { + if (!input) + return output; + if (output == null) + output = {}; + if (attrs == null) + attrs = Object.getOwnPropertyNames(input); + for (var key of attrs) { + if (input.hasOwnProperty(key) && !output.hasOwnProperty(key)) + output[key] = input[key]; + } + return output; + } + createPageElement(className, props) { + var elem = this.createElement("section", { className }); + if (props) { + if (props.pageMargins) { + elem.style.paddingLeft = props.pageMargins.left; + elem.style.paddingRight = props.pageMargins.right; + elem.style.paddingTop = props.pageMargins.top; + elem.style.paddingBottom = props.pageMargins.bottom; + } + if (props.pageSize) { + if (!this.options.ignoreWidth) + elem.style.width = props.pageSize.width; + if (!this.options.ignoreHeight) + elem.style.minHeight = props.pageSize.height; + } + } + return elem; + } + createSectionContent(props) { + var elem = this.createElement("article"); + if (props.columns && props.columns.numberOfColumns) { + elem.style.columnCount = `${props.columns.numberOfColumns}`; + elem.style.columnGap = props.columns.space; + if (props.columns.separator) { + elem.style.columnRule = "1px solid black"; + } + } + return elem; + } + renderSections(document2) { + const result = []; + this.processElement(document2); + const sections = this.splitBySection(document2.children, document2.props); + const pages = this.groupByPageBreaks(sections); + let prevProps = null; + for (let i7 = 0, l5 = pages.length; i7 < l5; i7++) { + this.currentFootnoteIds = []; + const section = pages[i7][0]; + let props = section.sectProps; + const pageElement = this.createPageElement(this.className, props); + this.renderStyleValues(document2.cssStyle, pageElement); + this.options.renderHeaders && this.renderHeaderFooter(props.headerRefs, props, result.length, prevProps != props, pageElement); + for (const sect of pages[i7]) { + var contentElement = this.createSectionContent(sect.sectProps); + this.renderElements(sect.elements, contentElement); + pageElement.appendChild(contentElement); + props = sect.sectProps; + } + if (this.options.renderFootnotes) { + this.renderNotes(this.currentFootnoteIds, this.footnoteMap, pageElement); + } + if (this.options.renderEndnotes && i7 == l5 - 1) { + this.renderNotes(this.currentEndnoteIds, this.endnoteMap, pageElement); + } + this.options.renderFooters && this.renderHeaderFooter(props.footerRefs, props, result.length, prevProps != props, pageElement); + result.push(pageElement); + prevProps = props; + } + return result; + } + renderHeaderFooter(refs, props, page, firstOfSection, into) { + if (!refs) + return; + var ref = (props.titlePage && firstOfSection ? refs.find((x2) => x2.type == "first") : null) ?? (page % 2 == 1 ? refs.find((x2) => x2.type == "even") : null) ?? refs.find((x2) => x2.type == "default"); + var part = ref && this.document.findPartByRelId(ref.id, this.document.documentPart); + if (part) { + this.currentPart = part; + if (!this.usedHederFooterParts.includes(part.path)) { + this.processElement(part.rootElement); + this.usedHederFooterParts.push(part.path); + } + const [el] = this.renderElements([part.rootElement], into); + if (props?.pageMargins) { + if (part.rootElement.type === DomType.Header) { + el.style.marginTop = `calc(${props.pageMargins.header} - ${props.pageMargins.top})`; + el.style.minHeight = `calc(${props.pageMargins.top} - ${props.pageMargins.header})`; + } else if (part.rootElement.type === DomType.Footer) { + el.style.marginBottom = `calc(${props.pageMargins.footer} - ${props.pageMargins.bottom})`; + el.style.minHeight = `calc(${props.pageMargins.bottom} - ${props.pageMargins.footer})`; + } + } + this.currentPart = null; + } + } + isPageBreakElement(elem) { + if (elem.type != DomType.Break) + return false; + if (elem.break == "lastRenderedPageBreak") + return !this.options.ignoreLastRenderedPageBreak; + return elem.break == "page"; + } + isPageBreakSection(prev, next) { + if (!prev) + return false; + if (!next) + return false; + return prev.pageSize?.orientation != next.pageSize?.orientation || prev.pageSize?.width != next.pageSize?.width || prev.pageSize?.height != next.pageSize?.height; + } + splitBySection(elements2, defaultProps) { + var current2 = { sectProps: null, elements: [], pageBreak: false }; + var result = [current2]; + for (let elem of elements2) { + if (elem.type == DomType.Paragraph) { + const s6 = this.findStyle(elem.styleName); + if (s6?.paragraphProps?.pageBreakBefore) { + current2.sectProps = sectProps; + current2.pageBreak = true; + current2 = { sectProps: null, elements: [], pageBreak: false }; + result.push(current2); + } + } + current2.elements.push(elem); + if (elem.type == DomType.Paragraph) { + const p4 = elem; + var sectProps = p4.sectionProps; + var pBreakIndex = -1; + var rBreakIndex = -1; + if (this.options.breakPages && p4.children) { + pBreakIndex = p4.children.findIndex((r8) => { + rBreakIndex = r8.children?.findIndex(this.isPageBreakElement.bind(this)) ?? -1; + return rBreakIndex != -1; + }); + } + if (sectProps || pBreakIndex != -1) { + current2.sectProps = sectProps; + current2.pageBreak = pBreakIndex != -1; + current2 = { sectProps: null, elements: [], pageBreak: false }; + result.push(current2); + } + if (pBreakIndex != -1) { + let breakRun = p4.children[pBreakIndex]; + let splitRun = rBreakIndex < breakRun.children.length - 1; + if (pBreakIndex < p4.children.length - 1 || splitRun) { + var children = elem.children; + var newParagraph = { ...elem, children: children.slice(pBreakIndex) }; + elem.children = children.slice(0, pBreakIndex); + current2.elements.push(newParagraph); + if (splitRun) { + let runChildren = breakRun.children; + let newRun = { ...breakRun, children: runChildren.slice(0, rBreakIndex) }; + elem.children.push(newRun); + breakRun.children = runChildren.slice(rBreakIndex); + } + } + } + } + } + let currentSectProps = null; + for (let i7 = result.length - 1; i7 >= 0; i7--) { + if (result[i7].sectProps == null) { + result[i7].sectProps = currentSectProps ?? defaultProps; + } else { + currentSectProps = result[i7].sectProps; + } + } + return result; + } + groupByPageBreaks(sections) { + let current2 = []; + let prev; + const result = [current2]; + for (let s6 of sections) { + current2.push(s6); + if (this.options.ignoreLastRenderedPageBreak || s6.pageBreak || this.isPageBreakSection(prev, s6.sectProps)) + result.push(current2 = []); + prev = s6.sectProps; + } + return result.filter((x2) => x2.length > 0); + } + renderWrapper(children) { + return this.createElement("div", { className: `${this.className}-wrapper` }, children); + } + renderDefaultStyle() { + var c6 = this.className; + var wrapperStyle = ` +.${c6}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } +.${c6}-wrapper>section.${c6} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`; + if (this.options.hideWrapperOnPrint) { + wrapperStyle = `@media not print { ${wrapperStyle} }`; + } + var styleText = `${wrapperStyle} +.${c6} { color: black; hyphens: auto; text-underline-position: from-font; } +section.${c6} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; } +section.${c6}>article { margin-bottom: auto; z-index: 1; } +section.${c6}>footer { z-index: 1; } +.${c6} table { border-collapse: collapse; } +.${c6} table td, .${c6} table th { vertical-align: top; } +.${c6} p { margin: 0pt; min-height: 1em; } +.${c6} span { white-space: pre-wrap; overflow-wrap: break-word; } +.${c6} a { color: inherit; text-decoration: inherit; } +.${c6} svg { fill: transparent; } +`; + if (this.options.renderComments) { + styleText += ` +.${c6}-comment-ref { cursor: default; } +.${c6}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; } +.${c6}-comment-ref:hover~.${c6}-comment-popover { display: block; } +.${c6}-comment-author,.${c6}-comment-date { font-size: 0.875rem; color: #888; } +`; + } + return this.createStyleElement(styleText); + } + renderNumbering(numberings, styleContainer) { + var styleText = ""; + var resetCounters = []; + for (var num of numberings) { + var selector = `p.${this.numberingClass(num.id, num.level)}`; + var listStyleType = "none"; + if (num.bullet) { + let valiable = `--${this.className}-${num.bullet.src}`.toLowerCase(); + styleText += this.styleToString(`${selector}:before`, { + "content": "' '", + "display": "inline-block", + "background": `var(${valiable})` + }, num.bullet.style); + this.tasks.push(this.document.loadNumberingImage(num.bullet.src).then((data) => { + var text3 = `${this.rootSelector} { ${valiable}: url(${data}) }`; + styleContainer.appendChild(this.createStyleElement(text3)); + })); + } else if (num.levelText) { + let counter = this.numberingCounter(num.id, num.level); + const counterReset = counter + " " + (num.start - 1); + if (num.level > 0) { + styleText += this.styleToString(`p.${this.numberingClass(num.id, num.level - 1)}`, { + "counter-set": counterReset + }); + } + resetCounters.push(counterReset); + styleText += this.styleToString(`${selector}:before`, { + "content": this.levelTextToContent(num.levelText, num.suff, num.id, this.numFormatToCssValue(num.format)), + "counter-increment": counter, + ...num.rStyle + }); + } else { + listStyleType = this.numFormatToCssValue(num.format); + } + styleText += this.styleToString(selector, { + "display": "list-item", + "list-style-position": "inside", + "list-style-type": listStyleType, + ...num.pStyle + }); + } + if (resetCounters.length > 0) { + styleText += this.styleToString(this.rootSelector, { + "counter-reset": resetCounters.join(" ") + }); + } + return this.createStyleElement(styleText); + } + renderStyles(styles2) { + var styleText = ""; + const stylesMap = this.styleMap; + const defautStyles = keyBy(styles2.filter((s6) => s6.isDefault), (s6) => s6.target); + for (const style of styles2) { + var subStyles = style.styles; + if (style.linked) { + var linkedStyle = style.linked && stylesMap[style.linked]; + if (linkedStyle) + subStyles = subStyles.concat(linkedStyle.styles); + else if (this.options.debug) + console.warn(`Can't find linked style ${style.linked}`); + } + for (const subStyle of subStyles) { + var selector = `${style.target ?? ""}.${style.cssName}`; + if (style.target != subStyle.target) + selector += ` ${subStyle.target}`; + if (defautStyles[style.target] == style) + selector = `.${this.className} ${style.target}, ` + selector; + styleText += this.styleToString(selector, subStyle.values); + } + } + return this.createStyleElement(styleText); + } + renderNotes(noteIds, notesMap, into) { + var notes = noteIds.map((id) => notesMap[id]).filter((x2) => x2); + if (notes.length > 0) { + var result = this.createElement("ol", null, this.renderElements(notes)); + into.appendChild(result); + } + } + renderElement(elem) { + switch (elem.type) { + case DomType.Paragraph: + return this.renderParagraph(elem); + case DomType.BookmarkStart: + return this.renderBookmarkStart(elem); + case DomType.BookmarkEnd: + return null; + case DomType.Run: + return this.renderRun(elem); + case DomType.Table: + return this.renderTable(elem); + case DomType.Row: + return this.renderTableRow(elem); + case DomType.Cell: + return this.renderTableCell(elem); + case DomType.Hyperlink: + return this.renderHyperlink(elem); + case DomType.SmartTag: + return this.renderSmartTag(elem); + case DomType.Drawing: + return this.renderDrawing(elem); + case DomType.Image: + return this.renderImage(elem); + case DomType.Text: + return this.renderText(elem); + case DomType.Text: + return this.renderText(elem); + case DomType.DeletedText: + return this.renderDeletedText(elem); + case DomType.Tab: + return this.renderTab(elem); + case DomType.Symbol: + return this.renderSymbol(elem); + case DomType.Break: + return this.renderBreak(elem); + case DomType.Footer: + return this.renderContainer(elem, "footer"); + case DomType.Header: + return this.renderContainer(elem, "header"); + case DomType.Footnote: + case DomType.Endnote: + return this.renderContainer(elem, "li"); + case DomType.FootnoteReference: + return this.renderFootnoteReference(elem); + case DomType.EndnoteReference: + return this.renderEndnoteReference(elem); + case DomType.NoBreakHyphen: + return this.createElement("wbr"); + case DomType.VmlPicture: + return this.renderVmlPicture(elem); + case DomType.VmlElement: + return this.renderVmlElement(elem); + case DomType.MmlMath: + return this.renderContainerNS(elem, ns.mathML, "math", { xmlns: ns.mathML }); + case DomType.MmlMathParagraph: + return this.renderContainer(elem, "span"); + case DomType.MmlFraction: + return this.renderContainerNS(elem, ns.mathML, "mfrac"); + case DomType.MmlBase: + return this.renderContainerNS(elem, ns.mathML, elem.parent.type == DomType.MmlMatrixRow ? "mtd" : "mrow"); + case DomType.MmlNumerator: + case DomType.MmlDenominator: + case DomType.MmlFunction: + case DomType.MmlLimit: + case DomType.MmlBox: + return this.renderContainerNS(elem, ns.mathML, "mrow"); + case DomType.MmlGroupChar: + return this.renderMmlGroupChar(elem); + case DomType.MmlLimitLower: + return this.renderContainerNS(elem, ns.mathML, "munder"); + case DomType.MmlMatrix: + return this.renderContainerNS(elem, ns.mathML, "mtable"); + case DomType.MmlMatrixRow: + return this.renderContainerNS(elem, ns.mathML, "mtr"); + case DomType.MmlRadical: + return this.renderMmlRadical(elem); + case DomType.MmlSuperscript: + return this.renderContainerNS(elem, ns.mathML, "msup"); + case DomType.MmlSubscript: + return this.renderContainerNS(elem, ns.mathML, "msub"); + case DomType.MmlDegree: + case DomType.MmlSuperArgument: + case DomType.MmlSubArgument: + return this.renderContainerNS(elem, ns.mathML, "mn"); + case DomType.MmlFunctionName: + return this.renderContainerNS(elem, ns.mathML, "ms"); + case DomType.MmlDelimiter: + return this.renderMmlDelimiter(elem); + case DomType.MmlRun: + return this.renderMmlRun(elem); + case DomType.MmlNary: + return this.renderMmlNary(elem); + case DomType.MmlPreSubSuper: + return this.renderMmlPreSubSuper(elem); + case DomType.MmlBar: + return this.renderMmlBar(elem); + case DomType.MmlEquationArray: + return this.renderMllList(elem); + case DomType.Inserted: + return this.renderInserted(elem); + case DomType.Deleted: + return this.renderDeleted(elem); + case DomType.CommentRangeStart: + return this.renderCommentRangeStart(elem); + case DomType.CommentRangeEnd: + return this.renderCommentRangeEnd(elem); + case DomType.CommentReference: + return this.renderCommentReference(elem); + case DomType.AltChunk: + return this.renderAltChunk(elem); + } + return null; + } + renderElements(elems, into) { + if (elems == null) + return null; + var result = elems.flatMap((e9) => this.renderElement(e9)).filter((e9) => e9 != null); + if (into) + appendChildren(into, result); + return result; + } + renderContainer(elem, tagName, props) { + return this.createElement(tagName, props, this.renderElements(elem.children)); + } + renderContainerNS(elem, ns2, tagName, props) { + return this.createElementNS(ns2, tagName, props, this.renderElements(elem.children)); + } + renderParagraph(elem) { + var result = this.renderContainer(elem, "p"); + const style = this.findStyle(elem.styleName); + elem.tabs ?? (elem.tabs = style?.paragraphProps?.tabs); + this.renderClass(elem, result); + this.renderStyleValues(elem.cssStyle, result); + this.renderCommonProperties(result.style, elem); + const numbering = elem.numbering ?? style?.paragraphProps?.numbering; + if (numbering) { + result.classList.add(this.numberingClass(numbering.id, numbering.level)); + } + return result; + } + renderRunProperties(style, props) { + this.renderCommonProperties(style, props); + } + renderCommonProperties(style, props) { + if (props == null) + return; + if (props.color) { + style["color"] = props.color; + } + if (props.fontSize) { + style["font-size"] = props.fontSize; + } + } + renderHyperlink(elem) { + var result = this.renderContainer(elem, "a"); + this.renderStyleValues(elem.cssStyle, result); + let href = ""; + if (elem.id) { + const rel2 = this.document.documentPart.rels.find((it) => it.id == elem.id && it.targetMode === "External"); + href = rel2?.target ?? href; + } + if (elem.anchor) { + href += `#${elem.anchor}`; + } + result.href = href; + return result; + } + renderSmartTag(elem) { + return this.renderContainer(elem, "span"); + } + renderCommentRangeStart(commentStart) { + if (!this.options.renderComments) + return null; + const rng = new Range(); + this.commentHighlight?.add(rng); + const result = this.createComment(`start of comment #${commentStart.id}`); + this.later(() => rng.setStart(result, 0)); + this.commentMap[commentStart.id] = rng; + return result; + } + renderCommentRangeEnd(commentEnd) { + if (!this.options.renderComments) + return null; + const rng = this.commentMap[commentEnd.id]; + const result = this.createComment(`end of comment #${commentEnd.id}`); + this.later(() => rng?.setEnd(result, 0)); + return result; + } + renderCommentReference(commentRef) { + if (!this.options.renderComments) + return null; + var comment = this.document.commentsPart?.commentMap[commentRef.id]; + if (!comment) + return null; + const frg = new DocumentFragment(); + const commentRefEl = this.createElement("span", { className: `${this.className}-comment-ref` }, ["\u{1F4AC}"]); + const commentsContainerEl = this.createElement("div", { className: `${this.className}-comment-popover` }); + this.renderCommentContent(comment, commentsContainerEl); + frg.appendChild(this.createComment(`comment #${comment.id} by ${comment.author} on ${comment.date}`)); + frg.appendChild(commentRefEl); + frg.appendChild(commentsContainerEl); + return frg; + } + renderAltChunk(elem) { + if (!this.options.renderAltChunks) + return null; + var result = this.createElement("iframe"); + this.tasks.push(this.document.loadAltChunk(elem.id, this.currentPart).then((x2) => { + result.srcdoc = x2; + })); + return result; + } + renderCommentContent(comment, container) { + container.appendChild(this.createElement("div", { className: `${this.className}-comment-author` }, [comment.author])); + container.appendChild(this.createElement("div", { className: `${this.className}-comment-date` }, [new Date(comment.date).toLocaleString()])); + this.renderElements(comment.children, container); + } + renderDrawing(elem) { + var result = this.renderContainer(elem, "div"); + result.style.display = "inline-block"; + result.style.position = "relative"; + result.style.textIndent = "0px"; + this.renderStyleValues(elem.cssStyle, result); + return result; + } + renderImage(elem) { + let result = this.createElement("img"); + let transform = elem.cssStyle?.transform; + this.renderStyleValues(elem.cssStyle, result); + if (elem.srcRect && elem.srcRect.some((x2) => x2 != 0)) { + var [left, top, right, bottom] = elem.srcRect; + transform = `scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`; + result.style["clip-path"] = `rect(${(100 * top).toFixed(2)}% ${(100 * (1 - right)).toFixed(2)}% ${(100 * (1 - bottom)).toFixed(2)}% ${(100 * left).toFixed(2)}%)`; + } + if (elem.rotation) + transform = `rotate(${elem.rotation}deg) ${transform ?? ""}`; + result.style.transform = transform?.trim(); + if (this.document) { + this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart).then((x2) => { + result.src = x2; + })); + } + return result; + } + renderText(elem) { + return this.htmlDocument.createTextNode(elem.text); + } + renderDeletedText(elem) { + return this.options.renderChanges ? this.renderText(elem) : null; + } + renderBreak(elem) { + if (elem.break == "textWrapping") { + return this.createElement("br"); + } + return null; + } + renderInserted(elem) { + if (this.options.renderChanges) + return this.renderContainer(elem, "ins"); + return this.renderElements(elem.children); + } + renderDeleted(elem) { + if (this.options.renderChanges) + return this.renderContainer(elem, "del"); + return null; + } + renderSymbol(elem) { + var span = this.createElement("span"); + span.style.fontFamily = elem.font; + span.innerHTML = `&#x${elem.char};`; + return span; + } + renderFootnoteReference(elem) { + var result = this.createElement("sup"); + this.currentFootnoteIds.push(elem.id); + result.textContent = `${this.currentFootnoteIds.length}`; + return result; + } + renderEndnoteReference(elem) { + var result = this.createElement("sup"); + this.currentEndnoteIds.push(elem.id); + result.textContent = `${this.currentEndnoteIds.length}`; + return result; + } + renderTab(elem) { + var tabSpan = this.createElement("span"); + tabSpan.innerHTML = " "; + if (this.options.experimental) { + tabSpan.className = this.tabStopClass(); + var stops = findParent(elem, DomType.Paragraph)?.tabs; + this.currentTabs.push({ stops, span: tabSpan }); + } + return tabSpan; + } + renderBookmarkStart(elem) { + return this.createElement("span", { id: elem.name }); + } + renderRun(elem) { + if (elem.fieldRun) + return null; + const result = this.createElement("span"); + if (elem.id) + result.id = elem.id; + this.renderClass(elem, result); + this.renderStyleValues(elem.cssStyle, result); + if (elem.verticalAlign) { + const wrapper = this.createElement(elem.verticalAlign); + this.renderElements(elem.children, wrapper); + result.appendChild(wrapper); + } else { + this.renderElements(elem.children, result); + } + return result; + } + renderTable(elem) { + let result = this.createElement("table"); + this.tableCellPositions.push(this.currentCellPosition); + this.tableVerticalMerges.push(this.currentVerticalMerge); + this.currentVerticalMerge = {}; + this.currentCellPosition = { col: 0, row: 0 }; + if (elem.columns) + result.appendChild(this.renderTableColumns(elem.columns)); + this.renderClass(elem, result); + this.renderElements(elem.children, result); + this.renderStyleValues(elem.cssStyle, result); + this.currentVerticalMerge = this.tableVerticalMerges.pop(); + this.currentCellPosition = this.tableCellPositions.pop(); + return result; + } + renderTableColumns(columns) { + let result = this.createElement("colgroup"); + for (let col of columns) { + let colElem = this.createElement("col"); + if (col.width) + colElem.style.width = col.width; + result.appendChild(colElem); + } + return result; + } + renderTableRow(elem) { + let result = this.createElement("tr"); + this.currentCellPosition.col = 0; + if (elem.gridBefore) + result.appendChild(this.renderTableCellPlaceholder(elem.gridBefore)); + this.renderClass(elem, result); + this.renderElements(elem.children, result); + this.renderStyleValues(elem.cssStyle, result); + if (elem.gridAfter) + result.appendChild(this.renderTableCellPlaceholder(elem.gridAfter)); + this.currentCellPosition.row++; + return result; + } + renderTableCellPlaceholder(colSpan) { + const result = this.createElement("td", { colSpan }); + result.style["border"] = "none"; + return result; + } + renderTableCell(elem) { + let result = this.renderContainer(elem, "td"); + const key = this.currentCellPosition.col; + if (elem.verticalMerge) { + if (elem.verticalMerge == "restart") { + this.currentVerticalMerge[key] = result; + result.rowSpan = 1; + } else if (this.currentVerticalMerge[key]) { + this.currentVerticalMerge[key].rowSpan += 1; + result.style.display = "none"; + } + } else { + this.currentVerticalMerge[key] = null; + } + this.renderClass(elem, result); + this.renderStyleValues(elem.cssStyle, result); + if (elem.span) + result.colSpan = elem.span; + this.currentCellPosition.col += result.colSpan; + return result; + } + renderVmlPicture(elem) { + return this.renderContainer(elem, "div"); + } + renderVmlElement(elem) { + var container = this.createSvgElement("svg"); + container.setAttribute("style", elem.cssStyleText); + const result = this.renderVmlChildElement(elem); + if (elem.imageHref?.id) { + this.tasks.push(this.document?.loadDocumentImage(elem.imageHref.id, this.currentPart).then((x2) => result.setAttribute("href", x2))); + } + container.appendChild(result); + requestAnimationFrame(() => { + const bb = container.firstElementChild.getBBox(); + container.setAttribute("width", `${Math.ceil(bb.x + bb.width)}`); + container.setAttribute("height", `${Math.ceil(bb.y + bb.height)}`); + }); + return container; + } + renderVmlChildElement(elem) { + const result = this.createSvgElement(elem.tagName); + Object.entries(elem.attrs).forEach(([k2, v4]) => result.setAttribute(k2, v4)); + for (let child of elem.children) { + if (child.type == DomType.VmlElement) { + result.appendChild(this.renderVmlChildElement(child)); + } else { + result.appendChild(...asArray(this.renderElement(child))); + } + } + return result; + } + renderMmlRadical(elem) { + const base = elem.children.find((el) => el.type == DomType.MmlBase); + if (elem.props?.hideDegree) { + return this.createElementNS(ns.mathML, "msqrt", null, this.renderElements([base])); + } + const degree = elem.children.find((el) => el.type == DomType.MmlDegree); + return this.createElementNS(ns.mathML, "mroot", null, this.renderElements([base, degree])); + } + renderMmlDelimiter(elem) { + const children = []; + children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.beginChar ?? "("])); + children.push(...this.renderElements(elem.children)); + children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.endChar ?? ")"])); + return this.createElementNS(ns.mathML, "mrow", null, children); + } + renderMmlNary(elem) { + const children = []; + const grouped = keyBy(elem.children, (x2) => x2.type); + const sup2 = grouped[DomType.MmlSuperArgument]; + const sub2 = grouped[DomType.MmlSubArgument]; + const supElem = sup2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup2))) : null; + const subElem = sub2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub2))) : null; + const charElem = this.createElementNS(ns.mathML, "mo", null, [elem.props?.char ?? "\u222B"]); + if (supElem || subElem) { + children.push(this.createElementNS(ns.mathML, "munderover", null, [charElem, subElem, supElem])); + } else if (supElem) { + children.push(this.createElementNS(ns.mathML, "mover", null, [charElem, supElem])); + } else if (subElem) { + children.push(this.createElementNS(ns.mathML, "munder", null, [charElem, subElem])); + } else { + children.push(charElem); + } + children.push(...this.renderElements(grouped[DomType.MmlBase].children)); + return this.createElementNS(ns.mathML, "mrow", null, children); + } + renderMmlPreSubSuper(elem) { + const children = []; + const grouped = keyBy(elem.children, (x2) => x2.type); + const sup2 = grouped[DomType.MmlSuperArgument]; + const sub2 = grouped[DomType.MmlSubArgument]; + const supElem = sup2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup2))) : null; + const subElem = sub2 ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub2))) : null; + const stubElem = this.createElementNS(ns.mathML, "mo", null); + children.push(this.createElementNS(ns.mathML, "msubsup", null, [stubElem, subElem, supElem])); + children.push(...this.renderElements(grouped[DomType.MmlBase].children)); + return this.createElementNS(ns.mathML, "mrow", null, children); + } + renderMmlGroupChar(elem) { + const tagName = elem.props.verticalJustification === "bot" ? "mover" : "munder"; + const result = this.renderContainerNS(elem, ns.mathML, tagName); + if (elem.props.char) { + result.appendChild(this.createElementNS(ns.mathML, "mo", null, [elem.props.char])); + } + return result; + } + renderMmlBar(elem) { + const result = this.renderContainerNS(elem, ns.mathML, "mrow"); + switch (elem.props.position) { + case "top": + result.style.textDecoration = "overline"; + break; + case "bottom": + result.style.textDecoration = "underline"; + break; + } + return result; + } + renderMmlRun(elem) { + const result = this.createElementNS(ns.mathML, "ms", null, this.renderElements(elem.children)); + this.renderClass(elem, result); + this.renderStyleValues(elem.cssStyle, result); + return result; + } + renderMllList(elem) { + const result = this.createElementNS(ns.mathML, "mtable"); + this.renderClass(elem, result); + this.renderStyleValues(elem.cssStyle, result); + for (let child of this.renderElements(elem.children)) { + result.appendChild(this.createElementNS(ns.mathML, "mtr", null, [ + this.createElementNS(ns.mathML, "mtd", null, [child]) + ])); + } + return result; + } + renderStyleValues(style, ouput) { + for (let k2 in style) { + if (k2.startsWith("$")) { + ouput.setAttribute(k2.slice(1), style[k2]); + } else { + ouput.style[k2] = style[k2]; + } + } + } + renderClass(input, ouput) { + if (input.className) + ouput.className = input.className; + if (input.styleName) + ouput.classList.add(this.processStyleName(input.styleName)); + } + findStyle(styleName) { + return styleName && this.styleMap?.[styleName]; + } + numberingClass(id, lvl) { + return `${this.className}-num-${id}-${lvl}`; + } + tabStopClass() { + return `${this.className}-tab-stop`; + } + styleToString(selectors, values2, cssText = null) { + let result = `${selectors} {\r +`; + for (const key in values2) { + if (key.startsWith("$")) + continue; + result += ` ${key}: ${values2[key]};\r +`; + } + if (cssText) + result += cssText; + return result + "}\r\n"; + } + numberingCounter(id, lvl) { + return `${this.className}-num-${id}-${lvl}`; + } + levelTextToContent(text3, suff, id, numformat) { + const suffMap = { + "tab": "\\9", + "space": "\\a0" + }; + var result = text3.replace(/%\d*/g, (s6) => { + let lvl = parseInt(s6.substring(1), 10) - 1; + return `"counter(${this.numberingCounter(id, lvl)}, ${numformat})"`; + }); + return `"${result}${suffMap[suff] ?? ""}"`; + } + numFormatToCssValue(format2) { + var mapping = { + none: "none", + bullet: "disc", + decimal: "decimal", + lowerLetter: "lower-alpha", + upperLetter: "upper-alpha", + lowerRoman: "lower-roman", + upperRoman: "upper-roman", + decimalZero: "decimal-leading-zero", + aiueo: "katakana", + aiueoFullWidth: "katakana", + chineseCounting: "simp-chinese-informal", + chineseCountingThousand: "simp-chinese-informal", + chineseLegalSimplified: "simp-chinese-formal", + chosung: "hangul-consonant", + ideographDigital: "cjk-ideographic", + ideographTraditional: "cjk-heavenly-stem", + ideographLegalTraditional: "trad-chinese-formal", + ideographZodiac: "cjk-earthly-branch", + iroha: "katakana-iroha", + irohaFullWidth: "katakana-iroha", + japaneseCounting: "japanese-informal", + japaneseDigitalTenThousand: "cjk-decimal", + japaneseLegal: "japanese-formal", + thaiNumbers: "thai", + koreanCounting: "korean-hangul-formal", + koreanDigital: "korean-hangul-formal", + koreanDigital2: "korean-hanja-informal", + hebrew1: "hebrew", + hebrew2: "hebrew", + hindiNumbers: "devanagari", + ganada: "hangul", + taiwaneseCounting: "cjk-ideographic", + taiwaneseCountingThousand: "cjk-ideographic", + taiwaneseDigital: "cjk-decimal" + }; + return mapping[format2] ?? format2; + } + refreshTabStops() { + if (!this.options.experimental) + return; + setTimeout(() => { + const pixelToPoint = computePixelToPoint(); + for (let tab of this.currentTabs) { + updateTabStop(tab.span, tab.stops, this.defaultTabSize, pixelToPoint); + } + }, 500); + } + createElementNS(ns2, tagName, props, children) { + var result = ns2 ? this.htmlDocument.createElementNS(ns2, tagName) : this.htmlDocument.createElement(tagName); + Object.assign(result, props); + children && appendChildren(result, children); + return result; + } + createElement(tagName, props, children) { + return this.createElementNS(void 0, tagName, props, children); + } + createSvgElement(tagName, props, children) { + return this.createElementNS(ns.svg, tagName, props, children); + } + createStyleElement(cssText) { + return this.createElement("style", { innerHTML: cssText }); + } + createComment(text3) { + return this.htmlDocument.createComment(text3); + } + later(func) { + this.postRenderTasks.push(func); + } + }; + defaultOptions2 = { + ignoreHeight: false, + ignoreWidth: false, + ignoreFonts: false, + breakPages: true, + debug: false, + experimental: false, + className: "docx", + inWrapper: true, + hideWrapperOnPrint: false, + trimXmlDeclaration: true, + ignoreLastRenderedPageBreak: true, + renderHeaders: true, + renderFooters: true, + renderFootnotes: true, + renderEndnotes: true, + useBase64URL: false, + renderChanges: false, + renderComments: false, + renderAltChunks: true + }; + } +}); + +// ../pi-mono/node_modules/pdfjs-dist/build/pdf.mjs +function setVerbosityLevel(level) { + if (Number.isInteger(level)) { + verbosity = level; + } +} +function getVerbosityLevel() { + return verbosity; +} +function info(msg) { + if (verbosity >= VerbosityLevel.INFOS) { + console.info(`Info: ${msg}`); + } +} +function warn(msg) { + if (verbosity >= VerbosityLevel.WARNINGS) { + console.warn(`Warning: ${msg}`); + } +} +function unreachable(msg) { + throw new Error(msg); +} +function assert(cond, msg) { + if (!cond) { + unreachable(msg); + } +} +function _isValidProtocol(url) { + switch (url?.protocol) { + case "http:": + case "https:": + case "ftp:": + case "mailto:": + case "tel:": + return true; + default: + return false; + } +} +function createValidAbsoluteUrl(url, baseUrl = null, options = null) { + if (!url) { + return null; + } + if (options && typeof url === "string") { + if (options.addDefaultProtocol && url.startsWith("www.")) { + const dots = url.match(/\./g); + if (dots?.length >= 2) { + url = `http://${url}`; + } + } + if (options.tryConvertEncoding) { + try { + url = stringToUTF8String(url); + } catch { + } + } + } + const absoluteUrl = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url); + return _isValidProtocol(absoluteUrl) ? absoluteUrl : null; +} +function updateUrlHash(url, hash, allowRel = false) { + const res = URL.parse(url); + if (res) { + res.hash = hash; + return res.href; + } + if (allowRel && createValidAbsoluteUrl(url, "http://example.com")) { + return url.split("#", 1)[0] + `${hash ? `#${hash}` : ""}`; + } + return ""; +} +function shadow(obj, prop, value, nonSerializable = false) { + Object.defineProperty(obj, prop, { + value, + enumerable: !nonSerializable, + configurable: true, + writable: false + }); + return value; +} +function bytesToString(bytes) { + if (typeof bytes !== "object" || bytes?.length === void 0) { + unreachable("Invalid argument for bytesToString"); + } + const length = bytes.length; + const MAX_ARGUMENT_COUNT = 8192; + if (length < MAX_ARGUMENT_COUNT) { + return String.fromCharCode.apply(null, bytes); + } + const strBuf = []; + for (let i7 = 0; i7 < length; i7 += MAX_ARGUMENT_COUNT) { + const chunkEnd = Math.min(i7 + MAX_ARGUMENT_COUNT, length); + const chunk = bytes.subarray(i7, chunkEnd); + strBuf.push(String.fromCharCode.apply(null, chunk)); + } + return strBuf.join(""); +} +function stringToBytes(str2) { + if (typeof str2 !== "string") { + unreachable("Invalid argument for stringToBytes"); + } + const length = str2.length; + const bytes = new Uint8Array(length); + for (let i7 = 0; i7 < length; ++i7) { + bytes[i7] = str2.charCodeAt(i7) & 255; + } + return bytes; +} +function string32(value) { + return String.fromCharCode(value >> 24 & 255, value >> 16 & 255, value >> 8 & 255, value & 255); +} +function isLittleEndian() { + const buffer8 = new Uint8Array(4); + buffer8[0] = 1; + const view32 = new Uint32Array(buffer8.buffer, 0, 1); + return view32[0] === 1; +} +function isEvalSupported() { + try { + new Function(""); + return true; + } catch { + return false; + } +} +function stringToUTF8String(str2) { + return decodeURIComponent(escape(str2)); +} +function normalizeUnicode(str2) { + if (!NormalizeRegex) { + NormalizeRegex = /([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu; + NormalizationMap = /* @__PURE__ */ new Map([["\uFB05", "\u017Ft"]]); + } + return str2.replaceAll(NormalizeRegex, (_3, p1, p22) => p1 ? p1.normalize("NFKC") : NormalizationMap.get(p22)); +} +function getUuid() { + if (typeof crypto.randomUUID === "function") { + return crypto.randomUUID(); + } + const buf = new Uint8Array(32); + crypto.getRandomValues(buf); + return bytesToString(buf); +} +function _isValidExplicitDest(validRef, validName, dest) { + if (!Array.isArray(dest) || dest.length < 2) { + return false; + } + const [page, zoom, ...args] = dest; + if (!validRef(page) && !Number.isInteger(page)) { + return false; + } + if (!validName(zoom)) { + return false; + } + const argsLen = args.length; + let allowNull = true; + switch (zoom.name) { + case "XYZ": + if (argsLen < 2 || argsLen > 3) { + return false; + } + break; + case "Fit": + case "FitB": + return argsLen === 0; + case "FitH": + case "FitBH": + case "FitV": + case "FitBV": + if (argsLen > 1) { + return false; + } + break; + case "FitR": + if (argsLen !== 4) { + return false; + } + allowNull = false; + break; + default: + return false; + } + for (const arg of args) { + if (typeof arg === "number" || allowNull && arg === null) { + continue; + } + return false; + } + return true; +} +function MathClamp(v4, min, max) { + return Math.min(Math.max(v4, min), max); +} +function toBase64Util(arr) { + if (Uint8Array.prototype.toBase64) { + return arr.toBase64(); + } + return btoa(bytesToString(arr)); +} +function fromBase64Util(str2) { + if (Uint8Array.fromBase64) { + return Uint8Array.fromBase64(str2); + } + return stringToBytes(atob(str2)); +} +async function fetchData(url, type = "text") { + if (isValidFetchUrl(url, document.baseURI)) { + const response = await fetch(url); + if (!response.ok) { + throw new Error(response.statusText); + } + switch (type) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "json": + return response.json(); + } + return response.text(); + } + return new Promise((resolve2, reject) => { + const request = new XMLHttpRequest(); + request.open("GET", url, true); + request.responseType = type; + request.onreadystatechange = () => { + if (request.readyState !== XMLHttpRequest.DONE) { + return; + } + if (request.status === 200 || request.status === 0) { + switch (type) { + case "arraybuffer": + case "blob": + case "json": + resolve2(request.response); + return; + } + resolve2(request.responseText); + return; + } + reject(new Error(request.statusText)); + }; + request.send(null); + }); +} +function isDataScheme(url) { + const ii = url.length; + let i7 = 0; + while (i7 < ii && url[i7].trim() === "") { + i7++; + } + return url.substring(i7, i7 + 5).toLowerCase() === "data:"; +} +function isPdfFile(filename) { + return typeof filename === "string" && /\.pdf$/i.test(filename); +} +function getFilenameFromUrl(url) { + [url] = url.split(/[#?]/, 1); + return url.substring(url.lastIndexOf("/") + 1); +} +function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { + if (typeof url !== "string") { + return defaultFilename; + } + if (isDataScheme(url)) { + warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); + return defaultFilename; + } + const getURL = (urlString) => { + try { + return new URL(urlString); + } catch { + try { + return new URL(decodeURIComponent(urlString)); + } catch { + try { + return new URL(urlString, "https://foo.bar"); + } catch { + try { + return new URL(decodeURIComponent(urlString), "https://foo.bar"); + } catch { + return null; + } + } + } + } + }; + const newURL = getURL(url); + if (!newURL) { + return defaultFilename; + } + const decode5 = (name) => { + try { + let decoded = decodeURIComponent(name); + if (decoded.includes("/")) { + decoded = decoded.split("/").at(-1); + if (decoded.test(/^\.pdf$/i)) { + return decoded; + } + return name; + } + return decoded; + } catch { + return name; + } + }; + const pdfRegex = /\.pdf$/i; + const filename = newURL.pathname.split("/").at(-1); + if (pdfRegex.test(filename)) { + return decode5(filename); + } + if (newURL.searchParams.size > 0) { + const values2 = Array.from(newURL.searchParams.values()).reverse(); + for (const value of values2) { + if (pdfRegex.test(value)) { + return decode5(value); + } + } + const keys2 = Array.from(newURL.searchParams.keys()).reverse(); + for (const key of keys2) { + if (pdfRegex.test(key)) { + return decode5(key); + } + } + } + if (newURL.hash) { + const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; + const hashFilename = reFilename.exec(newURL.hash); + if (hashFilename) { + return decode5(hashFilename[0]); + } + } + return defaultFilename; +} +function isValidFetchUrl(url, baseUrl) { + const res = baseUrl ? URL.parse(url, baseUrl) : URL.parse(url); + return res?.protocol === "http:" || res?.protocol === "https:"; +} +function noContextMenu(e9) { + e9.preventDefault(); +} +function stopEvent(e9) { + e9.preventDefault(); + e9.stopPropagation(); +} +function deprecated(details) { + console.log("Deprecated API usage: " + details); +} +function getXfaPageViewport(xfaPage, { + scale = 1, + rotation = 0 +}) { + const { + width, + height + } = xfaPage.attributes.style; + const viewBox = [0, 0, parseInt(width), parseInt(height)]; + return new PageViewport({ + viewBox, + userUnit: 1, + scale, + rotation + }); +} +function getRGB(color2) { + if (color2.startsWith("#")) { + const colorRGB = parseInt(color2.slice(1), 16); + return [(colorRGB & 16711680) >> 16, (colorRGB & 65280) >> 8, colorRGB & 255]; + } + if (color2.startsWith("rgb(")) { + return color2.slice(4, -1).split(",").map((x2) => parseInt(x2)); + } + if (color2.startsWith("rgba(")) { + return color2.slice(5, -1).split(",").map((x2) => parseInt(x2)).slice(0, 3); + } + warn(`Not a valid color format: "${color2}"`); + return [0, 0, 0]; +} +function getColorValues(colors2) { + const span = document.createElement("span"); + span.style.visibility = "hidden"; + span.style.colorScheme = "only light"; + document.body.append(span); + for (const name of colors2.keys()) { + span.style.color = name; + const computedColor = window.getComputedStyle(span).color; + colors2.set(name, getRGB(computedColor)); + } + span.remove(); +} +function getCurrentTransform(ctx) { + const { + a: a3, + b: b4, + c: c6, + d: d4, + e: e9, + f: f4 + } = ctx.getTransform(); + return [a3, b4, c6, d4, e9, f4]; +} +function getCurrentTransformInverse(ctx) { + const { + a: a3, + b: b4, + c: c6, + d: d4, + e: e9, + f: f4 + } = ctx.getTransform().invertSelf(); + return [a3, b4, c6, d4, e9, f4]; +} +function setLayerDimensions(div, viewport, mustFlip = false, mustRotate = true) { + if (viewport instanceof PageViewport) { + const { + pageWidth, + pageHeight + } = viewport.rawDims; + const { + style + } = div; + const useRound = util_FeatureTest.isCSSRoundSupported; + const w3 = `var(--total-scale-factor) * ${pageWidth}px`, h7 = `var(--total-scale-factor) * ${pageHeight}px`; + const widthStr = useRound ? `round(down, ${w3}, var(--scale-round-x))` : `calc(${w3})`, heightStr = useRound ? `round(down, ${h7}, var(--scale-round-y))` : `calc(${h7})`; + if (!mustFlip || viewport.rotation % 180 === 0) { + style.width = widthStr; + style.height = heightStr; + } else { + style.width = heightStr; + style.height = widthStr; + } + } + if (mustRotate) { + div.setAttribute("data-main-rotation", viewport.rotation); + } +} +function applyOpacity(r8, g3, b4, opacity) { + opacity = Math.min(Math.max(opacity ?? 1, 0), 1); + const white = 255 * (1 - opacity); + r8 = Math.round(r8 * opacity + white); + g3 = Math.round(g3 * opacity + white); + b4 = Math.round(b4 * opacity + white); + return [r8, g3, b4]; +} +function RGBToHSL(rgb, output) { + const r8 = rgb[0] / 255; + const g3 = rgb[1] / 255; + const b4 = rgb[2] / 255; + const max = Math.max(r8, g3, b4); + const min = Math.min(r8, g3, b4); + const l5 = (max + min) / 2; + if (max === min) { + output[0] = output[1] = 0; + } else { + const d4 = max - min; + output[1] = l5 < 0.5 ? d4 / (max + min) : d4 / (2 - max - min); + switch (max) { + case r8: + output[0] = ((g3 - b4) / d4 + (g3 < b4 ? 6 : 0)) * 60; + break; + case g3: + output[0] = ((b4 - r8) / d4 + 2) * 60; + break; + case b4: + output[0] = ((r8 - g3) / d4 + 4) * 60; + break; + } + } + output[2] = l5; +} +function HSLToRGB(hsl, output) { + const h7 = hsl[0]; + const s6 = hsl[1]; + const l5 = hsl[2]; + const c6 = (1 - Math.abs(2 * l5 - 1)) * s6; + const x2 = c6 * (1 - Math.abs(h7 / 60 % 2 - 1)); + const m4 = l5 - c6 / 2; + switch (Math.floor(h7 / 60)) { + case 0: + output[0] = c6 + m4; + output[1] = x2 + m4; + output[2] = m4; + break; + case 1: + output[0] = x2 + m4; + output[1] = c6 + m4; + output[2] = m4; + break; + case 2: + output[0] = m4; + output[1] = c6 + m4; + output[2] = x2 + m4; + break; + case 3: + output[0] = m4; + output[1] = x2 + m4; + output[2] = c6 + m4; + break; + case 4: + output[0] = x2 + m4; + output[1] = m4; + output[2] = c6 + m4; + break; + case 5: + case 6: + output[0] = c6 + m4; + output[1] = m4; + output[2] = x2 + m4; + break; + } +} +function computeLuminance(x2) { + return x2 <= 0.03928 ? x2 / 12.92 : ((x2 + 0.055) / 1.055) ** 2.4; +} +function contrastRatio(hsl1, hsl2, output) { + HSLToRGB(hsl1, output); + output.map(computeLuminance); + const lum1 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; + HSLToRGB(hsl2, output); + output.map(computeLuminance); + const lum2 = 0.2126 * output[0] + 0.7152 * output[1] + 0.0722 * output[2]; + return lum1 > lum2 ? (lum1 + 0.05) / (lum2 + 0.05) : (lum2 + 0.05) / (lum1 + 0.05); +} +function findContrastColor(baseColor, fixedColor) { + const key = baseColor[0] + baseColor[1] * 256 + baseColor[2] * 65536 + fixedColor[0] * 16777216 + fixedColor[1] * 4294967296 + fixedColor[2] * 1099511627776; + let cachedValue = contrastCache.get(key); + if (cachedValue) { + return cachedValue; + } + const array = new Float32Array(9); + const output = array.subarray(0, 3); + const baseHSL = array.subarray(3, 6); + RGBToHSL(baseColor, baseHSL); + const fixedHSL = array.subarray(6, 9); + RGBToHSL(fixedColor, fixedHSL); + const isFixedColorDark = fixedHSL[2] < 0.5; + const minContrast = isFixedColorDark ? 12 : 4.5; + baseHSL[2] = isFixedColorDark ? Math.sqrt(baseHSL[2]) : 1 - Math.sqrt(1 - baseHSL[2]); + if (contrastRatio(baseHSL, fixedHSL, output) < minContrast) { + let start, end; + if (isFixedColorDark) { + start = baseHSL[2]; + end = 1; + } else { + start = 0; + end = baseHSL[2]; + } + const PRECISION = 5e-3; + while (end - start > PRECISION) { + const mid = baseHSL[2] = (start + end) / 2; + if (isFixedColorDark === contrastRatio(baseHSL, fixedHSL, output) < minContrast) { + start = mid; + } else { + end = mid; + } + } + baseHSL[2] = isFixedColorDark ? end : start; + } + HSLToRGB(baseHSL, output); + cachedValue = Util.makeHexColor(Math.round(output[0] * 255), Math.round(output[1] * 255), Math.round(output[2] * 255)); + contrastCache.set(key, cachedValue); + return cachedValue; +} +function renderRichText({ + html, + dir, + className +}, container) { + const fragment2 = document.createDocumentFragment(); + if (typeof html === "string") { + const p4 = document.createElement("p"); + p4.dir = dir || "auto"; + const lines = html.split(/(?:\r\n?|\n)/); + for (let i7 = 0, ii = lines.length; i7 < ii; ++i7) { + const line = lines[i7]; + p4.append(document.createTextNode(line)); + if (i7 < ii - 1) { + p4.append(document.createElement("br")); + } + } + fragment2.append(p4); + } else { + XfaLayer.render({ + xfaHtml: html, + div: fragment2, + intent: "richText" + }); + } + fragment2.firstChild.classList.add("richText", className); + container.append(fragment2); +} +function makePathFromDrawOPS(data) { + const path6 = new Path2D(); + if (!data) { + return path6; + } + for (let i7 = 0, ii = data.length; i7 < ii; ) { + switch (data[i7++]) { + case DrawOPS.moveTo: + path6.moveTo(data[i7++], data[i7++]); + break; + case DrawOPS.lineTo: + path6.lineTo(data[i7++], data[i7++]); + break; + case DrawOPS.curveTo: + path6.bezierCurveTo(data[i7++], data[i7++], data[i7++], data[i7++], data[i7++], data[i7++]); + break; + case DrawOPS.quadraticCurveTo: + path6.quadraticCurveTo(data[i7++], data[i7++], data[i7++], data[i7++]); + break; + case DrawOPS.closePath: + path6.closePath(); + break; + default: + warn(`Unrecognized drawing path operator: ${data[i7 - 1]}`); + break; + } + } + return path6; +} +function bindEvents(obj, element, names2) { + for (const name of names2) { + element.addEventListener(name, obj[name].bind(obj)); + } +} +function getUrlProp(val2) { + if (val2 instanceof URL) { + return val2.href; + } + if (typeof val2 === "string") { + if (isNodeJS) { + return val2; + } + const url = URL.parse(val2, window.location); + if (url) { + return url.href; + } + } + throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property."); +} +function getDataProp(val2) { + if (isNodeJS && typeof Buffer !== "undefined" && val2 instanceof Buffer) { + throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`."); + } + if (val2 instanceof Uint8Array && val2.byteLength === val2.buffer.byteLength) { + return val2; + } + if (typeof val2 === "string") { + return stringToBytes(val2); + } + if (val2 instanceof ArrayBuffer || ArrayBuffer.isView(val2) || typeof val2 === "object" && !isNaN(val2?.length)) { + return new Uint8Array(val2); + } + throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property."); +} +function getFactoryUrlProp(val2) { + if (typeof val2 !== "string") { + return null; + } + if (val2.endsWith("/")) { + return val2; + } + throw new Error(`Invalid factory url: "${val2}" must include trailing slash.`); +} +function onFn() { +} +function wrapReason(ex) { + if (ex instanceof AbortException || ex instanceof InvalidPDFException || ex instanceof PasswordException || ex instanceof ResponseException || ex instanceof UnknownErrorException) { + return ex; + } + if (!(ex instanceof Error || typeof ex === "object" && ex !== null)) { + unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'); + } + switch (ex.name) { + case "AbortException": + return new AbortException(ex.message); + case "InvalidPDFException": + return new InvalidPDFException(ex.message); + case "PasswordException": + return new PasswordException(ex.message, ex.code); + case "ResponseException": + return new ResponseException(ex.message, ex.status, ex.missing); + case "UnknownErrorException": + return new UnknownErrorException(ex.message, ex.details); + } + return new UnknownErrorException(ex.message, ex.toString()); +} +async function node_utils_fetchData(url) { + const fs = process.getBuiltinModule("fs"); + const data = await fs.promises.readFile(url); + return new Uint8Array(data); +} +function expandBBox(array, index2, minX, minY, maxX, maxY) { + array[index2 * 4 + 0] = Math.min(array[index2 * 4 + 0], minX); + array[index2 * 4 + 1] = Math.min(array[index2 * 4 + 1], minY); + array[index2 * 4 + 2] = Math.max(array[index2 * 4 + 2], maxX); + array[index2 * 4 + 3] = Math.max(array[index2 * 4 + 3], maxY); +} +function applyBoundingBox(ctx, bbox) { + if (!bbox) { + return; + } + const width = bbox[2] - bbox[0]; + const height = bbox[3] - bbox[1]; + const region = new Path2D(); + region.rect(bbox[0], bbox[1], width, height); + ctx.clip(region); +} +function drawTriangle(data, context, p1, p22, p32, c1, c22, c32) { + const coords = context.coords, colors2 = context.colors; + const bytes = data.data, rowSize = data.width * 4; + let tmp; + if (coords[p1 + 1] > coords[p22 + 1]) { + tmp = p1; + p1 = p22; + p22 = tmp; + tmp = c1; + c1 = c22; + c22 = tmp; + } + if (coords[p22 + 1] > coords[p32 + 1]) { + tmp = p22; + p22 = p32; + p32 = tmp; + tmp = c22; + c22 = c32; + c32 = tmp; + } + if (coords[p1 + 1] > coords[p22 + 1]) { + tmp = p1; + p1 = p22; + p22 = tmp; + tmp = c1; + c1 = c22; + c22 = tmp; + } + const x1 = (coords[p1] + context.offsetX) * context.scaleX; + const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; + const x2 = (coords[p22] + context.offsetX) * context.scaleX; + const y22 = (coords[p22 + 1] + context.offsetY) * context.scaleY; + const x3 = (coords[p32] + context.offsetX) * context.scaleX; + const y32 = (coords[p32 + 1] + context.offsetY) * context.scaleY; + if (y1 >= y32) { + return; + } + const c1r = colors2[c1], c1g = colors2[c1 + 1], c1b = colors2[c1 + 2]; + const c2r = colors2[c22], c2g = colors2[c22 + 1], c2b = colors2[c22 + 2]; + const c3r = colors2[c32], c3g = colors2[c32 + 1], c3b = colors2[c32 + 2]; + const minY = Math.round(y1), maxY = Math.round(y32); + let xa, car, cag, cab; + let xb, cbr, cbg, cbb; + for (let y4 = minY; y4 <= maxY; y4++) { + if (y4 < y22) { + const k3 = y4 < y1 ? 0 : (y1 - y4) / (y1 - y22); + xa = x1 - (x1 - x2) * k3; + car = c1r - (c1r - c2r) * k3; + cag = c1g - (c1g - c2g) * k3; + cab = c1b - (c1b - c2b) * k3; + } else { + let k3; + if (y4 > y32) { + k3 = 1; + } else if (y22 === y32) { + k3 = 0; + } else { + k3 = (y22 - y4) / (y22 - y32); + } + xa = x2 - (x2 - x3) * k3; + car = c2r - (c2r - c3r) * k3; + cag = c2g - (c2g - c3g) * k3; + cab = c2b - (c2b - c3b) * k3; + } + let k2; + if (y4 < y1) { + k2 = 0; + } else if (y4 > y32) { + k2 = 1; + } else { + k2 = (y1 - y4) / (y1 - y32); + } + xb = x1 - (x1 - x3) * k2; + cbr = c1r - (c1r - c3r) * k2; + cbg = c1g - (c1g - c3g) * k2; + cbb = c1b - (c1b - c3b) * k2; + const x1_ = Math.round(Math.min(xa, xb)); + const x2_ = Math.round(Math.max(xa, xb)); + let j3 = rowSize * y4 + x1_ * 4; + for (let x4 = x1_; x4 <= x2_; x4++) { + k2 = (xa - x4) / (xa - xb); + if (k2 < 0) { + k2 = 0; + } else if (k2 > 1) { + k2 = 1; + } + bytes[j3++] = car - (car - cbr) * k2 | 0; + bytes[j3++] = cag - (cag - cbg) * k2 | 0; + bytes[j3++] = cab - (cab - cbb) * k2 | 0; + bytes[j3++] = 255; + } + } +} +function drawFigure(data, figure, context) { + const ps = figure.coords; + const cs = figure.colors; + let i7, ii; + switch (figure.type) { + case MeshFigureType.LATTICE: + const verticesPerRow = figure.verticesPerRow; + const rows = Math.floor(ps.length / verticesPerRow) - 1; + const cols = verticesPerRow - 1; + for (i7 = 0; i7 < rows; i7++) { + let q2 = i7 * verticesPerRow; + for (let j3 = 0; j3 < cols; j3++, q2++) { + drawTriangle(data, context, ps[q2], ps[q2 + 1], ps[q2 + verticesPerRow], cs[q2], cs[q2 + 1], cs[q2 + verticesPerRow]); + drawTriangle(data, context, ps[q2 + verticesPerRow + 1], ps[q2 + 1], ps[q2 + verticesPerRow], cs[q2 + verticesPerRow + 1], cs[q2 + 1], cs[q2 + verticesPerRow]); + } + } + break; + case MeshFigureType.TRIANGLES: + for (i7 = 0, ii = ps.length; i7 < ii; i7 += 3) { + drawTriangle(data, context, ps[i7], ps[i7 + 1], ps[i7 + 2], cs[i7], cs[i7 + 1], cs[i7 + 2]); + } + break; + default: + throw new Error("illegal figure"); + } +} +function getShadingPattern(IR) { + switch (IR[0]) { + case "RadialAxial": + return new RadialAxialShadingPattern(IR); + case "Mesh": + return new MeshShadingPattern(IR); + case "Dummy": + return new DummyShadingPattern(); + } + throw new Error(`Unknown IR type: ${IR[0]}`); +} +function convertBlackAndWhiteToRGBA({ + src, + srcPos = 0, + dest, + width, + height, + nonBlackColor = 4294967295, + inverseDecode = false +}) { + const black = util_FeatureTest.isLittleEndian ? 4278190080 : 255; + const [zeroMapping, oneMapping] = inverseDecode ? [nonBlackColor, black] : [black, nonBlackColor]; + const widthInSource = width >> 3; + const widthRemainder = width & 7; + const srcLength = src.length; + dest = new Uint32Array(dest.buffer); + let destPos = 0; + for (let i7 = 0; i7 < height; i7++) { + for (const max = srcPos + widthInSource; srcPos < max; srcPos++) { + const elem2 = srcPos < srcLength ? src[srcPos] : 255; + dest[destPos++] = elem2 & 128 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 64 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 32 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 16 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 8 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 4 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 2 ? oneMapping : zeroMapping; + dest[destPos++] = elem2 & 1 ? oneMapping : zeroMapping; + } + if (widthRemainder === 0) { + continue; + } + const elem = srcPos < srcLength ? src[srcPos++] : 255; + for (let j3 = 0; j3 < widthRemainder; j3++) { + dest[destPos++] = elem & 1 << 7 - j3 ? oneMapping : zeroMapping; + } + } + return { + srcPos, + destPos + }; +} +function mirrorContextOperations(ctx, destCtx) { + if (ctx._removeMirroring) { + throw new Error("Context is already forwarding operations."); + } + ctx.__originalSave = ctx.save; + ctx.__originalRestore = ctx.restore; + ctx.__originalRotate = ctx.rotate; + ctx.__originalScale = ctx.scale; + ctx.__originalTranslate = ctx.translate; + ctx.__originalTransform = ctx.transform; + ctx.__originalSetTransform = ctx.setTransform; + ctx.__originalResetTransform = ctx.resetTransform; + ctx.__originalClip = ctx.clip; + ctx.__originalMoveTo = ctx.moveTo; + ctx.__originalLineTo = ctx.lineTo; + ctx.__originalBezierCurveTo = ctx.bezierCurveTo; + ctx.__originalRect = ctx.rect; + ctx.__originalClosePath = ctx.closePath; + ctx.__originalBeginPath = ctx.beginPath; + ctx._removeMirroring = () => { + ctx.save = ctx.__originalSave; + ctx.restore = ctx.__originalRestore; + ctx.rotate = ctx.__originalRotate; + ctx.scale = ctx.__originalScale; + ctx.translate = ctx.__originalTranslate; + ctx.transform = ctx.__originalTransform; + ctx.setTransform = ctx.__originalSetTransform; + ctx.resetTransform = ctx.__originalResetTransform; + ctx.clip = ctx.__originalClip; + ctx.moveTo = ctx.__originalMoveTo; + ctx.lineTo = ctx.__originalLineTo; + ctx.bezierCurveTo = ctx.__originalBezierCurveTo; + ctx.rect = ctx.__originalRect; + ctx.closePath = ctx.__originalClosePath; + ctx.beginPath = ctx.__originalBeginPath; + delete ctx._removeMirroring; + }; + ctx.save = function() { + destCtx.save(); + this.__originalSave(); + }; + ctx.restore = function() { + destCtx.restore(); + this.__originalRestore(); + }; + ctx.translate = function(x2, y4) { + destCtx.translate(x2, y4); + this.__originalTranslate(x2, y4); + }; + ctx.scale = function(x2, y4) { + destCtx.scale(x2, y4); + this.__originalScale(x2, y4); + }; + ctx.transform = function(a3, b4, c6, d4, e9, f4) { + destCtx.transform(a3, b4, c6, d4, e9, f4); + this.__originalTransform(a3, b4, c6, d4, e9, f4); + }; + ctx.setTransform = function(a3, b4, c6, d4, e9, f4) { + destCtx.setTransform(a3, b4, c6, d4, e9, f4); + this.__originalSetTransform(a3, b4, c6, d4, e9, f4); + }; + ctx.resetTransform = function() { + destCtx.resetTransform(); + this.__originalResetTransform(); + }; + ctx.rotate = function(angle) { + destCtx.rotate(angle); + this.__originalRotate(angle); + }; + ctx.clip = function(rule) { + destCtx.clip(rule); + this.__originalClip(rule); + }; + ctx.moveTo = function(x2, y4) { + destCtx.moveTo(x2, y4); + this.__originalMoveTo(x2, y4); + }; + ctx.lineTo = function(x2, y4) { + destCtx.lineTo(x2, y4); + this.__originalLineTo(x2, y4); + }; + ctx.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x2, y4) { + destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y4); + this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x2, y4); + }; + ctx.rect = function(x2, y4, width, height) { + destCtx.rect(x2, y4, width, height); + this.__originalRect(x2, y4, width, height); + }; + ctx.closePath = function() { + destCtx.closePath(); + this.__originalClosePath(); + }; + ctx.beginPath = function() { + destCtx.beginPath(); + this.__originalBeginPath(); + }; +} +function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) { + const [a3, b4, c6, d4, tx, ty] = getCurrentTransform(ctx); + if (b4 === 0 && c6 === 0) { + const tlX = destX * a3 + tx; + const rTlX = Math.round(tlX); + const tlY = destY * d4 + ty; + const rTlY = Math.round(tlY); + const brX = (destX + destW) * a3 + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destY + destH) * d4 + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(Math.sign(a3), 0, 0, Math.sign(d4), rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight); + ctx.setTransform(a3, b4, c6, d4, tx, ty); + return [rWidth, rHeight]; + } + if (a3 === 0 && d4 === 0) { + const tlX = destY * c6 + tx; + const rTlX = Math.round(tlX); + const tlY = destX * b4 + ty; + const rTlY = Math.round(tlY); + const brX = (destY + destH) * c6 + tx; + const rWidth = Math.abs(Math.round(brX) - rTlX) || 1; + const brY = (destX + destW) * b4 + ty; + const rHeight = Math.abs(Math.round(brY) - rTlY) || 1; + ctx.setTransform(0, Math.sign(b4), Math.sign(c6), 0, rTlX, rTlY); + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth); + ctx.setTransform(a3, b4, c6, d4, tx, ty); + return [rHeight, rWidth]; + } + ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH); + const scaleX = Math.hypot(a3, b4); + const scaleY = Math.hypot(c6, d4); + return [scaleX * destW, scaleY * destH]; +} +function putBinaryImageData(ctx, imgData) { + if (imgData instanceof ImageData) { + ctx.putImageData(imgData, 0, 0); + return; + } + const height = imgData.height, width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0, destPos; + const src = imgData.data; + const dest = chunkImgData.data; + let i7, j3, thisChunkHeight, elemsInThisChunk; + if (imgData.kind === util_ImageKind.GRAYSCALE_1BPP) { + const srcLength = src.byteLength; + const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2); + const dest32DataLength = dest32.length; + const fullSrcDiff = width + 7 >> 3; + const white = 4294967295; + const black = util_FeatureTest.isLittleEndian ? 4278190080 : 255; + for (i7 = 0; i7 < totalChunks; i7++) { + thisChunkHeight = i7 < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + destPos = 0; + for (j3 = 0; j3 < thisChunkHeight; j3++) { + const srcDiff = srcLength - srcPos; + let k2 = 0; + const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7; + const kEndUnrolled = kEnd & ~7; + let mask = 0; + let srcByte = 0; + for (; k2 < kEndUnrolled; k2 += 8) { + srcByte = src[srcPos++]; + dest32[destPos++] = srcByte & 128 ? white : black; + dest32[destPos++] = srcByte & 64 ? white : black; + dest32[destPos++] = srcByte & 32 ? white : black; + dest32[destPos++] = srcByte & 16 ? white : black; + dest32[destPos++] = srcByte & 8 ? white : black; + dest32[destPos++] = srcByte & 4 ? white : black; + dest32[destPos++] = srcByte & 2 ? white : black; + dest32[destPos++] = srcByte & 1 ? white : black; + } + for (; k2 < kEnd; k2++) { + if (mask === 0) { + srcByte = src[srcPos++]; + mask = 128; + } + dest32[destPos++] = srcByte & mask ? white : black; + mask >>= 1; + } + } + while (destPos < dest32DataLength) { + dest32[destPos++] = 0; + } + ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT); + } + } else if (imgData.kind === util_ImageKind.RGBA_32BPP) { + j3 = 0; + elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; + for (i7 = 0; i7 < fullChunks; i7++) { + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + srcPos += elemsInThisChunk; + ctx.putImageData(chunkImgData, 0, j3); + j3 += FULL_CHUNK_HEIGHT; + } + if (i7 < totalChunks) { + elemsInThisChunk = width * partialChunkHeight * 4; + dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); + ctx.putImageData(chunkImgData, 0, j3); + } + } else if (imgData.kind === util_ImageKind.RGB_24BPP) { + thisChunkHeight = FULL_CHUNK_HEIGHT; + elemsInThisChunk = width * thisChunkHeight; + for (i7 = 0; i7 < totalChunks; i7++) { + if (i7 >= fullChunks) { + thisChunkHeight = partialChunkHeight; + elemsInThisChunk = width * thisChunkHeight; + } + destPos = 0; + for (j3 = elemsInThisChunk; j3--; ) { + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = src[srcPos++]; + dest[destPos++] = 255; + } + ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT); + } + } else { + throw new Error(`bad image kind: ${imgData.kind}`); + } +} +function putBinaryImageMask(ctx, imgData) { + if (imgData.bitmap) { + ctx.drawImage(imgData.bitmap, 0, 0); + return; + } + const height = imgData.height, width = imgData.width; + const partialChunkHeight = height % FULL_CHUNK_HEIGHT; + const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; + const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; + const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); + let srcPos = 0; + const src = imgData.data; + const dest = chunkImgData.data; + for (let i7 = 0; i7 < totalChunks; i7++) { + const thisChunkHeight = i7 < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight; + ({ + srcPos + } = convertBlackAndWhiteToRGBA({ + src, + srcPos, + dest, + width, + height: thisChunkHeight, + nonBlackColor: 0 + })); + ctx.putImageData(chunkImgData, 0, i7 * FULL_CHUNK_HEIGHT); + } +} +function copyCtxState(sourceCtx, destCtx) { + const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font", "filter"]; + for (const property of properties) { + if (sourceCtx[property] !== void 0) { + destCtx[property] = sourceCtx[property]; + } + } + if (sourceCtx.setLineDash !== void 0) { + destCtx.setLineDash(sourceCtx.getLineDash()); + destCtx.lineDashOffset = sourceCtx.lineDashOffset; + } +} +function resetCtxToDefault(ctx) { + ctx.strokeStyle = ctx.fillStyle = "#000000"; + ctx.fillRule = "nonzero"; + ctx.globalAlpha = 1; + ctx.lineWidth = 1; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 10; + ctx.globalCompositeOperation = "source-over"; + ctx.font = "10px sans-serif"; + if (ctx.setLineDash !== void 0) { + ctx.setLineDash([]); + ctx.lineDashOffset = 0; + } + const { + filter: filter2 + } = ctx; + if (filter2 !== "none" && filter2 !== "") { + ctx.filter = "none"; + } +} +function getImageSmoothingEnabled(transform, interpolate3) { + if (interpolate3) { + return true; + } + Util.singularValueDecompose2dScale(transform, XY); + const actualScale = Math.fround(OutputScale.pixelRatio * PixelsPerInch.PDF_TO_CSS_UNITS); + return XY[0] <= actualScale && XY[1] <= actualScale; +} +function getFilenameFromContentDispositionHeader(contentDisposition) { + let needsEncodingFixup = true; + let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = unescape(filename); + filename = rfc5987decode(filename); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + tmp = rfc2231getparam(contentDisposition); + if (tmp) { + const filename = rfc2047decode(tmp); + return fixupEncoding(filename); + } + tmp = toParamRegExp("filename", "i").exec(contentDisposition); + if (tmp) { + tmp = tmp[1]; + let filename = rfc2616unquote(tmp); + filename = rfc2047decode(filename); + return fixupEncoding(filename); + } + function toParamRegExp(attributePattern, flags) { + return new RegExp("(?:^|;)\\s*" + attributePattern + '\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)', flags); + } + function textdecode(encoding, value) { + if (encoding) { + if (!/^[\x00-\xFF]+$/.test(value)) { + return value; + } + try { + const decoder = new TextDecoder(encoding, { + fatal: true + }); + const buffer = stringToBytes(value); + value = decoder.decode(buffer); + needsEncodingFixup = false; + } catch { + } + } + return value; + } + function fixupEncoding(value) { + if (needsEncodingFixup && /[\x80-\xff]/.test(value)) { + value = textdecode("utf-8", value); + if (needsEncodingFixup) { + value = textdecode("iso-8859-1", value); + } + } + return value; + } + function rfc2231getparam(contentDispositionStr) { + const matches = []; + let match2; + const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig"); + while ((match2 = iter.exec(contentDispositionStr)) !== null) { + let [, n7, quot, part] = match2; + n7 = parseInt(n7, 10); + if (n7 in matches) { + if (n7 === 0) { + break; + } + continue; + } + matches[n7] = [quot, part]; + } + const parts = []; + for (let n7 = 0; n7 < matches.length; ++n7) { + if (!(n7 in matches)) { + break; + } + let [quot, part] = matches[n7]; + part = rfc2616unquote(part); + if (quot) { + part = unescape(part); + if (n7 === 0) { + part = rfc5987decode(part); + } + } + parts.push(part); + } + return parts.join(""); + } + function rfc2616unquote(value) { + if (value.startsWith('"')) { + const parts = value.slice(1).split('\\"'); + for (let i7 = 0; i7 < parts.length; ++i7) { + const quotindex = parts[i7].indexOf('"'); + if (quotindex !== -1) { + parts[i7] = parts[i7].slice(0, quotindex); + parts.length = i7 + 1; + } + parts[i7] = parts[i7].replaceAll(/\\(.)/g, "$1"); + } + value = parts.join('"'); + } + return value; + } + function rfc5987decode(extvalue) { + const encodingend = extvalue.indexOf("'"); + if (encodingend === -1) { + return extvalue; + } + const encoding = extvalue.slice(0, encodingend); + const langvalue = extvalue.slice(encodingend + 1); + const value = langvalue.replace(/^[^']*'/, ""); + return textdecode(encoding, value); + } + function rfc2047decode(value) { + if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) { + return value; + } + return value.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function(matches, charset, encoding, text3) { + if (encoding === "q" || encoding === "Q") { + text3 = text3.replaceAll("_", " "); + text3 = text3.replaceAll(/=([0-9a-fA-F]{2})/g, function(match2, hex2) { + return String.fromCharCode(parseInt(hex2, 16)); + }); + return textdecode(charset, text3); + } + try { + text3 = atob(text3); + } catch { + } + return textdecode(charset, text3); + }); + } + return ""; +} +function createHeaders(isHttp, httpHeaders) { + const headers = new Headers(); + if (!isHttp || !httpHeaders || typeof httpHeaders !== "object") { + return headers; + } + for (const key in httpHeaders) { + const val2 = httpHeaders[key]; + if (val2 !== void 0) { + headers.append(key, val2); + } + } + return headers; +} +function getResponseOrigin(url) { + return URL.parse(url)?.origin ?? null; +} +function validateRangeRequestCapabilities({ + responseHeaders, + isHttp, + rangeChunkSize, + disableRange +}) { + const returnValues = { + allowRangeRequests: false, + suggestedLength: void 0 + }; + const length = parseInt(responseHeaders.get("Content-Length"), 10); + if (!Number.isInteger(length)) { + return returnValues; + } + returnValues.suggestedLength = length; + if (length <= 2 * rangeChunkSize) { + return returnValues; + } + if (disableRange || !isHttp) { + return returnValues; + } + if (responseHeaders.get("Accept-Ranges") !== "bytes") { + return returnValues; + } + const contentEncoding = responseHeaders.get("Content-Encoding") || "identity"; + if (contentEncoding !== "identity") { + return returnValues; + } + returnValues.allowRangeRequests = true; + return returnValues; +} +function extractFilenameFromHeader(responseHeaders) { + const contentDisposition = responseHeaders.get("Content-Disposition"); + if (contentDisposition) { + let filename = getFilenameFromContentDispositionHeader(contentDisposition); + if (filename.includes("%")) { + try { + filename = decodeURIComponent(filename); + } catch { + } + } + if (isPdfFile(filename)) { + return filename; + } + } + return null; +} +function createResponseError(status, url) { + return new ResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status, status === 404 || status === 0 && url.startsWith("file:")); +} +function validateResponseStatus(status) { + return status === 200 || status === 206; +} +function createFetchOptions(headers, withCredentials, abortController) { + return { + method: "GET", + headers, + signal: abortController.signal, + mode: "cors", + credentials: withCredentials ? "include" : "same-origin", + redirect: "follow" + }; +} +function getArrayBuffer(val2) { + if (val2 instanceof Uint8Array) { + return val2.buffer; + } + if (val2 instanceof ArrayBuffer) { + return val2; + } + warn(`getArrayBuffer - unexpected data format: ${val2}`); + return new Uint8Array(val2).buffer; +} +function network_getArrayBuffer(xhr) { + const data = xhr.response; + if (typeof data !== "string") { + return data; + } + return stringToBytes(data).buffer; +} +function parseUrlOrPath(sourceUrl) { + if (urlRegex.test(sourceUrl)) { + return new URL(sourceUrl); + } + const url = process.getBuiltinModule("url"); + return new URL(url.pathToFileURL(sourceUrl)); +} +function getDocument(src = {}) { + if (typeof src === "string" || src instanceof URL) { + src = { + url: src + }; + } else if (src instanceof ArrayBuffer || ArrayBuffer.isView(src)) { + src = { + data: src + }; + } + const task = new PDFDocumentLoadingTask(); + const { + docId + } = task; + const url = src.url ? getUrlProp(src.url) : null; + const data = src.data ? getDataProp(src.data) : null; + const httpHeaders = src.httpHeaders || null; + const withCredentials = src.withCredentials === true; + const password = src.password ?? null; + const rangeTransport = src.range instanceof PDFDataRangeTransport ? src.range : null; + const rangeChunkSize = Number.isInteger(src.rangeChunkSize) && src.rangeChunkSize > 0 ? src.rangeChunkSize : 2 ** 16; + let worker = src.worker instanceof PDFWorker ? src.worker : null; + const verbosity2 = src.verbosity; + const docBaseUrl = typeof src.docBaseUrl === "string" && !isDataScheme(src.docBaseUrl) ? src.docBaseUrl : null; + const cMapUrl = getFactoryUrlProp(src.cMapUrl); + const cMapPacked = src.cMapPacked !== false; + const CMapReaderFactory = src.CMapReaderFactory || (isNodeJS ? NodeCMapReaderFactory : DOMCMapReaderFactory); + const iccUrl = getFactoryUrlProp(src.iccUrl); + const standardFontDataUrl = getFactoryUrlProp(src.standardFontDataUrl); + const StandardFontDataFactory = src.StandardFontDataFactory || (isNodeJS ? NodeStandardFontDataFactory : DOMStandardFontDataFactory); + const wasmUrl = getFactoryUrlProp(src.wasmUrl); + const WasmFactory = src.WasmFactory || (isNodeJS ? NodeWasmFactory : DOMWasmFactory); + const ignoreErrors = src.stopAtErrors !== true; + const maxImageSize = Number.isInteger(src.maxImageSize) && src.maxImageSize > -1 ? src.maxImageSize : -1; + const isEvalSupported2 = src.isEvalSupported !== false; + const isOffscreenCanvasSupported = typeof src.isOffscreenCanvasSupported === "boolean" ? src.isOffscreenCanvasSupported : !isNodeJS; + const isImageDecoderSupported = typeof src.isImageDecoderSupported === "boolean" ? src.isImageDecoderSupported : !isNodeJS && (util_FeatureTest.platform.isFirefox || !globalThis.chrome); + const canvasMaxAreaInBytes = Number.isInteger(src.canvasMaxAreaInBytes) ? src.canvasMaxAreaInBytes : -1; + const disableFontFace = typeof src.disableFontFace === "boolean" ? src.disableFontFace : isNodeJS; + const fontExtraProperties = src.fontExtraProperties === true; + const enableXfa = src.enableXfa === true; + const ownerDocument = src.ownerDocument || globalThis.document; + const disableRange = src.disableRange === true; + const disableStream = src.disableStream === true; + const disableAutoFetch = src.disableAutoFetch === true; + const pdfBug = src.pdfBug === true; + const CanvasFactory = src.CanvasFactory || (isNodeJS ? NodeCanvasFactory : DOMCanvasFactory); + const FilterFactory = src.FilterFactory || (isNodeJS ? NodeFilterFactory : DOMFilterFactory); + const enableHWA = src.enableHWA === true; + const useWasm = src.useWasm !== false; + const length = rangeTransport ? rangeTransport.length : src.length ?? NaN; + const useSystemFonts = typeof src.useSystemFonts === "boolean" ? src.useSystemFonts : !isNodeJS && !disableFontFace; + const useWorkerFetch = typeof src.useWorkerFetch === "boolean" ? src.useWorkerFetch : !!(CMapReaderFactory === DOMCMapReaderFactory && StandardFontDataFactory === DOMStandardFontDataFactory && WasmFactory === DOMWasmFactory && cMapUrl && standardFontDataUrl && wasmUrl && isValidFetchUrl(cMapUrl, document.baseURI) && isValidFetchUrl(standardFontDataUrl, document.baseURI) && isValidFetchUrl(wasmUrl, document.baseURI)); + const styleElement = null; + setVerbosityLevel(verbosity2); + const transportFactory = { + canvasFactory: new CanvasFactory({ + ownerDocument, + enableHWA + }), + filterFactory: new FilterFactory({ + docId, + ownerDocument + }), + cMapReaderFactory: useWorkerFetch ? null : new CMapReaderFactory({ + baseUrl: cMapUrl, + isCompressed: cMapPacked + }), + standardFontDataFactory: useWorkerFetch ? null : new StandardFontDataFactory({ + baseUrl: standardFontDataUrl + }), + wasmFactory: useWorkerFetch ? null : new WasmFactory({ + baseUrl: wasmUrl + }) + }; + if (!worker) { + worker = PDFWorker.create({ + verbosity: verbosity2, + port: GlobalWorkerOptions.workerPort + }); + task._worker = worker; + } + const docParams = { + docId, + apiVersion: "5.4.394", + data, + password, + disableAutoFetch, + rangeChunkSize, + length, + docBaseUrl, + enableXfa, + evaluatorOptions: { + maxImageSize, + disableFontFace, + ignoreErrors, + isEvalSupported: isEvalSupported2, + isOffscreenCanvasSupported, + isImageDecoderSupported, + canvasMaxAreaInBytes, + fontExtraProperties, + useSystemFonts, + useWasm, + useWorkerFetch, + cMapUrl, + iccUrl, + standardFontDataUrl, + wasmUrl + } + }; + const transportParams = { + ownerDocument, + pdfBug, + styleElement, + loadingParams: { + disableAutoFetch, + enableXfa + } + }; + worker.promise.then(function() { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const workerIdPromise = worker.messageHandler.sendWithPromise("GetDocRequest", docParams, data ? [data.buffer] : null); + let networkStream; + if (rangeTransport) { + networkStream = new PDFDataTransportStream(rangeTransport, { + disableRange, + disableStream + }); + } else if (!data) { + if (!url) { + throw new Error("getDocument - no `url` parameter provided."); + } + const NetworkStream = isValidFetchUrl(url) ? PDFFetchStream : isNodeJS ? PDFNodeStream : PDFNetworkStream; + networkStream = new NetworkStream({ + url, + length, + httpHeaders, + withCredentials, + rangeChunkSize, + disableRange, + disableStream + }); + } + return workerIdPromise.then((workerId) => { + if (task.destroyed) { + throw new Error("Loading aborted"); + } + if (worker.destroyed) { + throw new Error("Worker was destroyed"); + } + const messageHandler = new MessageHandler(docId, workerId, worker.port); + const transport = new WorkerTransport(messageHandler, task, networkStream, transportParams, transportFactory, enableHWA); + task._transport = transport; + messageHandler.send("Ready", null); + }); + }).catch(task._capability.reject); + return task; +} +function makeColorComp(n7) { + return Math.floor(Math.max(0, Math.min(1, n7)) * 255).toString(16).padStart(2, "0"); +} +function scaleAndClamp(x2) { + return Math.max(0, Math.min(255, 255 * x2)); +} +var __webpack_require__, isNodeJS, FONT_IDENTITY_MATRIX, LINE_FACTOR, LINE_DESCENT_FACTOR, BASELINE_FACTOR, RenderingIntentFlag, AnnotationMode, AnnotationEditorPrefix, AnnotationEditorType, AnnotationEditorParamsType, PermissionFlag, MeshFigureType, TextRenderingMode, util_ImageKind, AnnotationType, AnnotationBorderStyleType, VerbosityLevel, OPS, DrawOPS, PasswordResponses, verbosity, BaseException, PasswordException, UnknownErrorException, InvalidPDFException, ResponseException, FormatError, AbortException, util_FeatureTest, hexNumbers, Util, NormalizeRegex, NormalizationMap, AnnotationPrefix, XfaText, XfaLayer, SVG_NS, PixelsPerInch, PageViewport, RenderingCancelledException, StatTimer, PDFDateString, OutputScale, SupportedImageMimeTypes, ColorScheme, CSSConstants, contrastCache, EditorToolbar, FloatingToolbar, CurrentPointers, IdManager, ImageManager, CommandManager, KeyboardManager, ColorManager, AnnotationEditorUIManager, AltText, Comment, TouchManager, AnnotationEditor, FakeEditor, SEED, MASK_HIGH, MASK_LOW, MurmurHash3_64, SerializableEmpty, AnnotationStorage, PrintAnnotationStorage, FontLoader, FontFaceObject, CssFontInfo, SystemFontInfo, FontInfo, PatternInfo, isRefProxy, isNameProxy, isValidExplicitDest, LoopbackPort, CallbackKind, StreamKind, MessageHandler, BaseCanvasFactory, DOMCanvasFactory, BaseCMapReaderFactory, DOMCMapReaderFactory, BaseFilterFactory, DOMFilterFactory, BaseStandardFontDataFactory, DOMStandardFontDataFactory, BaseWasmFactory, DOMWasmFactory, NodeFilterFactory, NodeCanvasFactory, NodeCMapReaderFactory, NodeStandardFontDataFactory, NodeWasmFactory, FORCED_DEPENDENCY_LABEL, floor, ceil, EMPTY_BBOX, BBoxReader, ensureDebugMetadata, CanvasDependencyTracker, CanvasNestedDependencyTracker, Dependencies, PathType, BaseShadingPattern, RadialAxialShadingPattern, MeshShadingPattern, DummyShadingPattern, PaintType, TilingPattern, MIN_FONT_SIZE, MAX_FONT_SIZE, EXECUTION_TIME, EXECUTION_STEPS, FULL_CHUNK_HEIGHT, SCALE_MATRIX, XY, MIN_MAX_INIT, CachedCanvases, CanvasExtraState, LINE_CAP_STYLES, LINE_JOIN_STYLES, NORMAL_CLIP, EO_CLIP, CanvasGraphics, GlobalWorkerOptions, Metadata, INTERNAL, OptionalContentGroup, OptionalContentConfig, PDFDataTransportStream, PDFDataTransportStreamReader, PDFDataTransportStreamRangeReader, PDFFetchStream, PDFFetchStreamReader, PDFFetchStreamRangeReader, OK_RESPONSE, PARTIAL_CONTENT_RESPONSE, NetworkManager, PDFNetworkStream, PDFNetworkStreamFullRequestReader, PDFNetworkStreamRangeRequestReader, urlRegex, PDFNodeStream, PDFNodeStreamFsFullReader, PDFNodeStreamFsRangeReader, INITIAL_DATA, PDFObjects, MAX_TEXT_DIVS_TO_RENDER, DEFAULT_FONT_SIZE, TextLayer, RENDERING_CANCELLED_TIMEOUT, PDFDocumentLoadingTask, PDFDataRangeTransport, PDFDocumentProxy, PDFPageProxy, PDFWorker, WorkerTransport, RenderTask, InternalRenderTask, version2, build, ColorPicker, BasicColorPicker, ColorConverters, BaseSVGFactory, DOMSVGFactory, annotation_layer_DEFAULT_FONT_SIZE, GetElementsByNameSet, TIMEZONE_OFFSET, AnnotationElementFactory, AnnotationElement, EditorAnnotationElement, LinkAnnotationElement, TextAnnotationElement, WidgetAnnotationElement, TextWidgetAnnotationElement, SignatureWidgetAnnotationElement, CheckboxWidgetAnnotationElement, RadioButtonWidgetAnnotationElement, PushButtonWidgetAnnotationElement, ChoiceWidgetAnnotationElement, PopupAnnotationElement, PopupElement, FreeTextAnnotationElement, LineAnnotationElement, SquareAnnotationElement, CircleAnnotationElement, PolylineAnnotationElement, PolygonAnnotationElement, CaretAnnotationElement, InkAnnotationElement, HighlightAnnotationElement, UnderlineAnnotationElement, SquigglyAnnotationElement, StrikeOutAnnotationElement, StampAnnotationElement, FileAttachmentAnnotationElement, AnnotationLayer, EOL_PATTERN, FreeTextEditor, Outline, FreeDrawOutliner, FreeDrawOutline, HighlightOutliner, HighlightOutline, FreeHighlightOutliner, FreeHighlightOutline, HighlightEditor, DrawingOptions, DrawingEditor, InkDrawOutliner, InkDrawOutline, InkDrawingOptions, InkEditor, ContourDrawOutline, BASE_HEADER_LENGTH, POINTS_PROPERTIES_NUMBER, SignatureExtractor, SignatureOptions, DrawnSignatureOptions, SignatureEditor, StampEditor, AnnotationEditorLayer, DrawLayer; +var init_pdf = __esm({ + "../pi-mono/node_modules/pdfjs-dist/build/pdf.mjs"() { + init_process_shim(); + __webpack_require__ = {}; + (() => { + __webpack_require__.d = (exports, definition) => { + for (var key in definition) { + if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); + } + } + }; + })(); + (() => { + __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop); + })(); + isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser"); + FONT_IDENTITY_MATRIX = [1e-3, 0, 0, 1e-3, 0, 0]; + LINE_FACTOR = 1.35; + LINE_DESCENT_FACTOR = 0.35; + BASELINE_FACTOR = LINE_DESCENT_FACTOR / LINE_FACTOR; + RenderingIntentFlag = { + ANY: 1, + DISPLAY: 2, + PRINT: 4, + SAVE: 8, + ANNOTATIONS_FORMS: 16, + ANNOTATIONS_STORAGE: 32, + ANNOTATIONS_DISABLE: 64, + IS_EDITING: 128, + OPLIST: 256 + }; + AnnotationMode = { + DISABLE: 0, + ENABLE: 1, + ENABLE_FORMS: 2, + ENABLE_STORAGE: 3 + }; + AnnotationEditorPrefix = "pdfjs_internal_editor_"; + AnnotationEditorType = { + DISABLE: -1, + NONE: 0, + FREETEXT: 3, + HIGHLIGHT: 9, + STAMP: 13, + INK: 15, + POPUP: 16, + SIGNATURE: 101, + COMMENT: 102 + }; + AnnotationEditorParamsType = { + RESIZE: 1, + CREATE: 2, + FREETEXT_SIZE: 11, + FREETEXT_COLOR: 12, + FREETEXT_OPACITY: 13, + INK_COLOR: 21, + INK_THICKNESS: 22, + INK_OPACITY: 23, + HIGHLIGHT_COLOR: 31, + HIGHLIGHT_THICKNESS: 32, + HIGHLIGHT_FREE: 33, + HIGHLIGHT_SHOW_ALL: 34, + DRAW_STEP: 41 + }; + PermissionFlag = { + PRINT: 4, + MODIFY_CONTENTS: 8, + COPY: 16, + MODIFY_ANNOTATIONS: 32, + FILL_INTERACTIVE_FORMS: 256, + COPY_FOR_ACCESSIBILITY: 512, + ASSEMBLE: 1024, + PRINT_HIGH_QUALITY: 2048 + }; + MeshFigureType = { + TRIANGLES: 1, + LATTICE: 2, + PATCH: 3 + }; + TextRenderingMode = { + FILL: 0, + STROKE: 1, + FILL_STROKE: 2, + INVISIBLE: 3, + FILL_ADD_TO_PATH: 4, + STROKE_ADD_TO_PATH: 5, + FILL_STROKE_ADD_TO_PATH: 6, + ADD_TO_PATH: 7, + FILL_STROKE_MASK: 3, + ADD_TO_PATH_FLAG: 4 + }; + util_ImageKind = { + GRAYSCALE_1BPP: 1, + RGB_24BPP: 2, + RGBA_32BPP: 3 + }; + AnnotationType = { + TEXT: 1, + LINK: 2, + FREETEXT: 3, + LINE: 4, + SQUARE: 5, + CIRCLE: 6, + POLYGON: 7, + POLYLINE: 8, + HIGHLIGHT: 9, + UNDERLINE: 10, + SQUIGGLY: 11, + STRIKEOUT: 12, + STAMP: 13, + CARET: 14, + INK: 15, + POPUP: 16, + FILEATTACHMENT: 17, + SOUND: 18, + MOVIE: 19, + WIDGET: 20, + SCREEN: 21, + PRINTERMARK: 22, + TRAPNET: 23, + WATERMARK: 24, + THREED: 25, + REDACT: 26 + }; + AnnotationBorderStyleType = { + SOLID: 1, + DASHED: 2, + BEVELED: 3, + INSET: 4, + UNDERLINE: 5 + }; + VerbosityLevel = { + ERRORS: 0, + WARNINGS: 1, + INFOS: 5 + }; + OPS = { + dependency: 1, + setLineWidth: 2, + setLineCap: 3, + setLineJoin: 4, + setMiterLimit: 5, + setDash: 6, + setRenderingIntent: 7, + setFlatness: 8, + setGState: 9, + save: 10, + restore: 11, + transform: 12, + moveTo: 13, + lineTo: 14, + curveTo: 15, + curveTo2: 16, + curveTo3: 17, + closePath: 18, + rectangle: 19, + stroke: 20, + closeStroke: 21, + fill: 22, + eoFill: 23, + fillStroke: 24, + eoFillStroke: 25, + closeFillStroke: 26, + closeEOFillStroke: 27, + endPath: 28, + clip: 29, + eoClip: 30, + beginText: 31, + endText: 32, + setCharSpacing: 33, + setWordSpacing: 34, + setHScale: 35, + setLeading: 36, + setFont: 37, + setTextRenderingMode: 38, + setTextRise: 39, + moveText: 40, + setLeadingMoveText: 41, + setTextMatrix: 42, + nextLine: 43, + showText: 44, + showSpacedText: 45, + nextLineShowText: 46, + nextLineSetSpacingShowText: 47, + setCharWidth: 48, + setCharWidthAndBounds: 49, + setStrokeColorSpace: 50, + setFillColorSpace: 51, + setStrokeColor: 52, + setStrokeColorN: 53, + setFillColor: 54, + setFillColorN: 55, + setStrokeGray: 56, + setFillGray: 57, + setStrokeRGBColor: 58, + setFillRGBColor: 59, + setStrokeCMYKColor: 60, + setFillCMYKColor: 61, + shadingFill: 62, + beginInlineImage: 63, + beginImageData: 64, + endInlineImage: 65, + paintXObject: 66, + markPoint: 67, + markPointProps: 68, + beginMarkedContent: 69, + beginMarkedContentProps: 70, + endMarkedContent: 71, + beginCompat: 72, + endCompat: 73, + paintFormXObjectBegin: 74, + paintFormXObjectEnd: 75, + beginGroup: 76, + endGroup: 77, + beginAnnotation: 80, + endAnnotation: 81, + paintImageMaskXObject: 83, + paintImageMaskXObjectGroup: 84, + paintImageXObject: 85, + paintInlineImageXObject: 86, + paintInlineImageXObjectGroup: 87, + paintImageXObjectRepeat: 88, + paintImageMaskXObjectRepeat: 89, + paintSolidColorImageMask: 90, + constructPath: 91, + setStrokeTransparent: 92, + setFillTransparent: 93, + rawFillPath: 94 + }; + DrawOPS = { + moveTo: 0, + lineTo: 1, + curveTo: 2, + quadraticCurveTo: 3, + closePath: 4 + }; + PasswordResponses = { + NEED_PASSWORD: 1, + INCORRECT_PASSWORD: 2 + }; + verbosity = VerbosityLevel.WARNINGS; + BaseException = (function BaseExceptionClosure() { + function BaseException2(message, name) { + this.message = message; + this.name = name; + } + BaseException2.prototype = new Error(); + BaseException2.constructor = BaseException2; + return BaseException2; + })(); + PasswordException = class extends BaseException { + constructor(msg, code) { + super(msg, "PasswordException"); + this.code = code; + } + }; + UnknownErrorException = class extends BaseException { + constructor(msg, details) { + super(msg, "UnknownErrorException"); + this.details = details; + } + }; + InvalidPDFException = class extends BaseException { + constructor(msg) { + super(msg, "InvalidPDFException"); + } + }; + ResponseException = class extends BaseException { + constructor(msg, status, missing) { + super(msg, "ResponseException"); + this.status = status; + this.missing = missing; + } + }; + FormatError = class extends BaseException { + constructor(msg) { + super(msg, "FormatError"); + } + }; + AbortException = class extends BaseException { + constructor(msg) { + super(msg, "AbortException"); + } + }; + util_FeatureTest = class { + static get isLittleEndian() { + return shadow(this, "isLittleEndian", isLittleEndian()); + } + static get isEvalSupported() { + return shadow(this, "isEvalSupported", isEvalSupported()); + } + static get isOffscreenCanvasSupported() { + return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined"); + } + static get isImageDecoderSupported() { + return shadow(this, "isImageDecoderSupported", typeof ImageDecoder !== "undefined"); + } + static get isFloat16ArraySupported() { + return shadow(this, "isFloat16ArraySupported", typeof Float16Array !== "undefined"); + } + static get isSanitizerSupported() { + return shadow(this, "isSanitizerSupported", typeof Sanitizer !== "undefined"); + } + static get platform() { + const { + platform, + userAgent + } = navigator; + return shadow(this, "platform", { + isAndroid: userAgent.includes("Android"), + isLinux: platform.includes("Linux"), + isMac: platform.includes("Mac"), + isWindows: platform.includes("Win"), + isFirefox: userAgent.includes("Firefox") + }); + } + static get isCSSRoundSupported() { + return shadow(this, "isCSSRoundSupported", globalThis.CSS?.supports?.("width: round(1.5px, 1px)")); + } + }; + hexNumbers = Array.from(Array(256).keys(), (n7) => n7.toString(16).padStart(2, "0")); + Util = class { + static makeHexColor(r8, g3, b4) { + return `#${hexNumbers[r8]}${hexNumbers[g3]}${hexNumbers[b4]}`; + } + static domMatrixToTransform(dm) { + return [dm.a, dm.b, dm.c, dm.d, dm.e, dm.f]; + } + static scaleMinMax(transform, minMax) { + let temp; + if (transform[0]) { + if (transform[0] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[0]; + minMax[2] *= transform[0]; + if (transform[3] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[3]; + minMax[3] *= transform[3]; + } else { + temp = minMax[0]; + minMax[0] = minMax[1]; + minMax[1] = temp; + temp = minMax[2]; + minMax[2] = minMax[3]; + minMax[3] = temp; + if (transform[1] < 0) { + temp = minMax[1]; + minMax[1] = minMax[3]; + minMax[3] = temp; + } + minMax[1] *= transform[1]; + minMax[3] *= transform[1]; + if (transform[2] < 0) { + temp = minMax[0]; + minMax[0] = minMax[2]; + minMax[2] = temp; + } + minMax[0] *= transform[2]; + minMax[2] *= transform[2]; + } + minMax[0] += transform[4]; + minMax[1] += transform[5]; + minMax[2] += transform[4]; + minMax[3] += transform[5]; + } + static transform(m1, m22) { + return [m1[0] * m22[0] + m1[2] * m22[1], m1[1] * m22[0] + m1[3] * m22[1], m1[0] * m22[2] + m1[2] * m22[3], m1[1] * m22[2] + m1[3] * m22[3], m1[0] * m22[4] + m1[2] * m22[5] + m1[4], m1[1] * m22[4] + m1[3] * m22[5] + m1[5]]; + } + static multiplyByDOMMatrix(m4, md) { + return [m4[0] * md.a + m4[2] * md.b, m4[1] * md.a + m4[3] * md.b, m4[0] * md.c + m4[2] * md.d, m4[1] * md.c + m4[3] * md.d, m4[0] * md.e + m4[2] * md.f + m4[4], m4[1] * md.e + m4[3] * md.f + m4[5]]; + } + static applyTransform(p4, m4, pos = 0) { + const p0 = p4[pos]; + const p1 = p4[pos + 1]; + p4[pos] = p0 * m4[0] + p1 * m4[2] + m4[4]; + p4[pos + 1] = p0 * m4[1] + p1 * m4[3] + m4[5]; + } + static applyTransformToBezier(p4, transform, pos = 0) { + const m0 = transform[0]; + const m1 = transform[1]; + const m22 = transform[2]; + const m32 = transform[3]; + const m4 = transform[4]; + const m5 = transform[5]; + for (let i7 = 0; i7 < 6; i7 += 2) { + const pI = p4[pos + i7]; + const pI1 = p4[pos + i7 + 1]; + p4[pos + i7] = pI * m0 + pI1 * m22 + m4; + p4[pos + i7 + 1] = pI * m1 + pI1 * m32 + m5; + } + } + static applyInverseTransform(p4, m4) { + const p0 = p4[0]; + const p1 = p4[1]; + const d4 = m4[0] * m4[3] - m4[1] * m4[2]; + p4[0] = (p0 * m4[3] - p1 * m4[2] + m4[2] * m4[5] - m4[4] * m4[3]) / d4; + p4[1] = (-p0 * m4[1] + p1 * m4[0] + m4[4] * m4[1] - m4[5] * m4[0]) / d4; + } + static axialAlignedBoundingBox(rect, transform, output) { + const m0 = transform[0]; + const m1 = transform[1]; + const m22 = transform[2]; + const m32 = transform[3]; + const m4 = transform[4]; + const m5 = transform[5]; + const r0 = rect[0]; + const r1 = rect[1]; + const r22 = rect[2]; + const r32 = rect[3]; + let a0 = m0 * r0 + m4; + let a22 = a0; + let a1 = m0 * r22 + m4; + let a3 = a1; + let b0 = m32 * r1 + m5; + let b22 = b0; + let b1 = m32 * r32 + m5; + let b32 = b1; + if (m1 !== 0 || m22 !== 0) { + const m1r0 = m1 * r0; + const m1r2 = m1 * r22; + const m2r1 = m22 * r1; + const m2r3 = m22 * r32; + a0 += m2r1; + a3 += m2r1; + a1 += m2r3; + a22 += m2r3; + b0 += m1r0; + b32 += m1r0; + b1 += m1r2; + b22 += m1r2; + } + output[0] = Math.min(output[0], a0, a1, a22, a3); + output[1] = Math.min(output[1], b0, b1, b22, b32); + output[2] = Math.max(output[2], a0, a1, a22, a3); + output[3] = Math.max(output[3], b0, b1, b22, b32); + } + static inverseTransform(m4) { + const d4 = m4[0] * m4[3] - m4[1] * m4[2]; + return [m4[3] / d4, -m4[1] / d4, -m4[2] / d4, m4[0] / d4, (m4[2] * m4[5] - m4[4] * m4[3]) / d4, (m4[4] * m4[1] - m4[5] * m4[0]) / d4]; + } + static singularValueDecompose2dScale(matrix, output) { + const m0 = matrix[0]; + const m1 = matrix[1]; + const m22 = matrix[2]; + const m32 = matrix[3]; + const a3 = m0 ** 2 + m1 ** 2; + const b4 = m0 * m22 + m1 * m32; + const c6 = m22 ** 2 + m32 ** 2; + const first = (a3 + c6) / 2; + const second = Math.sqrt(first ** 2 - (a3 * c6 - b4 ** 2)); + output[0] = Math.sqrt(first + second || 1); + output[1] = Math.sqrt(first - second || 1); + } + static normalizeRect(rect) { + const r8 = rect.slice(0); + if (rect[0] > rect[2]) { + r8[0] = rect[2]; + r8[2] = rect[0]; + } + if (rect[1] > rect[3]) { + r8[1] = rect[3]; + r8[3] = rect[1]; + } + return r8; + } + static intersect(rect1, rect2) { + const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2])); + const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2])); + if (xLow > xHigh) { + return null; + } + const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3])); + const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3])); + if (yLow > yHigh) { + return null; + } + return [xLow, yLow, xHigh, yHigh]; + } + static pointBoundingBox(x2, y4, minMax) { + minMax[0] = Math.min(minMax[0], x2); + minMax[1] = Math.min(minMax[1], y4); + minMax[2] = Math.max(minMax[2], x2); + minMax[3] = Math.max(minMax[3], y4); + } + static rectBoundingBox(x0, y0, x1, y1, minMax) { + minMax[0] = Math.min(minMax[0], x0, x1); + minMax[1] = Math.min(minMax[1], y0, y1); + minMax[2] = Math.max(minMax[2], x0, x1); + minMax[3] = Math.max(minMax[3], y0, y1); + } + static #getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, t6, minMax) { + if (t6 <= 0 || t6 >= 1) { + return; + } + const mt = 1 - t6; + const tt = t6 * t6; + const ttt = tt * t6; + const x4 = mt * (mt * (mt * x0 + 3 * t6 * x1) + 3 * tt * x2) + ttt * x3; + const y4 = mt * (mt * (mt * y0 + 3 * t6 * y1) + 3 * tt * y22) + ttt * y32; + minMax[0] = Math.min(minMax[0], x4); + minMax[1] = Math.min(minMax[1], y4); + minMax[2] = Math.max(minMax[2], x4); + minMax[3] = Math.max(minMax[3], y4); + } + static #getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, a3, b4, c6, minMax) { + if (Math.abs(a3) < 1e-12) { + if (Math.abs(b4) >= 1e-12) { + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, -c6 / b4, minMax); + } + return; + } + const delta = b4 ** 2 - 4 * c6 * a3; + if (delta < 0) { + return; + } + const sqrtDelta = Math.sqrt(delta); + const a22 = 2 * a3; + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, (-b4 + sqrtDelta) / a22, minMax); + this.#getExtremumOnCurve(x0, x1, x2, x3, y0, y1, y22, y32, (-b4 - sqrtDelta) / a22, minMax); + } + static bezierBoundingBox(x0, y0, x1, y1, x2, y22, x3, y32, minMax) { + minMax[0] = Math.min(minMax[0], x0, x3); + minMax[1] = Math.min(minMax[1], y0, y32); + minMax[2] = Math.max(minMax[2], x0, x3); + minMax[3] = Math.max(minMax[3], y0, y32); + this.#getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, 3 * (-x0 + 3 * (x1 - x2) + x3), 6 * (x0 - 2 * x1 + x2), 3 * (x1 - x0), minMax); + this.#getExtremum(x0, x1, x2, x3, y0, y1, y22, y32, 3 * (-y0 + 3 * (y1 - y22) + y32), 6 * (y0 - 2 * y1 + y22), 3 * (y1 - y0), minMax); + } + }; + NormalizeRegex = null; + NormalizationMap = null; + AnnotationPrefix = "pdfjs_internal_id_"; + if (typeof Promise.try !== "function") { + Promise.try = function(fn, ...args) { + return new Promise((resolve2) => { + resolve2(fn(...args)); + }); + }; + } + if (typeof Math.sumPrecise !== "function") { + Math.sumPrecise = function(numbers2) { + return numbers2.reduce((a3, b4) => a3 + b4, 0); + }; + } + XfaText = class _XfaText { + static textContent(xfa) { + const items = []; + const output = { + items, + styles: /* @__PURE__ */ Object.create(null) + }; + function walk(node) { + if (!node) { + return; + } + let str2 = null; + const name = node.name; + if (name === "#text") { + str2 = node.value; + } else if (!_XfaText.shouldBuildText(name)) { + return; + } else if (node?.attributes?.textContent) { + str2 = node.attributes.textContent; + } else if (node.value) { + str2 = node.value; + } + if (str2 !== null) { + items.push({ + str: str2 + }); + } + if (!node.children) { + return; + } + for (const child of node.children) { + walk(child); + } + } + walk(xfa); + return output; + } + static shouldBuildText(name) { + return !(name === "textarea" || name === "input" || name === "option" || name === "select"); + } + }; + XfaLayer = class { + static setupStorage(html, id, element, storage2, intent) { + const storedData = storage2.getValue(id, { + value: null + }); + switch (element.name) { + case "textarea": + if (storedData.value !== null) { + html.textContent = storedData.value; + } + if (intent === "print") { + break; + } + html.addEventListener("input", (event) => { + storage2.setValue(id, { + value: event.target.value + }); + }); + break; + case "input": + if (element.attributes.type === "radio" || element.attributes.type === "checkbox") { + if (storedData.value === element.attributes.xfaOn) { + html.setAttribute("checked", true); + } else if (storedData.value === element.attributes.xfaOff) { + html.removeAttribute("checked"); + } + if (intent === "print") { + break; + } + html.addEventListener("change", (event) => { + storage2.setValue(id, { + value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff") + }); + }); + } else { + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + } + if (intent === "print") { + break; + } + html.addEventListener("input", (event) => { + storage2.setValue(id, { + value: event.target.value + }); + }); + } + break; + case "select": + if (storedData.value !== null) { + html.setAttribute("value", storedData.value); + for (const option of element.children) { + if (option.attributes.value === storedData.value) { + option.attributes.selected = true; + } else if (option.attributes.hasOwnProperty("selected")) { + delete option.attributes.selected; + } + } + } + html.addEventListener("input", (event) => { + const options = event.target.options; + const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value; + storage2.setValue(id, { + value + }); + }); + break; + } + } + static setAttributes({ + html, + element, + storage: storage2 = null, + intent, + linkService + }) { + const { + attributes + } = element; + const isHTMLAnchorElement = html instanceof HTMLAnchorElement; + if (attributes.type === "radio") { + attributes.name = `${attributes.name}-${intent}`; + } + for (const [key, value] of Object.entries(attributes)) { + if (value === null || value === void 0) { + continue; + } + switch (key) { + case "class": + if (value.length) { + html.setAttribute(key, value.join(" ")); + } + break; + case "dataId": + break; + case "id": + html.setAttribute("data-element-id", value); + break; + case "style": + Object.assign(html.style, value); + break; + case "textContent": + html.textContent = value; + break; + default: + if (!isHTMLAnchorElement || key !== "href" && key !== "newWindow") { + html.setAttribute(key, value); + } + } + } + if (isHTMLAnchorElement) { + linkService.addLinkAttributes(html, attributes.href, attributes.newWindow); + } + if (storage2 && attributes.dataId) { + this.setupStorage(html, attributes.dataId, element, storage2); + } + } + static render(parameters) { + const storage2 = parameters.annotationStorage; + const linkService = parameters.linkService; + const root = parameters.xfaHtml; + const intent = parameters.intent || "display"; + const rootHtml = document.createElement(root.name); + if (root.attributes) { + this.setAttributes({ + html: rootHtml, + element: root, + intent, + linkService + }); + } + const isNotForRichText = intent !== "richText"; + const rootDiv = parameters.div; + rootDiv.append(rootHtml); + if (parameters.viewport) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + rootDiv.style.transform = transform; + } + if (isNotForRichText) { + rootDiv.setAttribute("class", "xfaLayer xfaFont"); + } + const textDivs = []; + if (root.children.length === 0) { + if (root.value) { + const node = document.createTextNode(root.value); + rootHtml.append(node); + if (isNotForRichText && XfaText.shouldBuildText(root.name)) { + textDivs.push(node); + } + } + return { + textDivs + }; + } + const stack = [[root, -1, rootHtml]]; + while (stack.length > 0) { + const [parent, i7, html] = stack.at(-1); + if (i7 + 1 === parent.children.length) { + stack.pop(); + continue; + } + const child = parent.children[++stack.at(-1)[1]]; + if (child === null) { + continue; + } + const { + name + } = child; + if (name === "#text") { + const node = document.createTextNode(child.value); + textDivs.push(node); + html.append(node); + continue; + } + const childHtml = child?.attributes?.xmlns ? document.createElementNS(child.attributes.xmlns, name) : document.createElement(name); + html.append(childHtml); + if (child.attributes) { + this.setAttributes({ + html: childHtml, + element: child, + storage: storage2, + intent, + linkService + }); + } + if (child.children?.length > 0) { + stack.push([child, -1, childHtml]); + } else if (child.value) { + const node = document.createTextNode(child.value); + if (isNotForRichText && XfaText.shouldBuildText(name)) { + textDivs.push(node); + } + childHtml.append(node); + } + } + for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) { + el.setAttribute("readOnly", true); + } + return { + textDivs + }; + } + static update(parameters) { + const transform = `matrix(${parameters.viewport.transform.join(",")})`; + parameters.div.style.transform = transform; + parameters.div.hidden = false; + } + }; + SVG_NS = "http://www.w3.org/2000/svg"; + PixelsPerInch = class { + static CSS = 96; + static PDF = 72; + static PDF_TO_CSS_UNITS = this.CSS / this.PDF; + }; + PageViewport = class _PageViewport { + constructor({ + viewBox, + userUnit, + scale, + rotation, + offsetX = 0, + offsetY = 0, + dontFlip = false + }) { + this.viewBox = viewBox; + this.userUnit = userUnit; + this.scale = scale; + this.rotation = rotation; + this.offsetX = offsetX; + this.offsetY = offsetY; + scale *= userUnit; + const centerX = (viewBox[2] + viewBox[0]) / 2; + const centerY = (viewBox[3] + viewBox[1]) / 2; + let rotateA, rotateB, rotateC, rotateD; + rotation %= 360; + if (rotation < 0) { + rotation += 360; + } + switch (rotation) { + case 180: + rotateA = -1; + rotateB = 0; + rotateC = 0; + rotateD = 1; + break; + case 90: + rotateA = 0; + rotateB = 1; + rotateC = 1; + rotateD = 0; + break; + case 270: + rotateA = 0; + rotateB = -1; + rotateC = -1; + rotateD = 0; + break; + case 0: + rotateA = 1; + rotateB = 0; + rotateC = 0; + rotateD = -1; + break; + default: + throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees."); + } + if (dontFlip) { + rotateC = -rotateC; + rotateD = -rotateD; + } + let offsetCanvasX, offsetCanvasY; + let width, height; + if (rotateA === 0) { + offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; + offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; + width = (viewBox[3] - viewBox[1]) * scale; + height = (viewBox[2] - viewBox[0]) * scale; + } else { + offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; + offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; + width = (viewBox[2] - viewBox[0]) * scale; + height = (viewBox[3] - viewBox[1]) * scale; + } + this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY]; + this.width = width; + this.height = height; + } + get rawDims() { + const dims = this.viewBox; + return shadow(this, "rawDims", { + pageWidth: dims[2] - dims[0], + pageHeight: dims[3] - dims[1], + pageX: dims[0], + pageY: dims[1] + }); + } + clone({ + scale = this.scale, + rotation = this.rotation, + offsetX = this.offsetX, + offsetY = this.offsetY, + dontFlip = false + } = {}) { + return new _PageViewport({ + viewBox: this.viewBox.slice(), + userUnit: this.userUnit, + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + convertToViewportPoint(x2, y4) { + const p4 = [x2, y4]; + Util.applyTransform(p4, this.transform); + return p4; + } + convertToViewportRectangle(rect) { + const topLeft = [rect[0], rect[1]]; + Util.applyTransform(topLeft, this.transform); + const bottomRight = [rect[2], rect[3]]; + Util.applyTransform(bottomRight, this.transform); + return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; + } + convertToPdfPoint(x2, y4) { + const p4 = [x2, y4]; + Util.applyInverseTransform(p4, this.transform); + return p4; + } + }; + RenderingCancelledException = class extends BaseException { + constructor(msg, extraDelay = 0) { + super(msg, "RenderingCancelledException"); + this.extraDelay = extraDelay; + } + }; + StatTimer = class { + started = /* @__PURE__ */ Object.create(null); + times = []; + time(name) { + if (name in this.started) { + warn(`Timer is already running for ${name}`); + } + this.started[name] = Date.now(); + } + timeEnd(name) { + if (!(name in this.started)) { + warn(`Timer has not been started for ${name}`); + } + this.times.push({ + name, + start: this.started[name], + end: Date.now() + }); + delete this.started[name]; + } + toString() { + const outBuf = []; + let longest = 0; + for (const { + name + } of this.times) { + longest = Math.max(name.length, longest); + } + for (const { + name, + start, + end + } of this.times) { + outBuf.push(`${name.padEnd(longest)} ${end - start}ms +`); + } + return outBuf.join(""); + } + }; + PDFDateString = class { + static #regex; + static toDateObject(input) { + if (input instanceof Date) { + return input; + } + if (!input || typeof input !== "string") { + return null; + } + this.#regex ||= new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"); + const matches = this.#regex.exec(input); + if (!matches) { + return null; + } + const year = parseInt(matches[1], 10); + let month = parseInt(matches[2], 10); + month = month >= 1 && month <= 12 ? month - 1 : 0; + let day = parseInt(matches[3], 10); + day = day >= 1 && day <= 31 ? day : 1; + let hour = parseInt(matches[4], 10); + hour = hour >= 0 && hour <= 23 ? hour : 0; + let minute = parseInt(matches[5], 10); + minute = minute >= 0 && minute <= 59 ? minute : 0; + let second = parseInt(matches[6], 10); + second = second >= 0 && second <= 59 ? second : 0; + const universalTimeRelation = matches[7] || "Z"; + let offsetHour = parseInt(matches[8], 10); + offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; + let offsetMinute = parseInt(matches[9], 10) || 0; + offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; + if (universalTimeRelation === "-") { + hour += offsetHour; + minute += offsetMinute; + } else if (universalTimeRelation === "+") { + hour -= offsetHour; + minute -= offsetMinute; + } + return new Date(Date.UTC(year, month, day, hour, minute, second)); + } + }; + OutputScale = class _OutputScale { + constructor() { + const { + pixelRatio + } = _OutputScale; + this.sx = pixelRatio; + this.sy = pixelRatio; + } + get scaled() { + return this.sx !== 1 || this.sy !== 1; + } + get symmetric() { + return this.sx === this.sy; + } + limitCanvas(width, height, maxPixels, maxDim, capAreaFactor = -1) { + let maxAreaScale = Infinity, maxWidthScale = Infinity, maxHeightScale = Infinity; + maxPixels = _OutputScale.capPixels(maxPixels, capAreaFactor); + if (maxPixels > 0) { + maxAreaScale = Math.sqrt(maxPixels / (width * height)); + } + if (maxDim !== -1) { + maxWidthScale = maxDim / width; + maxHeightScale = maxDim / height; + } + const maxScale = Math.min(maxAreaScale, maxWidthScale, maxHeightScale); + if (this.sx > maxScale || this.sy > maxScale) { + this.sx = maxScale; + this.sy = maxScale; + return true; + } + return false; + } + static get pixelRatio() { + return globalThis.devicePixelRatio || 1; + } + static capPixels(maxPixels, capAreaFactor) { + if (capAreaFactor >= 0) { + const winPixels = Math.ceil(window.screen.availWidth * window.screen.availHeight * this.pixelRatio ** 2 * (1 + capAreaFactor / 100)); + return maxPixels > 0 ? Math.min(maxPixels, winPixels) : winPixels; + } + return maxPixels; + } + }; + SupportedImageMimeTypes = ["image/apng", "image/avif", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/svg+xml", "image/webp", "image/x-icon"]; + ColorScheme = class { + static get isDarkMode() { + return shadow(this, "isDarkMode", !!window?.matchMedia?.("(prefers-color-scheme: dark)").matches); + } + }; + CSSConstants = class { + static get commentForegroundColor() { + const element = document.createElement("span"); + element.classList.add("comment", "sidebar"); + const { + style + } = element; + style.width = style.height = "0"; + style.display = "none"; + style.color = "var(--comment-fg-color)"; + document.body.append(element); + const { + color: color2 + } = window.getComputedStyle(element); + element.remove(); + return shadow(this, "commentForegroundColor", getRGB(color2)); + } + }; + contrastCache = /* @__PURE__ */ new Map(); + EditorToolbar = class _EditorToolbar { + #toolbar = null; + #colorPicker = null; + #editor; + #buttons = null; + #altText = null; + #comment = null; + #commentButtonDivider = null; + #signatureDescriptionButton = null; + static #l10nRemove = null; + constructor(editor) { + this.#editor = editor; + _EditorToolbar.#l10nRemove ||= Object.freeze({ + freetext: "pdfjs-editor-remove-freetext-button", + highlight: "pdfjs-editor-remove-highlight-button", + ink: "pdfjs-editor-remove-ink-button", + stamp: "pdfjs-editor-remove-stamp-button", + signature: "pdfjs-editor-remove-signature-button" + }); + } + render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.classList.add("editToolbar", "hidden"); + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#editor._uiManager._signal; + if (signal instanceof AbortSignal && !signal.aborted) { + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal + }); + editToolbar.addEventListener("pointerdown", _EditorToolbar.#pointerDown, { + signal + }); + } + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + const position = this.#editor.toolbarPosition; + if (position) { + const { + style + } = editToolbar; + const x2 = this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0]; + style.insetInlineEnd = `${100 * x2}%`; + style.top = `calc(${100 * position[1]}% + var(--editor-toolbar-vert-offset))`; + } + return editToolbar; + } + get div() { + return this.#toolbar; + } + static #pointerDown(e9) { + e9.stopPropagation(); + } + #focusIn(e9) { + this.#editor._focusEventsAllowed = false; + stopEvent(e9); + } + #focusOut(e9) { + this.#editor._focusEventsAllowed = true; + stopEvent(e9); + } + #addListenersToElement(element) { + const signal = this.#editor._uiManager._signal; + if (!(signal instanceof AbortSignal) || signal.aborted) { + return false; + } + element.addEventListener("focusin", this.#focusIn.bind(this), { + capture: true, + signal + }); + element.addEventListener("focusout", this.#focusOut.bind(this), { + capture: true, + signal + }); + element.addEventListener("contextmenu", noContextMenu, { + signal + }); + return true; + } + hide() { + this.#toolbar.classList.add("hidden"); + this.#colorPicker?.hideDropdown(); + } + show() { + this.#toolbar.classList.remove("hidden"); + this.#altText?.shown(); + this.#comment?.shown(); + } + addDeleteButton() { + const { + editorType, + _uiManager + } = this.#editor; + const button = document.createElement("button"); + button.classList.add("basic", "deleteButton"); + button.tabIndex = 0; + button.setAttribute("data-l10n-id", _EditorToolbar.#l10nRemove[editorType]); + if (this.#addListenersToElement(button)) { + button.addEventListener("click", (e9) => { + _uiManager.delete(); + }, { + signal: _uiManager._signal + }); + } + this.#buttons.append(button); + } + get #divider() { + const divider = document.createElement("div"); + divider.className = "divider"; + return divider; + } + async addAltText(altText) { + const button = await altText.render(); + this.#addListenersToElement(button); + this.#buttons.append(button, this.#divider); + this.#altText = altText; + } + addComment(comment, beforeElement = null) { + if (this.#comment) { + return; + } + const button = comment.renderForToolbar(); + if (!button) { + return; + } + this.#addListenersToElement(button); + const divider = this.#commentButtonDivider = this.#divider; + if (!beforeElement) { + this.#buttons.append(button, divider); + } else { + this.#buttons.insertBefore(button, beforeElement); + this.#buttons.insertBefore(divider, beforeElement); + } + this.#comment = comment; + comment.toolbar = this; + } + addColorPicker(colorPicker) { + if (this.#colorPicker) { + return; + } + this.#colorPicker = colorPicker; + const button = colorPicker.renderButton(); + this.#addListenersToElement(button); + this.#buttons.append(button, this.#divider); + } + async addEditSignatureButton(signatureManager) { + const button = this.#signatureDescriptionButton = await signatureManager.renderEditButton(this.#editor); + this.#addListenersToElement(button); + this.#buttons.append(button, this.#divider); + } + removeButton(name) { + switch (name) { + case "comment": + this.#comment?.removeToolbarCommentButton(); + this.#comment = null; + this.#commentButtonDivider?.remove(); + this.#commentButtonDivider = null; + break; + } + } + async addButton(name, tool) { + switch (name) { + case "colorPicker": + if (tool) { + this.addColorPicker(tool); + } + break; + case "altText": + if (tool) { + await this.addAltText(tool); + } + break; + case "editSignature": + if (tool) { + await this.addEditSignatureButton(tool); + } + break; + case "delete": + this.addDeleteButton(); + break; + case "comment": + if (tool) { + this.addComment(tool); + } + break; + } + } + async addButtonBefore(name, tool, beforeSelector) { + if (!tool && name === "comment") { + return; + } + const beforeElement = this.#buttons.querySelector(beforeSelector); + if (!beforeElement) { + return; + } + if (name === "comment") { + this.addComment(tool, beforeElement); + } + } + updateEditSignatureButton(description) { + if (this.#signatureDescriptionButton) { + this.#signatureDescriptionButton.title = description; + } + } + remove() { + this.#toolbar.remove(); + this.#colorPicker?.destroy(); + this.#colorPicker = null; + } + }; + FloatingToolbar = class { + #buttons = null; + #toolbar = null; + #uiManager; + constructor(uiManager) { + this.#uiManager = uiManager; + } + #render() { + const editToolbar = this.#toolbar = document.createElement("div"); + editToolbar.className = "editToolbar"; + editToolbar.setAttribute("role", "toolbar"); + const signal = this.#uiManager._signal; + if (signal instanceof AbortSignal && !signal.aborted) { + editToolbar.addEventListener("contextmenu", noContextMenu, { + signal + }); + } + const buttons = this.#buttons = document.createElement("div"); + buttons.className = "buttons"; + editToolbar.append(buttons); + if (this.#uiManager.hasCommentManager()) { + this.#makeButton("commentButton", `pdfjs-comment-floating-button`, "pdfjs-comment-floating-button-label", () => { + this.#uiManager.commentSelection("floating_button"); + }); + } + this.#makeButton("highlightButton", `pdfjs-highlight-floating-button1`, "pdfjs-highlight-floating-button-label", () => { + this.#uiManager.highlightSelection("floating_button"); + }); + return editToolbar; + } + #getLastPoint(boxes, isLTR) { + let lastY = 0; + let lastX = 0; + for (const box of boxes) { + const y4 = box.y + box.height; + if (y4 < lastY) { + continue; + } + const x2 = box.x + (isLTR ? box.width : 0); + if (y4 > lastY) { + lastX = x2; + lastY = y4; + continue; + } + if (isLTR) { + if (x2 > lastX) { + lastX = x2; + } + } else if (x2 < lastX) { + lastX = x2; + } + } + return [isLTR ? 1 - lastX : lastX, lastY]; + } + show(parent, boxes, isLTR) { + const [x2, y4] = this.#getLastPoint(boxes, isLTR); + const { + style + } = this.#toolbar ||= this.#render(); + parent.append(this.#toolbar); + style.insetInlineEnd = `${100 * x2}%`; + style.top = `calc(${100 * y4}% + var(--editor-toolbar-vert-offset))`; + } + hide() { + this.#toolbar.remove(); + } + #makeButton(buttonClass, l10nId, labelL10nId, clickHandler) { + const button = document.createElement("button"); + button.classList.add("basic", buttonClass); + button.tabIndex = 0; + button.setAttribute("data-l10n-id", l10nId); + const span = document.createElement("span"); + button.append(span); + span.className = "visuallyHidden"; + span.setAttribute("data-l10n-id", labelL10nId); + const signal = this.#uiManager._signal; + if (signal instanceof AbortSignal && !signal.aborted) { + button.addEventListener("contextmenu", noContextMenu, { + signal + }); + button.addEventListener("click", clickHandler, { + signal + }); + } + this.#buttons.append(button); + } + }; + CurrentPointers = class _CurrentPointers { + static #pointerId = NaN; + static #pointerIds = null; + static #moveTimestamp = NaN; + static #pointerType = null; + static initializeAndAddPointerId(pointerId) { + (_CurrentPointers.#pointerIds ||= /* @__PURE__ */ new Set()).add(pointerId); + } + static setPointer(pointerType, pointerId) { + _CurrentPointers.#pointerId ||= pointerId; + _CurrentPointers.#pointerType ??= pointerType; + } + static setTimeStamp(timeStamp) { + _CurrentPointers.#moveTimestamp = timeStamp; + } + static isSamePointerId(pointerId) { + return _CurrentPointers.#pointerId === pointerId; + } + static isSamePointerIdOrRemove(pointerId) { + if (_CurrentPointers.#pointerId === pointerId) { + return true; + } + _CurrentPointers.#pointerIds?.delete(pointerId); + return false; + } + static isSamePointerType(pointerType) { + return _CurrentPointers.#pointerType === pointerType; + } + static isInitializedAndDifferentPointerType(pointerType) { + return _CurrentPointers.#pointerType !== null && !_CurrentPointers.isSamePointerType(pointerType); + } + static isSameTimeStamp(timeStamp) { + return _CurrentPointers.#moveTimestamp === timeStamp; + } + static isUsingMultiplePointers() { + return _CurrentPointers.#pointerIds?.size >= 1; + } + static clearPointerType() { + _CurrentPointers.#pointerType = null; + } + static clearPointerIds() { + _CurrentPointers.#pointerId = NaN; + _CurrentPointers.#pointerIds = null; + } + static clearTimeStamp() { + _CurrentPointers.#moveTimestamp = NaN; + } + }; + IdManager = class { + #id = 0; + get id() { + return `${AnnotationEditorPrefix}${this.#id++}`; + } + }; + ImageManager = class _ImageManager { + #baseId = getUuid(); + #id = 0; + #cache = null; + static get _isSVGFittingCanvas() { + const svg = `data:image/svg+xml;charset=UTF-8,`; + const canvas = new OffscreenCanvas(1, 3); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); + const image = new Image(); + image.src = svg; + const promise = image.decode().then(() => { + ctx.drawImage(image, 0, 0, 1, 1, 0, 0, 1, 3); + return new Uint32Array(ctx.getImageData(0, 0, 1, 1).data.buffer)[0] === 0; + }); + return shadow(this, "_isSVGFittingCanvas", promise); + } + async #get(key, rawData) { + this.#cache ||= /* @__PURE__ */ new Map(); + let data = this.#cache.get(key); + if (data === null) { + return null; + } + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + try { + data ||= { + bitmap: null, + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 0, + isSvg: false + }; + let image; + if (typeof rawData === "string") { + data.url = rawData; + image = await fetchData(rawData, "blob"); + } else if (rawData instanceof File) { + image = data.file = rawData; + } else if (rawData instanceof Blob) { + image = rawData; + } + if (image.type === "image/svg+xml") { + const mustRemoveAspectRatioPromise = _ImageManager._isSVGFittingCanvas; + const fileReader = new FileReader(); + const imageElement = new Image(); + const imagePromise = new Promise((resolve2, reject) => { + imageElement.onload = () => { + data.bitmap = imageElement; + data.isSvg = true; + resolve2(); + }; + fileReader.onload = async () => { + const url = data.svgUrl = fileReader.result; + imageElement.src = await mustRemoveAspectRatioPromise ? `${url}#svgView(preserveAspectRatio(none))` : url; + }; + imageElement.onerror = fileReader.onerror = reject; + }); + fileReader.readAsDataURL(image); + await imagePromise; + } else { + data.bitmap = await createImageBitmap(image); + } + data.refCounter = 1; + } catch (e9) { + warn(e9); + data = null; + } + this.#cache.set(key, data); + if (data) { + this.#cache.set(data.id, data); + } + return data; + } + async getFromFile(file) { + const { + lastModified, + name, + size, + type + } = file; + return this.#get(`${lastModified}_${name}_${size}_${type}`, file); + } + async getFromUrl(url) { + return this.#get(url, url); + } + async getFromBlob(id, blobPromise) { + const blob = await blobPromise; + return this.#get(id, blob); + } + async getFromId(id) { + this.#cache ||= /* @__PURE__ */ new Map(); + const data = this.#cache.get(id); + if (!data) { + return null; + } + if (data.bitmap) { + data.refCounter += 1; + return data; + } + if (data.file) { + return this.getFromFile(data.file); + } + if (data.blobPromise) { + const { + blobPromise + } = data; + delete data.blobPromise; + return this.getFromBlob(data.id, blobPromise); + } + return this.getFromUrl(data.url); + } + getFromCanvas(id, canvas) { + this.#cache ||= /* @__PURE__ */ new Map(); + let data = this.#cache.get(id); + if (data?.bitmap) { + data.refCounter += 1; + return data; + } + const offscreen = new OffscreenCanvas(canvas.width, canvas.height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(canvas, 0, 0); + data = { + bitmap: offscreen.transferToImageBitmap(), + id: `image_${this.#baseId}_${this.#id++}`, + refCounter: 1, + isSvg: false + }; + this.#cache.set(id, data); + this.#cache.set(data.id, data); + return data; + } + getSvgUrl(id) { + const data = this.#cache.get(id); + if (!data?.isSvg) { + return null; + } + return data.svgUrl; + } + deleteId(id) { + this.#cache ||= /* @__PURE__ */ new Map(); + const data = this.#cache.get(id); + if (!data) { + return; + } + data.refCounter -= 1; + if (data.refCounter !== 0) { + return; + } + const { + bitmap + } = data; + if (!data.url && !data.file) { + const canvas = new OffscreenCanvas(bitmap.width, bitmap.height); + const ctx = canvas.getContext("bitmaprenderer"); + ctx.transferFromImageBitmap(bitmap); + data.blobPromise = canvas.convertToBlob(); + } + bitmap.close?.(); + data.bitmap = null; + } + isValidId(id) { + return id.startsWith(`image_${this.#baseId}_`); + } + }; + CommandManager = class { + #commands = []; + #locked = false; + #maxSize; + #position = -1; + constructor(maxSize = 128) { + this.#maxSize = maxSize; + } + add({ + cmd, + undo, + post: post2, + mustExec, + type = NaN, + overwriteIfSameType = false, + keepUndo = false + }) { + if (mustExec) { + cmd(); + } + if (this.#locked) { + return; + } + const save = { + cmd, + undo, + post: post2, + type + }; + if (this.#position === -1) { + if (this.#commands.length > 0) { + this.#commands.length = 0; + } + this.#position = 0; + this.#commands.push(save); + return; + } + if (overwriteIfSameType && this.#commands[this.#position].type === type) { + if (keepUndo) { + save.undo = this.#commands[this.#position].undo; + } + this.#commands[this.#position] = save; + return; + } + const next = this.#position + 1; + if (next === this.#maxSize) { + this.#commands.splice(0, 1); + } else { + this.#position = next; + if (next < this.#commands.length) { + this.#commands.splice(next); + } + } + this.#commands.push(save); + } + undo() { + if (this.#position === -1) { + return; + } + this.#locked = true; + const { + undo, + post: post2 + } = this.#commands[this.#position]; + undo(); + post2?.(); + this.#locked = false; + this.#position -= 1; + } + redo() { + if (this.#position < this.#commands.length - 1) { + this.#position += 1; + this.#locked = true; + const { + cmd, + post: post2 + } = this.#commands[this.#position]; + cmd(); + post2?.(); + this.#locked = false; + } + } + hasSomethingToUndo() { + return this.#position !== -1; + } + hasSomethingToRedo() { + return this.#position < this.#commands.length - 1; + } + cleanType(type) { + if (this.#position === -1) { + return; + } + for (let i7 = this.#position; i7 >= 0; i7--) { + if (this.#commands[i7].type !== type) { + this.#commands.splice(i7 + 1, this.#position - i7); + this.#position = i7; + return; + } + } + this.#commands.length = 0; + this.#position = -1; + } + destroy() { + this.#commands = null; + } + }; + KeyboardManager = class { + constructor(callbacks) { + this.buffer = []; + this.callbacks = /* @__PURE__ */ new Map(); + this.allKeys = /* @__PURE__ */ new Set(); + const { + isMac + } = util_FeatureTest.platform; + for (const [keys2, callback2, options = {}] of callbacks) { + for (const key of keys2) { + const isMacKey = key.startsWith("mac+"); + if (isMac && isMacKey) { + this.callbacks.set(key.slice(4), { + callback: callback2, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } else if (!isMac && !isMacKey) { + this.callbacks.set(key, { + callback: callback2, + options + }); + this.allKeys.add(key.split("+").at(-1)); + } + } + } + } + #serialize(event) { + if (event.altKey) { + this.buffer.push("alt"); + } + if (event.ctrlKey) { + this.buffer.push("ctrl"); + } + if (event.metaKey) { + this.buffer.push("meta"); + } + if (event.shiftKey) { + this.buffer.push("shift"); + } + this.buffer.push(event.key); + const str2 = this.buffer.join("+"); + this.buffer.length = 0; + return str2; + } + exec(self2, event) { + if (!this.allKeys.has(event.key)) { + return; + } + const info2 = this.callbacks.get(this.#serialize(event)); + if (!info2) { + return; + } + const { + callback: callback2, + options: { + bubbles = false, + args = [], + checker = null + } + } = info2; + if (checker && !checker(self2, event)) { + return; + } + callback2.bind(self2, ...args, event)(); + if (!bubbles) { + stopEvent(event); + } + } + }; + ColorManager = class _ColorManager { + static _colorsMapping = /* @__PURE__ */ new Map([["CanvasText", [0, 0, 0]], ["Canvas", [255, 255, 255]]]); + get _colors() { + const colors2 = /* @__PURE__ */ new Map([["CanvasText", null], ["Canvas", null]]); + getColorValues(colors2); + return shadow(this, "_colors", colors2); + } + convert(color2) { + const rgb = getRGB(color2); + if (!window.matchMedia("(forced-colors: active)").matches) { + return rgb; + } + for (const [name, RGB] of this._colors) { + if (RGB.every((x2, i7) => x2 === rgb[i7])) { + return _ColorManager._colorsMapping.get(name); + } + } + return rgb; + } + getHexCode(name) { + const rgb = this._colors.get(name); + if (!rgb) { + return name; + } + return Util.makeHexColor(...rgb); + } + }; + AnnotationEditorUIManager = class _AnnotationEditorUIManager { + #abortController = new AbortController(); + #activeEditor = null; + #allEditableAnnotations = null; + #allEditors = /* @__PURE__ */ new Map(); + #allLayers = /* @__PURE__ */ new Map(); + #altTextManager = null; + #annotationStorage = null; + #changedExistingAnnotations = null; + #commandManager = new CommandManager(); + #commentManager = null; + #copyPasteAC = null; + #currentDrawingSession = null; + #currentPageIndex = 0; + #deletedAnnotationsElementIds = /* @__PURE__ */ new Set(); + #draggingEditors = null; + #editorTypes = null; + #editorsToRescale = /* @__PURE__ */ new Set(); + _editorUndoBar = null; + #enableHighlightFloatingButton = false; + #enableUpdatedAddImage = false; + #enableNewAltTextWhenAddingImage = false; + #filterFactory = null; + #focusMainContainerTimeoutId = null; + #focusManagerAC = null; + #highlightColors = null; + #highlightWhenShiftUp = false; + #floatingToolbar = null; + #idManager = new IdManager(); + #isEnabled = false; + #isPointerDown = false; + #isWaiting = false; + #keyboardManagerAC = null; + #lastActiveElement = null; + #mainHighlightColorPicker = null; + #missingCanvases = null; + #mlManager = null; + #mode = AnnotationEditorType.NONE; + #selectedEditors = /* @__PURE__ */ new Set(); + #selectedTextNode = null; + #signatureManager = null; + #pageColors = null; + #showAllStates = null; + #pdfDocument = null; + #previousStates = { + isEditing: false, + isEmpty: true, + hasSomethingToUndo: false, + hasSomethingToRedo: false, + hasSelectedEditor: false, + hasSelectedText: false + }; + #translation = [0, 0]; + #translationTimeoutId = null; + #container = null; + #viewer = null; + #viewerAlert = null; + #updateModeCapability = null; + static TRANSLATE_SMALL = 1; + static TRANSLATE_BIG = 10; + static get _keyboardManager() { + const proto = _AnnotationEditorUIManager.prototype; + const arrowChecker = (self2) => self2.#container.contains(document.activeElement) && document.activeElement.tagName !== "BUTTON" && self2.hasSomethingToControl(); + const textInputChecker = (_self, { + target: el + }) => { + if (el instanceof HTMLInputElement) { + const { + type + } = el; + return type !== "text" && type !== "number"; + } + return true; + }; + const small = this.TRANSLATE_SMALL; + const big = this.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+a", "mac+meta+a"], proto.selectAll, { + checker: textInputChecker + }], [["ctrl+z", "mac+meta+z"], proto.undo, { + checker: textInputChecker + }], [["ctrl+y", "ctrl+shift+z", "mac+meta+shift+z", "ctrl+shift+Z", "mac+meta+shift+Z"], proto.redo, { + checker: textInputChecker + }], [["Backspace", "alt+Backspace", "ctrl+Backspace", "shift+Backspace", "mac+Backspace", "mac+alt+Backspace", "mac+ctrl+Backspace", "Delete", "ctrl+Delete", "shift+Delete", "mac+Delete"], proto.delete, { + checker: textInputChecker + }], [["Enter", "mac+Enter"], proto.addNewEditorFromKeyboard, { + checker: (self2, { + target: el + }) => !(el instanceof HTMLButtonElement) && self2.#container.contains(el) && !self2.isEnterHandled + }], [[" ", "mac+ "], proto.addNewEditorFromKeyboard, { + checker: (self2, { + target: el + }) => !(el instanceof HTMLButtonElement) && self2.#container.contains(document.activeElement) + }], [["Escape", "mac+Escape"], proto.unselectAll], [["ArrowLeft", "mac+ArrowLeft"], proto.translateSelectedEditors, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto.translateSelectedEditors, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto.translateSelectedEditors, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto.translateSelectedEditors, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto.translateSelectedEditors, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto.translateSelectedEditors, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto.translateSelectedEditors, { + args: [0, big], + checker: arrowChecker + }]])); + } + constructor(container, viewer, viewerAlert, altTextManager, commentManager, signatureManager, eventBus, pdfDocument, pageColors, highlightColors, enableHighlightFloatingButton, enableUpdatedAddImage, enableNewAltTextWhenAddingImage, mlManager, editorUndoBar, supportsPinchToZoom) { + const signal = this._signal = this.#abortController.signal; + this.#container = container; + this.#viewer = viewer; + this.#viewerAlert = viewerAlert; + this.#altTextManager = altTextManager; + this.#commentManager = commentManager; + this.#signatureManager = signatureManager; + this.#pdfDocument = pdfDocument; + this._eventBus = eventBus; + eventBus._on("editingaction", this.onEditingAction.bind(this), { + signal + }); + eventBus._on("pagechanging", this.onPageChanging.bind(this), { + signal + }); + eventBus._on("scalechanging", this.onScaleChanging.bind(this), { + signal + }); + eventBus._on("rotationchanging", this.onRotationChanging.bind(this), { + signal + }); + eventBus._on("setpreference", this.onSetPreference.bind(this), { + signal + }); + eventBus._on("switchannotationeditorparams", (evt) => this.updateParams(evt.type, evt.value), { + signal + }); + window.addEventListener("pointerdown", () => { + this.#isPointerDown = true; + }, { + capture: true, + signal + }); + window.addEventListener("pointerup", () => { + this.#isPointerDown = false; + }, { + capture: true, + signal + }); + this.#addSelectionListener(); + this.#addDragAndDropListeners(); + this.#addKeyboardManager(); + this.#annotationStorage = pdfDocument.annotationStorage; + this.#filterFactory = pdfDocument.filterFactory; + this.#pageColors = pageColors; + this.#highlightColors = highlightColors || null; + this.#enableHighlightFloatingButton = enableHighlightFloatingButton; + this.#enableUpdatedAddImage = enableUpdatedAddImage; + this.#enableNewAltTextWhenAddingImage = enableNewAltTextWhenAddingImage; + this.#mlManager = mlManager || null; + this.viewParameters = { + realScale: PixelsPerInch.PDF_TO_CSS_UNITS, + rotation: 0 + }; + this.isShiftKeyDown = false; + this._editorUndoBar = editorUndoBar || null; + this._supportsPinchToZoom = supportsPinchToZoom !== false; + commentManager?.setSidebarUiManager(this); + } + destroy() { + this.#updateModeCapability?.resolve(); + this.#updateModeCapability = null; + this.#abortController?.abort(); + this.#abortController = null; + this._signal = null; + for (const layer of this.#allLayers.values()) { + layer.destroy(); + } + this.#allLayers.clear(); + this.#allEditors.clear(); + this.#editorsToRescale.clear(); + this.#missingCanvases?.clear(); + this.#activeEditor = null; + this.#selectedEditors.clear(); + this.#commandManager.destroy(); + this.#altTextManager?.destroy(); + this.#commentManager?.destroy(); + this.#signatureManager?.destroy(); + this.#floatingToolbar?.hide(); + this.#floatingToolbar = null; + this.#mainHighlightColorPicker?.destroy(); + this.#mainHighlightColorPicker = null; + this.#allEditableAnnotations = null; + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + this.#focusMainContainerTimeoutId = null; + } + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + this.#translationTimeoutId = null; + } + this._editorUndoBar?.destroy(); + this.#pdfDocument = null; + } + combinedSignal(ac) { + return AbortSignal.any([this._signal, ac.signal]); + } + get mlManager() { + return this.#mlManager; + } + get useNewAltTextFlow() { + return this.#enableUpdatedAddImage; + } + get useNewAltTextWhenAddingImage() { + return this.#enableNewAltTextWhenAddingImage; + } + get hcmFilter() { + return shadow(this, "hcmFilter", this.#pageColors ? this.#filterFactory.addHCMFilter(this.#pageColors.foreground, this.#pageColors.background) : "none"); + } + get direction() { + return shadow(this, "direction", getComputedStyle(this.#container).direction); + } + get _highlightColors() { + return shadow(this, "_highlightColors", this.#highlightColors ? new Map(this.#highlightColors.split(",").map((pair) => { + pair = pair.split("=").map((x2) => x2.trim()); + pair[1] = pair[1].toUpperCase(); + return pair; + })) : null); + } + get highlightColors() { + const { + _highlightColors + } = this; + if (!_highlightColors) { + return shadow(this, "highlightColors", null); + } + const map3 = /* @__PURE__ */ new Map(); + const hasHCM = !!this.#pageColors; + for (const [name, color2] of _highlightColors) { + const isNameForHCM = name.endsWith("_HCM"); + if (hasHCM && isNameForHCM) { + map3.set(name.replace("_HCM", ""), color2); + continue; + } + if (!hasHCM && !isNameForHCM) { + map3.set(name, color2); + } + } + return shadow(this, "highlightColors", map3); + } + get highlightColorNames() { + return shadow(this, "highlightColorNames", this.highlightColors ? new Map(Array.from(this.highlightColors, (e9) => e9.reverse())) : null); + } + getNonHCMColor(color2) { + if (!this._highlightColors) { + return color2; + } + const colorName2 = this.highlightColorNames.get(color2); + return this._highlightColors.get(colorName2) || color2; + } + getNonHCMColorName(color2) { + return this.highlightColorNames.get(color2) || color2; + } + setCurrentDrawingSession(layer) { + if (layer) { + this.unselectAll(); + this.disableUserSelect(true); + } else { + this.disableUserSelect(false); + } + this.#currentDrawingSession = layer; + } + setMainHighlightColorPicker(colorPicker) { + this.#mainHighlightColorPicker = colorPicker; + } + editAltText(editor, firstTime = false) { + this.#altTextManager?.editAltText(this, editor, firstTime); + } + hasCommentManager() { + return !!this.#commentManager; + } + editComment(editor, posX, posY, options) { + this.#commentManager?.showDialog(this, editor, posX, posY, options); + } + selectComment(pageIndex, uid2) { + const layer = this.#allLayers.get(pageIndex); + const editor = layer?.getEditorByUID(uid2); + editor?.toggleComment(true, true); + } + updateComment(editor) { + this.#commentManager?.updateComment(editor.getData()); + } + updatePopupColor(editor) { + this.#commentManager?.updatePopupColor(editor); + } + removeComment(editor) { + this.#commentManager?.removeComments([editor.uid]); + } + toggleComment(editor, isSelected, visibility = void 0) { + this.#commentManager?.toggleCommentPopup(editor, isSelected, visibility); + } + makeCommentColor(color2, opacity) { + return color2 && this.#commentManager?.makeCommentColor(color2, opacity) || null; + } + getCommentDialogElement() { + return this.#commentManager?.dialogElement || null; + } + async waitForEditorsRendered(pageNumber) { + if (this.#allLayers.has(pageNumber - 1)) { + return; + } + const { + resolve: resolve2, + promise + } = Promise.withResolvers(); + const onEditorsRendered = (evt) => { + if (evt.pageNumber === pageNumber) { + this._eventBus._off("editorsrendered", onEditorsRendered); + resolve2(); + } + }; + this._eventBus.on("editorsrendered", onEditorsRendered); + await promise; + } + getSignature(editor) { + this.#signatureManager?.getSignature({ + uiManager: this, + editor + }); + } + get signatureManager() { + return this.#signatureManager; + } + switchToMode(mode, callback2) { + this._eventBus.on("annotationeditormodechanged", callback2, { + once: true, + signal: this._signal + }); + this._eventBus.dispatch("showannotationeditorui", { + source: this, + mode + }); + } + setPreference(name, value) { + this._eventBus.dispatch("setpreference", { + source: this, + name, + value + }); + } + onSetPreference({ + name, + value + }) { + switch (name) { + case "enableNewAltTextWhenAddingImage": + this.#enableNewAltTextWhenAddingImage = value; + break; + } + } + onPageChanging({ + pageNumber + }) { + this.#currentPageIndex = pageNumber - 1; + } + focusMainContainer() { + this.#container.focus(); + } + findParent(x2, y4) { + for (const layer of this.#allLayers.values()) { + const { + x: layerX, + y: layerY, + width, + height + } = layer.div.getBoundingClientRect(); + if (x2 >= layerX && x2 <= layerX + width && y4 >= layerY && y4 <= layerY + height) { + return layer; + } + } + return null; + } + disableUserSelect(value = false) { + this.#viewer.classList.toggle("noUserSelect", value); + } + addShouldRescale(editor) { + this.#editorsToRescale.add(editor); + } + removeShouldRescale(editor) { + this.#editorsToRescale.delete(editor); + } + onScaleChanging({ + scale + }) { + this.commitOrRemove(); + this.viewParameters.realScale = scale * PixelsPerInch.PDF_TO_CSS_UNITS; + for (const editor of this.#editorsToRescale) { + editor.onScaleChanging(); + } + this.#currentDrawingSession?.onScaleChanging(); + } + onRotationChanging({ + pagesRotation + }) { + this.commitOrRemove(); + this.viewParameters.rotation = pagesRotation; + } + #getAnchorElementForSelection({ + anchorNode + }) { + return anchorNode.nodeType === Node.TEXT_NODE ? anchorNode.parentElement : anchorNode; + } + #getLayerForTextLayer(textLayer) { + const { + currentLayer + } = this; + if (currentLayer.hasTextLayer(textLayer)) { + return currentLayer; + } + for (const layer of this.#allLayers.values()) { + if (layer.hasTextLayer(textLayer)) { + return layer; + } + } + return null; + } + highlightSelection(methodOfCreation = "", comment = false) { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const { + anchorNode, + anchorOffset, + focusNode, + focusOffset + } = selection; + const text3 = selection.toString(); + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + selection.empty(); + const layer = this.#getLayerForTextLayer(textLayer); + const isNoneMode = this.#mode === AnnotationEditorType.NONE; + const callback2 = () => { + const editor = layer?.createAndAddNewEditor({ + x: 0, + y: 0 + }, false, { + methodOfCreation, + boxes, + anchorNode, + anchorOffset, + focusNode, + focusOffset, + text: text3 + }); + if (isNoneMode) { + this.showAllEditors("highlight", true, true); + } + if (comment) { + editor?.editComment(); + } + }; + if (isNoneMode) { + this.switchToMode(AnnotationEditorType.HIGHLIGHT, callback2); + return; + } + callback2(); + } + commentSelection(methodOfCreation = "") { + this.highlightSelection(methodOfCreation, true); + } + #displayFloatingToolbar() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + const boxes = this.getSelectionBoxes(textLayer); + if (!boxes) { + return; + } + this.#floatingToolbar ||= new FloatingToolbar(this); + this.#floatingToolbar.show(textLayer, boxes, this.direction === "ltr"); + } + getAndRemoveDataFromAnnotationStorage(annotationId) { + if (!this.#annotationStorage) { + return null; + } + const key = `${AnnotationEditorPrefix}${annotationId}`; + const storedValue = this.#annotationStorage.getRawValue(key); + if (storedValue) { + this.#annotationStorage.remove(key); + } + return storedValue; + } + addToAnnotationStorage(editor) { + if (!editor.isEmpty() && this.#annotationStorage && !this.#annotationStorage.has(editor.id)) { + this.#annotationStorage.setValue(editor.id, editor); + } + } + a11yAlert(messageId, args = null) { + const viewerAlert = this.#viewerAlert; + if (!viewerAlert) { + return; + } + viewerAlert.setAttribute("data-l10n-id", messageId); + if (args) { + viewerAlert.setAttribute("data-l10n-args", JSON.stringify(args)); + } else { + viewerAlert.removeAttribute("data-l10n-args"); + } + } + #selectionChange() { + const selection = document.getSelection(); + if (!selection || selection.isCollapsed) { + if (this.#selectedTextNode) { + this.#floatingToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + const { + anchorNode + } = selection; + if (anchorNode === this.#selectedTextNode) { + return; + } + const anchorElement = this.#getAnchorElementForSelection(selection); + const textLayer = anchorElement.closest(".textLayer"); + if (!textLayer) { + if (this.#selectedTextNode) { + this.#floatingToolbar?.hide(); + this.#selectedTextNode = null; + this.#dispatchUpdateStates({ + hasSelectedText: false + }); + } + return; + } + this.#floatingToolbar?.hide(); + this.#selectedTextNode = anchorNode; + this.#dispatchUpdateStates({ + hasSelectedText: true + }); + if (this.#mode !== AnnotationEditorType.HIGHLIGHT && this.#mode !== AnnotationEditorType.NONE) { + return; + } + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.showAllEditors("highlight", true, true); + } + this.#highlightWhenShiftUp = this.isShiftKeyDown; + if (!this.isShiftKeyDown) { + const activeLayer = this.#mode === AnnotationEditorType.HIGHLIGHT ? this.#getLayerForTextLayer(textLayer) : null; + activeLayer?.toggleDrawing(); + if (this.#isPointerDown) { + const ac = new AbortController(); + const signal = this.combinedSignal(ac); + const pointerup = (e9) => { + if (e9.type === "pointerup" && e9.button !== 0) { + return; + } + ac.abort(); + activeLayer?.toggleDrawing(true); + if (e9.type === "pointerup") { + this.#onSelectEnd("main_toolbar"); + } + }; + window.addEventListener("pointerup", pointerup, { + signal + }); + window.addEventListener("blur", pointerup, { + signal + }); + } else { + activeLayer?.toggleDrawing(true); + this.#onSelectEnd("main_toolbar"); + } + } + } + #onSelectEnd(methodOfCreation = "") { + if (this.#mode === AnnotationEditorType.HIGHLIGHT) { + this.highlightSelection(methodOfCreation); + } else if (this.#enableHighlightFloatingButton) { + this.#displayFloatingToolbar(); + } + } + #addSelectionListener() { + document.addEventListener("selectionchange", this.#selectionChange.bind(this), { + signal: this._signal + }); + } + #addFocusManager() { + if (this.#focusManagerAC) { + return; + } + this.#focusManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#focusManagerAC); + window.addEventListener("focus", this.focus.bind(this), { + signal + }); + window.addEventListener("blur", this.blur.bind(this), { + signal + }); + } + #removeFocusManager() { + this.#focusManagerAC?.abort(); + this.#focusManagerAC = null; + } + blur() { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + if (!this.hasSelection) { + return; + } + const { + activeElement + } = document; + for (const editor of this.#selectedEditors) { + if (editor.div.contains(activeElement)) { + this.#lastActiveElement = [editor, activeElement]; + editor._focusEventsAllowed = false; + break; + } + } + } + focus() { + if (!this.#lastActiveElement) { + return; + } + const [lastEditor, lastActiveElement] = this.#lastActiveElement; + this.#lastActiveElement = null; + lastActiveElement.addEventListener("focusin", () => { + lastEditor._focusEventsAllowed = true; + }, { + once: true, + signal: this._signal + }); + lastActiveElement.focus(); + } + #addKeyboardManager() { + if (this.#keyboardManagerAC) { + return; + } + this.#keyboardManagerAC = new AbortController(); + const signal = this.combinedSignal(this.#keyboardManagerAC); + window.addEventListener("keydown", this.keydown.bind(this), { + signal + }); + window.addEventListener("keyup", this.keyup.bind(this), { + signal + }); + } + #removeKeyboardManager() { + this.#keyboardManagerAC?.abort(); + this.#keyboardManagerAC = null; + } + #addCopyPasteListeners() { + if (this.#copyPasteAC) { + return; + } + this.#copyPasteAC = new AbortController(); + const signal = this.combinedSignal(this.#copyPasteAC); + document.addEventListener("copy", this.copy.bind(this), { + signal + }); + document.addEventListener("cut", this.cut.bind(this), { + signal + }); + document.addEventListener("paste", this.paste.bind(this), { + signal + }); + } + #removeCopyPasteListeners() { + this.#copyPasteAC?.abort(); + this.#copyPasteAC = null; + } + #addDragAndDropListeners() { + const signal = this._signal; + document.addEventListener("dragover", this.dragOver.bind(this), { + signal + }); + document.addEventListener("drop", this.drop.bind(this), { + signal + }); + } + addEditListeners() { + this.#addKeyboardManager(); + this.setEditingState(true); + } + removeEditListeners() { + this.#removeKeyboardManager(); + this.setEditingState(false); + } + dragOver(event) { + for (const { + type + } of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(type)) { + event.dataTransfer.dropEffect = "copy"; + event.preventDefault(); + return; + } + } + } + } + drop(event) { + for (const item of event.dataTransfer.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + event.preventDefault(); + return; + } + } + } + } + copy(event) { + event.preventDefault(); + this.#activeEditor?.commitOrRemove(); + if (!this.hasSelection) { + return; + } + const editors = []; + for (const editor of this.#selectedEditors) { + const serialized = editor.serialize(true); + if (serialized) { + editors.push(serialized); + } + } + if (editors.length === 0) { + return; + } + event.clipboardData.setData("application/pdfjs", JSON.stringify(editors)); + } + cut(event) { + this.copy(event); + this.delete(); + } + async paste(event) { + event.preventDefault(); + const { + clipboardData + } = event; + for (const item of clipboardData.items) { + for (const editorType of this.#editorTypes) { + if (editorType.isHandlingMimeForPasting(item.type)) { + editorType.paste(item, this.currentLayer); + return; + } + } + } + let data = clipboardData.getData("application/pdfjs"); + if (!data) { + return; + } + try { + data = JSON.parse(data); + } catch (ex) { + warn(`paste: "${ex.message}".`); + return; + } + if (!Array.isArray(data)) { + return; + } + this.unselectAll(); + const layer = this.currentLayer; + try { + const newEditors = []; + for (const editor of data) { + const deserializedEditor = await layer.deserialize(editor); + if (!deserializedEditor) { + return; + } + newEditors.push(deserializedEditor); + } + const cmd = () => { + for (const editor of newEditors) { + this.#addEditorToLayer(editor); + } + this.#selectEditors(newEditors); + }; + const undo = () => { + for (const editor of newEditors) { + editor.remove(); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } catch (ex) { + warn(`paste: "${ex.message}".`); + } + } + keydown(event) { + if (!this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = true; + } + if (this.#mode !== AnnotationEditorType.NONE && !this.isEditorHandlingKeyboard) { + _AnnotationEditorUIManager._keyboardManager.exec(this, event); + } + } + keyup(event) { + if (this.isShiftKeyDown && event.key === "Shift") { + this.isShiftKeyDown = false; + if (this.#highlightWhenShiftUp) { + this.#highlightWhenShiftUp = false; + this.#onSelectEnd("main_toolbar"); + } + } + } + onEditingAction({ + name + }) { + switch (name) { + case "undo": + case "redo": + case "delete": + case "selectAll": + this[name](); + break; + case "highlightSelection": + this.highlightSelection("context_menu"); + break; + case "commentSelection": + this.commentSelection("context_menu"); + break; + } + } + #dispatchUpdateStates(details) { + const hasChanged = Object.entries(details).some(([key, value]) => this.#previousStates[key] !== value); + if (hasChanged) { + this._eventBus.dispatch("annotationeditorstateschanged", { + source: this, + details: Object.assign(this.#previousStates, details) + }); + if (this.#mode === AnnotationEditorType.HIGHLIGHT && details.hasSelectedEditor === false) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_FREE, true]]); + } + } + } + #dispatchUpdateUI(details) { + this._eventBus.dispatch("annotationeditorparamschanged", { + source: this, + details + }); + } + setEditingState(isEditing) { + if (isEditing) { + this.#addFocusManager(); + this.#addCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: this.#mode !== AnnotationEditorType.NONE, + isEmpty: this.#isEmpty(), + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + hasSelectedEditor: false + }); + } else { + this.#removeFocusManager(); + this.#removeCopyPasteListeners(); + this.#dispatchUpdateStates({ + isEditing: false + }); + this.disableUserSelect(false); + } + } + registerEditorTypes(types2) { + if (this.#editorTypes) { + return; + } + this.#editorTypes = types2; + for (const editorType of this.#editorTypes) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + } + getId() { + return this.#idManager.id; + } + get currentLayer() { + return this.#allLayers.get(this.#currentPageIndex); + } + getLayer(pageIndex) { + return this.#allLayers.get(pageIndex); + } + get currentPageIndex() { + return this.#currentPageIndex; + } + addLayer(layer) { + this.#allLayers.set(layer.pageIndex, layer); + if (this.#isEnabled) { + layer.enable(); + } else { + layer.disable(); + } + } + removeLayer(layer) { + this.#allLayers.delete(layer.pageIndex); + } + async updateMode(mode, editId = null, isFromKeyboard = false, mustEnterInEditMode = false, editComment = false) { + if (this.#mode === mode) { + return; + } + if (this.#updateModeCapability) { + await this.#updateModeCapability.promise; + if (!this.#updateModeCapability) { + return; + } + } + this.#updateModeCapability = Promise.withResolvers(); + this.#currentDrawingSession?.commitOrRemove(); + if (this.#mode === AnnotationEditorType.POPUP) { + this.#commentManager?.hideSidebar(); + } + this.#commentManager?.destroyPopup(); + this.#mode = mode; + if (mode === AnnotationEditorType.NONE) { + this.setEditingState(false); + this.#disableAll(); + for (const editor of this.#allEditors.values()) { + editor.hideStandaloneCommentButton(); + } + this._editorUndoBar?.hide(); + this.toggleComment(null); + this.#updateModeCapability.resolve(); + return; + } + for (const editor of this.#allEditors.values()) { + editor.addStandaloneCommentButton(); + } + if (mode === AnnotationEditorType.SIGNATURE) { + await this.#signatureManager?.loadSignatures(); + } + this.setEditingState(true); + await this.#enableAll(); + this.unselectAll(); + for (const layer of this.#allLayers.values()) { + layer.updateMode(mode); + } + if (mode === AnnotationEditorType.POPUP) { + this.#allEditableAnnotations ||= await this.#pdfDocument.getAnnotationsByType(new Set(this.#editorTypes.map((editorClass) => editorClass._editorType))); + const elementIds = /* @__PURE__ */ new Set(); + const allComments = []; + for (const editor of this.#allEditors.values()) { + const { + annotationElementId, + hasComment, + deleted + } = editor; + if (annotationElementId) { + elementIds.add(annotationElementId); + } + if (hasComment && !deleted) { + allComments.push(editor.getData()); + } + } + for (const annotation of this.#allEditableAnnotations) { + const { + id, + popupRef, + contentsObj + } = annotation; + if (popupRef && contentsObj?.str && !elementIds.has(id) && !this.#deletedAnnotationsElementIds.has(id)) { + allComments.push(annotation); + } + } + this.#commentManager?.showSidebar(allComments); + } + if (!editId) { + if (isFromKeyboard) { + this.addNewEditorFromKeyboard(); + } + this.#updateModeCapability.resolve(); + return; + } + for (const editor of this.#allEditors.values()) { + if (editor.uid === editId) { + this.setSelected(editor); + if (editComment) { + editor.editComment(); + } else if (mustEnterInEditMode) { + editor.enterInEditMode(); + } else { + editor.focus(); + } + } else { + editor.unselect(); + } + } + this.#updateModeCapability.resolve(); + } + addNewEditorFromKeyboard() { + if (this.currentLayer.canCreateNewEmptyEditor()) { + this.currentLayer.addNewEditor(); + } + } + updateToolbar(options) { + if (options.mode === this.#mode) { + return; + } + this._eventBus.dispatch("switchannotationeditormode", { + source: this, + ...options + }); + } + updateParams(type, value) { + if (!this.#editorTypes) { + return; + } + switch (type) { + case AnnotationEditorParamsType.CREATE: + this.currentLayer.addNewEditor(value); + return; + case AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL: + this._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data: { + type: "highlight", + action: "toggle_visibility" + } + } + }); + (this.#showAllStates ||= /* @__PURE__ */ new Map()).set(type, value); + this.showAllEditors("highlight", value); + break; + } + if (this.hasSelection) { + for (const editor of this.#selectedEditors) { + editor.updateParams(type, value); + } + } else { + for (const editorType of this.#editorTypes) { + editorType.updateDefaultParams(type, value); + } + } + } + showAllEditors(type, visible, updateButton = false) { + for (const editor of this.#allEditors.values()) { + if (editor.editorType === type) { + editor.show(visible); + } + } + const state = this.#showAllStates?.get(AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL) ?? true; + if (state !== visible) { + this.#dispatchUpdateUI([[AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL, visible]]); + } + } + enableWaiting(mustWait = false) { + if (this.#isWaiting === mustWait) { + return; + } + this.#isWaiting = mustWait; + for (const layer of this.#allLayers.values()) { + if (mustWait) { + layer.disableClick(); + } else { + layer.enableClick(); + } + layer.div.classList.toggle("waiting", mustWait); + } + } + async #enableAll() { + if (!this.#isEnabled) { + this.#isEnabled = true; + const promises = []; + for (const layer of this.#allLayers.values()) { + promises.push(layer.enable()); + } + await Promise.all(promises); + for (const editor of this.#allEditors.values()) { + editor.enable(); + } + } + } + #disableAll() { + this.unselectAll(); + if (this.#isEnabled) { + this.#isEnabled = false; + for (const layer of this.#allLayers.values()) { + layer.disable(); + } + for (const editor of this.#allEditors.values()) { + editor.disable(); + } + } + } + *getEditors(pageIndex) { + for (const editor of this.#allEditors.values()) { + if (editor.pageIndex === pageIndex) { + yield editor; + } + } + } + getEditor(id) { + return this.#allEditors.get(id); + } + addEditor(editor) { + this.#allEditors.set(editor.id, editor); + } + removeEditor(editor) { + if (editor.div.contains(document.activeElement)) { + if (this.#focusMainContainerTimeoutId) { + clearTimeout(this.#focusMainContainerTimeoutId); + } + this.#focusMainContainerTimeoutId = setTimeout(() => { + this.focusMainContainer(); + this.#focusMainContainerTimeoutId = null; + }, 0); + } + this.#allEditors.delete(editor.id); + if (editor.annotationElementId) { + this.#missingCanvases?.delete(editor.annotationElementId); + } + this.unselect(editor); + if (!editor.annotationElementId || !this.#deletedAnnotationsElementIds.has(editor.annotationElementId)) { + this.#annotationStorage?.remove(editor.id); + } + } + addDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.add(editor.annotationElementId); + this.addChangedExistingAnnotation(editor); + editor.deleted = true; + } + isDeletedAnnotationElement(annotationElementId) { + return this.#deletedAnnotationsElementIds.has(annotationElementId); + } + removeDeletedAnnotationElement(editor) { + this.#deletedAnnotationsElementIds.delete(editor.annotationElementId); + this.removeChangedExistingAnnotation(editor); + editor.deleted = false; + } + #addEditorToLayer(editor) { + const layer = this.#allLayers.get(editor.pageIndex); + if (layer) { + layer.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + } + } + setActiveEditor(editor) { + if (this.#activeEditor === editor) { + return; + } + this.#activeEditor = editor; + if (editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } + get #lastSelectedEditor() { + let ed = null; + for (ed of this.#selectedEditors) { + } + return ed; + } + updateUI(editor) { + if (this.#lastSelectedEditor === editor) { + this.#dispatchUpdateUI(editor.propertiesToUpdate); + } + } + updateUIForDefaultProperties(editorType) { + this.#dispatchUpdateUI(editorType.defaultPropertiesToUpdate); + } + toggleSelected(editor) { + if (this.#selectedEditors.has(editor)) { + this.#selectedEditors.delete(editor); + editor.unselect(); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + return; + } + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + setSelected(editor) { + this.updateToolbar({ + mode: editor.mode, + editId: editor.uid + }); + this.#currentDrawingSession?.commitOrRemove(); + for (const ed of this.#selectedEditors) { + if (ed !== editor) { + ed.unselect(); + } + } + this.#selectedEditors.clear(); + this.#selectedEditors.add(editor); + editor.select(); + this.#dispatchUpdateUI(editor.propertiesToUpdate); + this.#dispatchUpdateStates({ + hasSelectedEditor: true + }); + } + isSelected(editor) { + return this.#selectedEditors.has(editor); + } + get firstSelectedEditor() { + return this.#selectedEditors.values().next().value; + } + unselect(editor) { + editor.unselect(); + this.#selectedEditors.delete(editor); + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + get hasSelection() { + return this.#selectedEditors.size !== 0; + } + get isEnterHandled() { + return this.#selectedEditors.size === 1 && this.firstSelectedEditor.isEnterHandled; + } + undo() { + this.#commandManager.undo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: this.#commandManager.hasSomethingToUndo(), + hasSomethingToRedo: true, + isEmpty: this.#isEmpty() + }); + this._editorUndoBar?.hide(); + } + redo() { + this.#commandManager.redo(); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: this.#commandManager.hasSomethingToRedo(), + isEmpty: this.#isEmpty() + }); + } + addCommands(params) { + this.#commandManager.add(params); + this.#dispatchUpdateStates({ + hasSomethingToUndo: true, + hasSomethingToRedo: false, + isEmpty: this.#isEmpty() + }); + } + cleanUndoStack(type) { + this.#commandManager.cleanType(type); + } + #isEmpty() { + if (this.#allEditors.size === 0) { + return true; + } + if (this.#allEditors.size === 1) { + for (const editor of this.#allEditors.values()) { + return editor.isEmpty(); + } + } + return false; + } + delete() { + this.commitOrRemove(); + const drawingEditor = this.currentLayer?.endDrawingSession(true); + if (!this.hasSelection && !drawingEditor) { + return; + } + const editors = drawingEditor ? [drawingEditor] : [...this.#selectedEditors]; + const cmd = () => { + this._editorUndoBar?.show(undo, editors.length === 1 ? editors[0].editorType : editors.length); + for (const editor of editors) { + editor.remove(); + } + }; + const undo = () => { + for (const editor of editors) { + this.#addEditorToLayer(editor); + } + }; + this.addCommands({ + cmd, + undo, + mustExec: true + }); + } + commitOrRemove() { + this.#activeEditor?.commitOrRemove(); + } + hasSomethingToControl() { + return this.#activeEditor || this.hasSelection; + } + #selectEditors(editors) { + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + for (const editor of editors) { + if (editor.isEmpty()) { + continue; + } + this.#selectedEditors.add(editor); + editor.select(); + } + this.#dispatchUpdateStates({ + hasSelectedEditor: this.hasSelection + }); + } + selectAll() { + for (const editor of this.#selectedEditors) { + editor.commit(); + } + this.#selectEditors(this.#allEditors.values()); + } + unselectAll() { + if (this.#activeEditor) { + this.#activeEditor.commitOrRemove(); + if (this.#mode !== AnnotationEditorType.NONE) { + return; + } + } + if (this.#currentDrawingSession?.commitOrRemove()) { + return; + } + if (!this.hasSelection) { + return; + } + for (const editor of this.#selectedEditors) { + editor.unselect(); + } + this.#selectedEditors.clear(); + this.#dispatchUpdateStates({ + hasSelectedEditor: false + }); + } + translateSelectedEditors(x2, y4, noCommit = false) { + if (!noCommit) { + this.commitOrRemove(); + } + if (!this.hasSelection) { + return; + } + this.#translation[0] += x2; + this.#translation[1] += y4; + const [totalX, totalY] = this.#translation; + const editors = [...this.#selectedEditors]; + const TIME_TO_WAIT = 1e3; + if (this.#translationTimeoutId) { + clearTimeout(this.#translationTimeoutId); + } + this.#translationTimeoutId = setTimeout(() => { + this.#translationTimeoutId = null; + this.#translation[0] = this.#translation[1] = 0; + this.addCommands({ + cmd: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(totalX, totalY); + editor.translationDone(); + } + } + }, + undo: () => { + for (const editor of editors) { + if (this.#allEditors.has(editor.id)) { + editor.translateInPage(-totalX, -totalY); + editor.translationDone(); + } + } + }, + mustExec: false + }); + }, TIME_TO_WAIT); + for (const editor of editors) { + editor.translateInPage(x2, y4); + editor.translationDone(); + } + } + setUpDragSession() { + if (!this.hasSelection) { + return; + } + this.disableUserSelect(true); + this.#draggingEditors = /* @__PURE__ */ new Map(); + for (const editor of this.#selectedEditors) { + this.#draggingEditors.set(editor, { + savedX: editor.x, + savedY: editor.y, + savedPageIndex: editor.pageIndex, + newX: 0, + newY: 0, + newPageIndex: -1 + }); + } + } + endDragSession() { + if (!this.#draggingEditors) { + return false; + } + this.disableUserSelect(false); + const map3 = this.#draggingEditors; + this.#draggingEditors = null; + let mustBeAddedInUndoStack = false; + for (const [{ + x: x2, + y: y4, + pageIndex + }, value] of map3) { + value.newX = x2; + value.newY = y4; + value.newPageIndex = pageIndex; + mustBeAddedInUndoStack ||= x2 !== value.savedX || y4 !== value.savedY || pageIndex !== value.savedPageIndex; + } + if (!mustBeAddedInUndoStack) { + return false; + } + const move = (editor, x2, y4, pageIndex) => { + if (this.#allEditors.has(editor.id)) { + const parent = this.#allLayers.get(pageIndex); + if (parent) { + editor._setParentAndPosition(parent, x2, y4); + } else { + editor.pageIndex = pageIndex; + editor.x = x2; + editor.y = y4; + } + } + }; + this.addCommands({ + cmd: () => { + for (const [editor, { + newX, + newY, + newPageIndex + }] of map3) { + move(editor, newX, newY, newPageIndex); + } + }, + undo: () => { + for (const [editor, { + savedX, + savedY, + savedPageIndex + }] of map3) { + move(editor, savedX, savedY, savedPageIndex); + } + }, + mustExec: true + }); + return true; + } + dragSelectedEditors(tx, ty) { + if (!this.#draggingEditors) { + return; + } + for (const editor of this.#draggingEditors.keys()) { + editor.drag(tx, ty); + } + } + rebuild(editor) { + if (editor.parent === null) { + const parent = this.getLayer(editor.pageIndex); + if (parent) { + parent.changeParent(editor); + parent.addOrRebuild(editor); + } else { + this.addEditor(editor); + this.addToAnnotationStorage(editor); + editor.rebuild(); + } + } else { + editor.parent.addOrRebuild(editor); + } + } + get isEditorHandlingKeyboard() { + return this.getActive()?.shouldGetKeyboardEvents() || this.#selectedEditors.size === 1 && this.firstSelectedEditor.shouldGetKeyboardEvents(); + } + isActive(editor) { + return this.#activeEditor === editor; + } + getActive() { + return this.#activeEditor; + } + getMode() { + return this.#mode; + } + isEditingMode() { + return this.#mode !== AnnotationEditorType.NONE; + } + get imageManager() { + return shadow(this, "imageManager", new ImageManager()); + } + getSelectionBoxes(textLayer) { + if (!textLayer) { + return null; + } + const selection = document.getSelection(); + for (let i7 = 0, ii = selection.rangeCount; i7 < ii; i7++) { + if (!textLayer.contains(selection.getRangeAt(i7).commonAncestorContainer)) { + return null; + } + } + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + let rotator; + switch (textLayer.getAttribute("data-main-rotation")) { + case "90": + rotator = (x2, y4, w3, h7) => ({ + x: (y4 - layerY) / parentHeight, + y: 1 - (x2 + w3 - layerX) / parentWidth, + width: h7 / parentHeight, + height: w3 / parentWidth + }); + break; + case "180": + rotator = (x2, y4, w3, h7) => ({ + x: 1 - (x2 + w3 - layerX) / parentWidth, + y: 1 - (y4 + h7 - layerY) / parentHeight, + width: w3 / parentWidth, + height: h7 / parentHeight + }); + break; + case "270": + rotator = (x2, y4, w3, h7) => ({ + x: 1 - (y4 + h7 - layerY) / parentHeight, + y: (x2 - layerX) / parentWidth, + width: h7 / parentHeight, + height: w3 / parentWidth + }); + break; + default: + rotator = (x2, y4, w3, h7) => ({ + x: (x2 - layerX) / parentWidth, + y: (y4 - layerY) / parentHeight, + width: w3 / parentWidth, + height: h7 / parentHeight + }); + break; + } + const boxes = []; + for (let i7 = 0, ii = selection.rangeCount; i7 < ii; i7++) { + const range2 = selection.getRangeAt(i7); + if (range2.collapsed) { + continue; + } + for (const { + x: x2, + y: y4, + width, + height + } of range2.getClientRects()) { + if (width === 0 || height === 0) { + continue; + } + boxes.push(rotator(x2, y4, width, height)); + } + } + return boxes.length === 0 ? null : boxes; + } + addChangedExistingAnnotation({ + annotationElementId, + id + }) { + (this.#changedExistingAnnotations ||= /* @__PURE__ */ new Map()).set(annotationElementId, id); + } + removeChangedExistingAnnotation({ + annotationElementId + }) { + this.#changedExistingAnnotations?.delete(annotationElementId); + } + renderAnnotationElement(annotation) { + const editorId = this.#changedExistingAnnotations?.get(annotation.data.id); + if (!editorId) { + return; + } + const editor = this.#annotationStorage.getRawValue(editorId); + if (!editor) { + return; + } + if (this.#mode === AnnotationEditorType.NONE && !editor.hasBeenModified) { + return; + } + editor.renderAnnotationElement(annotation); + } + setMissingCanvas(annotationId, annotationElementId, canvas) { + const editor = this.#missingCanvases?.get(annotationId); + if (!editor) { + return; + } + editor.setCanvas(annotationElementId, canvas); + this.#missingCanvases.delete(annotationId); + } + addMissingCanvas(annotationId, editor) { + (this.#missingCanvases ||= /* @__PURE__ */ new Map()).set(annotationId, editor); + } + }; + AltText = class _AltText { + #altText = null; + #altTextDecorative = false; + #altTextButton = null; + #altTextButtonLabel = null; + #altTextTooltip = null; + #altTextTooltipTimeout = null; + #altTextWasFromKeyBoard = false; + #badge = null; + #editor = null; + #guessedText = null; + #textWithDisclaimer = null; + #useNewAltTextFlow = false; + static #l10nNewButton = null; + static _l10n = null; + constructor(editor) { + this.#editor = editor; + this.#useNewAltTextFlow = editor._uiManager.useNewAltTextFlow; + _AltText.#l10nNewButton ||= Object.freeze({ + added: "pdfjs-editor-new-alt-text-added-button", + "added-label": "pdfjs-editor-new-alt-text-added-button-label", + missing: "pdfjs-editor-new-alt-text-missing-button", + "missing-label": "pdfjs-editor-new-alt-text-missing-button-label", + review: "pdfjs-editor-new-alt-text-to-review-button", + "review-label": "pdfjs-editor-new-alt-text-to-review-button-label" + }); + } + static initialize(l10n) { + _AltText._l10n ??= l10n; + } + async render() { + const altText = this.#altTextButton = document.createElement("button"); + altText.className = "altText"; + altText.tabIndex = "0"; + const label = this.#altTextButtonLabel = document.createElement("span"); + altText.append(label); + if (this.#useNewAltTextFlow) { + altText.classList.add("new"); + altText.setAttribute("data-l10n-id", _AltText.#l10nNewButton.missing); + label.setAttribute("data-l10n-id", _AltText.#l10nNewButton["missing-label"]); + } else { + altText.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button"); + label.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-button-label"); + } + const signal = this.#editor._uiManager._signal; + altText.addEventListener("contextmenu", noContextMenu, { + signal + }); + altText.addEventListener("pointerdown", (event) => event.stopPropagation(), { + signal + }); + const onClick = (event) => { + event.preventDefault(); + this.#editor._uiManager.editAltText(this.#editor); + if (this.#useNewAltTextFlow) { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_clicked", + data: { + label: this.#label + } + }); + } + }; + altText.addEventListener("click", onClick, { + capture: true, + signal + }); + altText.addEventListener("keydown", (event) => { + if (event.target === altText && event.key === "Enter") { + this.#altTextWasFromKeyBoard = true; + onClick(event); + } + }, { + signal + }); + await this.#setState(); + return altText; + } + get #label() { + return this.#altText && "added" || this.#altText === null && this.guessedText && "review" || "missing"; + } + finish() { + if (!this.#altTextButton) { + return; + } + this.#altTextButton.focus({ + focusVisible: this.#altTextWasFromKeyBoard + }); + this.#altTextWasFromKeyBoard = false; + } + isEmpty() { + if (this.#useNewAltTextFlow) { + return this.#altText === null; + } + return !this.#altText && !this.#altTextDecorative; + } + hasData() { + if (this.#useNewAltTextFlow) { + return this.#altText !== null || !!this.#guessedText; + } + return this.isEmpty(); + } + get guessedText() { + return this.#guessedText; + } + async setGuessedText(guessedText) { + if (this.#altText !== null) { + return; + } + this.#guessedText = guessedText; + this.#textWithDisclaimer = await _AltText._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer", { + generatedAltText: guessedText + }); + this.#setState(); + } + toggleAltTextBadge(visibility = false) { + if (!this.#useNewAltTextFlow || this.#altText) { + this.#badge?.remove(); + this.#badge = null; + return; + } + if (!this.#badge) { + const badge = this.#badge = document.createElement("div"); + badge.className = "noAltTextBadge"; + this.#editor.div.append(badge); + } + this.#badge.classList.toggle("hidden", !visibility); + } + serialize(isForCopying) { + let altText = this.#altText; + if (!isForCopying && this.#guessedText === altText) { + altText = this.#textWithDisclaimer; + } + return { + altText, + decorative: this.#altTextDecorative, + guessedText: this.#guessedText, + textWithDisclaimer: this.#textWithDisclaimer + }; + } + get data() { + return { + altText: this.#altText, + decorative: this.#altTextDecorative + }; + } + set data({ + altText, + decorative, + guessedText, + textWithDisclaimer, + cancel = false + }) { + if (guessedText) { + this.#guessedText = guessedText; + this.#textWithDisclaimer = textWithDisclaimer; + } + if (this.#altText === altText && this.#altTextDecorative === decorative) { + return; + } + if (!cancel) { + this.#altText = altText; + this.#altTextDecorative = decorative; + } + this.#setState(); + } + toggle(enabled = false) { + if (!this.#altTextButton) { + return; + } + if (!enabled && this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextButton.disabled = !enabled; + } + shown() { + this.#editor._reportTelemetry({ + action: "pdfjs.image.alt_text.image_status_label_displayed", + data: { + label: this.#label + } + }); + } + destroy() { + this.#altTextButton?.remove(); + this.#altTextButton = null; + this.#altTextButtonLabel = null; + this.#altTextTooltip = null; + this.#badge?.remove(); + this.#badge = null; + } + async #setState() { + const button = this.#altTextButton; + if (!button) { + return; + } + if (this.#useNewAltTextFlow) { + button.classList.toggle("done", !!this.#altText); + button.setAttribute("data-l10n-id", _AltText.#l10nNewButton[this.#label]); + this.#altTextButtonLabel?.setAttribute("data-l10n-id", _AltText.#l10nNewButton[`${this.#label}-label`]); + if (!this.#altText) { + this.#altTextTooltip?.remove(); + return; + } + } else { + if (!this.#altText && !this.#altTextDecorative) { + button.classList.remove("done"); + this.#altTextTooltip?.remove(); + return; + } + button.classList.add("done"); + button.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-edit-button"); + } + let tooltip = this.#altTextTooltip; + if (!tooltip) { + this.#altTextTooltip = tooltip = document.createElement("span"); + tooltip.className = "tooltip"; + tooltip.setAttribute("role", "tooltip"); + tooltip.id = `alt-text-tooltip-${this.#editor.id}`; + const DELAY_TO_SHOW_TOOLTIP = 100; + const signal = this.#editor._uiManager._signal; + signal.addEventListener("abort", () => { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + }, { + once: true + }); + button.addEventListener("mouseenter", () => { + this.#altTextTooltipTimeout = setTimeout(() => { + this.#altTextTooltipTimeout = null; + this.#altTextTooltip.classList.add("show"); + this.#editor._reportTelemetry({ + action: "alt_text_tooltip" + }); + }, DELAY_TO_SHOW_TOOLTIP); + }, { + signal + }); + button.addEventListener("mouseleave", () => { + if (this.#altTextTooltipTimeout) { + clearTimeout(this.#altTextTooltipTimeout); + this.#altTextTooltipTimeout = null; + } + this.#altTextTooltip?.classList.remove("show"); + }, { + signal + }); + } + if (this.#altTextDecorative) { + tooltip.setAttribute("data-l10n-id", "pdfjs-editor-alt-text-decorative-tooltip"); + } else { + tooltip.removeAttribute("data-l10n-id"); + tooltip.textContent = this.#altText; + } + if (!tooltip.parentNode) { + button.append(tooltip); + } + const element = this.#editor.getElementForAltText(); + element?.setAttribute("aria-describedby", tooltip.id); + } + }; + Comment = class { + #commentStandaloneButton = null; + #commentToolbarButton = null; + #commentWasFromKeyBoard = false; + #editor = null; + #initialText = null; + #richText = null; + #text = null; + #date = null; + #deleted = false; + #popupPosition = null; + constructor(editor) { + this.#editor = editor; + } + renderForToolbar() { + const button = this.#commentToolbarButton = document.createElement("button"); + button.className = "comment"; + return this.#render(button, false); + } + renderForStandalone() { + const button = this.#commentStandaloneButton = document.createElement("button"); + button.className = "annotationCommentButton"; + const position = this.#editor.commentButtonPosition; + if (position) { + const { + style + } = button; + style.insetInlineEnd = `calc(${100 * (this.#editor._uiManager.direction === "ltr" ? 1 - position[0] : position[0])}% - var(--comment-button-dim))`; + style.top = `calc(${100 * position[1]}% - var(--comment-button-dim))`; + const color2 = this.#editor.commentButtonColor; + if (color2) { + style.backgroundColor = color2; + } + } + return this.#render(button, true); + } + focusButton() { + setTimeout(() => { + (this.#commentStandaloneButton ?? this.#commentToolbarButton)?.focus(); + }, 0); + } + onUpdatedColor() { + if (!this.#commentStandaloneButton) { + return; + } + const color2 = this.#editor.commentButtonColor; + if (color2) { + this.#commentStandaloneButton.style.backgroundColor = color2; + } + this.#editor._uiManager.updatePopupColor(this.#editor); + } + get commentButtonWidth() { + return (this.#commentStandaloneButton?.getBoundingClientRect().width ?? 0) / this.#editor.parent.boundingClientRect.width; + } + get commentPopupPositionInLayer() { + if (this.#popupPosition) { + return this.#popupPosition; + } + if (!this.#commentStandaloneButton) { + return null; + } + const { + x: x2, + y: y4, + height + } = this.#commentStandaloneButton.getBoundingClientRect(); + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = this.#editor.parent.boundingClientRect; + return [(x2 - parentX) / parentWidth, (y4 + height - parentY) / parentHeight]; + } + set commentPopupPositionInLayer(pos) { + this.#popupPosition = pos; + } + hasDefaultPopupPosition() { + return this.#popupPosition === null; + } + removeStandaloneCommentButton() { + this.#commentStandaloneButton?.remove(); + this.#commentStandaloneButton = null; + } + removeToolbarCommentButton() { + this.#commentToolbarButton?.remove(); + this.#commentToolbarButton = null; + } + setCommentButtonStates({ + selected, + hasPopup + }) { + if (!this.#commentStandaloneButton) { + return; + } + this.#commentStandaloneButton.classList.toggle("selected", selected); + this.#commentStandaloneButton.ariaExpanded = hasPopup; + } + #render(comment, isStandalone) { + if (!this.#editor._uiManager.hasCommentManager()) { + return null; + } + comment.tabIndex = "0"; + comment.ariaHasPopup = "dialog"; + if (isStandalone) { + comment.ariaControls = "commentPopup"; + comment.setAttribute("data-l10n-id", "pdfjs-show-comment-button"); + } else { + comment.ariaControlsElements = [this.#editor._uiManager.getCommentDialogElement()]; + comment.setAttribute("data-l10n-id", "pdfjs-editor-add-comment-button"); + } + const signal = this.#editor._uiManager._signal; + if (!(signal instanceof AbortSignal) || signal.aborted) { + return comment; + } + comment.addEventListener("contextmenu", noContextMenu, { + signal + }); + if (isStandalone) { + comment.addEventListener("focusin", (e9) => { + this.#editor._focusEventsAllowed = false; + stopEvent(e9); + }, { + capture: true, + signal + }); + comment.addEventListener("focusout", (e9) => { + this.#editor._focusEventsAllowed = true; + stopEvent(e9); + }, { + capture: true, + signal + }); + } + comment.addEventListener("pointerdown", (event) => event.stopPropagation(), { + signal + }); + const onClick = (event) => { + event.preventDefault(); + if (comment === this.#commentToolbarButton) { + this.edit(); + } else { + this.#editor.toggleComment(true); + } + }; + comment.addEventListener("click", onClick, { + capture: true, + signal + }); + comment.addEventListener("keydown", (event) => { + if (event.target === comment && event.key === "Enter") { + this.#commentWasFromKeyBoard = true; + onClick(event); + } + }, { + signal + }); + comment.addEventListener("pointerenter", () => { + this.#editor.toggleComment(false, true); + }, { + signal + }); + comment.addEventListener("pointerleave", () => { + this.#editor.toggleComment(false, false); + }, { + signal + }); + return comment; + } + edit(options) { + const position = this.commentPopupPositionInLayer; + let posX, posY; + if (position) { + [posX, posY] = position; + } else { + [posX, posY] = this.#editor.commentButtonPosition; + const { + width, + height, + x: x2, + y: y4 + } = this.#editor; + posX = x2 + posX * width; + posY = y4 + posY * height; + } + const parentDimensions = this.#editor.parent.boundingClientRect; + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = parentDimensions; + this.#editor._uiManager.editComment(this.#editor, parentX + posX * parentWidth, parentY + posY * parentHeight, { + ...options, + parentDimensions + }); + } + finish() { + if (!this.#commentToolbarButton) { + return; + } + this.#commentToolbarButton.focus({ + focusVisible: this.#commentWasFromKeyBoard + }); + this.#commentWasFromKeyBoard = false; + } + isDeleted() { + return this.#deleted || this.#text === ""; + } + isEmpty() { + return this.#text === null; + } + hasBeenEdited() { + return this.isDeleted() || this.#text !== this.#initialText; + } + serialize() { + return this.data; + } + get data() { + return { + text: this.#text, + richText: this.#richText, + date: this.#date, + deleted: this.isDeleted() + }; + } + set data(text3) { + if (text3 !== this.#text) { + this.#richText = null; + } + if (text3 === null) { + this.#text = ""; + this.#deleted = true; + return; + } + this.#text = text3; + this.#date = /* @__PURE__ */ new Date(); + this.#deleted = false; + } + setInitialText(text3, richText = null) { + this.#initialText = text3; + this.data = text3; + this.#date = null; + this.#richText = richText; + } + shown() { + } + destroy() { + this.#commentToolbarButton?.remove(); + this.#commentToolbarButton = null; + this.#commentStandaloneButton?.remove(); + this.#commentStandaloneButton = null; + this.#text = ""; + this.#richText = null; + this.#date = null; + this.#editor = null; + this.#commentWasFromKeyBoard = false; + this.#deleted = false; + } + }; + TouchManager = class _TouchManager { + #container; + #isPinching = false; + #isPinchingStopped = null; + #isPinchingDisabled; + #onPinchStart; + #onPinching; + #onPinchEnd; + #pointerDownAC = null; + #signal; + #touchInfo = null; + #touchManagerAC; + #touchMoveAC = null; + constructor({ + container, + isPinchingDisabled = null, + isPinchingStopped = null, + onPinchStart = null, + onPinching = null, + onPinchEnd = null, + signal + }) { + this.#container = container; + this.#isPinchingStopped = isPinchingStopped; + this.#isPinchingDisabled = isPinchingDisabled; + this.#onPinchStart = onPinchStart; + this.#onPinching = onPinching; + this.#onPinchEnd = onPinchEnd; + this.#touchManagerAC = new AbortController(); + this.#signal = AbortSignal.any([signal, this.#touchManagerAC.signal]); + container.addEventListener("touchstart", this.#onTouchStart.bind(this), { + passive: false, + signal: this.#signal + }); + } + get MIN_TOUCH_DISTANCE_TO_PINCH() { + return 35 / OutputScale.pixelRatio; + } + #onTouchStart(evt) { + if (this.#isPinchingDisabled?.()) { + return; + } + if (evt.touches.length === 1) { + if (this.#pointerDownAC) { + return; + } + const pointerDownAC = this.#pointerDownAC = new AbortController(); + const signal = AbortSignal.any([this.#signal, pointerDownAC.signal]); + const container = this.#container; + const opts = { + capture: true, + signal, + passive: false + }; + const cancelPointerDown = (e9) => { + if (e9.pointerType === "touch") { + this.#pointerDownAC?.abort(); + this.#pointerDownAC = null; + } + }; + container.addEventListener("pointerdown", (e9) => { + if (e9.pointerType === "touch") { + stopEvent(e9); + cancelPointerDown(e9); + } + }, opts); + container.addEventListener("pointerup", cancelPointerDown, opts); + container.addEventListener("pointercancel", cancelPointerDown, opts); + return; + } + if (!this.#touchMoveAC) { + this.#touchMoveAC = new AbortController(); + const signal = AbortSignal.any([this.#signal, this.#touchMoveAC.signal]); + const container = this.#container; + const opt = { + signal, + capture: false, + passive: false + }; + container.addEventListener("touchmove", this.#onTouchMove.bind(this), opt); + const onTouchEnd = this.#onTouchEnd.bind(this); + container.addEventListener("touchend", onTouchEnd, opt); + container.addEventListener("touchcancel", onTouchEnd, opt); + opt.capture = true; + container.addEventListener("pointerdown", stopEvent, opt); + container.addEventListener("pointermove", stopEvent, opt); + container.addEventListener("pointercancel", stopEvent, opt); + container.addEventListener("pointerup", stopEvent, opt); + this.#onPinchStart?.(); + } + stopEvent(evt); + if (evt.touches.length !== 2 || this.#isPinchingStopped?.()) { + this.#touchInfo = null; + return; + } + let [touch0, touch1] = evt.touches; + if (touch0.identifier > touch1.identifier) { + [touch0, touch1] = [touch1, touch0]; + } + this.#touchInfo = { + touch0X: touch0.screenX, + touch0Y: touch0.screenY, + touch1X: touch1.screenX, + touch1Y: touch1.screenY + }; + } + #onTouchMove(evt) { + if (!this.#touchInfo || evt.touches.length !== 2) { + return; + } + stopEvent(evt); + let [touch0, touch1] = evt.touches; + if (touch0.identifier > touch1.identifier) { + [touch0, touch1] = [touch1, touch0]; + } + const { + screenX: screen0X, + screenY: screen0Y + } = touch0; + const { + screenX: screen1X, + screenY: screen1Y + } = touch1; + const touchInfo = this.#touchInfo; + const { + touch0X: pTouch0X, + touch0Y: pTouch0Y, + touch1X: pTouch1X, + touch1Y: pTouch1Y + } = touchInfo; + const prevGapX = pTouch1X - pTouch0X; + const prevGapY = pTouch1Y - pTouch0Y; + const currGapX = screen1X - screen0X; + const currGapY = screen1Y - screen0Y; + const distance = Math.hypot(currGapX, currGapY) || 1; + const pDistance = Math.hypot(prevGapX, prevGapY) || 1; + if (!this.#isPinching && Math.abs(pDistance - distance) <= _TouchManager.MIN_TOUCH_DISTANCE_TO_PINCH) { + return; + } + touchInfo.touch0X = screen0X; + touchInfo.touch0Y = screen0Y; + touchInfo.touch1X = screen1X; + touchInfo.touch1Y = screen1Y; + if (!this.#isPinching) { + this.#isPinching = true; + return; + } + const origin = [(screen0X + screen1X) / 2, (screen0Y + screen1Y) / 2]; + this.#onPinching?.(origin, pDistance, distance); + } + #onTouchEnd(evt) { + if (evt.touches.length >= 2) { + return; + } + if (this.#touchMoveAC) { + this.#touchMoveAC.abort(); + this.#touchMoveAC = null; + this.#onPinchEnd?.(); + } + if (!this.#touchInfo) { + return; + } + stopEvent(evt); + this.#touchInfo = null; + this.#isPinching = false; + } + destroy() { + this.#touchManagerAC?.abort(); + this.#touchManagerAC = null; + this.#pointerDownAC?.abort(); + this.#pointerDownAC = null; + } + }; + AnnotationEditor = class _AnnotationEditor { + #accessibilityData = null; + #allResizerDivs = null; + #altText = null; + #comment = null; + #commentStandaloneButton = null; + #disabled = false; + #dragPointerId = null; + #dragPointerType = ""; + #resizersDiv = null; + #lastPointerCoords = null; + #savedDimensions = null; + #fakeAnnotation = null; + #focusAC = null; + #focusedResizerName = ""; + #hasBeenClicked = false; + #initialRect = null; + #isEditing = false; + #isInEditMode = false; + #isResizerEnabledForKeyboard = false; + #moveInDOMTimeout = null; + #prevDragX = 0; + #prevDragY = 0; + #telemetryTimeouts = null; + #touchManager = null; + isSelected = false; + _isCopy = false; + _editToolbar = null; + _initialOptions = /* @__PURE__ */ Object.create(null); + _initialData = null; + _isVisible = true; + _uiManager = null; + _focusEventsAllowed = true; + static _l10n = null; + static _l10nResizer = null; + #isDraggable = false; + #zIndex = _AnnotationEditor._zIndex++; + static _borderLineWidth = -1; + static _colorManager = new ColorManager(); + static _zIndex = 1; + static _telemetryTimeout = 1e3; + static get _resizerKeyboardManager() { + const resize = _AnnotationEditor.prototype._resizeWithKeyboard; + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_resizerKeyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], resize, { + args: [-small, 0] + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], resize, { + args: [-big, 0] + }], [["ArrowRight", "mac+ArrowRight"], resize, { + args: [small, 0] + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], resize, { + args: [big, 0] + }], [["ArrowUp", "mac+ArrowUp"], resize, { + args: [0, -small] + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], resize, { + args: [0, -big] + }], [["ArrowDown", "mac+ArrowDown"], resize, { + args: [0, small] + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], resize, { + args: [0, big] + }], [["Escape", "mac+Escape"], _AnnotationEditor.prototype._stopResizingWithKeyboard]])); + } + constructor(parameters) { + this.parent = parameters.parent; + this.id = parameters.id; + this.width = this.height = null; + this.pageIndex = parameters.parent.pageIndex; + this.name = parameters.name; + this.div = null; + this._uiManager = parameters.uiManager; + this.annotationElementId = null; + this._willKeepAspectRatio = false; + this._initialOptions.isCentered = parameters.isCentered; + this._structTreeParentId = null; + this.annotationElementId = parameters.annotationElementId || null; + this.creationDate = parameters.creationDate || /* @__PURE__ */ new Date(); + this.modificationDate = parameters.modificationDate || null; + this.canAddComment = true; + const { + rotation, + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = this.parent.viewport; + this.rotation = rotation; + this.pageRotation = (360 + rotation - this._uiManager.viewParameters.rotation) % 360; + this.pageDimensions = [pageWidth, pageHeight]; + this.pageTranslation = [pageX, pageY]; + const [width, height] = this.parentDimensions; + this.x = parameters.x / width; + this.y = parameters.y / height; + this.isAttachedToDOM = false; + this.deleted = false; + } + get editorType() { + return Object.getPrototypeOf(this).constructor._type; + } + get mode() { + return Object.getPrototypeOf(this).constructor._editorType; + } + static get isDrawer() { + return false; + } + static get _defaultLineColor() { + return shadow(this, "_defaultLineColor", this._colorManager.getHexCode("CanvasText")); + } + static deleteAnnotationElement(editor) { + const fakeEditor = new FakeEditor({ + id: editor.parent.getNextId(), + parent: editor.parent, + uiManager: editor._uiManager + }); + fakeEditor.annotationElementId = editor.annotationElementId; + fakeEditor.deleted = true; + fakeEditor._uiManager.addToAnnotationStorage(fakeEditor); + } + static initialize(l10n, _uiManager) { + _AnnotationEditor._l10n ??= l10n; + _AnnotationEditor._l10nResizer ||= Object.freeze({ + topLeft: "pdfjs-editor-resizer-top-left", + topMiddle: "pdfjs-editor-resizer-top-middle", + topRight: "pdfjs-editor-resizer-top-right", + middleRight: "pdfjs-editor-resizer-middle-right", + bottomRight: "pdfjs-editor-resizer-bottom-right", + bottomMiddle: "pdfjs-editor-resizer-bottom-middle", + bottomLeft: "pdfjs-editor-resizer-bottom-left", + middleLeft: "pdfjs-editor-resizer-middle-left" + }); + if (_AnnotationEditor._borderLineWidth !== -1) { + return; + } + const style = getComputedStyle(document.documentElement); + _AnnotationEditor._borderLineWidth = parseFloat(style.getPropertyValue("--outline-width")) || 0; + } + static updateDefaultParams(_type, _value) { + } + static get defaultPropertiesToUpdate() { + return []; + } + static isHandlingMimeForPasting(mime) { + return false; + } + static paste(item, parent) { + unreachable("Not implemented"); + } + get propertiesToUpdate() { + return []; + } + get _isDraggable() { + return this.#isDraggable; + } + set _isDraggable(value) { + this.#isDraggable = value; + this.div?.classList.toggle("draggable", value); + } + get uid() { + return this.annotationElementId || this.id; + } + get isEnterHandled() { + return true; + } + center() { + const [pageWidth, pageHeight] = this.pageDimensions; + switch (this.parentRotation) { + case 90: + this.x -= this.height * pageHeight / (pageWidth * 2); + this.y += this.width * pageWidth / (pageHeight * 2); + break; + case 180: + this.x += this.width / 2; + this.y += this.height / 2; + break; + case 270: + this.x += this.height * pageHeight / (pageWidth * 2); + this.y -= this.width * pageWidth / (pageHeight * 2); + break; + default: + this.x -= this.width / 2; + this.y -= this.height / 2; + break; + } + this.fixAndSetPosition(); + } + addCommands(params) { + this._uiManager.addCommands(params); + } + get currentLayer() { + return this._uiManager.currentLayer; + } + setInBackground() { + this.div.style.zIndex = 0; + } + setInForeground() { + this.div.style.zIndex = this.#zIndex; + } + setParent(parent) { + if (parent !== null) { + this.pageIndex = parent.pageIndex; + this.pageDimensions = parent.pageDimensions; + } else { + this.#stopResizing(); + this.#fakeAnnotation?.remove(); + this.#fakeAnnotation = null; + } + this.parent = parent; + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.#hasBeenClicked) { + this.parent.setSelected(this); + } else { + this.#hasBeenClicked = false; + } + } + focusout(event) { + if (!this._focusEventsAllowed) { + return; + } + if (!this.isAttachedToDOM) { + return; + } + const target = event.relatedTarget; + if (target?.closest(`#${this.id}`)) { + return; + } + event.preventDefault(); + if (!this.parent?.isMultipleSelection) { + this.commitOrRemove(); + } + } + commitOrRemove() { + if (this.isEmpty()) { + this.remove(); + } else { + this.commit(); + } + } + commit() { + if (!this.isInEditMode()) { + return; + } + this.addToAnnotationStorage(); + } + addToAnnotationStorage() { + this._uiManager.addToAnnotationStorage(this); + } + setAt(x2, y4, tx, ty) { + const [width, height] = this.parentDimensions; + [tx, ty] = this.screenToPageTranslation(tx, ty); + this.x = (x2 + tx) / width; + this.y = (y4 + ty) / height; + this.fixAndSetPosition(); + } + _moveAfterPaste(baseX, baseY) { + const [parentWidth, parentHeight] = this.parentDimensions; + this.setAt(baseX * parentWidth, baseY * parentHeight, this.width * parentWidth, this.height * parentHeight); + this._onTranslated(); + } + #translate([width, height], x2, y4) { + [x2, y4] = this.screenToPageTranslation(x2, y4); + this.x += x2 / width; + this.y += y4 / height; + this._onTranslating(this.x, this.y); + this.fixAndSetPosition(); + } + translate(x2, y4) { + this.#translate(this.parentDimensions, x2, y4); + } + translateInPage(x2, y4) { + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + this.#translate(this.pageDimensions, x2, y4); + this.div.scrollIntoView({ + block: "nearest" + }); + } + translationDone() { + this._onTranslated(this.x, this.y); + } + drag(tx, ty) { + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + const { + div, + parentDimensions: [parentWidth, parentHeight] + } = this; + this.x += tx / parentWidth; + this.y += ty / parentHeight; + if (this.parent && (this.x < 0 || this.x > 1 || this.y < 0 || this.y > 1)) { + const { + x: x3, + y: y5 + } = this.div.getBoundingClientRect(); + if (this.parent.findNewParent(this, x3, y5)) { + this.x -= Math.floor(this.x); + this.y -= Math.floor(this.y); + } + } + let { + x: x2, + y: y4 + } = this; + const [bx, by] = this.getBaseTranslation(); + x2 += bx; + y4 += by; + const { + style + } = div; + style.left = `${(100 * x2).toFixed(2)}%`; + style.top = `${(100 * y4).toFixed(2)}%`; + this._onTranslating(x2, y4); + div.scrollIntoView({ + block: "nearest" + }); + } + _onTranslating(x2, y4) { + } + _onTranslated(x2, y4) { + } + get _hasBeenMoved() { + return !!this.#initialRect && (this.#initialRect[0] !== this.x || this.#initialRect[1] !== this.y); + } + get _hasBeenResized() { + return !!this.#initialRect && (this.#initialRect[2] !== this.width || this.#initialRect[3] !== this.height); + } + getBaseTranslation() { + const [parentWidth, parentHeight] = this.parentDimensions; + const { + _borderLineWidth + } = _AnnotationEditor; + const x2 = _borderLineWidth / parentWidth; + const y4 = _borderLineWidth / parentHeight; + switch (this.rotation) { + case 90: + return [-x2, y4]; + case 180: + return [x2, y4]; + case 270: + return [x2, -y4]; + default: + return [-x2, -y4]; + } + } + get _mustFixPosition() { + return true; + } + fixAndSetPosition(rotation = this.rotation) { + const { + div: { + style + }, + pageDimensions: [pageWidth, pageHeight] + } = this; + let { + x: x2, + y: y4, + width, + height + } = this; + width *= pageWidth; + height *= pageHeight; + x2 *= pageWidth; + y4 *= pageHeight; + if (this._mustFixPosition) { + switch (rotation) { + case 0: + x2 = MathClamp(x2, 0, pageWidth - width); + y4 = MathClamp(y4, 0, pageHeight - height); + break; + case 90: + x2 = MathClamp(x2, 0, pageWidth - height); + y4 = MathClamp(y4, width, pageHeight); + break; + case 180: + x2 = MathClamp(x2, width, pageWidth); + y4 = MathClamp(y4, height, pageHeight); + break; + case 270: + x2 = MathClamp(x2, height, pageWidth); + y4 = MathClamp(y4, 0, pageHeight - width); + break; + } + } + this.x = x2 /= pageWidth; + this.y = y4 /= pageHeight; + const [bx, by] = this.getBaseTranslation(); + x2 += bx; + y4 += by; + style.left = `${(100 * x2).toFixed(2)}%`; + style.top = `${(100 * y4).toFixed(2)}%`; + this.moveInDOM(); + } + static #rotatePoint(x2, y4, angle) { + switch (angle) { + case 90: + return [y4, -x2]; + case 180: + return [-x2, -y4]; + case 270: + return [-y4, x2]; + default: + return [x2, y4]; + } + } + screenToPageTranslation(x2, y4) { + return _AnnotationEditor.#rotatePoint(x2, y4, this.parentRotation); + } + pageTranslationToScreen(x2, y4) { + return _AnnotationEditor.#rotatePoint(x2, y4, 360 - this.parentRotation); + } + #getRotationMatrix(rotation) { + switch (rotation) { + case 90: { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, -pageWidth / pageHeight, pageHeight / pageWidth, 0]; + } + case 180: + return [-1, 0, 0, -1]; + case 270: { + const [pageWidth, pageHeight] = this.pageDimensions; + return [0, pageWidth / pageHeight, -pageHeight / pageWidth, 0]; + } + default: + return [1, 0, 0, 1]; + } + } + get parentScale() { + return this._uiManager.viewParameters.realScale; + } + get parentRotation() { + return (this._uiManager.viewParameters.rotation + this.pageRotation) % 360; + } + get parentDimensions() { + const { + parentScale, + pageDimensions: [pageWidth, pageHeight] + } = this; + return [pageWidth * parentScale, pageHeight * parentScale]; + } + setDims() { + const { + div: { + style + }, + width, + height + } = this; + style.width = `${(100 * width).toFixed(2)}%`; + style.height = `${(100 * height).toFixed(2)}%`; + } + getInitialTranslation() { + return [0, 0]; + } + #createResizers() { + if (this.#resizersDiv) { + return; + } + this.#resizersDiv = document.createElement("div"); + this.#resizersDiv.classList.add("resizers"); + const classes = this._willKeepAspectRatio ? ["topLeft", "topRight", "bottomRight", "bottomLeft"] : ["topLeft", "topMiddle", "topRight", "middleRight", "bottomRight", "bottomMiddle", "bottomLeft", "middleLeft"]; + const signal = this._uiManager._signal; + for (const name of classes) { + const div = document.createElement("div"); + this.#resizersDiv.append(div); + div.classList.add("resizer", name); + div.setAttribute("data-resizer-name", name); + div.addEventListener("pointerdown", this.#resizerPointerdown.bind(this, name), { + signal + }); + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.tabIndex = -1; + } + this.div.prepend(this.#resizersDiv); + } + #resizerPointerdown(name, event) { + event.preventDefault(); + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#altText?.toggle(false); + const savedDraggable = this._isDraggable; + this._isDraggable = false; + this.#lastPointerCoords = [event.screenX, event.screenY]; + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + this.parent.togglePointerEvents(false); + window.addEventListener("pointermove", this.#resizerPointermove.bind(this, name), { + passive: true, + capture: true, + signal + }); + window.addEventListener("touchmove", stopEvent, { + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const savedParentCursor = this.parent.div.style.cursor; + const savedCursor = this.div.style.cursor; + this.div.style.cursor = this.parent.div.style.cursor = window.getComputedStyle(event.target).cursor; + const pointerUpCallback = () => { + ac.abort(); + this.parent.togglePointerEvents(true); + this.#altText?.toggle(true); + this._isDraggable = savedDraggable; + this.parent.div.style.cursor = savedParentCursor; + this.div.style.cursor = savedCursor; + this.#addResizeToUndoStack(); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + #resize(x2, y4, width, height) { + this.width = width; + this.height = height; + this.x = x2; + this.y = y4; + this.setDims(); + this.fixAndSetPosition(); + this._onResized(); + } + _onResized() { + } + #addResizeToUndoStack() { + if (!this.#savedDimensions) { + return; + } + const { + savedX, + savedY, + savedWidth, + savedHeight + } = this.#savedDimensions; + this.#savedDimensions = null; + const newX = this.x; + const newY = this.y; + const newWidth = this.width; + const newHeight = this.height; + if (newX === savedX && newY === savedY && newWidth === savedWidth && newHeight === savedHeight) { + return; + } + this.addCommands({ + cmd: this.#resize.bind(this, newX, newY, newWidth, newHeight), + undo: this.#resize.bind(this, savedX, savedY, savedWidth, savedHeight), + mustExec: true + }); + } + static _round(x2) { + return Math.round(x2 * 1e4) / 1e4; + } + #resizerPointermove(name, event) { + const [parentWidth, parentHeight] = this.parentDimensions; + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const minWidth = _AnnotationEditor.MIN_SIZE / parentWidth; + const minHeight = _AnnotationEditor.MIN_SIZE / parentHeight; + const rotationMatrix = this.#getRotationMatrix(this.rotation); + const transf = (x2, y4) => [rotationMatrix[0] * x2 + rotationMatrix[2] * y4, rotationMatrix[1] * x2 + rotationMatrix[3] * y4]; + const invRotationMatrix = this.#getRotationMatrix(360 - this.rotation); + const invTransf = (x2, y4) => [invRotationMatrix[0] * x2 + invRotationMatrix[2] * y4, invRotationMatrix[1] * x2 + invRotationMatrix[3] * y4]; + let getPoint2; + let getOpposite; + let isDiagonal = false; + let isHorizontal = false; + switch (name) { + case "topLeft": + isDiagonal = true; + getPoint2 = (w3, h7) => [0, 0]; + getOpposite = (w3, h7) => [w3, h7]; + break; + case "topMiddle": + getPoint2 = (w3, h7) => [w3 / 2, 0]; + getOpposite = (w3, h7) => [w3 / 2, h7]; + break; + case "topRight": + isDiagonal = true; + getPoint2 = (w3, h7) => [w3, 0]; + getOpposite = (w3, h7) => [0, h7]; + break; + case "middleRight": + isHorizontal = true; + getPoint2 = (w3, h7) => [w3, h7 / 2]; + getOpposite = (w3, h7) => [0, h7 / 2]; + break; + case "bottomRight": + isDiagonal = true; + getPoint2 = (w3, h7) => [w3, h7]; + getOpposite = (w3, h7) => [0, 0]; + break; + case "bottomMiddle": + getPoint2 = (w3, h7) => [w3 / 2, h7]; + getOpposite = (w3, h7) => [w3 / 2, 0]; + break; + case "bottomLeft": + isDiagonal = true; + getPoint2 = (w3, h7) => [0, h7]; + getOpposite = (w3, h7) => [w3, 0]; + break; + case "middleLeft": + isHorizontal = true; + getPoint2 = (w3, h7) => [0, h7 / 2]; + getOpposite = (w3, h7) => [w3, h7 / 2]; + break; + } + const point = getPoint2(savedWidth, savedHeight); + const oppositePoint = getOpposite(savedWidth, savedHeight); + let transfOppositePoint = transf(...oppositePoint); + const oppositeX = _AnnotationEditor._round(savedX + transfOppositePoint[0]); + const oppositeY = _AnnotationEditor._round(savedY + transfOppositePoint[1]); + let ratioX = 1; + let ratioY = 1; + let deltaX, deltaY; + if (!event.fromKeyboard) { + const { + screenX, + screenY + } = event; + const [lastScreenX, lastScreenY] = this.#lastPointerCoords; + [deltaX, deltaY] = this.screenToPageTranslation(screenX - lastScreenX, screenY - lastScreenY); + this.#lastPointerCoords[0] = screenX; + this.#lastPointerCoords[1] = screenY; + } else { + ({ + deltaX, + deltaY + } = event); + } + [deltaX, deltaY] = invTransf(deltaX / parentWidth, deltaY / parentHeight); + if (isDiagonal) { + const oldDiag = Math.hypot(savedWidth, savedHeight); + ratioX = ratioY = Math.max(Math.min(Math.hypot(oppositePoint[0] - point[0] - deltaX, oppositePoint[1] - point[1] - deltaY) / oldDiag, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); + } else if (isHorizontal) { + ratioX = MathClamp(Math.abs(oppositePoint[0] - point[0] - deltaX), minWidth, 1) / savedWidth; + } else { + ratioY = MathClamp(Math.abs(oppositePoint[1] - point[1] - deltaY), minHeight, 1) / savedHeight; + } + const newWidth = _AnnotationEditor._round(savedWidth * ratioX); + const newHeight = _AnnotationEditor._round(savedHeight * ratioY); + transfOppositePoint = transf(...getOpposite(newWidth, newHeight)); + const newX = oppositeX - transfOppositePoint[0]; + const newY = oppositeY - transfOppositePoint[1]; + this.#initialRect ||= [this.x, this.y, this.width, this.height]; + this.width = newWidth; + this.height = newHeight; + this.x = newX; + this.y = newY; + this.setDims(); + this.fixAndSetPosition(); + this._onResizing(); + } + _onResizing() { + } + altTextFinish() { + this.#altText?.finish(); + } + get toolbarButtons() { + return null; + } + async addEditToolbar() { + if (this._editToolbar || this.#isInEditMode) { + return this._editToolbar; + } + this._editToolbar = new EditorToolbar(this); + this.div.append(this._editToolbar.render()); + const { + toolbarButtons + } = this; + if (toolbarButtons) { + for (const [name, tool] of toolbarButtons) { + await this._editToolbar.addButton(name, tool); + } + } + if (!this.hasComment) { + this._editToolbar.addButton("comment", this.addCommentButton()); + } + this._editToolbar.addButton("delete"); + return this._editToolbar; + } + addCommentButtonInToolbar() { + this._editToolbar?.addButtonBefore("comment", this.addCommentButton(), ".deleteButton"); + } + removeCommentButtonFromToolbar() { + this._editToolbar?.removeButton("comment"); + } + removeEditToolbar() { + this._editToolbar?.remove(); + this._editToolbar = null; + this.#altText?.destroy(); + } + addContainer(container) { + const editToolbarDiv = this._editToolbar?.div; + if (editToolbarDiv) { + editToolbarDiv.before(container); + } else { + this.div.append(container); + } + } + getClientDimensions() { + return this.div.getBoundingClientRect(); + } + createAltText() { + if (!this.#altText) { + AltText.initialize(_AnnotationEditor._l10n); + this.#altText = new AltText(this); + if (this.#accessibilityData) { + this.#altText.data = this.#accessibilityData; + this.#accessibilityData = null; + } + } + return this.#altText; + } + get altTextData() { + return this.#altText?.data; + } + set altTextData(data) { + if (!this.#altText) { + return; + } + this.#altText.data = data; + } + get guessedAltText() { + return this.#altText?.guessedText; + } + async setGuessedAltText(text3) { + await this.#altText?.setGuessedText(text3); + } + serializeAltText(isForCopying) { + return this.#altText?.serialize(isForCopying); + } + hasAltText() { + return !!this.#altText && !this.#altText.isEmpty(); + } + hasAltTextData() { + return this.#altText?.hasData() ?? false; + } + focusCommentButton() { + this.#comment?.focusButton(); + } + addCommentButton() { + return this.canAddComment ? this.#comment ||= new Comment(this) : null; + } + addStandaloneCommentButton() { + if (!this._uiManager.hasCommentManager()) { + return; + } + if (this.#commentStandaloneButton) { + if (this._uiManager.isEditingMode()) { + this.#commentStandaloneButton.classList.remove("hidden"); + } + return; + } + if (!this.hasComment) { + return; + } + this.#commentStandaloneButton = this.#comment.renderForStandalone(); + this.div.append(this.#commentStandaloneButton); + } + removeStandaloneCommentButton() { + this.#comment.removeStandaloneCommentButton(); + this.#commentStandaloneButton = null; + } + hideStandaloneCommentButton() { + this.#commentStandaloneButton?.classList.add("hidden"); + } + get comment() { + const { + data: { + richText, + text: text3, + date, + deleted + } + } = this.#comment; + return { + text: text3, + richText, + date, + deleted, + color: this.getNonHCMColor(), + opacity: this.opacity ?? 1 + }; + } + set comment(text3) { + this.#comment ||= new Comment(this); + this.#comment.data = text3; + if (this.hasComment) { + this.removeCommentButtonFromToolbar(); + this.addStandaloneCommentButton(); + this._uiManager.updateComment(this); + } else { + this.addCommentButtonInToolbar(); + this.removeStandaloneCommentButton(); + this._uiManager.removeComment(this); + } + } + setCommentData({ + comment, + popupRef, + richText + }) { + if (!popupRef) { + return; + } + this.#comment ||= new Comment(this); + this.#comment.setInitialText(comment, richText); + if (!this.annotationElementId) { + return; + } + const storedData = this._uiManager.getAndRemoveDataFromAnnotationStorage(this.annotationElementId); + if (storedData) { + this.updateFromAnnotationLayer(storedData); + } + } + get hasEditedComment() { + return this.#comment?.hasBeenEdited(); + } + get hasDeletedComment() { + return this.#comment?.isDeleted(); + } + get hasComment() { + return !!this.#comment && !this.#comment.isEmpty() && !this.#comment.isDeleted(); + } + async editComment(options) { + this.#comment ||= new Comment(this); + this.#comment.edit(options); + } + toggleComment(isSelected, visibility = void 0) { + if (this.hasComment) { + this._uiManager.toggleComment(this, isSelected, visibility); + } + } + setSelectedCommentButton(selected) { + this.#comment.setSelectedButton(selected); + } + addComment(serialized) { + if (this.hasEditedComment) { + const DEFAULT_POPUP_WIDTH = 180; + const DEFAULT_POPUP_HEIGHT = 100; + const [, , , trY] = serialized.rect; + const [pageWidth] = this.pageDimensions; + const [pageX] = this.pageTranslation; + const blX = pageX + pageWidth + 1; + const blY = trY - DEFAULT_POPUP_HEIGHT; + const trX = blX + DEFAULT_POPUP_WIDTH; + serialized.popup = { + contents: this.comment.text, + deleted: this.comment.deleted, + rect: [blX, blY, trX, trY] + }; + } + } + updateFromAnnotationLayer({ + popup: { + contents, + deleted + } + }) { + this.#comment.data = deleted ? null : contents; + } + get parentBoundingClientRect() { + return this.parent.boundingClientRect; + } + render() { + const div = this.div = document.createElement("div"); + div.setAttribute("data-editor-rotation", (360 - this.rotation) % 360); + div.className = this.name; + div.setAttribute("id", this.id); + div.tabIndex = this.#disabled ? -1 : 0; + div.setAttribute("role", "application"); + if (this.defaultL10nId) { + div.setAttribute("data-l10n-id", this.defaultL10nId); + } + if (!this._isVisible) { + div.classList.add("hidden"); + } + this.setInForeground(); + this.#addFocusListeners(); + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.parentRotation % 180 !== 0) { + div.style.maxWidth = `${(100 * parentHeight / parentWidth).toFixed(2)}%`; + div.style.maxHeight = `${(100 * parentWidth / parentHeight).toFixed(2)}%`; + } + const [tx, ty] = this.getInitialTranslation(); + this.translate(tx, ty); + bindEvents(this, div, ["keydown", "pointerdown", "dblclick"]); + if (this.isResizable && this._uiManager._supportsPinchToZoom) { + this.#touchManager ||= new TouchManager({ + container: div, + isPinchingDisabled: () => !this.isSelected, + onPinchStart: this.#touchPinchStartCallback.bind(this), + onPinching: this.#touchPinchCallback.bind(this), + onPinchEnd: this.#touchPinchEndCallback.bind(this), + signal: this._uiManager._signal + }); + } + this.addStandaloneCommentButton(); + this._uiManager._editorUndoBar?.hide(); + return div; + } + #touchPinchStartCallback() { + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + this.#altText?.toggle(false); + this.parent.togglePointerEvents(false); + } + #touchPinchCallback(_origin2, prevDistance, distance) { + const slowDownFactor = 0.7; + let factor = slowDownFactor * (distance / prevDistance) + 1 - slowDownFactor; + if (factor === 1) { + return; + } + const rotationMatrix = this.#getRotationMatrix(this.rotation); + const transf = (x2, y4) => [rotationMatrix[0] * x2 + rotationMatrix[2] * y4, rotationMatrix[1] * x2 + rotationMatrix[3] * y4]; + const [parentWidth, parentHeight] = this.parentDimensions; + const savedX = this.x; + const savedY = this.y; + const savedWidth = this.width; + const savedHeight = this.height; + const minWidth = _AnnotationEditor.MIN_SIZE / parentWidth; + const minHeight = _AnnotationEditor.MIN_SIZE / parentHeight; + factor = Math.max(Math.min(factor, 1 / savedWidth, 1 / savedHeight), minWidth / savedWidth, minHeight / savedHeight); + const newWidth = _AnnotationEditor._round(savedWidth * factor); + const newHeight = _AnnotationEditor._round(savedHeight * factor); + if (newWidth === savedWidth && newHeight === savedHeight) { + return; + } + this.#initialRect ||= [savedX, savedY, savedWidth, savedHeight]; + const transfCenterPoint = transf(savedWidth / 2, savedHeight / 2); + const centerX = _AnnotationEditor._round(savedX + transfCenterPoint[0]); + const centerY = _AnnotationEditor._round(savedY + transfCenterPoint[1]); + const newTransfCenterPoint = transf(newWidth / 2, newHeight / 2); + this.x = centerX - newTransfCenterPoint[0]; + this.y = centerY - newTransfCenterPoint[1]; + this.width = newWidth; + this.height = newHeight; + this.setDims(); + this.fixAndSetPosition(); + this._onResizing(); + } + #touchPinchEndCallback() { + this.#altText?.toggle(true); + this.parent.togglePointerEvents(true); + this.#addResizeToUndoStack(); + } + pointerdown(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + event.preventDefault(); + return; + } + this.#hasBeenClicked = true; + if (this._isDraggable) { + this.#setUpDragSession(event); + return; + } + this.#selectOnPointerEvent(event); + } + #selectOnPointerEvent(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.ctrlKey && !isMac || event.shiftKey || event.metaKey && isMac) { + this.parent.toggleSelected(this); + } else { + this.parent.setSelected(this); + } + } + #setUpDragSession(event) { + const { + isSelected + } = this; + this._uiManager.setUpDragSession(); + let hasDraggingStarted = false; + const ac = new AbortController(); + const signal = this._uiManager.combinedSignal(ac); + const opts = { + capture: true, + passive: false, + signal + }; + const cancelDrag = (e9) => { + ac.abort(); + this.#dragPointerId = null; + this.#hasBeenClicked = false; + if (!this._uiManager.endDragSession()) { + this.#selectOnPointerEvent(e9); + } + if (hasDraggingStarted) { + this._onStopDragging(); + } + }; + if (isSelected) { + this.#prevDragX = event.clientX; + this.#prevDragY = event.clientY; + this.#dragPointerId = event.pointerId; + this.#dragPointerType = event.pointerType; + window.addEventListener("pointermove", (e9) => { + if (!hasDraggingStarted) { + hasDraggingStarted = true; + this._uiManager.toggleComment(this, true, false); + this._onStartDragging(); + } + const { + clientX: x2, + clientY: y4, + pointerId + } = e9; + if (pointerId !== this.#dragPointerId) { + stopEvent(e9); + return; + } + const [tx, ty] = this.screenToPageTranslation(x2 - this.#prevDragX, y4 - this.#prevDragY); + this.#prevDragX = x2; + this.#prevDragY = y4; + this._uiManager.dragSelectedEditors(tx, ty); + }, opts); + window.addEventListener("touchmove", stopEvent, opts); + window.addEventListener("pointerdown", (e9) => { + if (e9.pointerType === this.#dragPointerType) { + if (this.#touchManager || e9.isPrimary) { + cancelDrag(e9); + } + } + stopEvent(e9); + }, opts); + } + const pointerUpCallback = (e9) => { + if (!this.#dragPointerId || this.#dragPointerId === e9.pointerId) { + cancelDrag(e9); + return; + } + stopEvent(e9); + }; + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("blur", pointerUpCallback, { + signal + }); + } + _onStartDragging() { + } + _onStopDragging() { + } + moveInDOM() { + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + } + this.#moveInDOMTimeout = setTimeout(() => { + this.#moveInDOMTimeout = null; + this.parent?.moveEditorInDOM(this); + }, 0); + } + _setParentAndPosition(parent, x2, y4) { + parent.changeParent(this); + this.x = x2; + this.y = y4; + this.fixAndSetPosition(); + this._onTranslated(); + } + getRect(tx, ty, rotation = this.rotation) { + const scale = this.parentScale; + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const shiftX = tx / scale; + const shiftY = ty / scale; + const x2 = this.x * pageWidth; + const y4 = this.y * pageHeight; + const width = this.width * pageWidth; + const height = this.height * pageHeight; + switch (rotation) { + case 0: + return [x2 + shiftX + pageX, pageHeight - y4 - shiftY - height + pageY, x2 + shiftX + width + pageX, pageHeight - y4 - shiftY + pageY]; + case 90: + return [x2 + shiftY + pageX, pageHeight - y4 + shiftX + pageY, x2 + shiftY + height + pageX, pageHeight - y4 + shiftX + width + pageY]; + case 180: + return [x2 - shiftX - width + pageX, pageHeight - y4 + shiftY + pageY, x2 - shiftX + pageX, pageHeight - y4 + shiftY + height + pageY]; + case 270: + return [x2 - shiftY - height + pageX, pageHeight - y4 - shiftX - width + pageY, x2 - shiftY + pageX, pageHeight - y4 - shiftX + pageY]; + default: + throw new Error("Invalid rotation"); + } + } + getRectInCurrentCoords(rect, pageHeight) { + const [x1, y1, x2, y22] = rect; + const width = x2 - x1; + const height = y22 - y1; + switch (this.rotation) { + case 0: + return [x1, pageHeight - y22, width, height]; + case 90: + return [x1, pageHeight - y1, height, width]; + case 180: + return [x2, pageHeight - y1, width, height]; + case 270: + return [x2, pageHeight - y22, height, width]; + default: + throw new Error("Invalid rotation"); + } + } + getPDFRect() { + return this.getRect(0, 0); + } + getNonHCMColor() { + return this.color && _AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)); + } + onUpdatedColor() { + this.#comment?.onUpdatedColor(); + } + getData() { + const { + comment: { + text: str2, + color: color2, + date, + opacity, + deleted, + richText + }, + uid: id, + pageIndex, + creationDate, + modificationDate + } = this; + return { + id, + pageIndex, + rect: this.getPDFRect(), + richText, + contentsObj: { + str: str2 + }, + creationDate, + modificationDate: date || modificationDate, + popupRef: !deleted, + color: color2, + opacity + }; + } + onceAdded(focus) { + } + isEmpty() { + return false; + } + enableEditMode() { + if (this.isInEditMode()) { + return false; + } + this.parent.setEditingState(false); + this.#isInEditMode = true; + return true; + } + disableEditMode() { + if (!this.isInEditMode()) { + return false; + } + this.parent.setEditingState(true); + this.#isInEditMode = false; + return true; + } + isInEditMode() { + return this.#isInEditMode; + } + shouldGetKeyboardEvents() { + return this.#isResizerEnabledForKeyboard; + } + needsToBeRebuilt() { + return this.div && !this.isAttachedToDOM; + } + get isOnScreen() { + const { + top, + left, + bottom, + right + } = this.getClientDimensions(); + const { + innerHeight, + innerWidth + } = window; + return left < innerWidth && right > 0 && top < innerHeight && bottom > 0; + } + #addFocusListeners() { + if (this.#focusAC || !this.div) { + return; + } + this.#focusAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#focusAC); + this.div.addEventListener("focusin", this.focusin.bind(this), { + signal + }); + this.div.addEventListener("focusout", this.focusout.bind(this), { + signal + }); + } + rebuild() { + this.#addFocusListeners(); + } + rotate(_angle) { + } + resize() { + } + serializeDeleted() { + return { + id: this.annotationElementId, + deleted: true, + pageIndex: this.pageIndex, + popupRef: this._initialData?.popupRef || "" + }; + } + serialize(isForCopying = false, context = null) { + return { + annotationType: this.mode, + pageIndex: this.pageIndex, + rect: this.getPDFRect(), + rotation: this.rotation, + structTreeParentId: this._structTreeParentId, + popupRef: this._initialData?.popupRef || "" + }; + } + static async deserialize(data, parent, uiManager) { + const editor = new this.prototype.constructor({ + parent, + id: parent.getNextId(), + uiManager, + annotationElementId: data.annotationElementId, + creationDate: data.creationDate, + modificationDate: data.modificationDate + }); + editor.rotation = data.rotation; + editor.#accessibilityData = data.accessibilityData; + editor._isCopy = data.isCopy || false; + const [pageWidth, pageHeight] = editor.pageDimensions; + const [x2, y4, width, height] = editor.getRectInCurrentCoords(data.rect, pageHeight); + editor.x = x2 / pageWidth; + editor.y = y4 / pageHeight; + editor.width = width / pageWidth; + editor.height = height / pageHeight; + return editor; + } + get hasBeenModified() { + return !!this.annotationElementId && (this.deleted || this.serialize() !== null); + } + remove() { + this.#focusAC?.abort(); + this.#focusAC = null; + if (!this.isEmpty()) { + this.commit(); + } + if (this.parent) { + this.parent.remove(this); + } else { + this._uiManager.removeEditor(this); + } + this.hideCommentPopup(); + if (this.#moveInDOMTimeout) { + clearTimeout(this.#moveInDOMTimeout); + this.#moveInDOMTimeout = null; + } + this.#stopResizing(); + this.removeEditToolbar(); + if (this.#telemetryTimeouts) { + for (const timeout of this.#telemetryTimeouts.values()) { + clearTimeout(timeout); + } + this.#telemetryTimeouts = null; + } + this.parent = null; + this.#touchManager?.destroy(); + this.#touchManager = null; + this.#fakeAnnotation?.remove(); + this.#fakeAnnotation = null; + } + get isResizable() { + return false; + } + makeResizable() { + if (this.isResizable) { + this.#createResizers(); + this.#resizersDiv.classList.remove("hidden"); + } + } + get toolbarPosition() { + return null; + } + get commentButtonPosition() { + return this._uiManager.direction === "ltr" ? [1, 0] : [0, 0]; + } + get commentButtonPositionInPage() { + const { + commentButtonPosition: [posX, posY] + } = this; + const [blX, blY, trX, trY] = this.getPDFRect(); + return [_AnnotationEditor._round(blX + (trX - blX) * posX), _AnnotationEditor._round(blY + (trY - blY) * (1 - posY))]; + } + get commentButtonColor() { + return this._uiManager.makeCommentColor(this.getNonHCMColor(), this.opacity); + } + get commentPopupPosition() { + return this.#comment.commentPopupPositionInLayer; + } + set commentPopupPosition(pos) { + this.#comment.commentPopupPositionInLayer = pos; + } + hasDefaultPopupPosition() { + return this.#comment.hasDefaultPopupPosition(); + } + get commentButtonWidth() { + return this.#comment.commentButtonWidth; + } + get elementBeforePopup() { + return this.div; + } + setCommentButtonStates(options) { + this.#comment?.setCommentButtonStates(options); + } + keydown(event) { + if (!this.isResizable || event.target !== this.div || event.key !== "Enter") { + return; + } + this._uiManager.setSelected(this); + this.#savedDimensions = { + savedX: this.x, + savedY: this.y, + savedWidth: this.width, + savedHeight: this.height + }; + const children = this.#resizersDiv.children; + if (!this.#allResizerDivs) { + this.#allResizerDivs = Array.from(children); + const boundResizerKeydown = this.#resizerKeydown.bind(this); + const boundResizerBlur = this.#resizerBlur.bind(this); + const signal = this._uiManager._signal; + for (const div of this.#allResizerDivs) { + const name = div.getAttribute("data-resizer-name"); + div.setAttribute("role", "spinbutton"); + div.addEventListener("keydown", boundResizerKeydown, { + signal + }); + div.addEventListener("blur", boundResizerBlur, { + signal + }); + div.addEventListener("focus", this.#resizerFocus.bind(this, name), { + signal + }); + div.setAttribute("data-l10n-id", _AnnotationEditor._l10nResizer[name]); + } + } + const first = this.#allResizerDivs[0]; + let firstPosition = 0; + for (const div of children) { + if (div === first) { + break; + } + firstPosition++; + } + const nextFirstPosition = (360 - this.rotation + this.parentRotation) % 360 / 90 * (this.#allResizerDivs.length / 4); + if (nextFirstPosition !== firstPosition) { + if (nextFirstPosition < firstPosition) { + for (let i8 = 0; i8 < firstPosition - nextFirstPosition; i8++) { + this.#resizersDiv.append(this.#resizersDiv.firstChild); + } + } else if (nextFirstPosition > firstPosition) { + for (let i8 = 0; i8 < nextFirstPosition - firstPosition; i8++) { + this.#resizersDiv.firstChild.before(this.#resizersDiv.lastChild); + } + } + let i7 = 0; + for (const child of children) { + const div = this.#allResizerDivs[i7++]; + const name = div.getAttribute("data-resizer-name"); + child.setAttribute("data-l10n-id", _AnnotationEditor._l10nResizer[name]); + } + } + this.#setResizerTabIndex(0); + this.#isResizerEnabledForKeyboard = true; + this.#resizersDiv.firstChild.focus({ + focusVisible: true + }); + event.preventDefault(); + event.stopImmediatePropagation(); + } + #resizerKeydown(event) { + _AnnotationEditor._resizerKeyboardManager.exec(this, event); + } + #resizerBlur(event) { + if (this.#isResizerEnabledForKeyboard && event.relatedTarget?.parentNode !== this.#resizersDiv) { + this.#stopResizing(); + } + } + #resizerFocus(name) { + this.#focusedResizerName = this.#isResizerEnabledForKeyboard ? name : ""; + } + #setResizerTabIndex(value) { + if (!this.#allResizerDivs) { + return; + } + for (const div of this.#allResizerDivs) { + div.tabIndex = value; + } + } + _resizeWithKeyboard(x2, y4) { + if (!this.#isResizerEnabledForKeyboard) { + return; + } + this.#resizerPointermove(this.#focusedResizerName, { + deltaX: x2, + deltaY: y4, + fromKeyboard: true + }); + } + #stopResizing() { + this.#isResizerEnabledForKeyboard = false; + this.#setResizerTabIndex(-1); + this.#addResizeToUndoStack(); + } + _stopResizingWithKeyboard() { + this.#stopResizing(); + this.div.focus(); + } + select() { + if (this.isSelected && this._editToolbar) { + this._editToolbar.show(); + return; + } + this.isSelected = true; + this.makeResizable(); + this.div?.classList.add("selectedEditor"); + if (!this._editToolbar) { + this.addEditToolbar().then(() => { + if (this.div?.classList.contains("selectedEditor")) { + this._editToolbar?.show(); + } + }); + return; + } + this._editToolbar?.show(); + this.#altText?.toggleAltTextBadge(false); + } + focus() { + if (this.div && !this.div.contains(document.activeElement)) { + setTimeout(() => this.div?.focus({ + preventScroll: true + }), 0); + } + } + unselect() { + if (!this.isSelected) { + return; + } + this.isSelected = false; + this.#resizersDiv?.classList.add("hidden"); + this.div?.classList.remove("selectedEditor"); + if (this.div?.contains(document.activeElement)) { + this._uiManager.currentLayer.div.focus({ + preventScroll: true + }); + } + this._editToolbar?.hide(); + this.#altText?.toggleAltTextBadge(true); + this.hideCommentPopup(); + } + hideCommentPopup() { + if (this.hasComment) { + this._uiManager.toggleComment(null); + } + } + updateParams(type, value) { + } + disableEditing() { + } + enableEditing() { + } + get canChangeContent() { + return false; + } + enterInEditMode() { + if (!this.canChangeContent) { + return; + } + this.enableEditMode(); + this.div.focus(); + } + dblclick(event) { + if (event.target.nodeName === "BUTTON") { + return; + } + this.enterInEditMode(); + this.parent.updateToolbar({ + mode: this.constructor._editorType, + editId: this.uid + }); + } + getElementForAltText() { + return this.div; + } + get contentDiv() { + return this.div; + } + get isEditing() { + return this.#isEditing; + } + set isEditing(value) { + this.#isEditing = value; + if (!this.parent) { + return; + } + if (value) { + this.parent.setSelected(this); + this.parent.setActiveEditor(this); + } else { + this.parent.setActiveEditor(null); + } + } + static get MIN_SIZE() { + return 16; + } + static canCreateNewEmptyEditor() { + return true; + } + get telemetryInitialData() { + return { + action: "added" + }; + } + get telemetryFinalData() { + return null; + } + _reportTelemetry(data, mustWait = false) { + if (mustWait) { + this.#telemetryTimeouts ||= /* @__PURE__ */ new Map(); + const { + action + } = data; + let timeout = this.#telemetryTimeouts.get(action); + if (timeout) { + clearTimeout(timeout); + } + timeout = setTimeout(() => { + this._reportTelemetry(data); + this.#telemetryTimeouts.delete(action); + if (this.#telemetryTimeouts.size === 0) { + this.#telemetryTimeouts = null; + } + }, _AnnotationEditor._telemetryTimeout); + this.#telemetryTimeouts.set(action, timeout); + return; + } + data.type ||= this.editorType; + this._uiManager._eventBus.dispatch("reporttelemetry", { + source: this, + details: { + type: "editing", + data + } + }); + } + show(visible = this._isVisible) { + this.div.classList.toggle("hidden", !visible); + this._isVisible = visible; + } + enable() { + if (this.div) { + this.div.tabIndex = 0; + } + this.#disabled = false; + } + disable() { + if (this.div) { + this.div.tabIndex = -1; + } + this.#disabled = true; + } + updateFakeAnnotationElement(annotationLayer) { + if (!this.#fakeAnnotation && !this.deleted) { + this.#fakeAnnotation = annotationLayer.addFakeAnnotation(this); + return; + } + if (this.deleted) { + this.#fakeAnnotation.remove(); + this.#fakeAnnotation = null; + return; + } + if (this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized) { + this.#fakeAnnotation.updateEdited({ + rect: this.getPDFRect(), + popup: this.comment + }); + } + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + let content = annotation.container.querySelector(".annotationContent"); + if (!content) { + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + annotation.container.prepend(content); + } else if (content.nodeName === "CANVAS") { + const canvas = content; + content = document.createElement("div"); + content.classList.add("annotationContent", this.editorType); + canvas.before(content); + } + return content; + } + resetAnnotationElement(annotation) { + const { + firstChild + } = annotation.container; + if (firstChild?.nodeName === "DIV" && firstChild.classList.contains("annotationContent")) { + firstChild.remove(); + } + } + }; + FakeEditor = class extends AnnotationEditor { + constructor(params) { + super(params); + this.annotationElementId = params.annotationElementId; + this.deleted = true; + } + serialize() { + return this.serializeDeleted(); + } + }; + SEED = 3285377520; + MASK_HIGH = 4294901760; + MASK_LOW = 65535; + MurmurHash3_64 = class { + constructor(seed) { + this.h1 = seed ? seed & 4294967295 : SEED; + this.h2 = seed ? seed & 4294967295 : SEED; + } + update(input) { + let data, length; + if (typeof input === "string") { + data = new Uint8Array(input.length * 2); + length = 0; + for (let i7 = 0, ii = input.length; i7 < ii; i7++) { + const code = input.charCodeAt(i7); + if (code <= 255) { + data[length++] = code; + } else { + data[length++] = code >>> 8; + data[length++] = code & 255; + } + } + } else if (ArrayBuffer.isView(input)) { + data = input.slice(); + length = data.byteLength; + } else { + throw new Error("Invalid data format, must be a string or TypedArray."); + } + const blockCounts = length >> 2; + const tailLength = length - blockCounts * 4; + const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts); + let k1 = 0, k2 = 0; + let h12 = this.h1, h23 = this.h2; + const C1 = 3432918353, C22 = 461845907; + const C1_LOW = C1 & MASK_LOW, C2_LOW = C22 & MASK_LOW; + for (let i7 = 0; i7 < blockCounts; i7++) { + if (i7 & 1) { + k1 = dataUint32[i7]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C22 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + h12 ^= k1; + h12 = h12 << 13 | h12 >>> 19; + h12 = h12 * 5 + 3864292196; + } else { + k2 = dataUint32[i7]; + k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW; + k2 = k2 << 15 | k2 >>> 17; + k2 = k2 * C22 & MASK_HIGH | k2 * C2_LOW & MASK_LOW; + h23 ^= k2; + h23 = h23 << 13 | h23 >>> 19; + h23 = h23 * 5 + 3864292196; + } + } + k1 = 0; + switch (tailLength) { + case 3: + k1 ^= data[blockCounts * 4 + 2] << 16; + case 2: + k1 ^= data[blockCounts * 4 + 1] << 8; + case 1: + k1 ^= data[blockCounts * 4]; + k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW; + k1 = k1 << 15 | k1 >>> 17; + k1 = k1 * C22 & MASK_HIGH | k1 * C2_LOW & MASK_LOW; + if (blockCounts & 1) { + h12 ^= k1; + } else { + h23 ^= k1; + } + } + this.h1 = h12; + this.h2 = h23; + } + hexdigest() { + let h12 = this.h1, h23 = this.h2; + h12 ^= h23 >>> 1; + h12 = h12 * 3981806797 & MASK_HIGH | h12 * 36045 & MASK_LOW; + h23 = h23 * 4283543511 & MASK_HIGH | ((h23 << 16 | h12 >>> 16) * 2950163797 & MASK_HIGH) >>> 16; + h12 ^= h23 >>> 1; + h12 = h12 * 444984403 & MASK_HIGH | h12 * 60499 & MASK_LOW; + h23 = h23 * 3301882366 & MASK_HIGH | ((h23 << 16 | h12 >>> 16) * 3120437893 & MASK_HIGH) >>> 16; + h12 ^= h23 >>> 1; + return (h12 >>> 0).toString(16).padStart(8, "0") + (h23 >>> 0).toString(16).padStart(8, "0"); + } + }; + SerializableEmpty = Object.freeze({ + map: null, + hash: "", + transfer: void 0 + }); + AnnotationStorage = class { + #modified = false; + #modifiedIds = null; + #editorsMap = null; + #storage = /* @__PURE__ */ new Map(); + constructor() { + this.onSetModified = null; + this.onResetModified = null; + this.onAnnotationEditor = null; + } + getValue(key, defaultValue) { + const value = this.#storage.get(key); + if (value === void 0) { + return defaultValue; + } + return Object.assign(defaultValue, value); + } + getRawValue(key) { + return this.#storage.get(key); + } + remove(key) { + const storedValue = this.#storage.get(key); + if (storedValue === void 0) { + return; + } + if (storedValue instanceof AnnotationEditor) { + this.#editorsMap.delete(storedValue.annotationElementId); + } + this.#storage.delete(key); + if (this.#storage.size === 0) { + this.resetModified(); + } + if (typeof this.onAnnotationEditor === "function") { + for (const value of this.#storage.values()) { + if (value instanceof AnnotationEditor) { + return; + } + } + this.onAnnotationEditor(null); + } + } + setValue(key, value) { + const obj = this.#storage.get(key); + let modified = false; + if (obj !== void 0) { + for (const [entry, val2] of Object.entries(value)) { + if (obj[entry] !== val2) { + modified = true; + obj[entry] = val2; + } + } + } else { + modified = true; + this.#storage.set(key, value); + } + if (modified) { + this.#setModified(); + } + if (value instanceof AnnotationEditor) { + (this.#editorsMap ||= /* @__PURE__ */ new Map()).set(value.annotationElementId, value); + if (typeof this.onAnnotationEditor === "function") { + this.onAnnotationEditor(value.constructor._type); + } + } + } + has(key) { + return this.#storage.has(key); + } + get size() { + return this.#storage.size; + } + #setModified() { + if (!this.#modified) { + this.#modified = true; + if (typeof this.onSetModified === "function") { + this.onSetModified(); + } + } + } + resetModified() { + if (this.#modified) { + this.#modified = false; + if (typeof this.onResetModified === "function") { + this.onResetModified(); + } + } + } + get print() { + return new PrintAnnotationStorage(this); + } + get serializable() { + if (this.#storage.size === 0) { + return SerializableEmpty; + } + const map3 = /* @__PURE__ */ new Map(), hash = new MurmurHash3_64(), transfer = []; + const context = /* @__PURE__ */ Object.create(null); + let hasBitmap = false; + for (const [key, val2] of this.#storage) { + const serialized = val2 instanceof AnnotationEditor ? val2.serialize(false, context) : val2; + if (serialized) { + map3.set(key, serialized); + hash.update(`${key}:${JSON.stringify(serialized)}`); + hasBitmap ||= !!serialized.bitmap; + } + } + if (hasBitmap) { + for (const value of map3.values()) { + if (value.bitmap) { + transfer.push(value.bitmap); + } + } + } + return map3.size > 0 ? { + map: map3, + hash: hash.hexdigest(), + transfer + } : SerializableEmpty; + } + get editorStats() { + let stats = null; + const typeToEditor = /* @__PURE__ */ new Map(); + let numberOfEditedComments = 0; + let numberOfDeletedComments = 0; + for (const value of this.#storage.values()) { + if (!(value instanceof AnnotationEditor)) { + if (value.popup) { + if (value.popup.deleted) { + numberOfDeletedComments += 1; + } else { + numberOfEditedComments += 1; + } + } + continue; + } + if (value.isCommentDeleted) { + numberOfDeletedComments += 1; + } else if (value.hasEditedComment) { + numberOfEditedComments += 1; + } + const editorStats = value.telemetryFinalData; + if (!editorStats) { + continue; + } + const { + type + } = editorStats; + if (!typeToEditor.has(type)) { + typeToEditor.set(type, Object.getPrototypeOf(value).constructor); + } + stats ||= /* @__PURE__ */ Object.create(null); + const map3 = stats[type] ||= /* @__PURE__ */ new Map(); + for (const [key, val2] of Object.entries(editorStats)) { + if (key === "type") { + continue; + } + let counters = map3.get(key); + if (!counters) { + counters = /* @__PURE__ */ new Map(); + map3.set(key, counters); + } + const count = counters.get(val2) ?? 0; + counters.set(val2, count + 1); + } + } + if (numberOfDeletedComments > 0 || numberOfEditedComments > 0) { + stats ||= /* @__PURE__ */ Object.create(null); + stats.comments = { + deleted: numberOfDeletedComments, + edited: numberOfEditedComments + }; + } + if (!stats) { + return null; + } + for (const [type, editor] of typeToEditor) { + stats[type] = editor.computeTelemetryFinalData(stats[type]); + } + return stats; + } + resetModifiedIds() { + this.#modifiedIds = null; + } + updateEditor(annotationId, data) { + const value = this.#editorsMap?.get(annotationId); + if (value) { + value.updateFromAnnotationLayer(data); + return true; + } + return false; + } + getEditor(annotationId) { + return this.#editorsMap?.get(annotationId) || null; + } + get modifiedIds() { + if (this.#modifiedIds) { + return this.#modifiedIds; + } + const ids = []; + if (this.#editorsMap) { + for (const value of this.#editorsMap.values()) { + if (!value.serialize()) { + continue; + } + ids.push(value.annotationElementId); + } + } + return this.#modifiedIds = { + ids: new Set(ids), + hash: ids.join(",") + }; + } + [Symbol.iterator]() { + return this.#storage.entries(); + } + }; + PrintAnnotationStorage = class extends AnnotationStorage { + #serializable; + constructor(parent) { + super(); + const { + map: map3, + hash, + transfer + } = parent.serializable; + const clone3 = structuredClone(map3, transfer ? { + transfer + } : null); + this.#serializable = { + map: clone3, + hash, + transfer + }; + } + get print() { + unreachable("Should not call PrintAnnotationStorage.print"); + } + get serializable() { + return this.#serializable; + } + get modifiedIds() { + return shadow(this, "modifiedIds", { + ids: /* @__PURE__ */ new Set(), + hash: "" + }); + } + }; + FontLoader = class { + #systemFonts = /* @__PURE__ */ new Set(); + constructor({ + ownerDocument = globalThis.document, + styleElement = null + }) { + this._document = ownerDocument; + this.nativeFontFaces = /* @__PURE__ */ new Set(); + this.styleElement = null; + this.loadingRequests = []; + this.loadTestFontId = 0; + } + addNativeFontFace(nativeFontFace) { + this.nativeFontFaces.add(nativeFontFace); + this._document.fonts.add(nativeFontFace); + } + removeNativeFontFace(nativeFontFace) { + this.nativeFontFaces.delete(nativeFontFace); + this._document.fonts.delete(nativeFontFace); + } + insertRule(rule) { + if (!this.styleElement) { + this.styleElement = this._document.createElement("style"); + this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement); + } + const styleSheet = this.styleElement.sheet; + styleSheet.insertRule(rule, styleSheet.cssRules.length); + } + clear() { + for (const nativeFontFace of this.nativeFontFaces) { + this._document.fonts.delete(nativeFontFace); + } + this.nativeFontFaces.clear(); + this.#systemFonts.clear(); + if (this.styleElement) { + this.styleElement.remove(); + this.styleElement = null; + } + } + async loadSystemFont({ + systemFontInfo: info2, + disableFontFace, + _inspectFont + }) { + if (!info2 || this.#systemFonts.has(info2.loadedName)) { + return; + } + assert(!disableFontFace, "loadSystemFont shouldn't be called when `disableFontFace` is set."); + if (this.isFontLoadingAPISupported) { + const { + loadedName, + src, + style + } = info2; + const fontFace = new FontFace(loadedName, src, style); + this.addNativeFontFace(fontFace); + try { + await fontFace.load(); + this.#systemFonts.add(loadedName); + _inspectFont?.(info2); + } catch { + warn(`Cannot load system font: ${info2.baseFontName}, installing it could help to improve PDF rendering.`); + this.removeNativeFontFace(fontFace); + } + return; + } + unreachable("Not implemented: loadSystemFont without the Font Loading API."); + } + async bind(font) { + if (font.attached || font.missingFile && !font.systemFontInfo) { + return; + } + font.attached = true; + if (font.systemFontInfo) { + await this.loadSystemFont(font); + return; + } + if (this.isFontLoadingAPISupported) { + const nativeFontFace = font.createNativeFontFace(); + if (nativeFontFace) { + this.addNativeFontFace(nativeFontFace); + try { + await nativeFontFace.loaded; + } catch (ex) { + warn(`Failed to load font '${nativeFontFace.family}': '${ex}'.`); + font.disableFontFace = true; + throw ex; + } + } + return; + } + const rule = font.createFontFaceRule(); + if (rule) { + this.insertRule(rule); + if (this.isSyncFontLoadingSupported) { + return; + } + await new Promise((resolve2) => { + const request = this._queueLoadingCallback(resolve2); + this._prepareFontLoadEvent(font, request); + }); + } + } + get isFontLoadingAPISupported() { + const hasFonts = !!this._document?.fonts; + return shadow(this, "isFontLoadingAPISupported", hasFonts); + } + get isSyncFontLoadingSupported() { + return shadow(this, "isSyncFontLoadingSupported", isNodeJS || util_FeatureTest.platform.isFirefox); + } + _queueLoadingCallback(callback2) { + function completeRequest() { + assert(!request.done, "completeRequest() cannot be called twice."); + request.done = true; + while (loadingRequests.length > 0 && loadingRequests[0].done) { + const otherRequest = loadingRequests.shift(); + setTimeout(otherRequest.callback, 0); + } + } + const { + loadingRequests + } = this; + const request = { + done: false, + complete: completeRequest, + callback: callback2 + }; + loadingRequests.push(request); + return request; + } + get _loadTestFont() { + const testFont = atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA=="); + return shadow(this, "_loadTestFont", testFont); + } + _prepareFontLoadEvent(font, request) { + function int32(data2, offset) { + return data2.charCodeAt(offset) << 24 | data2.charCodeAt(offset + 1) << 16 | data2.charCodeAt(offset + 2) << 8 | data2.charCodeAt(offset + 3) & 255; + } + function spliceString(s6, offset, remove, insert) { + const chunk1 = s6.substring(0, offset); + const chunk2 = s6.substring(offset + remove); + return chunk1 + insert + chunk2; + } + let i7, ii; + const canvas = this._document.createElement("canvas"); + canvas.width = 1; + canvas.height = 1; + const ctx = canvas.getContext("2d"); + let called = 0; + function isFontReady(name, callback2) { + if (++called > 30) { + warn("Load test font never loaded."); + callback2(); + return; + } + ctx.font = "30px " + name; + ctx.fillText(".", 0, 20); + const imageData = ctx.getImageData(0, 0, 1, 1); + if (imageData.data[3] > 0) { + callback2(); + return; + } + setTimeout(isFontReady.bind(null, name, callback2)); + } + const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`; + let data = this._loadTestFont; + const COMMENT_OFFSET = 976; + data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); + const CFF_CHECKSUM_OFFSET = 16; + const XXXX_VALUE = 1482184792; + let checksum = int32(data, CFF_CHECKSUM_OFFSET); + for (i7 = 0, ii = loadTestFontId.length - 3; i7 < ii; i7 += 4) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i7) | 0; + } + if (i7 < loadTestFontId.length) { + checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i7) | 0; + } + data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); + const url = `url(data:font/opentype;base64,${btoa(data)});`; + const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`; + this.insertRule(rule); + const div = this._document.createElement("div"); + div.style.visibility = "hidden"; + div.style.width = div.style.height = "10px"; + div.style.position = "absolute"; + div.style.top = div.style.left = "0px"; + for (const name of [font.loadedName, loadTestFontId]) { + const span = this._document.createElement("span"); + span.textContent = "Hi"; + span.style.fontFamily = name; + div.append(span); + } + this._document.body.append(div); + isFontReady(loadTestFontId, () => { + div.remove(); + request.complete(); + }); + } + }; + FontFaceObject = class { + #fontData; + constructor(translatedData, inspectFont = null, extra, charProcOperatorList) { + this.compiledGlyphs = /* @__PURE__ */ Object.create(null); + this.#fontData = translatedData; + this._inspectFont = inspectFont; + if (extra) { + Object.assign(this, extra); + } + if (charProcOperatorList) { + this.charProcOperatorList = charProcOperatorList; + } + } + createNativeFontFace() { + if (!this.data || this.disableFontFace) { + return null; + } + let nativeFontFace; + if (!this.cssFontInfo) { + nativeFontFace = new FontFace(this.loadedName, this.data, {}); + } else { + const css2 = { + weight: this.cssFontInfo.fontWeight + }; + if (this.cssFontInfo.italicAngle) { + css2.style = `oblique ${this.cssFontInfo.italicAngle}deg`; + } + nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css2); + } + this._inspectFont?.(this); + return nativeFontFace; + } + createFontFaceRule() { + if (!this.data || this.disableFontFace) { + return null; + } + const url = `url(data:${this.mimetype};base64,${toBase64Util(this.data)});`; + let rule; + if (!this.cssFontInfo) { + rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`; + } else { + let css2 = `font-weight: ${this.cssFontInfo.fontWeight};`; + if (this.cssFontInfo.italicAngle) { + css2 += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`; + } + rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css2}src:${url}}`; + } + this._inspectFont?.(this, url); + return rule; + } + getPathGenerator(objs, character) { + if (this.compiledGlyphs[character] !== void 0) { + return this.compiledGlyphs[character]; + } + const objId = this.loadedName + "_path_" + character; + let cmds; + try { + cmds = objs.get(objId); + } catch (ex) { + warn(`getPathGenerator - ignoring character: "${ex}".`); + } + const path6 = makePathFromDrawOPS(cmds); + if (!this.fontExtraProperties) { + objs.delete(objId); + } + return this.compiledGlyphs[character] = path6; + } + get black() { + return this.#fontData.black; + } + get bold() { + return this.#fontData.bold; + } + get disableFontFace() { + return this.#fontData.disableFontFace ?? false; + } + get fontExtraProperties() { + return this.#fontData.fontExtraProperties ?? false; + } + get isInvalidPDFjsFont() { + return this.#fontData.isInvalidPDFjsFont; + } + get isType3Font() { + return this.#fontData.isType3Font; + } + get italic() { + return this.#fontData.italic; + } + get missingFile() { + return this.#fontData.missingFile; + } + get remeasure() { + return this.#fontData.remeasure; + } + get vertical() { + return this.#fontData.vertical; + } + get ascent() { + return this.#fontData.ascent; + } + get defaultWidth() { + return this.#fontData.defaultWidth; + } + get descent() { + return this.#fontData.descent; + } + get bbox() { + return this.#fontData.bbox; + } + get fontMatrix() { + return this.#fontData.fontMatrix; + } + get fallbackName() { + return this.#fontData.fallbackName; + } + get loadedName() { + return this.#fontData.loadedName; + } + get mimetype() { + return this.#fontData.mimetype; + } + get name() { + return this.#fontData.name; + } + get data() { + return this.#fontData.data; + } + clearData() { + this.#fontData.clearData(); + } + get cssFontInfo() { + return this.#fontData.cssFontInfo; + } + get systemFontInfo() { + return this.#fontData.systemFontInfo; + } + get defaultVMetrics() { + return this.#fontData.defaultVMetrics; + } + }; + CssFontInfo = class _CssFontInfo { + #buffer; + #view; + #decoder; + static strings = ["fontFamily", "fontWeight", "italicAngle"]; + static write(info2) { + const encoder = new TextEncoder(); + const encodedStrings = {}; + let stringsLength = 0; + for (const prop of _CssFontInfo.strings) { + const encoded = encoder.encode(info2[prop]); + encodedStrings[prop] = encoded; + stringsLength += 4 + encoded.length; + } + const buffer = new ArrayBuffer(stringsLength); + const data = new Uint8Array(buffer); + const view = new DataView(buffer); + let offset = 0; + for (const prop of _CssFontInfo.strings) { + const encoded = encodedStrings[prop]; + const length = encoded.length; + view.setUint32(offset, length); + data.set(encoded, offset + 4); + offset += 4 + length; + } + assert(offset === buffer.byteLength, "CssFontInfo.write: Buffer overflow"); + return buffer; + } + constructor(buffer) { + this.#buffer = buffer; + this.#view = new DataView(this.#buffer); + this.#decoder = new TextDecoder(); + } + #readString(index2) { + assert(index2 < _CssFontInfo.strings.length, "Invalid string index"); + let offset = 0; + for (let i7 = 0; i7 < index2; i7++) { + offset += this.#view.getUint32(offset) + 4; + } + const length = this.#view.getUint32(offset); + return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length)); + } + get fontFamily() { + return this.#readString(0); + } + get fontWeight() { + return this.#readString(1); + } + get italicAngle() { + return this.#readString(2); + } + }; + SystemFontInfo = class _SystemFontInfo { + #buffer; + #view; + #decoder; + static strings = ["css", "loadedName", "baseFontName", "src"]; + static write(info2) { + const encoder = new TextEncoder(); + const encodedStrings = {}; + let stringsLength = 0; + for (const prop of _SystemFontInfo.strings) { + const encoded = encoder.encode(info2[prop]); + encodedStrings[prop] = encoded; + stringsLength += 4 + encoded.length; + } + stringsLength += 4; + let encodedStyleStyle, encodedStyleWeight, lengthEstimate = 1 + stringsLength; + if (info2.style) { + encodedStyleStyle = encoder.encode(info2.style.style); + encodedStyleWeight = encoder.encode(info2.style.weight); + lengthEstimate += 4 + encodedStyleStyle.length + 4 + encodedStyleWeight.length; + } + const buffer = new ArrayBuffer(lengthEstimate); + const data = new Uint8Array(buffer); + const view = new DataView(buffer); + let offset = 0; + view.setUint8(offset++, info2.guessFallback ? 1 : 0); + view.setUint32(offset, 0); + offset += 4; + stringsLength = 0; + for (const prop of _SystemFontInfo.strings) { + const encoded = encodedStrings[prop]; + const length = encoded.length; + stringsLength += 4 + length; + view.setUint32(offset, length); + data.set(encoded, offset + 4); + offset += 4 + length; + } + view.setUint32(offset - stringsLength - 4, stringsLength); + if (info2.style) { + view.setUint32(offset, encodedStyleStyle.length); + data.set(encodedStyleStyle, offset + 4); + offset += 4 + encodedStyleStyle.length; + view.setUint32(offset, encodedStyleWeight.length); + data.set(encodedStyleWeight, offset + 4); + offset += 4 + encodedStyleWeight.length; + } + assert(offset <= buffer.byteLength, "SubstitionInfo.write: Buffer overflow"); + return buffer.transferToFixedLength(offset); + } + constructor(buffer) { + this.#buffer = buffer; + this.#view = new DataView(this.#buffer); + this.#decoder = new TextDecoder(); + } + get guessFallback() { + return this.#view.getUint8(0) !== 0; + } + #readString(index2) { + assert(index2 < _SystemFontInfo.strings.length, "Invalid string index"); + let offset = 5; + for (let i7 = 0; i7 < index2; i7++) { + offset += this.#view.getUint32(offset) + 4; + } + const length = this.#view.getUint32(offset); + return this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, length)); + } + get css() { + return this.#readString(0); + } + get loadedName() { + return this.#readString(1); + } + get baseFontName() { + return this.#readString(2); + } + get src() { + return this.#readString(3); + } + get style() { + let offset = 1; + offset += 4 + this.#view.getUint32(offset); + const styleLength = this.#view.getUint32(offset); + const style = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, styleLength)); + offset += 4 + styleLength; + const weightLength = this.#view.getUint32(offset); + const weight = this.#decoder.decode(new Uint8Array(this.#buffer, offset + 4, weightLength)); + return { + style, + weight + }; + } + }; + FontInfo = class _FontInfo { + static bools = ["black", "bold", "disableFontFace", "fontExtraProperties", "isInvalidPDFjsFont", "isType3Font", "italic", "missingFile", "remeasure", "vertical"]; + static numbers = ["ascent", "defaultWidth", "descent"]; + static strings = ["fallbackName", "loadedName", "mimetype", "name"]; + static #OFFSET_NUMBERS = Math.ceil(this.bools.length * 2 / 8); + static #OFFSET_BBOX = this.#OFFSET_NUMBERS + this.numbers.length * 8; + static #OFFSET_FONT_MATRIX = this.#OFFSET_BBOX + 1 + 2 * 4; + static #OFFSET_DEFAULT_VMETRICS = this.#OFFSET_FONT_MATRIX + 1 + 8 * 6; + static #OFFSET_STRINGS = this.#OFFSET_DEFAULT_VMETRICS + 1 + 2 * 3; + #buffer; + #decoder; + #view; + constructor({ + data, + extra + }) { + this.#buffer = data; + this.#decoder = new TextDecoder(); + this.#view = new DataView(this.#buffer); + if (extra) { + Object.assign(this, extra); + } + } + #readBoolean(index2) { + assert(index2 < _FontInfo.bools.length, "Invalid boolean index"); + const byteOffset = Math.floor(index2 / 4); + const bitOffset = index2 * 2 % 8; + const value = this.#view.getUint8(byteOffset) >> bitOffset & 3; + return value === 0 ? void 0 : value === 2; + } + get black() { + return this.#readBoolean(0); + } + get bold() { + return this.#readBoolean(1); + } + get disableFontFace() { + return this.#readBoolean(2); + } + get fontExtraProperties() { + return this.#readBoolean(3); + } + get isInvalidPDFjsFont() { + return this.#readBoolean(4); + } + get isType3Font() { + return this.#readBoolean(5); + } + get italic() { + return this.#readBoolean(6); + } + get missingFile() { + return this.#readBoolean(7); + } + get remeasure() { + return this.#readBoolean(8); + } + get vertical() { + return this.#readBoolean(9); + } + #readNumber(index2) { + assert(index2 < _FontInfo.numbers.length, "Invalid number index"); + return this.#view.getFloat64(_FontInfo.#OFFSET_NUMBERS + index2 * 8); + } + get ascent() { + return this.#readNumber(0); + } + get defaultWidth() { + return this.#readNumber(1); + } + get descent() { + return this.#readNumber(2); + } + get bbox() { + let offset = _FontInfo.#OFFSET_BBOX; + const numCoords = this.#view.getUint8(offset); + if (numCoords === 0) { + return void 0; + } + offset += 1; + const bbox = []; + for (let i7 = 0; i7 < 4; i7++) { + bbox.push(this.#view.getInt16(offset, true)); + offset += 2; + } + return bbox; + } + get fontMatrix() { + let offset = _FontInfo.#OFFSET_FONT_MATRIX; + const numPoints = this.#view.getUint8(offset); + if (numPoints === 0) { + return void 0; + } + offset += 1; + const fontMatrix = []; + for (let i7 = 0; i7 < 6; i7++) { + fontMatrix.push(this.#view.getFloat64(offset, true)); + offset += 8; + } + return fontMatrix; + } + get defaultVMetrics() { + let offset = _FontInfo.#OFFSET_DEFAULT_VMETRICS; + const numMetrics = this.#view.getUint8(offset); + if (numMetrics === 0) { + return void 0; + } + offset += 1; + const defaultVMetrics = []; + for (let i7 = 0; i7 < 3; i7++) { + defaultVMetrics.push(this.#view.getInt16(offset, true)); + offset += 2; + } + return defaultVMetrics; + } + #readString(index2) { + assert(index2 < _FontInfo.strings.length, "Invalid string index"); + let offset = _FontInfo.#OFFSET_STRINGS + 4; + for (let i7 = 0; i7 < index2; i7++) { + offset += this.#view.getUint32(offset) + 4; + } + const length = this.#view.getUint32(offset); + const stringData = new Uint8Array(length); + stringData.set(new Uint8Array(this.#buffer, offset + 4, length)); + return this.#decoder.decode(stringData); + } + get fallbackName() { + return this.#readString(0); + } + get loadedName() { + return this.#readString(1); + } + get mimetype() { + return this.#readString(2); + } + get name() { + return this.#readString(3); + } + get data() { + let offset = _FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + offset += 4 + systemFontInfoLength; + const cssFontInfoLength = this.#view.getUint32(offset); + offset += 4 + cssFontInfoLength; + const length = this.#view.getUint32(offset); + if (length === 0) { + return void 0; + } + return new Uint8Array(this.#buffer, offset + 4, length); + } + clearData() { + let offset = _FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + offset += 4 + systemFontInfoLength; + const cssFontInfoLength = this.#view.getUint32(offset); + offset += 4 + cssFontInfoLength; + const length = this.#view.getUint32(offset); + const data = new Uint8Array(this.#buffer, offset + 4, length); + data.fill(0); + this.#view.setUint32(offset, 0); + } + get cssFontInfo() { + let offset = _FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + offset += 4 + systemFontInfoLength; + const cssFontInfoLength = this.#view.getUint32(offset); + if (cssFontInfoLength === 0) { + return null; + } + const cssFontInfoData = new Uint8Array(cssFontInfoLength); + cssFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, cssFontInfoLength)); + return new CssFontInfo(cssFontInfoData.buffer); + } + get systemFontInfo() { + let offset = _FontInfo.#OFFSET_STRINGS; + const stringsLength = this.#view.getUint32(offset); + offset += 4 + stringsLength; + const systemFontInfoLength = this.#view.getUint32(offset); + if (systemFontInfoLength === 0) { + return null; + } + const systemFontInfoData = new Uint8Array(systemFontInfoLength); + systemFontInfoData.set(new Uint8Array(this.#buffer, offset + 4, systemFontInfoLength)); + return new SystemFontInfo(systemFontInfoData.buffer); + } + static write(font) { + const systemFontInfoBuffer = font.systemFontInfo ? SystemFontInfo.write(font.systemFontInfo) : null; + const cssFontInfoBuffer = font.cssFontInfo ? CssFontInfo.write(font.cssFontInfo) : null; + const encoder = new TextEncoder(); + const encodedStrings = {}; + let stringsLength = 0; + for (const prop of _FontInfo.strings) { + encodedStrings[prop] = encoder.encode(font[prop]); + stringsLength += 4 + encodedStrings[prop].length; + } + const lengthEstimate = _FontInfo.#OFFSET_STRINGS + 4 + stringsLength + 4 + (systemFontInfoBuffer ? systemFontInfoBuffer.byteLength : 0) + 4 + (cssFontInfoBuffer ? cssFontInfoBuffer.byteLength : 0) + 4 + (font.data ? font.data.length : 0); + const buffer = new ArrayBuffer(lengthEstimate); + const data = new Uint8Array(buffer); + const view = new DataView(buffer); + let offset = 0; + const numBools = _FontInfo.bools.length; + let boolByte = 0, boolBit = 0; + for (let i7 = 0; i7 < numBools; i7++) { + const value = font[_FontInfo.bools[i7]]; + const bits = value === void 0 ? 0 : value ? 2 : 1; + boolByte |= bits << boolBit; + boolBit += 2; + if (boolBit === 8 || i7 === numBools - 1) { + view.setUint8(offset++, boolByte); + boolByte = 0; + boolBit = 0; + } + } + assert(offset === _FontInfo.#OFFSET_NUMBERS, "FontInfo.write: Boolean properties offset mismatch"); + for (const prop of _FontInfo.numbers) { + view.setFloat64(offset, font[prop]); + offset += 8; + } + assert(offset === _FontInfo.#OFFSET_BBOX, "FontInfo.write: Number properties offset mismatch"); + if (font.bbox) { + view.setUint8(offset++, 4); + for (const coord of font.bbox) { + view.setInt16(offset, coord, true); + offset += 2; + } + } else { + view.setUint8(offset++, 0); + offset += 2 * 4; + } + assert(offset === _FontInfo.#OFFSET_FONT_MATRIX, "FontInfo.write: BBox properties offset mismatch"); + if (font.fontMatrix) { + view.setUint8(offset++, 6); + for (const point of font.fontMatrix) { + view.setFloat64(offset, point, true); + offset += 8; + } + } else { + view.setUint8(offset++, 0); + offset += 8 * 6; + } + assert(offset === _FontInfo.#OFFSET_DEFAULT_VMETRICS, "FontInfo.write: FontMatrix properties offset mismatch"); + if (font.defaultVMetrics) { + view.setUint8(offset++, 1); + for (const metric of font.defaultVMetrics) { + view.setInt16(offset, metric, true); + offset += 2; + } + } else { + view.setUint8(offset++, 0); + offset += 3 * 2; + } + assert(offset === _FontInfo.#OFFSET_STRINGS, "FontInfo.write: DefaultVMetrics properties offset mismatch"); + view.setUint32(_FontInfo.#OFFSET_STRINGS, 0); + offset += 4; + for (const prop of _FontInfo.strings) { + const encoded = encodedStrings[prop]; + const length = encoded.length; + view.setUint32(offset, length); + data.set(encoded, offset + 4); + offset += 4 + length; + } + view.setUint32(_FontInfo.#OFFSET_STRINGS, offset - _FontInfo.#OFFSET_STRINGS - 4); + if (!systemFontInfoBuffer) { + view.setUint32(offset, 0); + offset += 4; + } else { + const length = systemFontInfoBuffer.byteLength; + view.setUint32(offset, length); + assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at systemFontInfo"); + data.set(new Uint8Array(systemFontInfoBuffer), offset + 4); + offset += 4 + length; + } + if (!cssFontInfoBuffer) { + view.setUint32(offset, 0); + offset += 4; + } else { + const length = cssFontInfoBuffer.byteLength; + view.setUint32(offset, length); + assert(offset + 4 + length <= buffer.byteLength, "FontInfo.write: Buffer overflow at cssFontInfo"); + data.set(new Uint8Array(cssFontInfoBuffer), offset + 4); + offset += 4 + length; + } + if (font.data === void 0) { + view.setUint32(offset, 0); + offset += 4; + } else { + view.setUint32(offset, font.data.length); + data.set(font.data, offset + 4); + offset += 4 + font.data.length; + } + assert(offset <= buffer.byteLength, "FontInfo.write: Buffer overflow"); + return buffer.transferToFixedLength(offset); + } + }; + PatternInfo = class _PatternInfo { + static #KIND = 0; + static #HAS_BBOX = 1; + static #HAS_BACKGROUND = 2; + static #SHADING_TYPE = 3; + static #N_COORD = 4; + static #N_COLOR = 8; + static #N_STOP = 12; + static #N_FIGURES = 16; + constructor(buffer) { + this.buffer = buffer; + this.view = new DataView(buffer); + this.data = new Uint8Array(buffer); + } + static write(ir) { + let kind, bbox = null, coords = [], colors2 = [], colorStops = [], figures = [], shadingType = null, background = null; + switch (ir[0]) { + case "RadialAxial": + kind = ir[1] === "axial" ? 1 : 2; + bbox = ir[2]; + colorStops = ir[3]; + if (kind === 1) { + coords.push(...ir[4], ...ir[5]); + } else { + coords.push(ir[4][0], ir[4][1], ir[6], ir[5][0], ir[5][1], ir[7]); + } + break; + case "Mesh": + kind = 3; + shadingType = ir[1]; + coords = ir[2]; + colors2 = ir[3]; + figures = ir[4] || []; + bbox = ir[6]; + background = ir[7]; + break; + default: + throw new Error(`Unsupported pattern type: ${ir[0]}`); + } + const nCoord = Math.floor(coords.length / 2); + const nColor = Math.floor(colors2.length / 3); + const nStop = colorStops.length; + const nFigures = figures.length; + let figuresSize = 0; + for (const figure of figures) { + figuresSize += 1; + figuresSize = Math.ceil(figuresSize / 4) * 4; + figuresSize += 4 + figure.coords.length * 4; + figuresSize += 4 + figure.colors.length * 4; + if (figure.verticesPerRow !== void 0) { + figuresSize += 4; + } + } + const byteLen = 20 + nCoord * 8 + nColor * 3 + nStop * 8 + (bbox ? 16 : 0) + (background ? 3 : 0) + figuresSize; + const buffer = new ArrayBuffer(byteLen); + const dataView = new DataView(buffer); + const u8data = new Uint8Array(buffer); + dataView.setUint8(_PatternInfo.#KIND, kind); + dataView.setUint8(_PatternInfo.#HAS_BBOX, bbox ? 1 : 0); + dataView.setUint8(_PatternInfo.#HAS_BACKGROUND, background ? 1 : 0); + dataView.setUint8(_PatternInfo.#SHADING_TYPE, shadingType); + dataView.setUint32(_PatternInfo.#N_COORD, nCoord, true); + dataView.setUint32(_PatternInfo.#N_COLOR, nColor, true); + dataView.setUint32(_PatternInfo.#N_STOP, nStop, true); + dataView.setUint32(_PatternInfo.#N_FIGURES, nFigures, true); + let offset = 20; + const coordsView = new Float32Array(buffer, offset, nCoord * 2); + coordsView.set(coords); + offset += nCoord * 8; + u8data.set(colors2, offset); + offset += nColor * 3; + for (const [pos, hex2] of colorStops) { + dataView.setFloat32(offset, pos, true); + offset += 4; + dataView.setUint32(offset, parseInt(hex2.slice(1), 16), true); + offset += 4; + } + if (bbox) { + for (const v4 of bbox) { + dataView.setFloat32(offset, v4, true); + offset += 4; + } + } + if (background) { + u8data.set(background, offset); + offset += 3; + } + for (let i7 = 0; i7 < figures.length; i7++) { + const figure = figures[i7]; + dataView.setUint8(offset, figure.type); + offset += 1; + offset = Math.ceil(offset / 4) * 4; + dataView.setUint32(offset, figure.coords.length, true); + offset += 4; + const figureCoordsView = new Int32Array(buffer, offset, figure.coords.length); + figureCoordsView.set(figure.coords); + offset += figure.coords.length * 4; + dataView.setUint32(offset, figure.colors.length, true); + offset += 4; + const colorsView = new Int32Array(buffer, offset, figure.colors.length); + colorsView.set(figure.colors); + offset += figure.colors.length * 4; + if (figure.verticesPerRow !== void 0) { + dataView.setUint32(offset, figure.verticesPerRow, true); + offset += 4; + } + } + return buffer; + } + getIR() { + const dataView = this.view; + const kind = this.data[_PatternInfo.#KIND]; + const hasBBox = !!this.data[_PatternInfo.#HAS_BBOX]; + const hasBackground = !!this.data[_PatternInfo.#HAS_BACKGROUND]; + const nCoord = dataView.getUint32(_PatternInfo.#N_COORD, true); + const nColor = dataView.getUint32(_PatternInfo.#N_COLOR, true); + const nStop = dataView.getUint32(_PatternInfo.#N_STOP, true); + const nFigures = dataView.getUint32(_PatternInfo.#N_FIGURES, true); + let offset = 20; + const coords = new Float32Array(this.buffer, offset, nCoord * 2); + offset += nCoord * 8; + const colors2 = new Uint8Array(this.buffer, offset, nColor * 3); + offset += nColor * 3; + const stops = []; + for (let i7 = 0; i7 < nStop; ++i7) { + const p4 = dataView.getFloat32(offset, true); + offset += 4; + const rgb = dataView.getUint32(offset, true); + offset += 4; + stops.push([p4, `#${rgb.toString(16).padStart(6, "0")}`]); + } + let bbox = null; + if (hasBBox) { + bbox = []; + for (let i7 = 0; i7 < 4; ++i7) { + bbox.push(dataView.getFloat32(offset, true)); + offset += 4; + } + } + let background = null; + if (hasBackground) { + background = new Uint8Array(this.buffer, offset, 3); + offset += 3; + } + const figures = []; + for (let i7 = 0; i7 < nFigures; ++i7) { + const type = dataView.getUint8(offset); + offset += 1; + offset = Math.ceil(offset / 4) * 4; + const coordsLength = dataView.getUint32(offset, true); + offset += 4; + const figureCoords = new Int32Array(this.buffer, offset, coordsLength); + offset += coordsLength * 4; + const colorsLength = dataView.getUint32(offset, true); + offset += 4; + const figureColors = new Int32Array(this.buffer, offset, colorsLength); + offset += colorsLength * 4; + const figure = { + type, + coords: figureCoords, + colors: figureColors + }; + if (type === MeshFigureType.LATTICE) { + figure.verticesPerRow = dataView.getUint32(offset, true); + offset += 4; + } + figures.push(figure); + } + if (kind === 1) { + return ["RadialAxial", "axial", bbox, stops, Array.from(coords.slice(0, 2)), Array.from(coords.slice(2, 4)), null, null]; + } + if (kind === 2) { + return ["RadialAxial", "radial", bbox, stops, [coords[0], coords[1]], [coords[3], coords[4]], coords[2], coords[5]]; + } + if (kind === 3) { + const shadingType = this.data[_PatternInfo.#SHADING_TYPE]; + let bounds = null; + if (coords.length > 0) { + let minX = coords[0], maxX = coords[0]; + let minY = coords[1], maxY = coords[1]; + for (let i7 = 0; i7 < coords.length; i7 += 2) { + const x2 = coords[i7], y4 = coords[i7 + 1]; + minX = minX > x2 ? x2 : minX; + minY = minY > y4 ? y4 : minY; + maxX = maxX < x2 ? x2 : maxX; + maxY = maxY < y4 ? y4 : maxY; + } + bounds = [minX, minY, maxX, maxY]; + } + return ["Mesh", shadingType, coords, colors2, figures, bounds, bbox, background]; + } + throw new Error(`Unsupported pattern kind: ${kind}`); + } + }; + isRefProxy = (v4) => typeof v4 === "object" && Number.isInteger(v4?.num) && v4.num >= 0 && Number.isInteger(v4?.gen) && v4.gen >= 0; + isNameProxy = (v4) => typeof v4 === "object" && typeof v4?.name === "string"; + isValidExplicitDest = _isValidExplicitDest.bind(null, isRefProxy, isNameProxy); + LoopbackPort = class { + #listeners = /* @__PURE__ */ new Map(); + #deferred = Promise.resolve(); + postMessage(obj, transfer) { + const event = { + data: structuredClone(obj, transfer ? { + transfer + } : null) + }; + this.#deferred.then(() => { + for (const [listener] of this.#listeners) { + listener.call(this, event); + } + }); + } + addEventListener(name, listener, options = null) { + let rmAbort = null; + if (options?.signal instanceof AbortSignal) { + const { + signal + } = options; + if (signal.aborted) { + warn("LoopbackPort - cannot use an `aborted` signal."); + return; + } + const onAbort = () => this.removeEventListener(name, listener); + rmAbort = () => signal.removeEventListener("abort", onAbort); + signal.addEventListener("abort", onAbort); + } + this.#listeners.set(listener, rmAbort); + } + removeEventListener(name, listener) { + const rmAbort = this.#listeners.get(listener); + rmAbort?.(); + this.#listeners.delete(listener); + } + terminate() { + for (const [, rmAbort] of this.#listeners) { + rmAbort?.(); + } + this.#listeners.clear(); + } + }; + CallbackKind = { + DATA: 1, + ERROR: 2 + }; + StreamKind = { + CANCEL: 1, + CANCEL_COMPLETE: 2, + CLOSE: 3, + ENQUEUE: 4, + ERROR: 5, + PULL: 6, + PULL_COMPLETE: 7, + START_COMPLETE: 8 + }; + MessageHandler = class { + #messageAC = new AbortController(); + constructor(sourceName, targetName, comObj) { + this.sourceName = sourceName; + this.targetName = targetName; + this.comObj = comObj; + this.callbackId = 1; + this.streamId = 1; + this.streamSinks = /* @__PURE__ */ Object.create(null); + this.streamControllers = /* @__PURE__ */ Object.create(null); + this.callbackCapabilities = /* @__PURE__ */ Object.create(null); + this.actionHandler = /* @__PURE__ */ Object.create(null); + comObj.addEventListener("message", this.#onMessage.bind(this), { + signal: this.#messageAC.signal + }); + } + #onMessage({ + data + }) { + if (data.targetName !== this.sourceName) { + return; + } + if (data.stream) { + this.#processStreamMessage(data); + return; + } + if (data.callback) { + const callbackId = data.callbackId; + const capability = this.callbackCapabilities[callbackId]; + if (!capability) { + throw new Error(`Cannot resolve callback ${callbackId}`); + } + delete this.callbackCapabilities[callbackId]; + if (data.callback === CallbackKind.DATA) { + capability.resolve(data.data); + } else if (data.callback === CallbackKind.ERROR) { + capability.reject(wrapReason(data.reason)); + } else { + throw new Error("Unexpected callback case"); + } + return; + } + const action = this.actionHandler[data.action]; + if (!action) { + throw new Error(`Unknown action from worker: ${data.action}`); + } + if (data.callbackId) { + const sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj; + Promise.try(action, data.data).then(function(result) { + comObj.postMessage({ + sourceName, + targetName, + callback: CallbackKind.DATA, + callbackId: data.callbackId, + data: result + }); + }, function(reason) { + comObj.postMessage({ + sourceName, + targetName, + callback: CallbackKind.ERROR, + callbackId: data.callbackId, + reason: wrapReason(reason) + }); + }); + return; + } + if (data.streamId) { + this.#createStreamSink(data); + return; + } + action(data.data); + } + on(actionName, handler) { + const ah = this.actionHandler; + if (ah[actionName]) { + throw new Error(`There is already an actionName called "${actionName}"`); + } + ah[actionName] = handler; + } + send(actionName, data, transfers) { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + data + }, transfers); + } + sendWithPromise(actionName, data, transfers) { + const callbackId = this.callbackId++; + const capability = Promise.withResolvers(); + this.callbackCapabilities[callbackId] = capability; + try { + this.comObj.postMessage({ + sourceName: this.sourceName, + targetName: this.targetName, + action: actionName, + callbackId, + data + }, transfers); + } catch (ex) { + capability.reject(ex); + } + return capability.promise; + } + sendWithStream(actionName, data, queueingStrategy, transfers) { + const streamId = this.streamId++, sourceName = this.sourceName, targetName = this.targetName, comObj = this.comObj; + return new ReadableStream({ + start: (controller) => { + const startCapability = Promise.withResolvers(); + this.streamControllers[streamId] = { + controller, + startCall: startCapability, + pullCall: null, + cancelCall: null, + isClosed: false + }; + comObj.postMessage({ + sourceName, + targetName, + action: actionName, + streamId, + data, + desiredSize: controller.desiredSize + }, transfers); + return startCapability.promise; + }, + pull: (controller) => { + const pullCapability = Promise.withResolvers(); + this.streamControllers[streamId].pullCall = pullCapability; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL, + streamId, + desiredSize: controller.desiredSize + }); + return pullCapability.promise; + }, + cancel: (reason) => { + assert(reason instanceof Error, "cancel must have a valid reason"); + const cancelCapability = Promise.withResolvers(); + this.streamControllers[streamId].cancelCall = cancelCapability; + this.streamControllers[streamId].isClosed = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL, + streamId, + reason: wrapReason(reason) + }); + return cancelCapability.promise; + } + }, queueingStrategy); + } + #createStreamSink(data) { + const streamId = data.streamId, sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj; + const self2 = this, action = this.actionHandler[data.action]; + const streamSink = { + enqueue(chunk, size = 1, transfers) { + if (this.isCancelled) { + return; + } + const lastDesiredSize = this.desiredSize; + this.desiredSize -= size; + if (lastDesiredSize > 0 && this.desiredSize <= 0) { + this.sinkCapability = Promise.withResolvers(); + this.ready = this.sinkCapability.promise; + } + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ENQUEUE, + streamId, + chunk + }, transfers); + }, + close() { + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CLOSE, + streamId + }); + delete self2.streamSinks[streamId]; + }, + error(reason) { + assert(reason instanceof Error, "error must have a valid reason"); + if (this.isCancelled) { + return; + } + this.isCancelled = true; + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.ERROR, + streamId, + reason: wrapReason(reason) + }); + }, + sinkCapability: Promise.withResolvers(), + onPull: null, + onCancel: null, + isCancelled: false, + desiredSize: data.desiredSize, + ready: null + }; + streamSink.sinkCapability.resolve(); + streamSink.ready = streamSink.sinkCapability.promise; + this.streamSinks[streamId] = streamSink; + Promise.try(action, data.data, streamSink).then(function() { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + success: true + }); + }, function(reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.START_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + } + #processStreamMessage(data) { + const streamId = data.streamId, sourceName = this.sourceName, targetName = data.sourceName, comObj = this.comObj; + const streamController = this.streamControllers[streamId], streamSink = this.streamSinks[streamId]; + switch (data.stream) { + case StreamKind.START_COMPLETE: + if (data.success) { + streamController.startCall.resolve(); + } else { + streamController.startCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL_COMPLETE: + if (data.success) { + streamController.pullCall.resolve(); + } else { + streamController.pullCall.reject(wrapReason(data.reason)); + } + break; + case StreamKind.PULL: + if (!streamSink) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + break; + } + if (streamSink.desiredSize <= 0 && data.desiredSize > 0) { + streamSink.sinkCapability.resolve(); + } + streamSink.desiredSize = data.desiredSize; + Promise.try(streamSink.onPull || onFn).then(function() { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + success: true + }); + }, function(reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.PULL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + break; + case StreamKind.ENQUEUE: + assert(streamController, "enqueue should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.controller.enqueue(data.chunk); + break; + case StreamKind.CLOSE: + assert(streamController, "close should have stream controller"); + if (streamController.isClosed) { + break; + } + streamController.isClosed = true; + streamController.controller.close(); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.ERROR: + assert(streamController, "error should have stream controller"); + streamController.controller.error(wrapReason(data.reason)); + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL_COMPLETE: + if (data.success) { + streamController.cancelCall.resolve(); + } else { + streamController.cancelCall.reject(wrapReason(data.reason)); + } + this.#deleteStreamController(streamController, streamId); + break; + case StreamKind.CANCEL: + if (!streamSink) { + break; + } + const dataReason = wrapReason(data.reason); + Promise.try(streamSink.onCancel || onFn, dataReason).then(function() { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + success: true + }); + }, function(reason) { + comObj.postMessage({ + sourceName, + targetName, + stream: StreamKind.CANCEL_COMPLETE, + streamId, + reason: wrapReason(reason) + }); + }); + streamSink.sinkCapability.reject(dataReason); + streamSink.isCancelled = true; + delete this.streamSinks[streamId]; + break; + default: + throw new Error("Unexpected stream case"); + } + } + async #deleteStreamController(streamController, streamId) { + await Promise.allSettled([streamController.startCall?.promise, streamController.pullCall?.promise, streamController.cancelCall?.promise]); + delete this.streamControllers[streamId]; + } + destroy() { + this.#messageAC?.abort(); + this.#messageAC = null; + } + }; + BaseCanvasFactory = class { + #enableHWA = false; + constructor({ + enableHWA = false + }) { + this.#enableHWA = enableHWA; + } + create(width, height) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + const canvas = this._createCanvas(width, height); + return { + canvas, + context: canvas.getContext("2d", { + willReadFrequently: !this.#enableHWA + }) + }; + } + reset(canvasAndContext, width, height) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + if (width <= 0 || height <= 0) { + throw new Error("Invalid canvas size"); + } + canvasAndContext.canvas.width = width; + canvasAndContext.canvas.height = height; + } + destroy(canvasAndContext) { + if (!canvasAndContext.canvas) { + throw new Error("Canvas is not specified"); + } + canvasAndContext.canvas.width = 0; + canvasAndContext.canvas.height = 0; + canvasAndContext.canvas = null; + canvasAndContext.context = null; + } + _createCanvas(width, height) { + unreachable("Abstract method `_createCanvas` called."); + } + }; + DOMCanvasFactory = class extends BaseCanvasFactory { + constructor({ + ownerDocument = globalThis.document, + enableHWA = false + }) { + super({ + enableHWA + }); + this._document = ownerDocument; + } + _createCanvas(width, height) { + const canvas = this._document.createElement("canvas"); + canvas.width = width; + canvas.height = height; + return canvas; + } + }; + BaseCMapReaderFactory = class { + constructor({ + baseUrl = null, + isCompressed = true + }) { + this.baseUrl = baseUrl; + this.isCompressed = isCompressed; + } + async fetch({ + name + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided."); + } + if (!name) { + throw new Error("CMap name must be specified."); + } + const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : ""); + return this._fetch(url).then((cMapData) => ({ + cMapData, + isCompressed: this.isCompressed + })).catch((reason) => { + throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } + }; + DOMCMapReaderFactory = class extends BaseCMapReaderFactory { + async _fetch(url) { + const data = await fetchData(url, this.isCompressed ? "arraybuffer" : "text"); + return data instanceof ArrayBuffer ? new Uint8Array(data) : stringToBytes(data); + } + }; + BaseFilterFactory = class { + addFilter(maps) { + return "none"; + } + addHCMFilter(fgColor, bgColor) { + return "none"; + } + addAlphaFilter(map3) { + return "none"; + } + addLuminosityFilter(map3) { + return "none"; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + return "none"; + } + destroy(keepHCM = false) { + } + }; + DOMFilterFactory = class extends BaseFilterFactory { + #baseUrl; + #_cache; + #_defs; + #docId; + #document; + #_hcmCache; + #id = 0; + constructor({ + docId, + ownerDocument = globalThis.document + }) { + super(); + this.#docId = docId; + this.#document = ownerDocument; + } + get #cache() { + return this.#_cache ||= /* @__PURE__ */ new Map(); + } + get #hcmCache() { + return this.#_hcmCache ||= /* @__PURE__ */ new Map(); + } + get #defs() { + if (!this.#_defs) { + const div = this.#document.createElement("div"); + const { + style + } = div; + style.visibility = "hidden"; + style.contain = "strict"; + style.width = style.height = 0; + style.position = "absolute"; + style.top = style.left = 0; + style.zIndex = -1; + const svg = this.#document.createElementNS(SVG_NS, "svg"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + this.#_defs = this.#document.createElementNS(SVG_NS, "defs"); + div.append(svg); + svg.append(this.#_defs); + this.#document.body.append(div); + } + return this.#_defs; + } + #createTables(maps) { + if (maps.length === 1) { + const mapR2 = maps[0]; + const buffer = new Array(256); + for (let i7 = 0; i7 < 256; i7++) { + buffer[i7] = mapR2[i7] / 255; + } + const table = buffer.join(","); + return [table, table, table]; + } + const [mapR, mapG, mapB] = maps; + const bufferR = new Array(256); + const bufferG = new Array(256); + const bufferB = new Array(256); + for (let i7 = 0; i7 < 256; i7++) { + bufferR[i7] = mapR[i7] / 255; + bufferG[i7] = mapG[i7] / 255; + bufferB[i7] = mapB[i7] / 255; + } + return [bufferR.join(","), bufferG.join(","), bufferB.join(",")]; + } + #createUrl(id) { + if (this.#baseUrl === void 0) { + this.#baseUrl = ""; + const url = this.#document.URL; + if (url !== this.#document.baseURI) { + if (isDataScheme(url)) { + warn('#createUrl: ignore "data:"-URL for performance reasons.'); + } else { + this.#baseUrl = updateUrlHash(url, ""); + } + } + } + return `url(${this.#baseUrl}#${id})`; + } + addFilter(maps) { + if (!maps) { + return "none"; + } + let value = this.#cache.get(maps); + if (value) { + return value; + } + const [tableR, tableG, tableB] = this.#createTables(maps); + const key = maps.length === 1 ? tableR : `${tableR}${tableG}${tableB}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(maps, value); + return value; + } + const id = `g_${this.#docId}_transfer_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(maps, url); + this.#cache.set(key, url); + const filter2 = this.#createFilter(id); + this.#addTransferMapConversion(tableR, tableG, tableB, filter2); + return url; + } + addHCMFilter(fgColor, bgColor) { + const key = `${fgColor}-${bgColor}`; + const filterName = "base"; + let info2 = this.#hcmCache.get(filterName); + if (info2?.key === key) { + return info2.url; + } + if (info2) { + info2.filter?.remove(); + info2.key = key; + info2.url = "none"; + info2.filter = null; + } else { + info2 = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info2); + } + if (!fgColor || !bgColor) { + return info2.url; + } + const fgRGB = this.#getRGB(fgColor); + fgColor = Util.makeHexColor(...fgRGB); + const bgRGB = this.#getRGB(bgColor); + bgColor = Util.makeHexColor(...bgRGB); + this.#defs.style.color = ""; + if (fgColor === "#000000" && bgColor === "#ffffff" || fgColor === bgColor) { + return info2.url; + } + const map3 = new Array(256); + for (let i7 = 0; i7 <= 255; i7++) { + const x2 = i7 / 255; + map3[i7] = x2 <= 0.03928 ? x2 / 12.92 : ((x2 + 0.055) / 1.055) ** 2.4; + } + const table = map3.join(","); + const id = `g_${this.#docId}_hcm_filter`; + const filter2 = info2.filter = this.#createFilter(id); + this.#addTransferMapConversion(table, table, table, filter2); + this.#addGrayConversion(filter2); + const getSteps = (c6, n7) => { + const start = fgRGB[c6] / 255; + const end = bgRGB[c6] / 255; + const arr = new Array(n7 + 1); + for (let i7 = 0; i7 <= n7; i7++) { + arr[i7] = start + i7 / n7 * (end - start); + } + return arr.join(","); + }; + this.#addTransferMapConversion(getSteps(0, 5), getSteps(1, 5), getSteps(2, 5), filter2); + info2.url = this.#createUrl(id); + return info2.url; + } + addAlphaFilter(map3) { + let value = this.#cache.get(map3); + if (value) { + return value; + } + const [tableA] = this.#createTables([map3]); + const key = `alpha_${tableA}`; + value = this.#cache.get(key); + if (value) { + this.#cache.set(map3, value); + return value; + } + const id = `g_${this.#docId}_alpha_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map3, url); + this.#cache.set(key, url); + const filter2 = this.#createFilter(id); + this.#addTransferMapAlphaConversion(tableA, filter2); + return url; + } + addLuminosityFilter(map3) { + let value = this.#cache.get(map3 || "luminosity"); + if (value) { + return value; + } + let tableA, key; + if (map3) { + [tableA] = this.#createTables([map3]); + key = `luminosity_${tableA}`; + } else { + key = "luminosity"; + } + value = this.#cache.get(key); + if (value) { + this.#cache.set(map3, value); + return value; + } + const id = `g_${this.#docId}_luminosity_map_${this.#id++}`; + const url = this.#createUrl(id); + this.#cache.set(map3, url); + this.#cache.set(key, url); + const filter2 = this.#createFilter(id); + this.#addLuminosityConversion(filter2); + if (map3) { + this.#addTransferMapAlphaConversion(tableA, filter2); + } + return url; + } + addHighlightHCMFilter(filterName, fgColor, bgColor, newFgColor, newBgColor) { + const key = `${fgColor}-${bgColor}-${newFgColor}-${newBgColor}`; + let info2 = this.#hcmCache.get(filterName); + if (info2?.key === key) { + return info2.url; + } + if (info2) { + info2.filter?.remove(); + info2.key = key; + info2.url = "none"; + info2.filter = null; + } else { + info2 = { + key, + url: "none", + filter: null + }; + this.#hcmCache.set(filterName, info2); + } + if (!fgColor || !bgColor) { + return info2.url; + } + const [fgRGB, bgRGB] = [fgColor, bgColor].map(this.#getRGB.bind(this)); + let fgGray = Math.round(0.2126 * fgRGB[0] + 0.7152 * fgRGB[1] + 0.0722 * fgRGB[2]); + let bgGray = Math.round(0.2126 * bgRGB[0] + 0.7152 * bgRGB[1] + 0.0722 * bgRGB[2]); + let [newFgRGB, newBgRGB] = [newFgColor, newBgColor].map(this.#getRGB.bind(this)); + if (bgGray < fgGray) { + [fgGray, bgGray, newFgRGB, newBgRGB] = [bgGray, fgGray, newBgRGB, newFgRGB]; + } + this.#defs.style.color = ""; + const getSteps = (fg, bg, n7) => { + const arr = new Array(256); + const step = (bgGray - fgGray) / n7; + const newStart = fg / 255; + const newStep = (bg - fg) / (255 * n7); + let prev = 0; + for (let i7 = 0; i7 <= n7; i7++) { + const k2 = Math.round(fgGray + i7 * step); + const value = newStart + i7 * newStep; + for (let j3 = prev; j3 <= k2; j3++) { + arr[j3] = value; + } + prev = k2 + 1; + } + for (let i7 = prev; i7 < 256; i7++) { + arr[i7] = arr[prev - 1]; + } + return arr.join(","); + }; + const id = `g_${this.#docId}_hcm_${filterName}_filter`; + const filter2 = info2.filter = this.#createFilter(id); + this.#addGrayConversion(filter2); + this.#addTransferMapConversion(getSteps(newFgRGB[0], newBgRGB[0], 5), getSteps(newFgRGB[1], newBgRGB[1], 5), getSteps(newFgRGB[2], newBgRGB[2], 5), filter2); + info2.url = this.#createUrl(id); + return info2.url; + } + destroy(keepHCM = false) { + if (keepHCM && this.#_hcmCache?.size) { + return; + } + this.#_defs?.parentNode.parentNode.remove(); + this.#_defs = null; + this.#_cache?.clear(); + this.#_cache = null; + this.#_hcmCache?.clear(); + this.#_hcmCache = null; + this.#id = 0; + } + #addLuminosityConversion(filter2) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("values", "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"); + filter2.append(feColorMatrix); + } + #addGrayConversion(filter2) { + const feColorMatrix = this.#document.createElementNS(SVG_NS, "feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("values", "0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"); + filter2.append(feColorMatrix); + } + #createFilter(id) { + const filter2 = this.#document.createElementNS(SVG_NS, "filter"); + filter2.setAttribute("color-interpolation-filters", "sRGB"); + filter2.setAttribute("id", id); + this.#defs.append(filter2); + return filter2; + } + #appendFeFunc(feComponentTransfer, func, table) { + const feFunc = this.#document.createElementNS(SVG_NS, func); + feFunc.setAttribute("type", "discrete"); + feFunc.setAttribute("tableValues", table); + feComponentTransfer.append(feFunc); + } + #addTransferMapConversion(rTable, gTable, bTable, filter2) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter2.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncR", rTable); + this.#appendFeFunc(feComponentTransfer, "feFuncG", gTable); + this.#appendFeFunc(feComponentTransfer, "feFuncB", bTable); + } + #addTransferMapAlphaConversion(aTable, filter2) { + const feComponentTransfer = this.#document.createElementNS(SVG_NS, "feComponentTransfer"); + filter2.append(feComponentTransfer); + this.#appendFeFunc(feComponentTransfer, "feFuncA", aTable); + } + #getRGB(color2) { + this.#defs.style.color = color2; + return getRGB(getComputedStyle(this.#defs).getPropertyValue("color")); + } + }; + BaseStandardFontDataFactory = class { + constructor({ + baseUrl = null + }) { + this.baseUrl = baseUrl; + } + async fetch({ + filename + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided."); + } + if (!filename) { + throw new Error("Font filename must be specified."); + } + const url = `${this.baseUrl}${filename}`; + return this._fetch(url).catch((reason) => { + throw new Error(`Unable to load font data at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } + }; + DOMStandardFontDataFactory = class extends BaseStandardFontDataFactory { + async _fetch(url) { + const data = await fetchData(url, "arraybuffer"); + return new Uint8Array(data); + } + }; + BaseWasmFactory = class { + constructor({ + baseUrl = null + }) { + this.baseUrl = baseUrl; + } + async fetch({ + filename + }) { + if (!this.baseUrl) { + throw new Error("Ensure that the `wasmUrl` API parameter is provided."); + } + if (!filename) { + throw new Error("Wasm filename must be specified."); + } + const url = `${this.baseUrl}${filename}`; + return this._fetch(url).catch((reason) => { + throw new Error(`Unable to load wasm data at: ${url}`); + }); + } + async _fetch(url) { + unreachable("Abstract method `_fetch` called."); + } + }; + DOMWasmFactory = class extends BaseWasmFactory { + async _fetch(url) { + const data = await fetchData(url, "arraybuffer"); + return new Uint8Array(data); + } + }; + if (isNodeJS) { + warn("Please use the `legacy` build in Node.js environments."); + } + NodeFilterFactory = class extends BaseFilterFactory { + }; + NodeCanvasFactory = class extends BaseCanvasFactory { + _createCanvas(width, height) { + const require2 = process.getBuiltinModule("module").createRequire(import.meta.url); + const canvas = require2("@napi-rs/canvas"); + return canvas.createCanvas(width, height); + } + }; + NodeCMapReaderFactory = class extends BaseCMapReaderFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } + }; + NodeStandardFontDataFactory = class extends BaseStandardFontDataFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } + }; + NodeWasmFactory = class extends BaseWasmFactory { + async _fetch(url) { + return node_utils_fetchData(url); + } + }; + FORCED_DEPENDENCY_LABEL = "__forcedDependency"; + ({ + floor, + ceil + } = Math); + EMPTY_BBOX = new Uint32Array(new Uint8Array([255, 255, 0, 0]).buffer)[0]; + BBoxReader = class { + #bboxes; + #coords; + constructor(bboxes, coords) { + this.#bboxes = bboxes; + this.#coords = coords; + } + get length() { + return this.#bboxes.length; + } + isEmpty(i7) { + return this.#bboxes[i7] === EMPTY_BBOX; + } + minX(i7) { + return this.#coords[i7 * 4 + 0] / 256; + } + minY(i7) { + return this.#coords[i7 * 4 + 1] / 256; + } + maxX(i7) { + return (this.#coords[i7 * 4 + 2] + 1) / 256; + } + maxY(i7) { + return (this.#coords[i7 * 4 + 3] + 1) / 256; + } + }; + ensureDebugMetadata = (map3, key) => { + if (!map3) { + return void 0; + } + let value = map3.get(key); + if (!value) { + value = { + dependencies: /* @__PURE__ */ new Set(), + isRenderingOperation: false + }; + map3.set(key, value); + } + return value; + }; + CanvasDependencyTracker = class { + #simple = { + __proto__: null + }; + #incremental = { + __proto__: null, + transform: [], + moveText: [], + sameLineText: [], + [FORCED_DEPENDENCY_LABEL]: [] + }; + #namedDependencies = /* @__PURE__ */ new Map(); + #savesStack = []; + #markedContentStack = []; + #baseTransformStack = [[1, 0, 0, 1, 0, 0]]; + #clipBox = [-Infinity, -Infinity, Infinity, Infinity]; + #pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]); + #pendingBBoxIdx = -1; + #pendingDependencies = /* @__PURE__ */ new Set(); + #operations = /* @__PURE__ */ new Map(); + #fontBBoxTrustworthy = /* @__PURE__ */ new Map(); + #canvasWidth; + #canvasHeight; + #bboxesCoords; + #bboxes; + #debugMetadata; + constructor(canvas, operationsCount, recordDebugMetadata = false) { + this.#canvasWidth = canvas.width; + this.#canvasHeight = canvas.height; + this.#initializeBBoxes(operationsCount); + if (recordDebugMetadata) { + this.#debugMetadata = /* @__PURE__ */ new Map(); + } + } + growOperationsCount(operationsCount) { + if (operationsCount >= this.#bboxes.length) { + this.#initializeBBoxes(operationsCount, this.#bboxes); + } + } + #initializeBBoxes(operationsCount, oldBBoxes) { + const buffer = new ArrayBuffer(operationsCount * 4); + this.#bboxesCoords = new Uint8ClampedArray(buffer); + this.#bboxes = new Uint32Array(buffer); + if (oldBBoxes && oldBBoxes.length > 0) { + this.#bboxes.set(oldBBoxes); + this.#bboxes.fill(EMPTY_BBOX, oldBBoxes.length); + } else { + this.#bboxes.fill(EMPTY_BBOX); + } + } + save(opIdx) { + this.#simple = { + __proto__: this.#simple + }; + this.#incremental = { + __proto__: this.#incremental, + transform: { + __proto__: this.#incremental.transform + }, + moveText: { + __proto__: this.#incremental.moveText + }, + sameLineText: { + __proto__: this.#incremental.sameLineText + }, + [FORCED_DEPENDENCY_LABEL]: { + __proto__: this.#incremental[FORCED_DEPENDENCY_LABEL] + } + }; + this.#clipBox = { + __proto__: this.#clipBox + }; + this.#savesStack.push(opIdx); + return this; + } + restore(opIdx) { + const previous = Object.getPrototypeOf(this.#simple); + if (previous === null) { + return this; + } + this.#simple = previous; + this.#incremental = Object.getPrototypeOf(this.#incremental); + this.#clipBox = Object.getPrototypeOf(this.#clipBox); + const lastSave = this.#savesStack.pop(); + if (lastSave !== void 0) { + ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); + this.#bboxes[opIdx] = this.#bboxes[lastSave]; + } + return this; + } + recordOpenMarker(idx) { + this.#savesStack.push(idx); + return this; + } + getOpenMarker() { + if (this.#savesStack.length === 0) { + return null; + } + return this.#savesStack.at(-1); + } + recordCloseMarker(opIdx) { + const lastSave = this.#savesStack.pop(); + if (lastSave !== void 0) { + ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); + this.#bboxes[opIdx] = this.#bboxes[lastSave]; + } + return this; + } + beginMarkedContent(opIdx) { + this.#markedContentStack.push(opIdx); + return this; + } + endMarkedContent(opIdx) { + const lastSave = this.#markedContentStack.pop(); + if (lastSave !== void 0) { + ensureDebugMetadata(this.#debugMetadata, opIdx)?.dependencies.add(lastSave); + this.#bboxes[opIdx] = this.#bboxes[lastSave]; + } + return this; + } + pushBaseTransform(ctx) { + this.#baseTransformStack.push(Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform())); + return this; + } + popBaseTransform() { + if (this.#baseTransformStack.length > 1) { + this.#baseTransformStack.pop(); + } + return this; + } + recordSimpleData(name, idx) { + this.#simple[name] = idx; + return this; + } + recordIncrementalData(name, idx) { + this.#incremental[name].push(idx); + return this; + } + resetIncrementalData(name, idx) { + this.#incremental[name].length = 0; + return this; + } + recordNamedData(name, idx) { + this.#namedDependencies.set(name, idx); + return this; + } + recordSimpleDataFromNamed(name, depName, fallbackIdx) { + this.#simple[name] = this.#namedDependencies.get(depName) ?? fallbackIdx; + } + recordFutureForcedDependency(name, idx) { + this.recordIncrementalData(FORCED_DEPENDENCY_LABEL, idx); + return this; + } + inheritSimpleDataAsFutureForcedDependencies(names2) { + for (const name of names2) { + if (name in this.#simple) { + this.recordFutureForcedDependency(name, this.#simple[name]); + } + } + return this; + } + inheritPendingDependenciesAsFutureForcedDependencies() { + for (const dep of this.#pendingDependencies) { + this.recordFutureForcedDependency(FORCED_DEPENDENCY_LABEL, dep); + } + return this; + } + resetBBox(idx) { + if (this.#pendingBBoxIdx !== idx) { + this.#pendingBBoxIdx = idx; + this.#pendingBBox[0] = Infinity; + this.#pendingBBox[1] = Infinity; + this.#pendingBBox[2] = -Infinity; + this.#pendingBBox[3] = -Infinity; + } + return this; + } + recordClipBox(idx, ctx, minX, maxX, minY, maxY) { + const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()); + const clipBox = [Infinity, Infinity, -Infinity, -Infinity]; + Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox); + const intersection = Util.intersect(this.#clipBox, clipBox); + if (intersection) { + this.#clipBox[0] = intersection[0]; + this.#clipBox[1] = intersection[1]; + this.#clipBox[2] = intersection[2]; + this.#clipBox[3] = intersection[3]; + } else { + this.#clipBox[0] = this.#clipBox[1] = Infinity; + this.#clipBox[2] = this.#clipBox[3] = -Infinity; + } + return this; + } + recordBBox(idx, ctx, minX, maxX, minY, maxY) { + const clipBox = this.#clipBox; + if (clipBox[0] === Infinity) { + return this; + } + const transform = Util.multiplyByDOMMatrix(this.#baseTransformStack.at(-1), ctx.getTransform()); + if (clipBox[0] === -Infinity) { + Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, this.#pendingBBox); + return this; + } + const bbox = [Infinity, Infinity, -Infinity, -Infinity]; + Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox); + this.#pendingBBox[0] = Math.min(this.#pendingBBox[0], Math.max(bbox[0], clipBox[0])); + this.#pendingBBox[1] = Math.min(this.#pendingBBox[1], Math.max(bbox[1], clipBox[1])); + this.#pendingBBox[2] = Math.max(this.#pendingBBox[2], Math.min(bbox[2], clipBox[2])); + this.#pendingBBox[3] = Math.max(this.#pendingBBox[3], Math.min(bbox[3], clipBox[3])); + return this; + } + recordCharacterBBox(idx, ctx, font, scale = 1, x2 = 0, y4 = 0, getMeasure) { + const fontBBox = font.bbox; + let isBBoxTrustworthy; + let computedBBox; + if (fontBBox) { + isBBoxTrustworthy = fontBBox[2] !== fontBBox[0] && fontBBox[3] !== fontBBox[1] && this.#fontBBoxTrustworthy.get(font); + if (isBBoxTrustworthy !== false) { + computedBBox = [0, 0, 0, 0]; + Util.axialAlignedBoundingBox(fontBBox, font.fontMatrix, computedBBox); + if (scale !== 1 || x2 !== 0 || y4 !== 0) { + Util.scaleMinMax([scale, 0, 0, -scale, x2, y4], computedBBox); + } + if (isBBoxTrustworthy) { + return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]); + } + } + } + if (!getMeasure) { + return this.recordFullPageBBox(idx); + } + const measure = getMeasure(); + if (fontBBox && computedBBox && isBBoxTrustworthy === void 0) { + isBBoxTrustworthy = computedBBox[0] <= x2 - measure.actualBoundingBoxLeft && computedBBox[2] >= x2 + measure.actualBoundingBoxRight && computedBBox[1] <= y4 - measure.actualBoundingBoxAscent && computedBBox[3] >= y4 + measure.actualBoundingBoxDescent; + this.#fontBBoxTrustworthy.set(font, isBBoxTrustworthy); + if (isBBoxTrustworthy) { + return this.recordBBox(idx, ctx, computedBBox[0], computedBBox[2], computedBBox[1], computedBBox[3]); + } + } + return this.recordBBox(idx, ctx, x2 - measure.actualBoundingBoxLeft, x2 + measure.actualBoundingBoxRight, y4 - measure.actualBoundingBoxAscent, y4 + measure.actualBoundingBoxDescent); + } + recordFullPageBBox(idx) { + this.#pendingBBox[0] = Math.max(0, this.#clipBox[0]); + this.#pendingBBox[1] = Math.max(0, this.#clipBox[1]); + this.#pendingBBox[2] = Math.min(this.#canvasWidth, this.#clipBox[2]); + this.#pendingBBox[3] = Math.min(this.#canvasHeight, this.#clipBox[3]); + return this; + } + getSimpleIndex(dependencyName) { + return this.#simple[dependencyName]; + } + recordDependencies(idx, dependencyNames) { + const pendingDependencies = this.#pendingDependencies; + const simple = this.#simple; + const incremental = this.#incremental; + for (const name of dependencyNames) { + if (name in this.#simple) { + pendingDependencies.add(simple[name]); + } else if (name in incremental) { + incremental[name].forEach(pendingDependencies.add, pendingDependencies); + } + } + return this; + } + recordNamedDependency(idx, name) { + if (this.#namedDependencies.has(name)) { + this.#pendingDependencies.add(this.#namedDependencies.get(name)); + } + return this; + } + recordOperation(idx, preserve = false) { + this.recordDependencies(idx, [FORCED_DEPENDENCY_LABEL]); + if (this.#debugMetadata) { + const metadata = ensureDebugMetadata(this.#debugMetadata, idx); + const { + dependencies + } = metadata; + this.#pendingDependencies.forEach(dependencies.add, dependencies); + this.#savesStack.forEach(dependencies.add, dependencies); + this.#markedContentStack.forEach(dependencies.add, dependencies); + dependencies.delete(idx); + metadata.isRenderingOperation = true; + } + if (this.#pendingBBoxIdx === idx) { + const minX = floor(this.#pendingBBox[0] * 256 / this.#canvasWidth); + const minY = floor(this.#pendingBBox[1] * 256 / this.#canvasHeight); + const maxX = ceil(this.#pendingBBox[2] * 256 / this.#canvasWidth); + const maxY = ceil(this.#pendingBBox[3] * 256 / this.#canvasHeight); + expandBBox(this.#bboxesCoords, idx, minX, minY, maxX, maxY); + for (const depIdx of this.#pendingDependencies) { + if (depIdx !== idx) { + expandBBox(this.#bboxesCoords, depIdx, minX, minY, maxX, maxY); + } + } + for (const saveIdx of this.#savesStack) { + if (saveIdx !== idx) { + expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY); + } + } + for (const saveIdx of this.#markedContentStack) { + if (saveIdx !== idx) { + expandBBox(this.#bboxesCoords, saveIdx, minX, minY, maxX, maxY); + } + } + if (!preserve) { + this.#pendingDependencies.clear(); + this.#pendingBBoxIdx = -1; + } + } + return this; + } + recordShowTextOperation(idx, preserve = false) { + const deps = Array.from(this.#pendingDependencies); + this.recordOperation(idx, preserve); + this.recordIncrementalData("sameLineText", idx); + for (const dep of deps) { + this.recordIncrementalData("sameLineText", dep); + } + return this; + } + bboxToClipBoxDropOperation(idx, preserve = false) { + if (this.#pendingBBoxIdx === idx) { + this.#pendingBBoxIdx = -1; + this.#clipBox[0] = Math.max(this.#clipBox[0], this.#pendingBBox[0]); + this.#clipBox[1] = Math.max(this.#clipBox[1], this.#pendingBBox[1]); + this.#clipBox[2] = Math.min(this.#clipBox[2], this.#pendingBBox[2]); + this.#clipBox[3] = Math.min(this.#clipBox[3], this.#pendingBBox[3]); + if (!preserve) { + this.#pendingDependencies.clear(); + } + } + return this; + } + _takePendingDependencies() { + const pendingDependencies = this.#pendingDependencies; + this.#pendingDependencies = /* @__PURE__ */ new Set(); + return pendingDependencies; + } + _extractOperation(idx) { + const operation = this.#operations.get(idx); + this.#operations.delete(idx); + return operation; + } + _pushPendingDependencies(dependencies) { + for (const dep of dependencies) { + this.#pendingDependencies.add(dep); + } + } + take() { + this.#fontBBoxTrustworthy.clear(); + return new BBoxReader(this.#bboxes, this.#bboxesCoords); + } + takeDebugMetadata() { + return this.#debugMetadata; + } + }; + CanvasNestedDependencyTracker = class _CanvasNestedDependencyTracker { + #dependencyTracker; + #opIdx; + #ignoreBBoxes; + #nestingLevel = 0; + #savesLevel = 0; + constructor(dependencyTracker, opIdx, ignoreBBoxes) { + if (dependencyTracker instanceof _CanvasNestedDependencyTracker && dependencyTracker.#ignoreBBoxes === !!ignoreBBoxes) { + return dependencyTracker; + } + this.#dependencyTracker = dependencyTracker; + this.#opIdx = opIdx; + this.#ignoreBBoxes = !!ignoreBBoxes; + } + growOperationsCount() { + throw new Error("Unreachable"); + } + save(opIdx) { + this.#savesLevel++; + this.#dependencyTracker.save(this.#opIdx); + return this; + } + restore(opIdx) { + if (this.#savesLevel > 0) { + this.#dependencyTracker.restore(this.#opIdx); + this.#savesLevel--; + } + return this; + } + recordOpenMarker(idx) { + this.#nestingLevel++; + return this; + } + getOpenMarker() { + return this.#nestingLevel > 0 ? this.#opIdx : this.#dependencyTracker.getOpenMarker(); + } + recordCloseMarker(idx) { + this.#nestingLevel--; + return this; + } + beginMarkedContent(opIdx) { + return this; + } + endMarkedContent(opIdx) { + return this; + } + pushBaseTransform(ctx) { + this.#dependencyTracker.pushBaseTransform(ctx); + return this; + } + popBaseTransform() { + this.#dependencyTracker.popBaseTransform(); + return this; + } + recordSimpleData(name, idx) { + this.#dependencyTracker.recordSimpleData(name, this.#opIdx); + return this; + } + recordIncrementalData(name, idx) { + this.#dependencyTracker.recordIncrementalData(name, this.#opIdx); + return this; + } + resetIncrementalData(name, idx) { + this.#dependencyTracker.resetIncrementalData(name, this.#opIdx); + return this; + } + recordNamedData(name, idx) { + return this; + } + recordSimpleDataFromNamed(name, depName, fallbackIdx) { + this.#dependencyTracker.recordSimpleDataFromNamed(name, depName, this.#opIdx); + return this; + } + recordFutureForcedDependency(name, idx) { + this.#dependencyTracker.recordFutureForcedDependency(name, this.#opIdx); + return this; + } + inheritSimpleDataAsFutureForcedDependencies(names2) { + this.#dependencyTracker.inheritSimpleDataAsFutureForcedDependencies(names2); + return this; + } + inheritPendingDependenciesAsFutureForcedDependencies() { + this.#dependencyTracker.inheritPendingDependenciesAsFutureForcedDependencies(); + return this; + } + resetBBox(idx) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.resetBBox(this.#opIdx); + } + return this; + } + recordClipBox(idx, ctx, minX, maxX, minY, maxY) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordClipBox(this.#opIdx, ctx, minX, maxX, minY, maxY); + } + return this; + } + recordBBox(idx, ctx, minX, maxX, minY, maxY) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordBBox(this.#opIdx, ctx, minX, maxX, minY, maxY); + } + return this; + } + recordCharacterBBox(idx, ctx, font, scale, x2, y4, getMeasure) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordCharacterBBox(this.#opIdx, ctx, font, scale, x2, y4, getMeasure); + } + return this; + } + recordFullPageBBox(idx) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.recordFullPageBBox(this.#opIdx); + } + return this; + } + getSimpleIndex(dependencyName) { + return this.#dependencyTracker.getSimpleIndex(dependencyName); + } + recordDependencies(idx, dependencyNames) { + this.#dependencyTracker.recordDependencies(this.#opIdx, dependencyNames); + return this; + } + recordNamedDependency(idx, name) { + this.#dependencyTracker.recordNamedDependency(this.#opIdx, name); + return this; + } + recordOperation(idx) { + this.#dependencyTracker.recordOperation(this.#opIdx, true); + return this; + } + recordShowTextOperation(idx) { + this.#dependencyTracker.recordShowTextOperation(this.#opIdx, true); + return this; + } + bboxToClipBoxDropOperation(idx) { + if (!this.#ignoreBBoxes) { + this.#dependencyTracker.bboxToClipBoxDropOperation(this.#opIdx, true); + } + return this; + } + take() { + throw new Error("Unreachable"); + } + takeDebugMetadata() { + throw new Error("Unreachable"); + } + }; + Dependencies = { + stroke: ["path", "transform", "filter", "strokeColor", "strokeAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "dash"], + fill: ["path", "transform", "filter", "fillColor", "fillAlpha", "globalCompositeOperation", "SMask"], + imageXObject: ["transform", "SMask", "filter", "fillAlpha", "strokeAlpha", "globalCompositeOperation"], + rawFillPath: ["filter", "fillColor", "fillAlpha"], + showText: ["transform", "leading", "charSpacing", "wordSpacing", "hScale", "textRise", "moveText", "textMatrix", "font", "fontObj", "filter", "fillColor", "textRenderingMode", "SMask", "fillAlpha", "strokeAlpha", "globalCompositeOperation", "sameLineText"], + transform: ["transform"], + transformAndFill: ["transform", "fillColor"] + }; + PathType = { + FILL: "Fill", + STROKE: "Stroke", + SHADING: "Shading" + }; + BaseShadingPattern = class { + isModifyingCurrentTransform() { + return false; + } + getPattern() { + unreachable("Abstract method `getPattern` called."); + } + }; + RadialAxialShadingPattern = class extends BaseShadingPattern { + constructor(IR) { + super(); + this._type = IR[1]; + this._bbox = IR[2]; + this._colorStops = IR[3]; + this._p0 = IR[4]; + this._p1 = IR[5]; + this._r0 = IR[6]; + this._r1 = IR[7]; + this.matrix = null; + } + _createGradient(ctx) { + let grad; + if (this._type === "axial") { + grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]); + } else if (this._type === "radial") { + grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1); + } + for (const colorStop of this._colorStops) { + grad.addColorStop(colorStop[0], colorStop[1]); + } + return grad; + } + getPattern(ctx, owner, inverse, pathType) { + let pattern; + if (pathType === PathType.STROKE || pathType === PathType.FILL) { + const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, getCurrentTransform(ctx)) || [0, 0, 0, 0]; + const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1; + const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1; + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.beginPath(); + tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height); + tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]); + inverse = Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]); + tmpCtx.transform(...owner.baseTransform); + if (this.matrix) { + tmpCtx.transform(...this.matrix); + } + applyBoundingBox(tmpCtx, this._bbox); + tmpCtx.fillStyle = this._createGradient(tmpCtx); + tmpCtx.fill(); + pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat"); + const domMatrix = new DOMMatrix(inverse); + pattern.setTransform(domMatrix); + } else { + applyBoundingBox(ctx, this._bbox); + pattern = this._createGradient(ctx); + } + return pattern; + } + }; + MeshShadingPattern = class extends BaseShadingPattern { + constructor(IR) { + super(); + this._coords = IR[2]; + this._colors = IR[3]; + this._figures = IR[4]; + this._bounds = IR[5]; + this._bbox = IR[6]; + this._background = IR[7]; + this.matrix = null; + } + _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) { + const EXPECTED_SCALE = 1.1; + const MAX_PATTERN_SIZE = 3e3; + const BORDER_SIZE = 2; + const offsetX = Math.floor(this._bounds[0]); + const offsetY = Math.floor(this._bounds[1]); + const boundsWidth = Math.ceil(this._bounds[2]) - offsetX; + const boundsHeight = Math.ceil(this._bounds[3]) - offsetY; + const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); + const scaleX = boundsWidth / width; + const scaleY = boundsHeight / height; + const context = { + coords: this._coords, + colors: this._colors, + offsetX: -offsetX, + offsetY: -offsetY, + scaleX: 1 / scaleX, + scaleY: 1 / scaleY + }; + const paddedWidth = width + BORDER_SIZE * 2; + const paddedHeight = height + BORDER_SIZE * 2; + const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight); + const tmpCtx = tmpCanvas.context; + const data = tmpCtx.createImageData(width, height); + if (backgroundColor) { + const bytes = data.data; + for (let i7 = 0, ii = bytes.length; i7 < ii; i7 += 4) { + bytes[i7] = backgroundColor[0]; + bytes[i7 + 1] = backgroundColor[1]; + bytes[i7 + 2] = backgroundColor[2]; + bytes[i7 + 3] = 255; + } + } + for (const figure of this._figures) { + drawFigure(data, figure, context); + } + tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); + const canvas = tmpCanvas.canvas; + return { + canvas, + offsetX: offsetX - BORDER_SIZE * scaleX, + offsetY: offsetY - BORDER_SIZE * scaleY, + scaleX, + scaleY + }; + } + isModifyingCurrentTransform() { + return true; + } + getPattern(ctx, owner, inverse, pathType) { + applyBoundingBox(ctx, this._bbox); + const scale = new Float32Array(2); + if (pathType === PathType.SHADING) { + Util.singularValueDecompose2dScale(getCurrentTransform(ctx), scale); + } else if (this.matrix) { + Util.singularValueDecompose2dScale(this.matrix, scale); + const [matrixScaleX, matrixScaleY] = scale; + Util.singularValueDecompose2dScale(owner.baseTransform, scale); + scale[0] *= matrixScaleX; + scale[1] *= matrixScaleY; + } else { + Util.singularValueDecompose2dScale(owner.baseTransform, scale); + } + const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases); + if (pathType !== PathType.SHADING) { + ctx.setTransform(...owner.baseTransform); + if (this.matrix) { + ctx.transform(...this.matrix); + } + } + ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); + return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat"); + } + }; + DummyShadingPattern = class extends BaseShadingPattern { + getPattern() { + return "hotpink"; + } + }; + PaintType = { + COLORED: 1, + UNCOLORED: 2 + }; + TilingPattern = class _TilingPattern { + static MAX_PATTERN_SIZE = 3e3; + constructor(IR, ctx, canvasGraphicsFactory, baseTransform) { + this.color = IR[1]; + this.operatorList = IR[2]; + this.matrix = IR[3]; + this.bbox = IR[4]; + this.xstep = IR[5]; + this.ystep = IR[6]; + this.paintType = IR[7]; + this.tilingType = IR[8]; + this.ctx = ctx; + this.canvasGraphicsFactory = canvasGraphicsFactory; + this.baseTransform = baseTransform; + } + createPatternCanvas(owner, opIdx) { + const { + bbox, + operatorList, + paintType, + tilingType, + color: color2, + canvasGraphicsFactory + } = this; + let { + xstep, + ystep + } = this; + xstep = Math.abs(xstep); + ystep = Math.abs(ystep); + info("TilingType: " + tilingType); + const x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; + const width = x1 - x0; + const height = y1 - y0; + const scale = new Float32Array(2); + Util.singularValueDecompose2dScale(this.matrix, scale); + const [matrixScaleX, matrixScaleY] = scale; + Util.singularValueDecompose2dScale(this.baseTransform, scale); + const combinedScaleX = matrixScaleX * scale[0]; + const combinedScaleY = matrixScaleY * scale[1]; + let canvasWidth = width, canvasHeight = height, redrawHorizontally = false, redrawVertically = false; + const xScaledStep = Math.ceil(xstep * combinedScaleX); + const yScaledStep = Math.ceil(ystep * combinedScaleY); + const xScaledWidth = Math.ceil(width * combinedScaleX); + const yScaledHeight = Math.ceil(height * combinedScaleY); + if (xScaledStep >= xScaledWidth) { + canvasWidth = xstep; + } else { + redrawHorizontally = true; + } + if (yScaledStep >= yScaledHeight) { + canvasHeight = ystep; + } else { + redrawVertically = true; + } + const dimx = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size); + const tmpCtx = tmpCanvas.context; + const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx, opIdx); + graphics.groupLevel = owner.groupLevel; + this.setFillAndStrokeStyleToContext(graphics, paintType, color2); + tmpCtx.translate(-dimx.scale * x0, -dimy.scale * y0); + graphics.transform(0, dimx.scale, 0, 0, dimy.scale, 0, 0); + tmpCtx.save(); + graphics.dependencyTracker?.save(); + this.clipBbox(graphics, x0, y0, x1, y1); + graphics.baseTransform = getCurrentTransform(graphics.ctx); + graphics.executeOperatorList(operatorList); + graphics.endDrawing(); + graphics.dependencyTracker?.restore(); + tmpCtx.restore(); + if (redrawHorizontally || redrawVertically) { + const image = tmpCanvas.canvas; + if (redrawHorizontally) { + canvasWidth = xstep; + } + if (redrawVertically) { + canvasHeight = ystep; + } + const dimx2 = this.getSizeAndScale(canvasWidth, this.ctx.canvas.width, combinedScaleX); + const dimy2 = this.getSizeAndScale(canvasHeight, this.ctx.canvas.height, combinedScaleY); + const xSize = dimx2.size; + const ySize = dimy2.size; + const tmpCanvas2 = owner.cachedCanvases.getCanvas("pattern-workaround", xSize, ySize); + const tmpCtx2 = tmpCanvas2.context; + const ii = redrawHorizontally ? Math.floor(width / xstep) : 0; + const jj = redrawVertically ? Math.floor(height / ystep) : 0; + for (let i7 = 0; i7 <= ii; i7++) { + for (let j3 = 0; j3 <= jj; j3++) { + tmpCtx2.drawImage(image, xSize * i7, ySize * j3, xSize, ySize, 0, 0, xSize, ySize); + } + } + return { + canvas: tmpCanvas2.canvas, + scaleX: dimx2.scale, + scaleY: dimy2.scale, + offsetX: x0, + offsetY: y0 + }; + } + return { + canvas: tmpCanvas.canvas, + scaleX: dimx.scale, + scaleY: dimy.scale, + offsetX: x0, + offsetY: y0 + }; + } + getSizeAndScale(step, realOutputSize, scale) { + const maxSize = Math.max(_TilingPattern.MAX_PATTERN_SIZE, realOutputSize); + let size = Math.ceil(step * scale); + if (size >= maxSize) { + size = maxSize; + } else { + scale = size / step; + } + return { + scale, + size + }; + } + clipBbox(graphics, x0, y0, x1, y1) { + const bboxWidth = x1 - x0; + const bboxHeight = y1 - y0; + graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); + Util.axialAlignedBoundingBox([x0, y0, x1, y1], getCurrentTransform(graphics.ctx), graphics.current.minMax); + graphics.clip(); + graphics.endPath(); + } + setFillAndStrokeStyleToContext(graphics, paintType, color2) { + const context = graphics.ctx, current2 = graphics.current; + switch (paintType) { + case PaintType.COLORED: + const { + fillStyle, + strokeStyle + } = this.ctx; + context.fillStyle = current2.fillColor = fillStyle; + context.strokeStyle = current2.strokeColor = strokeStyle; + break; + case PaintType.UNCOLORED: + context.fillStyle = context.strokeStyle = color2; + current2.fillColor = current2.strokeColor = color2; + break; + default: + throw new FormatError(`Unsupported paint type: ${paintType}`); + } + } + isModifyingCurrentTransform() { + return false; + } + getPattern(ctx, owner, inverse, pathType, opIdx) { + let matrix = inverse; + if (pathType !== PathType.SHADING) { + matrix = Util.transform(matrix, owner.baseTransform); + if (this.matrix) { + matrix = Util.transform(matrix, this.matrix); + } + } + const temporaryPatternCanvas = this.createPatternCanvas(owner, opIdx); + let domMatrix = new DOMMatrix(matrix); + domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); + domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY); + const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat"); + pattern.setTransform(domMatrix); + return pattern; + } + }; + MIN_FONT_SIZE = 16; + MAX_FONT_SIZE = 100; + EXECUTION_TIME = 15; + EXECUTION_STEPS = 10; + FULL_CHUNK_HEIGHT = 16; + SCALE_MATRIX = new DOMMatrix(); + XY = new Float32Array(2); + MIN_MAX_INIT = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); + CachedCanvases = class { + constructor(canvasFactory) { + this.canvasFactory = canvasFactory; + this.cache = /* @__PURE__ */ Object.create(null); + } + getCanvas(id, width, height) { + let canvasEntry; + if (this.cache[id] !== void 0) { + canvasEntry = this.cache[id]; + this.canvasFactory.reset(canvasEntry, width, height); + } else { + canvasEntry = this.canvasFactory.create(width, height); + this.cache[id] = canvasEntry; + } + return canvasEntry; + } + delete(id) { + delete this.cache[id]; + } + clear() { + for (const id in this.cache) { + const canvasEntry = this.cache[id]; + this.canvasFactory.destroy(canvasEntry); + delete this.cache[id]; + } + } + }; + CanvasExtraState = class { + alphaIsShape = false; + fontSize = 0; + fontSizeScale = 1; + textMatrix = null; + textMatrixScale = 1; + fontMatrix = FONT_IDENTITY_MATRIX; + leading = 0; + x = 0; + y = 0; + lineX = 0; + lineY = 0; + charSpacing = 0; + wordSpacing = 0; + textHScale = 1; + textRenderingMode = TextRenderingMode.FILL; + textRise = 0; + fillColor = "#000000"; + strokeColor = "#000000"; + patternFill = false; + patternStroke = false; + fillAlpha = 1; + strokeAlpha = 1; + lineWidth = 1; + activeSMask = null; + transferMaps = "none"; + constructor(width, height, preInit) { + preInit?.(this); + this.clipBox = new Float32Array([0, 0, width, height]); + this.minMax = MIN_MAX_INIT.slice(); + } + clone() { + const clone3 = Object.create(this); + clone3.clipBox = this.clipBox.slice(); + clone3.minMax = this.minMax.slice(); + return clone3; + } + getPathBoundingBox(pathType = PathType.FILL, transform = null) { + const box = this.minMax.slice(); + if (pathType === PathType.STROKE) { + if (!transform) { + unreachable("Stroke bounding box must include transform."); + } + Util.singularValueDecompose2dScale(transform, XY); + const xStrokePad = XY[0] * this.lineWidth / 2; + const yStrokePad = XY[1] * this.lineWidth / 2; + box[0] -= xStrokePad; + box[1] -= yStrokePad; + box[2] += xStrokePad; + box[3] += yStrokePad; + } + return box; + } + updateClipFromPath() { + const intersect = Util.intersect(this.clipBox, this.getPathBoundingBox()); + this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]); + } + isEmptyClip() { + return this.minMax[0] === Infinity; + } + startNewPathAndClipBox(box) { + this.clipBox.set(box, 0); + this.minMax.set(MIN_MAX_INIT, 0); + } + getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) { + return Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform)); + } + }; + LINE_CAP_STYLES = ["butt", "round", "square"]; + LINE_JOIN_STYLES = ["miter", "round", "bevel"]; + NORMAL_CLIP = {}; + EO_CLIP = {}; + CanvasGraphics = class _CanvasGraphics { + constructor(canvasCtx, commonObjs, objs, canvasFactory, filterFactory, { + optionalContentConfig, + markedContentStack = null + }, annotationCanvasMap, pageColors, dependencyTracker) { + this.ctx = canvasCtx; + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.stateStack = []; + this.pendingClip = null; + this.pendingEOFill = false; + this.res = null; + this.xobjs = null; + this.commonObjs = commonObjs; + this.objs = objs; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this.groupStack = []; + this.baseTransform = null; + this.baseTransformStack = []; + this.groupLevel = 0; + this.smaskStack = []; + this.smaskCounter = 0; + this.tempSMask = null; + this.suspendedCtx = null; + this.contentVisible = true; + this.markedContentStack = markedContentStack || []; + this.optionalContentConfig = optionalContentConfig; + this.cachedCanvases = new CachedCanvases(this.canvasFactory); + this.cachedPatterns = /* @__PURE__ */ new Map(); + this.annotationCanvasMap = annotationCanvasMap; + this.viewportScale = 1; + this.outputScaleX = 1; + this.outputScaleY = 1; + this.pageColors = pageColors; + this._cachedScaleForStroking = [-1, 0]; + this._cachedGetSinglePixelWidth = null; + this._cachedBitmapsMap = /* @__PURE__ */ new Map(); + this.dependencyTracker = dependencyTracker ?? null; + } + getObject(opIdx, data, fallback = null) { + if (typeof data === "string") { + this.dependencyTracker?.recordNamedDependency(opIdx, data); + return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data); + } + return fallback; + } + beginDrawing({ + transform, + viewport, + transparency = false, + background = null + }) { + const width = this.ctx.canvas.width; + const height = this.ctx.canvas.height; + const savedFillStyle = this.ctx.fillStyle; + this.ctx.fillStyle = background || "#ffffff"; + this.ctx.fillRect(0, 0, width, height); + this.ctx.fillStyle = savedFillStyle; + if (transparency) { + const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height); + this.compositeCtx = this.ctx; + this.transparentCanvas = transparentCanvas.canvas; + this.ctx = transparentCanvas.context; + this.ctx.save(); + this.ctx.transform(...getCurrentTransform(this.compositeCtx)); + } + this.ctx.save(); + resetCtxToDefault(this.ctx); + if (transform) { + this.ctx.transform(...transform); + this.outputScaleX = transform[0]; + this.outputScaleY = transform[0]; + } + this.ctx.transform(...viewport.transform); + this.viewportScale = viewport.scale; + this.baseTransform = getCurrentTransform(this.ctx); + } + executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper, operationsFilter) { + const argsArray = operatorList.argsArray; + const fnArray = operatorList.fnArray; + let i7 = executionStartIdx || 0; + const argsArrayLen = argsArray.length; + if (argsArrayLen === i7) { + return i7; + } + const chunkOperations = argsArrayLen - i7 > EXECUTION_STEPS && typeof continueCallback === "function"; + const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; + let steps2 = 0; + const commonObjs = this.commonObjs; + const objs = this.objs; + let fnId, fnArgs; + while (true) { + if (stepper !== void 0 && i7 === stepper.nextBreakPoint) { + stepper.breakIt(i7, continueCallback); + return i7; + } + if (!operationsFilter || operationsFilter(i7)) { + fnId = fnArray[i7]; + fnArgs = argsArray[i7] ?? null; + if (fnId !== OPS.dependency) { + if (fnArgs === null) { + this[fnId](i7); + } else { + this[fnId](i7, ...fnArgs); + } + } else { + for (const depObjId of fnArgs) { + this.dependencyTracker?.recordNamedData(depObjId, i7); + const objsPool = depObjId.startsWith("g_") ? commonObjs : objs; + if (!objsPool.has(depObjId)) { + objsPool.get(depObjId, continueCallback); + return i7; + } + } + } + } + i7++; + if (i7 === argsArrayLen) { + return i7; + } + if (chunkOperations && ++steps2 > EXECUTION_STEPS) { + if (Date.now() > endTime) { + continueCallback(); + return i7; + } + steps2 = 0; + } + } + } + #restoreInitialState() { + while (this.stateStack.length || this.inSMaskMode) { + this.restore(); + } + this.current.activeSMask = null; + this.ctx.restore(); + if (this.transparentCanvas) { + this.ctx = this.compositeCtx; + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.drawImage(this.transparentCanvas, 0, 0); + this.ctx.restore(); + this.transparentCanvas = null; + } + } + endDrawing() { + this.#restoreInitialState(); + this.cachedCanvases.clear(); + this.cachedPatterns.clear(); + for (const cache of this._cachedBitmapsMap.values()) { + for (const canvas of cache.values()) { + if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) { + canvas.width = canvas.height = 0; + } + } + cache.clear(); + } + this._cachedBitmapsMap.clear(); + this.#drawFilter(); + } + #drawFilter() { + if (this.pageColors) { + const hcmFilterId = this.filterFactory.addHCMFilter(this.pageColors.foreground, this.pageColors.background); + if (hcmFilterId !== "none") { + const savedFilter = this.ctx.filter; + this.ctx.filter = hcmFilterId; + this.ctx.drawImage(this.ctx.canvas, 0, 0); + this.ctx.filter = savedFilter; + } + } + } + _scaleImage(img, inverseTransform) { + const width = img.width ?? img.displayWidth; + const height = img.height ?? img.displayHeight; + let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1); + let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1); + let paintWidth = width, paintHeight = height; + let tmpCanvasId = "prescale1"; + let tmpCanvas, tmpCtx; + while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) { + let newWidth = paintWidth, newHeight = paintHeight; + if (widthScale > 2 && paintWidth > 1) { + newWidth = paintWidth >= 16384 ? Math.floor(paintWidth / 2) - 1 || 1 : Math.ceil(paintWidth / 2); + widthScale /= paintWidth / newWidth; + } + if (heightScale > 2 && paintHeight > 1) { + newHeight = paintHeight >= 16384 ? Math.floor(paintHeight / 2) - 1 || 1 : Math.ceil(paintHeight) / 2; + heightScale /= paintHeight / newHeight; + } + tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); + tmpCtx = tmpCanvas.context; + tmpCtx.clearRect(0, 0, newWidth, newHeight); + tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); + img = tmpCanvas.canvas; + paintWidth = newWidth; + paintHeight = newHeight; + tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1"; + } + return { + img, + paintWidth, + paintHeight + }; + } + _createMaskCanvas(opIdx, img) { + const ctx = this.ctx; + const { + width, + height + } = img; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + const currentTransform = getCurrentTransform(ctx); + let cache, cacheKey, scaled, maskCanvas; + if ((img.bitmap || img.data) && img.count > 1) { + const mainKey = img.bitmap || img.data.buffer; + cacheKey = JSON.stringify(isPatternFill ? currentTransform : [currentTransform.slice(0, 4), fillColor]); + cache = this._cachedBitmapsMap.get(mainKey); + if (!cache) { + cache = /* @__PURE__ */ new Map(); + this._cachedBitmapsMap.set(mainKey, cache); + } + const cachedImage = cache.get(cacheKey); + if (cachedImage && !isPatternFill) { + const offsetX2 = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]); + const offsetY2 = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]); + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill); + return { + canvas: cachedImage, + offsetX: offsetX2, + offsetY: offsetY2 + }; + } + scaled = cachedImage; + } + if (!scaled) { + maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + putBinaryImageMask(maskCanvas.context, img); + } + let maskToCanvas = Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]); + maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]); + const minMax = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax); + const [minX, minY, maxX, maxY] = minMax; + const drawnWidth = Math.round(maxX - minX) || 1; + const drawnHeight = Math.round(maxY - minY) || 1; + const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight); + const fillCtx = fillCanvas.context; + const offsetX = minX; + const offsetY = minY; + fillCtx.translate(-offsetX, -offsetY); + fillCtx.transform(...maskToCanvas); + if (!scaled) { + scaled = this._scaleImage(maskCanvas.canvas, getCurrentTransformInverse(fillCtx)); + scaled = scaled.img; + if (cache && isPatternFill) { + cache.set(cacheKey, scaled); + } + } + fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(fillCtx), img.interpolate); + drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height); + fillCtx.globalCompositeOperation = "source-in"; + const inverse = Util.transform(getCurrentTransformInverse(fillCtx), [1, 0, 0, 1, -offsetX, -offsetY]); + fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, PathType.FILL, opIdx) : fillColor; + fillCtx.fillRect(0, 0, width, height); + if (cache && !isPatternFill) { + this.cachedCanvases.delete("fillCanvas"); + cache.set(cacheKey, fillCanvas.canvas); + } + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.transformAndFill); + return { + canvas: fillCanvas.canvas, + offsetX: Math.round(offsetX), + offsetY: Math.round(offsetY) + }; + } + setLineWidth(opIdx, width) { + this.dependencyTracker?.recordSimpleData("lineWidth", opIdx); + if (width !== this.current.lineWidth) { + this._cachedScaleForStroking[0] = -1; + } + this.current.lineWidth = width; + this.ctx.lineWidth = width; + } + setLineCap(opIdx, style) { + this.dependencyTracker?.recordSimpleData("lineCap", opIdx); + this.ctx.lineCap = LINE_CAP_STYLES[style]; + } + setLineJoin(opIdx, style) { + this.dependencyTracker?.recordSimpleData("lineJoin", opIdx); + this.ctx.lineJoin = LINE_JOIN_STYLES[style]; + } + setMiterLimit(opIdx, limit2) { + this.dependencyTracker?.recordSimpleData("miterLimit", opIdx); + this.ctx.miterLimit = limit2; + } + setDash(opIdx, dashArray, dashPhase) { + this.dependencyTracker?.recordSimpleData("dash", opIdx); + const ctx = this.ctx; + if (ctx.setLineDash !== void 0) { + ctx.setLineDash(dashArray); + ctx.lineDashOffset = dashPhase; + } + } + setRenderingIntent(opIdx, intent) { + } + setFlatness(opIdx, flatness) { + } + setGState(opIdx, states) { + for (const [key, value] of states) { + switch (key) { + case "LW": + this.setLineWidth(opIdx, value); + break; + case "LC": + this.setLineCap(opIdx, value); + break; + case "LJ": + this.setLineJoin(opIdx, value); + break; + case "ML": + this.setMiterLimit(opIdx, value); + break; + case "D": + this.setDash(opIdx, value[0], value[1]); + break; + case "RI": + this.setRenderingIntent(opIdx, value); + break; + case "FL": + this.setFlatness(opIdx, value); + break; + case "Font": + this.setFont(opIdx, value[0], value[1]); + break; + case "CA": + this.dependencyTracker?.recordSimpleData("strokeAlpha", opIdx); + this.current.strokeAlpha = value; + break; + case "ca": + this.dependencyTracker?.recordSimpleData("fillAlpha", opIdx); + this.ctx.globalAlpha = this.current.fillAlpha = value; + break; + case "BM": + this.dependencyTracker?.recordSimpleData("globalCompositeOperation", opIdx); + this.ctx.globalCompositeOperation = value; + break; + case "SMask": + this.dependencyTracker?.recordSimpleData("SMask", opIdx); + this.current.activeSMask = value ? this.tempSMask : null; + this.tempSMask = null; + this.checkSMaskState(); + break; + case "TR": + this.dependencyTracker?.recordSimpleData("filter", opIdx); + this.ctx.filter = this.current.transferMaps = this.filterFactory.addFilter(value); + break; + } + } + } + get inSMaskMode() { + return !!this.suspendedCtx; + } + checkSMaskState() { + const inSMaskMode = this.inSMaskMode; + if (this.current.activeSMask && !inSMaskMode) { + this.beginSMaskMode(); + } else if (!this.current.activeSMask && inSMaskMode) { + this.endSMaskMode(); + } + } + beginSMaskMode(opIdx) { + if (this.inSMaskMode) { + throw new Error("beginSMaskMode called while already in smask mode"); + } + const drawnWidth = this.ctx.canvas.width; + const drawnHeight = this.ctx.canvas.height; + const cacheId = "smaskGroupAt" + this.groupLevel; + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + this.suspendedCtx = this.ctx; + const ctx = this.ctx = scratchCanvas.context; + ctx.setTransform(this.suspendedCtx.getTransform()); + copyCtxState(this.suspendedCtx, ctx); + mirrorContextOperations(ctx, this.suspendedCtx); + this.setGState(opIdx, [["BM", "source-over"]]); + } + endSMaskMode() { + if (!this.inSMaskMode) { + throw new Error("endSMaskMode called while not in smask mode"); + } + this.ctx._removeMirroring(); + copyCtxState(this.ctx, this.suspendedCtx); + this.ctx = this.suspendedCtx; + this.suspendedCtx = null; + } + compose(dirtyBox) { + if (!this.current.activeSMask) { + return; + } + if (!dirtyBox) { + dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height]; + } else { + dirtyBox[0] = Math.floor(dirtyBox[0]); + dirtyBox[1] = Math.floor(dirtyBox[1]); + dirtyBox[2] = Math.ceil(dirtyBox[2]); + dirtyBox[3] = Math.ceil(dirtyBox[3]); + } + const smask = this.current.activeSMask; + const suspendedCtx = this.suspendedCtx; + this.composeSMask(suspendedCtx, smask, this.ctx, dirtyBox); + this.ctx.save(); + this.ctx.setTransform(1, 0, 0, 1, 0, 0); + this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); + this.ctx.restore(); + } + composeSMask(ctx, smask, layerCtx, layerBox) { + const layerOffsetX = layerBox[0]; + const layerOffsetY = layerBox[1]; + const layerWidth = layerBox[2] - layerOffsetX; + const layerHeight = layerBox[3] - layerOffsetY; + if (layerWidth === 0 || layerHeight === 0) { + return; + } + this.genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY); + ctx.save(); + ctx.globalAlpha = 1; + ctx.globalCompositeOperation = "source-over"; + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(layerCtx.canvas, 0, 0); + ctx.restore(); + } + genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) { + let maskCanvas = maskCtx.canvas; + let maskX = layerOffsetX - maskOffsetX; + let maskY = layerOffsetY - maskOffsetY; + if (backdrop) { + if (maskX < 0 || maskY < 0 || maskX + width > maskCanvas.width || maskY + height > maskCanvas.height) { + const canvas = this.cachedCanvases.getCanvas("maskExtension", width, height); + const ctx = canvas.context; + ctx.drawImage(maskCanvas, -maskX, -maskY); + ctx.globalCompositeOperation = "destination-atop"; + ctx.fillStyle = backdrop; + ctx.fillRect(0, 0, width, height); + ctx.globalCompositeOperation = "source-over"; + maskCanvas = canvas.canvas; + maskX = maskY = 0; + } else { + maskCtx.save(); + maskCtx.globalAlpha = 1; + maskCtx.setTransform(1, 0, 0, 1, 0, 0); + const clip2 = new Path2D(); + clip2.rect(maskX, maskY, width, height); + maskCtx.clip(clip2); + maskCtx.globalCompositeOperation = "destination-atop"; + maskCtx.fillStyle = backdrop; + maskCtx.fillRect(maskX, maskY, width, height); + maskCtx.restore(); + } + } + layerCtx.save(); + layerCtx.globalAlpha = 1; + layerCtx.setTransform(1, 0, 0, 1, 0, 0); + if (subtype === "Alpha" && transferMap) { + layerCtx.filter = this.filterFactory.addAlphaFilter(transferMap); + } else if (subtype === "Luminosity") { + layerCtx.filter = this.filterFactory.addLuminosityFilter(transferMap); + } + const clip = new Path2D(); + clip.rect(layerOffsetX, layerOffsetY, width, height); + layerCtx.clip(clip); + layerCtx.globalCompositeOperation = "destination-in"; + layerCtx.drawImage(maskCanvas, maskX, maskY, width, height, layerOffsetX, layerOffsetY, width, height); + layerCtx.restore(); + } + save(opIdx) { + if (this.inSMaskMode) { + copyCtxState(this.ctx, this.suspendedCtx); + } + this.ctx.save(); + const old = this.current; + this.stateStack.push(old); + this.current = old.clone(); + this.dependencyTracker?.save(opIdx); + } + restore(opIdx) { + this.dependencyTracker?.restore(opIdx); + if (this.stateStack.length === 0) { + if (this.inSMaskMode) { + this.endSMaskMode(); + } + return; + } + this.current = this.stateStack.pop(); + this.ctx.restore(); + if (this.inSMaskMode) { + copyCtxState(this.suspendedCtx, this.ctx); + } + this.checkSMaskState(); + this.pendingClip = null; + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + transform(opIdx, a3, b4, c6, d4, e9, f4) { + this.dependencyTracker?.recordIncrementalData("transform", opIdx); + this.ctx.transform(a3, b4, c6, d4, e9, f4); + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + } + constructPath(opIdx, op2, data, minMax) { + let [path6] = data; + if (!minMax) { + path6 ||= data[0] = new Path2D(); + this[op2](opIdx, path6); + return; + } + if (this.dependencyTracker !== null) { + const outerExtraSize = op2 === OPS.stroke ? this.current.lineWidth / 2 : 0; + this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]); + } + if (!(path6 instanceof Path2D)) { + path6 = data[0] = makePathFromDrawOPS(path6); + } + Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax); + this[op2](opIdx, path6); + this._pathStartIdx = opIdx; + } + closePath(opIdx) { + this.ctx.closePath(); + } + stroke(opIdx, path6, consumePath = true) { + const ctx = this.ctx; + const strokeColor = this.current.strokeColor; + ctx.globalAlpha = this.current.strokeAlpha; + if (this.contentVisible) { + if (typeof strokeColor === "object" && strokeColor?.getPattern) { + const baseTransform = strokeColor.isModifyingCurrentTransform() ? ctx.getTransform() : null; + ctx.save(); + ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx); + if (baseTransform) { + const newPath = new Path2D(); + newPath.addPath(path6, ctx.getTransform().invertSelf().multiplySelf(baseTransform)); + path6 = newPath; + } + this.rescaleAndStroke(path6, false); + ctx.restore(); + } else { + this.rescaleAndStroke(path6, true); + } + } + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke); + if (consumePath) { + this.consumePath(opIdx, path6, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx))); + } + ctx.globalAlpha = this.current.fillAlpha; + } + closeStroke(opIdx, path6) { + this.stroke(opIdx, path6); + } + fill(opIdx, path6, consumePath = true) { + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + let needRestore = false; + if (isPatternFill) { + const baseTransform = fillColor.isModifyingCurrentTransform() ? ctx.getTransform() : null; + this.dependencyTracker?.save(opIdx); + ctx.save(); + ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx); + if (baseTransform) { + const newPath = new Path2D(); + newPath.addPath(path6, ctx.getTransform().invertSelf().multiplySelf(baseTransform)); + path6 = newPath; + } + needRestore = true; + } + const intersect = this.current.getClippedPathBoundingBox(); + if (this.contentVisible && intersect !== null) { + if (this.pendingEOFill) { + ctx.fill(path6, "evenodd"); + this.pendingEOFill = false; + } else { + ctx.fill(path6); + } + } + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill); + if (needRestore) { + ctx.restore(); + this.dependencyTracker?.restore(opIdx); + } + if (consumePath) { + this.consumePath(opIdx, path6, intersect); + } + } + eoFill(opIdx, path6) { + this.pendingEOFill = true; + this.fill(opIdx, path6); + } + fillStroke(opIdx, path6) { + this.fill(opIdx, path6, false); + this.stroke(opIdx, path6, false); + this.consumePath(opIdx, path6); + } + eoFillStroke(opIdx, path6) { + this.pendingEOFill = true; + this.fillStroke(opIdx, path6); + } + closeFillStroke(opIdx, path6) { + this.fillStroke(opIdx, path6); + } + closeEOFillStroke(opIdx, path6) { + this.pendingEOFill = true; + this.fillStroke(opIdx, path6); + } + endPath(opIdx, path6) { + this.consumePath(opIdx, path6); + } + rawFillPath(opIdx, path6) { + this.ctx.fill(path6); + this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx); + } + clip(opIdx) { + this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx); + this.pendingClip = NORMAL_CLIP; + } + eoClip(opIdx) { + this.dependencyTracker?.recordFutureForcedDependency("clipMode", opIdx); + this.pendingClip = EO_CLIP; + } + beginText(opIdx) { + this.current.textMatrix = null; + this.current.textMatrixScale = 1; + this.current.x = this.current.lineX = 0; + this.current.y = this.current.lineY = 0; + this.dependencyTracker?.recordOpenMarker(opIdx).resetIncrementalData("sameLineText").resetIncrementalData("moveText", opIdx); + } + endText(opIdx) { + const paths = this.pendingTextPaths; + const ctx = this.ctx; + if (this.dependencyTracker) { + const { + dependencyTracker + } = this; + if (paths !== void 0) { + dependencyTracker.recordFutureForcedDependency("textClip", dependencyTracker.getOpenMarker()).recordFutureForcedDependency("textClip", opIdx); + } + dependencyTracker.recordCloseMarker(opIdx); + } + if (paths !== void 0) { + const newPath = new Path2D(); + const invTransf = ctx.getTransform().invertSelf(); + for (const { + transform, + x: x2, + y: y4, + fontSize, + path: path6 + } of paths) { + if (!path6) { + continue; + } + newPath.addPath(path6, new DOMMatrix(transform).preMultiplySelf(invTransf).translate(x2, y4).scale(fontSize, -fontSize)); + } + ctx.clip(newPath); + } + delete this.pendingTextPaths; + } + setCharSpacing(opIdx, spacing2) { + this.dependencyTracker?.recordSimpleData("charSpacing", opIdx); + this.current.charSpacing = spacing2; + } + setWordSpacing(opIdx, spacing2) { + this.dependencyTracker?.recordSimpleData("wordSpacing", opIdx); + this.current.wordSpacing = spacing2; + } + setHScale(opIdx, scale) { + this.dependencyTracker?.recordSimpleData("hScale", opIdx); + this.current.textHScale = scale / 100; + } + setLeading(opIdx, leading) { + this.dependencyTracker?.recordSimpleData("leading", opIdx); + this.current.leading = -leading; + } + setFont(opIdx, fontRefName, size) { + this.dependencyTracker?.recordSimpleData("font", opIdx).recordSimpleDataFromNamed("fontObj", fontRefName, opIdx); + const fontObj = this.commonObjs.get(fontRefName); + const current2 = this.current; + if (!fontObj) { + throw new Error(`Can't find font for ${fontRefName}`); + } + current2.fontMatrix = fontObj.fontMatrix || FONT_IDENTITY_MATRIX; + if (current2.fontMatrix[0] === 0 || current2.fontMatrix[3] === 0) { + warn("Invalid font matrix for font " + fontRefName); + } + if (size < 0) { + size = -size; + current2.fontDirection = -1; + } else { + current2.fontDirection = 1; + } + this.current.font = fontObj; + this.current.fontSize = size; + if (fontObj.isType3Font) { + return; + } + const name = fontObj.loadedName || "sans-serif"; + const typeface = fontObj.systemFontInfo?.css || `"${name}", ${fontObj.fallbackName}`; + let bold2 = "normal"; + if (fontObj.black) { + bold2 = "900"; + } else if (fontObj.bold) { + bold2 = "bold"; + } + const italic = fontObj.italic ? "italic" : "normal"; + let browserFontSize = size; + if (size < MIN_FONT_SIZE) { + browserFontSize = MIN_FONT_SIZE; + } else if (size > MAX_FONT_SIZE) { + browserFontSize = MAX_FONT_SIZE; + } + this.current.fontSizeScale = size / browserFontSize; + this.ctx.font = `${italic} ${bold2} ${browserFontSize}px ${typeface}`; + } + setTextRenderingMode(opIdx, mode) { + this.dependencyTracker?.recordSimpleData("textRenderingMode", opIdx); + this.current.textRenderingMode = mode; + } + setTextRise(opIdx, rise) { + this.dependencyTracker?.recordSimpleData("textRise", opIdx); + this.current.textRise = rise; + } + moveText(opIdx, x2, y4) { + this.dependencyTracker?.resetIncrementalData("sameLineText").recordIncrementalData("moveText", opIdx); + this.current.x = this.current.lineX += x2; + this.current.y = this.current.lineY += y4; + } + setLeadingMoveText(opIdx, x2, y4) { + this.setLeading(opIdx, -y4); + this.moveText(opIdx, x2, y4); + } + setTextMatrix(opIdx, matrix) { + this.dependencyTracker?.resetIncrementalData("sameLineText").recordSimpleData("textMatrix", opIdx); + const { + current: current2 + } = this; + current2.textMatrix = matrix; + current2.textMatrixScale = Math.hypot(matrix[0], matrix[1]); + current2.x = current2.lineX = 0; + current2.y = current2.lineY = 0; + } + nextLine(opIdx) { + this.moveText(opIdx, 0, this.current.leading); + this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx); + } + #getScaledPath(path6, currentTransform, transform) { + const newPath = new Path2D(); + newPath.addPath(path6, new DOMMatrix(transform).invertSelf().multiplySelf(currentTransform)); + return newPath; + } + paintChar(opIdx, character, x2, y4, patternFillTransform, patternStrokeTransform) { + const ctx = this.ctx; + const current2 = this.current; + const font = current2.font; + const textRenderingMode = current2.textRenderingMode; + const fontSize = current2.fontSize / current2.fontSizeScale; + const fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); + const patternFill = current2.patternFill && !font.missingFile; + const patternStroke = current2.patternStroke && !font.missingFile; + let path6; + if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) { + path6 = font.getPathGenerator(this.commonObjs, character); + } + if (path6 && (font.disableFontFace || patternFill || patternStroke)) { + ctx.save(); + ctx.translate(x2, y4); + ctx.scale(fontSize, -fontSize); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font); + let currentTransform; + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (patternFillTransform) { + currentTransform = ctx.getTransform(); + ctx.setTransform(...patternFillTransform); + const scaledPath = this.#getScaledPath(path6, currentTransform, patternFillTransform); + ctx.fill(scaledPath); + } else { + ctx.fill(path6); + } + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (patternStrokeTransform) { + currentTransform ||= ctx.getTransform(); + ctx.setTransform(...patternStrokeTransform); + const { + a: a3, + b: b4, + c: c6, + d: d4 + } = currentTransform; + const invPatternTransform = Util.inverseTransform(patternStrokeTransform); + const transf = Util.transform([a3, b4, c6, d4, 0, 0], invPatternTransform); + Util.singularValueDecompose2dScale(transf, XY); + ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize; + ctx.stroke(this.#getScaledPath(path6, currentTransform, patternStrokeTransform)); + } else { + ctx.lineWidth /= fontSize; + ctx.stroke(path6); + } + } + ctx.restore(); + } else { + if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + ctx.fillText(character, x2, y4); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4, () => ctx.measureText(character)); + } + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + if (this.dependencyTracker) { + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4, () => ctx.measureText(character)).recordDependencies(opIdx, Dependencies.stroke); + } + ctx.strokeText(character, x2, y4); + } + } + if (isAddToPathSet) { + const paths = this.pendingTextPaths ||= []; + paths.push({ + transform: getCurrentTransform(ctx), + x: x2, + y: y4, + fontSize, + path: path6 + }); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x2, y4); + } + } + get isFontSubpixelAAEnabled() { + const { + context: ctx + } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10); + ctx.scale(1.5, 1); + ctx.fillText("I", 0, 10); + const data = ctx.getImageData(0, 0, 10, 10).data; + let enabled = false; + for (let i7 = 3; i7 < data.length; i7 += 4) { + if (data[i7] > 0 && data[i7] < 255) { + enabled = true; + break; + } + } + return shadow(this, "isFontSubpixelAAEnabled", enabled); + } + showText(opIdx, glyphs) { + if (this.dependencyTracker) { + this.dependencyTracker.recordDependencies(opIdx, Dependencies.showText).resetBBox(opIdx); + if (this.current.textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG) { + this.dependencyTracker.recordFutureForcedDependency("textClip", opIdx).inheritPendingDependenciesAsFutureForcedDependencies(); + } + } + const current2 = this.current; + const font = current2.font; + if (font.isType3Font) { + this.showType3Text(opIdx, glyphs); + this.dependencyTracker?.recordShowTextOperation(opIdx); + return void 0; + } + const fontSize = current2.fontSize; + if (fontSize === 0) { + this.dependencyTracker?.recordOperation(opIdx); + return void 0; + } + const ctx = this.ctx; + const fontSizeScale = current2.fontSizeScale; + const charSpacing = current2.charSpacing; + const wordSpacing = current2.wordSpacing; + const fontDirection = current2.fontDirection; + const textHScale = current2.textHScale * fontDirection; + const glyphsLength = glyphs.length; + const vertical = font.vertical; + const spacingDir = vertical ? 1 : -1; + const defaultVMetrics = font.defaultVMetrics; + const widthAdvanceScale = fontSize * current2.fontMatrix[0]; + const simpleFillText = current2.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace && !current2.patternFill; + ctx.save(); + if (current2.textMatrix) { + ctx.transform(...current2.textMatrix); + } + ctx.translate(current2.x, current2.y + current2.textRise); + if (fontDirection > 0) { + ctx.scale(textHScale, -1); + } else { + ctx.scale(textHScale, 1); + } + let patternFillTransform, patternStrokeTransform; + if (current2.patternFill) { + ctx.save(); + const pattern = current2.fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx); + patternFillTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.fillStyle = pattern; + } + if (current2.patternStroke) { + ctx.save(); + const pattern = current2.strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE, opIdx); + patternStrokeTransform = getCurrentTransform(ctx); + ctx.restore(); + ctx.strokeStyle = pattern; + } + let lineWidth = current2.lineWidth; + const scale = current2.textMatrixScale; + if (scale === 0 || lineWidth === 0) { + const fillStrokeMode = current2.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; + if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { + lineWidth = this.getSinglePixelWidth(); + } + } else { + lineWidth /= scale; + } + if (fontSizeScale !== 1) { + ctx.scale(fontSizeScale, fontSizeScale); + lineWidth /= fontSizeScale; + } + ctx.lineWidth = lineWidth; + if (font.isInvalidPDFjsFont) { + const chars = []; + let width = 0; + for (const glyph of glyphs) { + chars.push(glyph.unicode); + width += glyph.width; + } + const joinedChars = chars.join(""); + ctx.fillText(joinedChars, 0, 0); + if (this.dependencyTracker !== null) { + const measure = ctx.measureText(joinedChars); + this.dependencyTracker.recordBBox(opIdx, this.ctx, -measure.actualBoundingBoxLeft, measure.actualBoundingBoxRight, -measure.actualBoundingBoxAscent, measure.actualBoundingBoxDescent).recordShowTextOperation(opIdx); + } + current2.x += width * widthAdvanceScale * textHScale; + ctx.restore(); + this.compose(); + return void 0; + } + let x2 = 0, i7; + for (i7 = 0; i7 < glyphsLength; ++i7) { + const glyph = glyphs[i7]; + if (typeof glyph === "number") { + x2 += spacingDir * glyph * fontSize / 1e3; + continue; + } + let restoreNeeded = false; + const spacing2 = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const character = glyph.fontChar; + const accent2 = glyph.accent; + let scaledX, scaledY; + let width = glyph.width; + if (vertical) { + const vmetric = glyph.vmetric || defaultVMetrics; + const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale; + const vy = vmetric[2] * widthAdvanceScale; + width = vmetric ? -vmetric[0] : width; + scaledX = vx / fontSizeScale; + scaledY = (x2 + vy) / fontSizeScale; + } else { + scaledX = x2 / fontSizeScale; + scaledY = 0; + } + let measure; + if (font.remeasure && width > 0) { + measure = ctx.measureText(character); + const measuredWidth = measure.width * 1e3 / fontSize * fontSizeScale; + if (width < measuredWidth && this.isFontSubpixelAAEnabled) { + const characterScaleX = width / measuredWidth; + restoreNeeded = true; + ctx.save(); + ctx.scale(characterScaleX, 1); + scaledX /= characterScaleX; + } else if (width !== measuredWidth) { + scaledX += (width - measuredWidth) / 2e3 * fontSize / fontSizeScale; + } + } + if (this.contentVisible && (glyph.isInFont || font.missingFile)) { + if (simpleFillText && !accent2) { + ctx.fillText(character, scaledX, scaledY); + this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, measure ? { + bbox: null + } : font, fontSize / fontSizeScale, scaledX, scaledY, () => measure ?? ctx.measureText(character)); + } else { + this.paintChar(opIdx, character, scaledX, scaledY, patternFillTransform, patternStrokeTransform); + if (accent2) { + const scaledAccentX = scaledX + fontSize * accent2.offset.x / fontSizeScale; + const scaledAccentY = scaledY - fontSize * accent2.offset.y / fontSizeScale; + this.paintChar(opIdx, accent2.fontChar, scaledAccentX, scaledAccentY, patternFillTransform, patternStrokeTransform); + } + } + } + const charWidth = vertical ? width * widthAdvanceScale - spacing2 * fontDirection : width * widthAdvanceScale + spacing2 * fontDirection; + x2 += charWidth; + if (restoreNeeded) { + ctx.restore(); + } + } + if (vertical) { + current2.y -= x2; + } else { + current2.x += x2 * textHScale; + } + ctx.restore(); + this.compose(); + this.dependencyTracker?.recordShowTextOperation(opIdx); + return void 0; + } + showType3Text(opIdx, glyphs) { + const ctx = this.ctx; + const current2 = this.current; + const font = current2.font; + const fontSize = current2.fontSize; + const fontDirection = current2.fontDirection; + const spacingDir = font.vertical ? 1 : -1; + const charSpacing = current2.charSpacing; + const wordSpacing = current2.wordSpacing; + const textHScale = current2.textHScale * fontDirection; + const fontMatrix = current2.fontMatrix || FONT_IDENTITY_MATRIX; + const glyphsLength = glyphs.length; + const isTextInvisible = current2.textRenderingMode === TextRenderingMode.INVISIBLE; + let i7, glyph, width, spacingLength; + if (isTextInvisible || fontSize === 0) { + return; + } + this._cachedScaleForStroking[0] = -1; + this._cachedGetSinglePixelWidth = null; + ctx.save(); + if (current2.textMatrix) { + ctx.transform(...current2.textMatrix); + } + ctx.translate(current2.x, current2.y + current2.textRise); + ctx.scale(textHScale, fontDirection); + const dependencyTracker = this.dependencyTracker; + this.dependencyTracker = dependencyTracker ? new CanvasNestedDependencyTracker(dependencyTracker, opIdx) : null; + for (i7 = 0; i7 < glyphsLength; ++i7) { + glyph = glyphs[i7]; + if (typeof glyph === "number") { + spacingLength = spacingDir * glyph * fontSize / 1e3; + this.ctx.translate(spacingLength, 0); + current2.x += spacingLength * textHScale; + continue; + } + const spacing2 = (glyph.isSpace ? wordSpacing : 0) + charSpacing; + const operatorList = font.charProcOperatorList[glyph.operatorListId]; + if (!operatorList) { + warn(`Type3 character "${glyph.operatorListId}" is not available.`); + } else if (this.contentVisible) { + this.save(); + ctx.scale(fontSize, fontSize); + ctx.transform(...fontMatrix); + this.executeOperatorList(operatorList); + this.restore(); + } + const p4 = [glyph.width, 0]; + Util.applyTransform(p4, fontMatrix); + width = p4[0] * fontSize + spacing2; + ctx.translate(width, 0); + current2.x += width * textHScale; + } + ctx.restore(); + if (dependencyTracker) { + this.dependencyTracker = dependencyTracker; + } + } + setCharWidth(opIdx, xWidth, yWidth) { + } + setCharWidthAndBounds(opIdx, xWidth, yWidth, llx, lly, urx, ury) { + const clip = new Path2D(); + clip.rect(llx, lly, urx - llx, ury - lly); + this.ctx.clip(clip); + this.dependencyTracker?.recordBBox(opIdx, this.ctx, llx, urx, lly, ury).recordClipBox(opIdx, this.ctx, llx, urx, lly, ury); + this.endPath(opIdx); + } + getColorN_Pattern(opIdx, IR) { + let pattern; + if (IR[0] === "TilingPattern") { + const baseTransform = this.baseTransform || getCurrentTransform(this.ctx); + const canvasGraphicsFactory = { + createCanvasGraphics: (ctx, renderingOpIdx) => new _CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig: this.optionalContentConfig, + markedContentStack: this.markedContentStack + }, void 0, void 0, this.dependencyTracker ? new CanvasNestedDependencyTracker(this.dependencyTracker, renderingOpIdx, true) : null) + }; + pattern = new TilingPattern(IR, this.ctx, canvasGraphicsFactory, baseTransform); + } else { + pattern = this._getPattern(opIdx, IR[1], IR[2]); + } + return pattern; + } + setStrokeColorN(opIdx, ...args) { + this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); + this.current.strokeColor = this.getColorN_Pattern(opIdx, args); + this.current.patternStroke = true; + } + setFillColorN(opIdx, ...args) { + this.dependencyTracker?.recordSimpleData("fillColor", opIdx); + this.current.fillColor = this.getColorN_Pattern(opIdx, args); + this.current.patternFill = true; + } + setStrokeRGBColor(opIdx, color2) { + this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); + this.ctx.strokeStyle = this.current.strokeColor = color2; + this.current.patternStroke = false; + } + setStrokeTransparent(opIdx) { + this.dependencyTracker?.recordSimpleData("strokeColor", opIdx); + this.ctx.strokeStyle = this.current.strokeColor = "transparent"; + this.current.patternStroke = false; + } + setFillRGBColor(opIdx, color2) { + this.dependencyTracker?.recordSimpleData("fillColor", opIdx); + this.ctx.fillStyle = this.current.fillColor = color2; + this.current.patternFill = false; + } + setFillTransparent(opIdx) { + this.dependencyTracker?.recordSimpleData("fillColor", opIdx); + this.ctx.fillStyle = this.current.fillColor = "transparent"; + this.current.patternFill = false; + } + _getPattern(opIdx, objId, matrix = null) { + let pattern; + if (this.cachedPatterns.has(objId)) { + pattern = this.cachedPatterns.get(objId); + } else { + pattern = getShadingPattern(this.getObject(opIdx, objId)); + this.cachedPatterns.set(objId, pattern); + } + if (matrix) { + pattern.matrix = matrix; + } + return pattern; + } + shadingFill(opIdx, objId) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + this.save(opIdx); + const pattern = this._getPattern(opIdx, objId); + ctx.fillStyle = pattern.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.SHADING, opIdx); + const inv = getCurrentTransformInverse(ctx); + if (inv) { + const { + width, + height + } = ctx.canvas; + const minMax = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax); + const [x0, y0, x1, y1] = minMax; + this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); + } else { + this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); + } + this.dependencyTracker?.resetBBox(opIdx).recordFullPageBBox(opIdx).recordDependencies(opIdx, Dependencies.transform).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx); + this.compose(this.current.getClippedPathBoundingBox()); + this.restore(opIdx); + } + beginInlineImage() { + unreachable("Should not call beginInlineImage"); + } + beginImageData() { + unreachable("Should not call beginImageData"); + } + paintFormXObjectBegin(opIdx, matrix, bbox) { + if (!this.contentVisible) { + return; + } + this.save(opIdx); + this.baseTransformStack.push(this.baseTransform); + if (matrix) { + this.transform(opIdx, ...matrix); + } + this.baseTransform = getCurrentTransform(this.ctx); + if (bbox) { + Util.axialAlignedBoundingBox(bbox, this.baseTransform, this.current.minMax); + const [x0, y0, x1, y1] = bbox; + const clip = new Path2D(); + clip.rect(x0, y0, x1 - x0, y1 - y0); + this.ctx.clip(clip); + this.dependencyTracker?.recordClipBox(opIdx, this.ctx, x0, x1, y0, y1); + this.endPath(opIdx); + } + } + paintFormXObjectEnd(opIdx) { + if (!this.contentVisible) { + return; + } + this.restore(opIdx); + this.baseTransform = this.baseTransformStack.pop(); + } + beginGroup(opIdx, group) { + if (!this.contentVisible) { + return; + } + this.save(opIdx); + if (this.inSMaskMode) { + this.endSMaskMode(); + this.current.activeSMask = null; + } + const currentCtx = this.ctx; + if (!group.isolated) { + info("TODO: Support non-isolated groups."); + } + if (group.knockout) { + warn("Knockout groups not supported."); + } + const currentTransform = getCurrentTransform(currentCtx); + if (group.matrix) { + currentCtx.transform(...group.matrix); + } + if (!group.bbox) { + throw new Error("Bounding box is required."); + } + let bounds = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox(group.bbox, getCurrentTransform(currentCtx), bounds); + const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; + bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; + const offsetX = Math.floor(bounds[0]); + const offsetY = Math.floor(bounds[1]); + const drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); + const drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); + this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]); + let cacheId = "groupAt" + this.groupLevel; + if (group.smask) { + cacheId += "_smask_" + this.smaskCounter++ % 2; + } + const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight); + const groupCtx = scratchCanvas.context; + groupCtx.translate(-offsetX, -offsetY); + groupCtx.transform(...currentTransform); + let clip = new Path2D(); + const [x0, y0, x1, y1] = group.bbox; + clip.rect(x0, y0, x1 - x0, y1 - y0); + if (group.matrix) { + const path6 = new Path2D(); + path6.addPath(clip, new DOMMatrix(group.matrix)); + clip = path6; + } + groupCtx.clip(clip); + if (group.smask) { + this.smaskStack.push({ + canvas: scratchCanvas.canvas, + context: groupCtx, + offsetX, + offsetY, + subtype: group.smask.subtype, + backdrop: group.smask.backdrop, + transferMap: group.smask.transferMap || null, + startTransformInverse: null + }); + } + if (!group.smask || this.dependencyTracker) { + currentCtx.setTransform(1, 0, 0, 1, 0, 0); + currentCtx.translate(offsetX, offsetY); + currentCtx.save(); + } + copyCtxState(currentCtx, groupCtx); + this.ctx = groupCtx; + this.dependencyTracker?.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha", "strokeAlpha", "globalCompositeOperation"]).pushBaseTransform(currentCtx); + this.setGState(opIdx, [["BM", "source-over"], ["ca", 1], ["CA", 1]]); + this.groupStack.push(currentCtx); + this.groupLevel++; + } + endGroup(opIdx, group) { + if (!this.contentVisible) { + return; + } + this.groupLevel--; + const groupCtx = this.ctx; + const ctx = this.groupStack.pop(); + this.ctx = ctx; + this.ctx.imageSmoothingEnabled = false; + this.dependencyTracker?.popBaseTransform(); + if (group.smask) { + this.tempSMask = this.smaskStack.pop(); + this.restore(opIdx); + if (this.dependencyTracker) { + this.ctx.restore(); + } + } else { + this.ctx.restore(); + const currentMtx = getCurrentTransform(this.ctx); + this.restore(opIdx); + this.ctx.save(); + this.ctx.setTransform(...currentMtx); + const dirtyBox = MIN_MAX_INIT.slice(); + Util.axialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx, dirtyBox); + this.ctx.drawImage(groupCtx.canvas, 0, 0); + this.ctx.restore(); + this.compose(dirtyBox); + } + } + beginAnnotation(opIdx, id, rect, transform, matrix, hasOwnCanvas) { + this.#restoreInitialState(); + resetCtxToDefault(this.ctx); + this.ctx.save(); + this.save(opIdx); + if (this.baseTransform) { + this.ctx.setTransform(...this.baseTransform); + } + if (rect) { + const width = rect[2] - rect[0]; + const height = rect[3] - rect[1]; + if (hasOwnCanvas && this.annotationCanvasMap) { + transform = transform.slice(); + transform[4] -= rect[0]; + transform[5] -= rect[1]; + rect = rect.slice(); + rect[0] = rect[1] = 0; + rect[2] = width; + rect[3] = height; + Util.singularValueDecompose2dScale(getCurrentTransform(this.ctx), XY); + const { + viewportScale + } = this; + const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale); + const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale); + this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight); + const { + canvas, + context + } = this.annotationCanvas; + this.annotationCanvasMap.set(id, canvas); + this.annotationCanvas.savedCtx = this.ctx; + this.ctx = context; + this.ctx.save(); + this.ctx.setTransform(XY[0], 0, 0, -XY[1], 0, height * XY[1]); + resetCtxToDefault(this.ctx); + } else { + resetCtxToDefault(this.ctx); + this.endPath(opIdx); + const clip = new Path2D(); + clip.rect(rect[0], rect[1], width, height); + this.ctx.clip(clip); + } + } + this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height); + this.transform(opIdx, ...transform); + this.transform(opIdx, ...matrix); + } + endAnnotation(opIdx) { + if (this.annotationCanvas) { + this.ctx.restore(); + this.#drawFilter(); + this.ctx = this.annotationCanvas.savedCtx; + delete this.annotationCanvas.savedCtx; + delete this.annotationCanvas; + } + } + paintImageMaskXObject(opIdx, img) { + if (!this.contentVisible) { + return; + } + const count = img.count; + img = this.getObject(opIdx, img.data, img); + img.count = count; + const ctx = this.ctx; + const mask = this._createMaskCanvas(opIdx, img); + const maskCanvas = mask.canvas; + ctx.save(); + ctx.setTransform(1, 0, 0, 1, 0, 0); + ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY); + this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, mask.offsetX, mask.offsetX + maskCanvas.width, mask.offsetY, mask.offsetY + maskCanvas.height).recordOperation(opIdx); + ctx.restore(); + this.compose(); + } + paintImageMaskXObjectRepeat(opIdx, img, scaleX, skewX = 0, skewY = 0, scaleY, positions2) { + if (!this.contentVisible) { + return; + } + img = this.getObject(opIdx, img.data, img); + const ctx = this.ctx; + ctx.save(); + const currentTransform = getCurrentTransform(ctx); + ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0); + const mask = this._createMaskCanvas(opIdx, img); + ctx.setTransform(1, 0, 0, 1, mask.offsetX - currentTransform[4], mask.offsetY - currentTransform[5]); + this.dependencyTracker?.resetBBox(opIdx); + for (let i7 = 0, ii = positions2.length; i7 < ii; i7 += 2) { + const trans = Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions2[i7], positions2[i7 + 1]]); + ctx.drawImage(mask.canvas, trans[4], trans[5]); + this.dependencyTracker?.recordBBox(opIdx, this.ctx, trans[4], trans[4] + mask.canvas.width, trans[5], trans[5] + mask.canvas.height); + } + ctx.restore(); + this.compose(); + this.dependencyTracker?.recordOperation(opIdx); + } + paintImageMaskXObjectGroup(opIdx, images) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + const fillColor = this.current.fillColor; + const isPatternFill = this.current.patternFill; + this.dependencyTracker?.resetBBox(opIdx).recordDependencies(opIdx, Dependencies.transformAndFill); + for (const image of images) { + const { + data, + width, + height, + transform + } = image; + const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height); + const maskCtx = maskCanvas.context; + maskCtx.save(); + const img = this.getObject(opIdx, data, image); + putBinaryImageMask(maskCtx, img); + maskCtx.globalCompositeOperation = "source-in"; + maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, getCurrentTransformInverse(ctx), PathType.FILL, opIdx) : fillColor; + maskCtx.fillRect(0, 0, width, height); + maskCtx.restore(); + ctx.save(); + ctx.transform(...transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); + this.dependencyTracker?.recordBBox(opIdx, ctx, 0, width, 0, height); + ctx.restore(); + } + this.compose(); + this.dependencyTracker?.recordOperation(opIdx); + } + paintImageXObject(opIdx, objId) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(opIdx, objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + this.paintInlineImageXObject(opIdx, imgData); + } + paintImageXObjectRepeat(opIdx, objId, scaleX, scaleY, positions2) { + if (!this.contentVisible) { + return; + } + const imgData = this.getObject(opIdx, objId); + if (!imgData) { + warn("Dependent image isn't ready yet"); + return; + } + const width = imgData.width; + const height = imgData.height; + const map3 = []; + for (let i7 = 0, ii = positions2.length; i7 < ii; i7 += 2) { + map3.push({ + transform: [scaleX, 0, 0, scaleY, positions2[i7], positions2[i7 + 1]], + x: 0, + y: 0, + w: width, + h: height + }); + } + this.paintInlineImageXObjectGroup(opIdx, imgData, map3); + } + applyTransferMapsToCanvas(ctx) { + if (this.current.transferMaps !== "none") { + ctx.filter = this.current.transferMaps; + ctx.drawImage(ctx.canvas, 0, 0); + ctx.filter = "none"; + } + return ctx.canvas; + } + applyTransferMapsToBitmap(imgData) { + if (this.current.transferMaps === "none") { + return imgData.bitmap; + } + const { + bitmap, + width, + height + } = imgData; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + tmpCtx.filter = this.current.transferMaps; + tmpCtx.drawImage(bitmap, 0, 0); + tmpCtx.filter = "none"; + return tmpCanvas.canvas; + } + paintInlineImageXObject(opIdx, imgData) { + if (!this.contentVisible) { + return; + } + const width = imgData.width; + const height = imgData.height; + const ctx = this.ctx; + this.save(opIdx); + const { + filter: filter2 + } = ctx; + if (filter2 !== "none" && filter2 !== "") { + ctx.filter = "none"; + } + ctx.scale(1 / width, -1 / height); + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = this.applyTransferMapsToBitmap(imgData); + } else if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) { + imgToPaint = imgData; + } else { + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + const scaled = this._scaleImage(imgToPaint, getCurrentTransformInverse(ctx)); + ctx.imageSmoothingEnabled = getImageSmoothingEnabled(getCurrentTransform(ctx), imgData.interpolate); + this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, ctx, 0, width, -height, 0).recordDependencies(opIdx, Dependencies.imageXObject).recordOperation(opIdx); + drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height); + this.compose(); + this.restore(opIdx); + } + paintInlineImageXObjectGroup(opIdx, imgData, map3) { + if (!this.contentVisible) { + return; + } + const ctx = this.ctx; + let imgToPaint; + if (imgData.bitmap) { + imgToPaint = imgData.bitmap; + } else { + const w3 = imgData.width; + const h7 = imgData.height; + const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w3, h7); + const tmpCtx = tmpCanvas.context; + putBinaryImageData(tmpCtx, imgData); + imgToPaint = this.applyTransferMapsToCanvas(tmpCtx); + } + this.dependencyTracker?.resetBBox(opIdx); + for (const entry of map3) { + ctx.save(); + ctx.transform(...entry.transform); + ctx.scale(1, -1); + drawImageAtIntegerCoords(ctx, imgToPaint, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); + this.dependencyTracker?.recordBBox(opIdx, ctx, 0, 1, -1, 0); + ctx.restore(); + } + this.dependencyTracker?.recordOperation(opIdx); + this.compose(); + } + paintSolidColorImageMask(opIdx) { + if (!this.contentVisible) { + return; + } + this.dependencyTracker?.resetBBox(opIdx).recordBBox(opIdx, this.ctx, 0, 1, 0, 1).recordDependencies(opIdx, Dependencies.fill).recordOperation(opIdx); + this.ctx.fillRect(0, 0, 1, 1); + this.compose(); + } + markPoint(opIdx, tag) { + } + markPointProps(opIdx, tag, properties) { + } + beginMarkedContent(opIdx, tag) { + this.dependencyTracker?.beginMarkedContent(opIdx); + this.markedContentStack.push({ + visible: true + }); + } + beginMarkedContentProps(opIdx, tag, properties) { + this.dependencyTracker?.beginMarkedContent(opIdx); + if (tag === "OC") { + this.markedContentStack.push({ + visible: this.optionalContentConfig.isVisible(properties) + }); + } else { + this.markedContentStack.push({ + visible: true + }); + } + this.contentVisible = this.isContentVisible(); + } + endMarkedContent(opIdx) { + this.dependencyTracker?.endMarkedContent(opIdx); + this.markedContentStack.pop(); + this.contentVisible = this.isContentVisible(); + } + beginCompat(opIdx) { + } + endCompat(opIdx) { + } + consumePath(opIdx, path6, clipBox) { + const isEmpty = this.current.isEmptyClip(); + if (this.pendingClip) { + this.current.updateClipFromPath(); + } + if (!this.pendingClip) { + this.compose(clipBox); + } + const ctx = this.ctx; + if (this.pendingClip) { + if (!isEmpty) { + if (this.pendingClip === EO_CLIP) { + ctx.clip(path6, "evenodd"); + } else { + ctx.clip(path6); + } + } + this.pendingClip = null; + this.dependencyTracker?.bboxToClipBoxDropOperation(opIdx).recordFutureForcedDependency("clipPath", opIdx); + } else { + this.dependencyTracker?.recordOperation(opIdx); + } + this.current.startNewPathAndClipBox(this.current.clipBox); + } + getSinglePixelWidth() { + if (!this._cachedGetSinglePixelWidth) { + const m4 = getCurrentTransform(this.ctx); + if (m4[1] === 0 && m4[2] === 0) { + this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m4[0]), Math.abs(m4[3])); + } else { + const absDet = Math.abs(m4[0] * m4[3] - m4[2] * m4[1]); + const normX = Math.hypot(m4[0], m4[2]); + const normY = Math.hypot(m4[1], m4[3]); + this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet; + } + } + return this._cachedGetSinglePixelWidth; + } + getScaleForStroking() { + if (this._cachedScaleForStroking[0] === -1) { + const { + lineWidth + } = this.current; + const { + a: a3, + b: b4, + c: c6, + d: d4 + } = this.ctx.getTransform(); + let scaleX, scaleY; + if (b4 === 0 && c6 === 0) { + const normX = Math.abs(a3); + const normY = Math.abs(d4); + if (normX === normY) { + if (lineWidth === 0) { + scaleX = scaleY = 1 / normX; + } else { + const scaledLineWidth = normX * lineWidth; + scaleX = scaleY = scaledLineWidth < 1 ? 1 / scaledLineWidth : 1; + } + } else if (lineWidth === 0) { + scaleX = 1 / normX; + scaleY = 1 / normY; + } else { + const scaledXLineWidth = normX * lineWidth; + const scaledYLineWidth = normY * lineWidth; + scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1; + scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1; + } + } else { + const absDet = Math.abs(a3 * d4 - b4 * c6); + const normX = Math.hypot(a3, b4); + const normY = Math.hypot(c6, d4); + if (lineWidth === 0) { + scaleX = normY / absDet; + scaleY = normX / absDet; + } else { + const baseArea = lineWidth * absDet; + scaleX = normY > baseArea ? normY / baseArea : 1; + scaleY = normX > baseArea ? normX / baseArea : 1; + } + } + this._cachedScaleForStroking[0] = scaleX; + this._cachedScaleForStroking[1] = scaleY; + } + return this._cachedScaleForStroking; + } + rescaleAndStroke(path6, saveRestore) { + const { + ctx, + current: { + lineWidth + } + } = this; + const [scaleX, scaleY] = this.getScaleForStroking(); + if (scaleX === scaleY) { + ctx.lineWidth = (lineWidth || 1) * scaleX; + ctx.stroke(path6); + return; + } + const dashes = ctx.getLineDash(); + if (saveRestore) { + ctx.save(); + } + ctx.scale(scaleX, scaleY); + SCALE_MATRIX.a = 1 / scaleX; + SCALE_MATRIX.d = 1 / scaleY; + const newPath = new Path2D(); + newPath.addPath(path6, SCALE_MATRIX); + if (dashes.length > 0) { + const scale = Math.max(scaleX, scaleY); + ctx.setLineDash(dashes.map((x2) => x2 / scale)); + ctx.lineDashOffset /= scale; + } + ctx.lineWidth = lineWidth || 1; + ctx.stroke(newPath); + if (saveRestore) { + ctx.restore(); + } + } + isContentVisible() { + for (let i7 = this.markedContentStack.length - 1; i7 >= 0; i7--) { + if (!this.markedContentStack[i7].visible) { + return false; + } + } + return true; + } + }; + for (const op2 in OPS) { + if (CanvasGraphics.prototype[op2] !== void 0) { + CanvasGraphics.prototype[OPS[op2]] = CanvasGraphics.prototype[op2]; + } + } + GlobalWorkerOptions = class { + static #port = null; + static #src = ""; + static get workerPort() { + return this.#port; + } + static set workerPort(val2) { + if (!(typeof Worker !== "undefined" && val2 instanceof Worker) && val2 !== null) { + throw new Error("Invalid `workerPort` type."); + } + this.#port = val2; + } + static get workerSrc() { + return this.#src; + } + static set workerSrc(val2) { + if (typeof val2 !== "string") { + throw new Error("Invalid `workerSrc` type."); + } + this.#src = val2; + } + }; + Metadata = class { + #map; + #data; + constructor({ + parsedData, + rawData + }) { + this.#map = parsedData; + this.#data = rawData; + } + getRaw() { + return this.#data; + } + get(name) { + return this.#map.get(name) ?? null; + } + [Symbol.iterator]() { + return this.#map.entries(); + } + }; + INTERNAL = Symbol("INTERNAL"); + OptionalContentGroup = class { + #isDisplay = false; + #isPrint = false; + #userSet = false; + #visible = true; + constructor(renderingIntent, { + name, + intent, + usage, + rbGroups + }) { + this.#isDisplay = !!(renderingIntent & RenderingIntentFlag.DISPLAY); + this.#isPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + this.name = name; + this.intent = intent; + this.usage = usage; + this.rbGroups = rbGroups; + } + get visible() { + if (this.#userSet) { + return this.#visible; + } + if (!this.#visible) { + return false; + } + const { + print, + view + } = this.usage; + if (this.#isDisplay) { + return view?.viewState !== "OFF"; + } else if (this.#isPrint) { + return print?.printState !== "OFF"; + } + return true; + } + _setVisible(internal, visible, userSet = false) { + if (internal !== INTERNAL) { + unreachable("Internal method `_setVisible` called."); + } + this.#userSet = userSet; + this.#visible = visible; + } + }; + OptionalContentConfig = class { + #cachedGetHash = null; + #groups = /* @__PURE__ */ new Map(); + #initialHash = null; + #order = null; + constructor(data, renderingIntent = RenderingIntentFlag.DISPLAY) { + this.renderingIntent = renderingIntent; + this.name = null; + this.creator = null; + if (data === null) { + return; + } + this.name = data.name; + this.creator = data.creator; + this.#order = data.order; + for (const group of data.groups) { + this.#groups.set(group.id, new OptionalContentGroup(renderingIntent, group)); + } + if (data.baseState === "OFF") { + for (const group of this.#groups.values()) { + group._setVisible(INTERNAL, false); + } + } + for (const on of data.on) { + this.#groups.get(on)._setVisible(INTERNAL, true); + } + for (const off of data.off) { + this.#groups.get(off)._setVisible(INTERNAL, false); + } + this.#initialHash = this.getHash(); + } + #evaluateVisibilityExpression(array) { + const length = array.length; + if (length < 2) { + return true; + } + const operator = array[0]; + for (let i7 = 1; i7 < length; i7++) { + const element = array[i7]; + let state; + if (Array.isArray(element)) { + state = this.#evaluateVisibilityExpression(element); + } else if (this.#groups.has(element)) { + state = this.#groups.get(element).visible; + } else { + warn(`Optional content group not found: ${element}`); + return true; + } + switch (operator) { + case "And": + if (!state) { + return false; + } + break; + case "Or": + if (state) { + return true; + } + break; + case "Not": + return !state; + default: + return true; + } + } + return operator === "And"; + } + isVisible(group) { + if (this.#groups.size === 0) { + return true; + } + if (!group) { + info("Optional content group not defined."); + return true; + } + if (group.type === "OCG") { + if (!this.#groups.has(group.id)) { + warn(`Optional content group not found: ${group.id}`); + return true; + } + return this.#groups.get(group.id).visible; + } else if (group.type === "OCMD") { + if (group.expression) { + return this.#evaluateVisibilityExpression(group.expression); + } + if (!group.policy || group.policy === "AnyOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOn") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return false; + } + } + return true; + } else if (group.policy === "AnyOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (!this.#groups.get(id).visible) { + return true; + } + } + return false; + } else if (group.policy === "AllOff") { + for (const id of group.ids) { + if (!this.#groups.has(id)) { + warn(`Optional content group not found: ${id}`); + return true; + } + if (this.#groups.get(id).visible) { + return false; + } + } + return true; + } + warn(`Unknown optional content policy ${group.policy}.`); + return true; + } + warn(`Unknown group type ${group.type}.`); + return true; + } + setVisibility(id, visible = true, preserveRB = true) { + const group = this.#groups.get(id); + if (!group) { + warn(`Optional content group not found: ${id}`); + return; + } + if (preserveRB && visible && group.rbGroups.length) { + for (const rbGroup of group.rbGroups) { + for (const otherId of rbGroup) { + if (otherId !== id) { + this.#groups.get(otherId)?._setVisible(INTERNAL, false, true); + } + } + } + } + group._setVisible(INTERNAL, !!visible, true); + this.#cachedGetHash = null; + } + setOCGState({ + state, + preserveRB + }) { + let operator; + for (const elem of state) { + switch (elem) { + case "ON": + case "OFF": + case "Toggle": + operator = elem; + continue; + } + const group = this.#groups.get(elem); + if (!group) { + continue; + } + switch (operator) { + case "ON": + this.setVisibility(elem, true, preserveRB); + break; + case "OFF": + this.setVisibility(elem, false, preserveRB); + break; + case "Toggle": + this.setVisibility(elem, !group.visible, preserveRB); + break; + } + } + this.#cachedGetHash = null; + } + get hasInitialVisibility() { + return this.#initialHash === null || this.getHash() === this.#initialHash; + } + getOrder() { + if (!this.#groups.size) { + return null; + } + if (this.#order) { + return this.#order.slice(); + } + return [...this.#groups.keys()]; + } + getGroup(id) { + return this.#groups.get(id) || null; + } + getHash() { + if (this.#cachedGetHash !== null) { + return this.#cachedGetHash; + } + const hash = new MurmurHash3_64(); + for (const [id, group] of this.#groups) { + hash.update(`${id}:${group.visible}`); + } + return this.#cachedGetHash = hash.hexdigest(); + } + [Symbol.iterator]() { + return this.#groups.entries(); + } + }; + PDFDataTransportStream = class { + constructor(pdfDataRangeTransport, { + disableRange = false, + disableStream = false + }) { + assert(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.'); + const { + length, + initialData, + progressiveDone, + contentDispositionFilename + } = pdfDataRangeTransport; + this._queuedChunks = []; + this._progressiveDone = progressiveDone; + this._contentDispositionFilename = contentDispositionFilename; + if (initialData?.length > 0) { + const buffer = initialData instanceof Uint8Array && initialData.byteLength === initialData.buffer.byteLength ? initialData.buffer : new Uint8Array(initialData).buffer; + this._queuedChunks.push(buffer); + } + this._pdfDataRangeTransport = pdfDataRangeTransport; + this._isStreamingSupported = !disableStream; + this._isRangeSupported = !disableRange; + this._contentLength = length; + this._fullRequestReader = null; + this._rangeReaders = []; + pdfDataRangeTransport.addRangeListener((begin, chunk) => { + this._onReceiveData({ + begin, + chunk + }); + }); + pdfDataRangeTransport.addProgressListener((loaded, total) => { + this._onProgress({ + loaded, + total + }); + }); + pdfDataRangeTransport.addProgressiveReadListener((chunk) => { + this._onReceiveData({ + chunk + }); + }); + pdfDataRangeTransport.addProgressiveDoneListener(() => { + this._onProgressiveDone(); + }); + pdfDataRangeTransport.transportReady(); + } + _onReceiveData({ + begin, + chunk + }) { + const buffer = chunk instanceof Uint8Array && chunk.byteLength === chunk.buffer.byteLength ? chunk.buffer : new Uint8Array(chunk).buffer; + if (begin === void 0) { + if (this._fullRequestReader) { + this._fullRequestReader._enqueue(buffer); + } else { + this._queuedChunks.push(buffer); + } + } else { + const found = this._rangeReaders.some(function(rangeReader) { + if (rangeReader._begin !== begin) { + return false; + } + rangeReader._enqueue(buffer); + return true; + }); + assert(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."); + } + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + _onProgress(evt) { + if (evt.total === void 0) { + this._rangeReaders[0]?.onProgress?.({ + loaded: evt.loaded + }); + } else { + this._fullRequestReader?.onProgress?.({ + loaded: evt.loaded, + total: evt.total + }); + } + } + _onProgressiveDone() { + this._fullRequestReader?.progressiveDone(); + this._progressiveDone = true; + } + _removeRangeReader(reader) { + const i7 = this._rangeReaders.indexOf(reader); + if (i7 >= 0) { + this._rangeReaders.splice(i7, 1); + } + } + getFullReader() { + assert(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once."); + const queuedChunks = this._queuedChunks; + this._queuedChunks = null; + return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename); + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new PDFDataTransportStreamRangeReader(this, begin, end); + this._pdfDataRangeTransport.requestDataRange(begin, end); + this._rangeReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeReaders.slice(0)) { + reader.cancel(reason); + } + this._pdfDataRangeTransport.abort(); + } + }; + PDFDataTransportStreamReader = class { + constructor(stream2, queuedChunks, progressiveDone = false, contentDispositionFilename = null) { + this._stream = stream2; + this._done = progressiveDone || false; + this._filename = isPdfFile(contentDispositionFilename) ? contentDispositionFilename : null; + this._queuedChunks = queuedChunks || []; + this._loaded = 0; + for (const chunk of this._queuedChunks) { + this._loaded += chunk.byteLength; + } + this._requests = []; + this._headersReady = Promise.resolve(); + stream2._fullRequestReader = this; + this.onProgress = null; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunks.push(chunk); + } + this._loaded += chunk.byteLength; + } + get headersReady() { + return this._headersReady; + } + get filename() { + return this._filename; + } + get isRangeSupported() { + return this._stream._isRangeSupported; + } + get isStreamingSupported() { + return this._stream._isStreamingSupported; + } + get contentLength() { + return this._stream._contentLength; + } + async read() { + if (this._queuedChunks.length > 0) { + const chunk = this._queuedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: void 0, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + } + progressiveDone() { + if (this._done) { + return; + } + this._done = true; + } + }; + PDFDataTransportStreamRangeReader = class { + constructor(stream2, begin, end) { + this._stream = stream2; + this._begin = begin; + this._end = end; + this._queuedChunk = null; + this._requests = []; + this._done = false; + this.onProgress = null; + } + _enqueue(chunk) { + if (this._done) { + return; + } + if (this._requests.length === 0) { + this._queuedChunk = chunk; + } else { + const requestsCapability = this._requests.shift(); + requestsCapability.resolve({ + value: chunk, + done: false + }); + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + } + this._done = true; + this._stream._removeRangeReader(this); + } + get isStreamingSupported() { + return false; + } + async read() { + if (this._queuedChunk) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: void 0, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + this._stream._removeRangeReader(this); + } + }; + PDFFetchStream = class { + _responseOrigin = null; + constructor(source) { + this.source = source; + this.isHttp = /^https?:/i.test(source.url); + this.headers = createHeaders(this.isHttp, source.httpHeaders); + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFFetchStreamReader(this); + return this._fullRequestReader; + } + getRangeReader(begin, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const reader = new PDFFetchStreamRangeReader(this, begin, end); + this._rangeRequestReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } + }; + PDFFetchStreamReader = class { + constructor(stream2) { + this._stream = stream2; + this._reader = null; + this._loaded = 0; + this._filename = null; + const source = stream2.source; + this._withCredentials = source.withCredentials || false; + this._contentLength = source.length; + this._headersCapability = Promise.withResolvers(); + this._disableRange = source.disableRange || false; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._abortController = new AbortController(); + this._isStreamingSupported = !source.disableStream; + this._isRangeSupported = !source.disableRange; + const headers = new Headers(stream2.headers); + const url = source.url; + fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then((response) => { + stream2._responseOrigin = getResponseOrigin(response.url); + if (!validateResponseStatus(response.status)) { + throw createResponseError(response.status, url); + } + this._reader = response.body.getReader(); + this._headersCapability.resolve(); + const responseHeaders = response.headers; + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: stream2.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + this._isRangeSupported = allowRangeRequests; + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (!this._isStreamingSupported && this._isRangeSupported) { + this.cancel(new AbortException("Streaming is disabled.")); + } + }).catch(this._headersCapability.reject); + this.onProgress = null; + } + get headersReady() { + return this._headersCapability.promise; + } + get filename() { + return this._filename; + } + get contentLength() { + return this._contentLength; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._headersCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + return { + value: getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } + }; + PDFFetchStreamRangeReader = class { + constructor(stream2, begin, end) { + this._stream = stream2; + this._reader = null; + this._loaded = 0; + const source = stream2.source; + this._withCredentials = source.withCredentials || false; + this._readCapability = Promise.withResolvers(); + this._isStreamingSupported = !source.disableStream; + this._abortController = new AbortController(); + const headers = new Headers(stream2.headers); + headers.append("Range", `bytes=${begin}-${end - 1}`); + const url = source.url; + fetch(url, createFetchOptions(headers, this._withCredentials, this._abortController)).then((response) => { + const responseOrigin = getResponseOrigin(response.url); + if (responseOrigin !== stream2._responseOrigin) { + throw new Error(`Expected range response-origin "${responseOrigin}" to match "${stream2._responseOrigin}".`); + } + if (!validateResponseStatus(response.status)) { + throw createResponseError(response.status, url); + } + this._readCapability.resolve(); + this._reader = response.body.getReader(); + }).catch(this._readCapability.reject); + this.onProgress = null; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + const { + value, + done + } = await this._reader.read(); + if (done) { + return { + value, + done + }; + } + this._loaded += value.byteLength; + this.onProgress?.({ + loaded: this._loaded + }); + return { + value: getArrayBuffer(value), + done: false + }; + } + cancel(reason) { + this._reader?.cancel(reason); + this._abortController.abort(); + } + }; + OK_RESPONSE = 200; + PARTIAL_CONTENT_RESPONSE = 206; + NetworkManager = class { + _responseOrigin = null; + constructor({ + url, + httpHeaders, + withCredentials + }) { + this.url = url; + this.isHttp = /^https?:/i.test(url); + this.headers = createHeaders(this.isHttp, httpHeaders); + this.withCredentials = withCredentials || false; + this.currXhrId = 0; + this.pendingRequests = /* @__PURE__ */ Object.create(null); + } + request(args) { + const xhr = new XMLHttpRequest(); + const xhrId = this.currXhrId++; + const pendingRequest = this.pendingRequests[xhrId] = { + xhr + }; + xhr.open("GET", this.url); + xhr.withCredentials = this.withCredentials; + for (const [key, val2] of this.headers) { + xhr.setRequestHeader(key, val2); + } + if (this.isHttp && "begin" in args && "end" in args) { + xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`); + pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE; + } else { + pendingRequest.expectedStatus = OK_RESPONSE; + } + xhr.responseType = "arraybuffer"; + assert(args.onError, "Expected `onError` callback to be provided."); + xhr.onerror = () => { + args.onError(xhr.status); + }; + xhr.onreadystatechange = this.onStateChange.bind(this, xhrId); + xhr.onprogress = this.onProgress.bind(this, xhrId); + pendingRequest.onHeadersReceived = args.onHeadersReceived; + pendingRequest.onDone = args.onDone; + pendingRequest.onError = args.onError; + pendingRequest.onProgress = args.onProgress; + xhr.send(null); + return xhrId; + } + onProgress(xhrId, evt) { + const pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + return; + } + pendingRequest.onProgress?.(evt); + } + onStateChange(xhrId, evt) { + const pendingRequest = this.pendingRequests[xhrId]; + if (!pendingRequest) { + return; + } + const xhr = pendingRequest.xhr; + if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) { + pendingRequest.onHeadersReceived(); + delete pendingRequest.onHeadersReceived; + } + if (xhr.readyState !== 4) { + return; + } + if (!(xhrId in this.pendingRequests)) { + return; + } + delete this.pendingRequests[xhrId]; + if (xhr.status === 0 && this.isHttp) { + pendingRequest.onError(xhr.status); + return; + } + const xhrStatus = xhr.status || OK_RESPONSE; + const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE; + if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) { + pendingRequest.onError(xhr.status); + return; + } + const chunk = network_getArrayBuffer(xhr); + if (xhrStatus === PARTIAL_CONTENT_RESPONSE) { + const rangeHeader = xhr.getResponseHeader("Content-Range"); + const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader); + if (matches) { + pendingRequest.onDone({ + begin: parseInt(matches[1], 10), + chunk + }); + } else { + warn(`Missing or invalid "Content-Range" header.`); + pendingRequest.onError(0); + } + } else if (chunk) { + pendingRequest.onDone({ + begin: 0, + chunk + }); + } else { + pendingRequest.onError(xhr.status); + } + } + getRequestXhr(xhrId) { + return this.pendingRequests[xhrId].xhr; + } + isPendingRequest(xhrId) { + return xhrId in this.pendingRequests; + } + abortRequest(xhrId) { + const xhr = this.pendingRequests[xhrId].xhr; + delete this.pendingRequests[xhrId]; + xhr.abort(); + } + }; + PDFNetworkStream = class { + constructor(source) { + this._source = source; + this._manager = new NetworkManager(source); + this._rangeChunkSize = source.rangeChunkSize; + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + _onRangeRequestReaderClosed(reader) { + const i7 = this._rangeRequestReaders.indexOf(reader); + if (i7 >= 0) { + this._rangeRequestReaders.splice(i7, 1); + } + } + getFullReader() { + assert(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source); + return this._fullRequestReader; + } + getRangeReader(begin, end) { + const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end); + reader.onClosed = this._onRangeRequestReaderClosed.bind(this); + this._rangeRequestReaders.push(reader); + return reader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } + }; + PDFNetworkStreamFullRequestReader = class { + constructor(manager, source) { + this._manager = manager; + this._url = source.url; + this._fullRequestId = manager.request({ + onHeadersReceived: this._onHeadersReceived.bind(this), + onDone: this._onDone.bind(this), + onError: this._onError.bind(this), + onProgress: this._onProgress.bind(this) + }); + this._headersCapability = Promise.withResolvers(); + this._disableRange = source.disableRange || false; + this._contentLength = source.length; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._isStreamingSupported = false; + this._isRangeSupported = false; + this._cachedChunks = []; + this._requests = []; + this._done = false; + this._storedError = void 0; + this._filename = null; + this.onProgress = null; + } + _onHeadersReceived() { + const fullRequestXhrId = this._fullRequestId; + const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId); + this._manager._responseOrigin = getResponseOrigin(fullRequestXhr.responseURL); + const rawResponseHeaders = fullRequestXhr.getAllResponseHeaders(); + const responseHeaders = new Headers(rawResponseHeaders ? rawResponseHeaders.trimStart().replace(/[^\S ]+$/, "").split(/[\r\n]+/).map((x2) => { + const [key, ...val2] = x2.split(": "); + return [key, val2.join(": ")]; + }) : []); + const { + allowRangeRequests, + suggestedLength + } = validateRangeRequestCapabilities({ + responseHeaders, + isHttp: this._manager.isHttp, + rangeChunkSize: this._rangeChunkSize, + disableRange: this._disableRange + }); + if (allowRangeRequests) { + this._isRangeSupported = true; + } + this._contentLength = suggestedLength || this._contentLength; + this._filename = extractFilenameFromHeader(responseHeaders); + if (this._isRangeSupported) { + this._manager.abortRequest(fullRequestXhrId); + } + this._headersCapability.resolve(); + } + _onDone(data) { + if (data) { + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: data.chunk, + done: false + }); + } else { + this._cachedChunks.push(data.chunk); + } + } + this._done = true; + if (this._cachedChunks.length > 0) { + return; + } + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + } + _onError(status) { + this._storedError = createResponseError(status, this._url); + this._headersCapability.reject(this._storedError); + for (const requestCapability of this._requests) { + requestCapability.reject(this._storedError); + } + this._requests.length = 0; + this._cachedChunks.length = 0; + } + _onProgress(evt) { + this.onProgress?.({ + loaded: evt.loaded, + total: evt.lengthComputable ? evt.total : this._contentLength + }); + } + get filename() { + return this._filename; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + get contentLength() { + return this._contentLength; + } + get headersReady() { + return this._headersCapability.promise; + } + async read() { + await this._headersCapability.promise; + if (this._storedError) { + throw this._storedError; + } + if (this._cachedChunks.length > 0) { + const chunk = this._cachedChunks.shift(); + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: void 0, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + this._headersCapability.reject(reason); + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + if (this._manager.isPendingRequest(this._fullRequestId)) { + this._manager.abortRequest(this._fullRequestId); + } + this._fullRequestReader = null; + } + }; + PDFNetworkStreamRangeRequestReader = class { + constructor(manager, begin, end) { + this._manager = manager; + this._url = manager.url; + this._requestId = manager.request({ + begin, + end, + onHeadersReceived: this._onHeadersReceived.bind(this), + onDone: this._onDone.bind(this), + onError: this._onError.bind(this), + onProgress: this._onProgress.bind(this) + }); + this._requests = []; + this._queuedChunk = null; + this._done = false; + this._storedError = void 0; + this.onProgress = null; + this.onClosed = null; + } + _onHeadersReceived() { + const responseOrigin = getResponseOrigin(this._manager.getRequestXhr(this._requestId)?.responseURL); + if (responseOrigin !== this._manager._responseOrigin) { + this._storedError = new Error(`Expected range response-origin "${responseOrigin}" to match "${this._manager._responseOrigin}".`); + this._onError(0); + } + } + _close() { + this.onClosed?.(this); + } + _onDone(data) { + const chunk = data.chunk; + if (this._requests.length > 0) { + const requestCapability = this._requests.shift(); + requestCapability.resolve({ + value: chunk, + done: false + }); + } else { + this._queuedChunk = chunk; + } + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + this._close(); + } + _onError(status) { + this._storedError ??= createResponseError(status, this._url); + for (const requestCapability of this._requests) { + requestCapability.reject(this._storedError); + } + this._requests.length = 0; + this._queuedChunk = null; + } + _onProgress(evt) { + if (!this.isStreamingSupported) { + this.onProgress?.({ + loaded: evt.loaded + }); + } + } + get isStreamingSupported() { + return false; + } + async read() { + if (this._storedError) { + throw this._storedError; + } + if (this._queuedChunk !== null) { + const chunk = this._queuedChunk; + this._queuedChunk = null; + return { + value: chunk, + done: false + }; + } + if (this._done) { + return { + value: void 0, + done: true + }; + } + const requestCapability = Promise.withResolvers(); + this._requests.push(requestCapability); + return requestCapability.promise; + } + cancel(reason) { + this._done = true; + for (const requestCapability of this._requests) { + requestCapability.resolve({ + value: void 0, + done: true + }); + } + this._requests.length = 0; + if (this._manager.isPendingRequest(this._requestId)) { + this._manager.abortRequest(this._requestId); + } + this._close(); + } + }; + urlRegex = /^[a-z][a-z0-9\-+.]+:/i; + PDFNodeStream = class { + constructor(source) { + this.source = source; + this.url = parseUrlOrPath(source.url); + assert(this.url.protocol === "file:", "PDFNodeStream only supports file:// URLs."); + this._fullRequestReader = null; + this._rangeRequestReaders = []; + } + get _progressiveDataLength() { + return this._fullRequestReader?._loaded ?? 0; + } + getFullReader() { + assert(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once."); + this._fullRequestReader = new PDFNodeStreamFsFullReader(this); + return this._fullRequestReader; + } + getRangeReader(start, end) { + if (end <= this._progressiveDataLength) { + return null; + } + const rangeReader = new PDFNodeStreamFsRangeReader(this, start, end); + this._rangeRequestReaders.push(rangeReader); + return rangeReader; + } + cancelAllRequests(reason) { + this._fullRequestReader?.cancel(reason); + for (const reader of this._rangeRequestReaders.slice(0)) { + reader.cancel(reason); + } + } + }; + PDFNodeStreamFsFullReader = class { + constructor(stream2) { + this._url = stream2.url; + this._done = false; + this._storedError = null; + this.onProgress = null; + const source = stream2.source; + this._contentLength = source.length; + this._loaded = 0; + this._filename = null; + this._disableRange = source.disableRange || false; + this._rangeChunkSize = source.rangeChunkSize; + if (!this._rangeChunkSize && !this._disableRange) { + this._disableRange = true; + } + this._isStreamingSupported = !source.disableStream; + this._isRangeSupported = !source.disableRange; + this._readableStream = null; + this._readCapability = Promise.withResolvers(); + this._headersCapability = Promise.withResolvers(); + const fs = process.getBuiltinModule("fs"); + fs.promises.lstat(this._url).then((stat) => { + this._contentLength = stat.size; + this._setReadableStream(fs.createReadStream(this._url)); + this._headersCapability.resolve(); + }, (error) => { + if (error.code === "ENOENT") { + error = createResponseError(0, this._url.href); + } + this._storedError = error; + this._headersCapability.reject(error); + }); + } + get headersReady() { + return this._headersCapability.promise; + } + get filename() { + return this._filename; + } + get contentLength() { + return this._contentLength; + } + get isRangeSupported() { + return this._isRangeSupported; + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + if (this._done) { + return { + value: void 0, + done: true + }; + } + if (this._storedError) { + throw this._storedError; + } + const chunk = this._readableStream.read(); + if (chunk === null) { + this._readCapability = Promise.withResolvers(); + return this.read(); + } + this._loaded += chunk.length; + this.onProgress?.({ + loaded: this._loaded, + total: this._contentLength + }); + const buffer = new Uint8Array(chunk).buffer; + return { + value: buffer, + done: false + }; + } + cancel(reason) { + if (!this._readableStream) { + this._error(reason); + return; + } + this._readableStream.destroy(reason); + } + _error(reason) { + this._storedError = reason; + this._readCapability.resolve(); + } + _setReadableStream(readableStream) { + this._readableStream = readableStream; + readableStream.on("readable", () => { + this._readCapability.resolve(); + }); + readableStream.on("end", () => { + readableStream.destroy(); + this._done = true; + this._readCapability.resolve(); + }); + readableStream.on("error", (reason) => { + this._error(reason); + }); + if (!this._isStreamingSupported && this._isRangeSupported) { + this._error(new AbortException("streaming is disabled")); + } + if (this._storedError) { + this._readableStream.destroy(this._storedError); + } + } + }; + PDFNodeStreamFsRangeReader = class { + constructor(stream2, start, end) { + this._url = stream2.url; + this._done = false; + this._storedError = null; + this.onProgress = null; + this._loaded = 0; + this._readableStream = null; + this._readCapability = Promise.withResolvers(); + const source = stream2.source; + this._isStreamingSupported = !source.disableStream; + const fs = process.getBuiltinModule("fs"); + this._setReadableStream(fs.createReadStream(this._url, { + start, + end: end - 1 + })); + } + get isStreamingSupported() { + return this._isStreamingSupported; + } + async read() { + await this._readCapability.promise; + if (this._done) { + return { + value: void 0, + done: true + }; + } + if (this._storedError) { + throw this._storedError; + } + const chunk = this._readableStream.read(); + if (chunk === null) { + this._readCapability = Promise.withResolvers(); + return this.read(); + } + this._loaded += chunk.length; + this.onProgress?.({ + loaded: this._loaded + }); + const buffer = new Uint8Array(chunk).buffer; + return { + value: buffer, + done: false + }; + } + cancel(reason) { + if (!this._readableStream) { + this._error(reason); + return; + } + this._readableStream.destroy(reason); + } + _error(reason) { + this._storedError = reason; + this._readCapability.resolve(); + } + _setReadableStream(readableStream) { + this._readableStream = readableStream; + readableStream.on("readable", () => { + this._readCapability.resolve(); + }); + readableStream.on("end", () => { + readableStream.destroy(); + this._done = true; + this._readCapability.resolve(); + }); + readableStream.on("error", (reason) => { + this._error(reason); + }); + if (this._storedError) { + this._readableStream.destroy(this._storedError); + } + } + }; + INITIAL_DATA = Symbol("INITIAL_DATA"); + PDFObjects = class { + #objs = /* @__PURE__ */ Object.create(null); + #ensureObj(objId) { + return this.#objs[objId] ||= { + ...Promise.withResolvers(), + data: INITIAL_DATA + }; + } + get(objId, callback2 = null) { + if (callback2) { + const obj2 = this.#ensureObj(objId); + obj2.promise.then(() => callback2(obj2.data)); + return null; + } + const obj = this.#objs[objId]; + if (!obj || obj.data === INITIAL_DATA) { + throw new Error(`Requesting object that isn't resolved yet ${objId}.`); + } + return obj.data; + } + has(objId) { + const obj = this.#objs[objId]; + return !!obj && obj.data !== INITIAL_DATA; + } + delete(objId) { + const obj = this.#objs[objId]; + if (!obj || obj.data === INITIAL_DATA) { + return false; + } + delete this.#objs[objId]; + return true; + } + resolve(objId, data = null) { + const obj = this.#ensureObj(objId); + obj.data = data; + obj.resolve(); + } + clear() { + for (const objId in this.#objs) { + const { + data + } = this.#objs[objId]; + data?.bitmap?.close(); + } + this.#objs = /* @__PURE__ */ Object.create(null); + } + *[Symbol.iterator]() { + for (const objId in this.#objs) { + const { + data + } = this.#objs[objId]; + if (data === INITIAL_DATA) { + continue; + } + yield [objId, data]; + } + } + }; + MAX_TEXT_DIVS_TO_RENDER = 1e5; + DEFAULT_FONT_SIZE = 30; + TextLayer = class _TextLayer { + #capability = Promise.withResolvers(); + #container = null; + #disableProcessItems = false; + #fontInspectorEnabled = !!globalThis.FontInspector?.enabled; + #lang = null; + #layoutTextParams = null; + #pageHeight = 0; + #pageWidth = 0; + #reader = null; + #rootContainer = null; + #rotation = 0; + #scale = 0; + #styleCache = /* @__PURE__ */ Object.create(null); + #textContentItemsStr = []; + #textContentSource = null; + #textDivs = []; + #textDivProperties = /* @__PURE__ */ new WeakMap(); + #transform = null; + static #ascentCache = /* @__PURE__ */ new Map(); + static #canvasContexts = /* @__PURE__ */ new Map(); + static #canvasCtxFonts = /* @__PURE__ */ new WeakMap(); + static #minFontSize = null; + static #pendingTextLayers = /* @__PURE__ */ new Set(); + constructor({ + textContentSource, + container, + viewport + }) { + if (textContentSource instanceof ReadableStream) { + this.#textContentSource = textContentSource; + } else if (typeof textContentSource === "object") { + this.#textContentSource = new ReadableStream({ + start(controller) { + controller.enqueue(textContentSource); + controller.close(); + } + }); + } else { + throw new Error('No "textContentSource" parameter specified.'); + } + this.#container = this.#rootContainer = container; + this.#scale = viewport.scale * OutputScale.pixelRatio; + this.#rotation = viewport.rotation; + this.#layoutTextParams = { + div: null, + properties: null, + ctx: null + }; + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + this.#transform = [1, 0, 0, -1, -pageX, pageY + pageHeight]; + this.#pageWidth = pageWidth; + this.#pageHeight = pageHeight; + _TextLayer.#ensureMinFontSizeComputed(); + setLayerDimensions(container, viewport); + this.#capability.promise.finally(() => { + _TextLayer.#pendingTextLayers.delete(this); + this.#layoutTextParams = null; + this.#styleCache = null; + }).catch(() => { + }); + } + static get fontFamilyMap() { + const { + isWindows, + isFirefox + } = util_FeatureTest.platform; + return shadow(this, "fontFamilyMap", /* @__PURE__ */ new Map([["sans-serif", `${isWindows && isFirefox ? "Calibri, " : ""}sans-serif`], ["monospace", `${isWindows && isFirefox ? "Lucida Console, " : ""}monospace`]])); + } + render() { + const pump = () => { + this.#reader.read().then(({ + value, + done + }) => { + if (done) { + this.#capability.resolve(); + return; + } + this.#lang ??= value.lang; + Object.assign(this.#styleCache, value.styles); + this.#processItems(value.items); + pump(); + }, this.#capability.reject); + }; + this.#reader = this.#textContentSource.getReader(); + _TextLayer.#pendingTextLayers.add(this); + pump(); + return this.#capability.promise; + } + update({ + viewport, + onBefore = null + }) { + const scale = viewport.scale * OutputScale.pixelRatio; + const rotation = viewport.rotation; + if (rotation !== this.#rotation) { + onBefore?.(); + this.#rotation = rotation; + setLayerDimensions(this.#rootContainer, { + rotation + }); + } + if (scale !== this.#scale) { + onBefore?.(); + this.#scale = scale; + const params = { + div: null, + properties: null, + ctx: _TextLayer.#getCtx(this.#lang) + }; + for (const div of this.#textDivs) { + params.properties = this.#textDivProperties.get(div); + params.div = div; + this.#layout(params); + } + } + } + cancel() { + const abortEx = new AbortException("TextLayer task cancelled."); + this.#reader?.cancel(abortEx).catch(() => { + }); + this.#reader = null; + this.#capability.reject(abortEx); + } + get textDivs() { + return this.#textDivs; + } + get textContentItemsStr() { + return this.#textContentItemsStr; + } + #processItems(items) { + if (this.#disableProcessItems) { + return; + } + this.#layoutTextParams.ctx ??= _TextLayer.#getCtx(this.#lang); + const textDivs = this.#textDivs, textContentItemsStr = this.#textContentItemsStr; + for (const item of items) { + if (textDivs.length > MAX_TEXT_DIVS_TO_RENDER) { + warn("Ignoring additional textDivs for performance reasons."); + this.#disableProcessItems = true; + return; + } + if (item.str === void 0) { + if (item.type === "beginMarkedContentProps" || item.type === "beginMarkedContent") { + const parent = this.#container; + this.#container = document.createElement("span"); + this.#container.classList.add("markedContent"); + if (item.id) { + this.#container.setAttribute("id", `${item.id}`); + } + parent.append(this.#container); + } else if (item.type === "endMarkedContent") { + this.#container = this.#container.parentNode; + } + continue; + } + textContentItemsStr.push(item.str); + this.#appendText(item); + } + } + #appendText(geom) { + const textDiv = document.createElement("span"); + const textDivProperties = { + angle: 0, + canvasWidth: 0, + hasText: geom.str !== "", + hasEOL: geom.hasEOL, + fontSize: 0 + }; + this.#textDivs.push(textDiv); + const tx = Util.transform(this.#transform, geom.transform); + let angle = Math.atan2(tx[1], tx[0]); + const style = this.#styleCache[geom.fontName]; + if (style.vertical) { + angle += Math.PI / 2; + } + let fontFamily = this.#fontInspectorEnabled && style.fontSubstitution || style.fontFamily; + fontFamily = _TextLayer.fontFamilyMap.get(fontFamily) || fontFamily; + const fontHeight = Math.hypot(tx[2], tx[3]); + const fontAscent = fontHeight * _TextLayer.#getAscent(fontFamily, style, this.#lang); + let left, top; + if (angle === 0) { + left = tx[4]; + top = tx[5] - fontAscent; + } else { + left = tx[4] + fontAscent * Math.sin(angle); + top = tx[5] - fontAscent * Math.cos(angle); + } + const scaleFactorStr = "calc(var(--total-scale-factor) *"; + const divStyle = textDiv.style; + if (this.#container === this.#rootContainer) { + divStyle.left = `${(100 * left / this.#pageWidth).toFixed(2)}%`; + divStyle.top = `${(100 * top / this.#pageHeight).toFixed(2)}%`; + } else { + divStyle.left = `${scaleFactorStr}${left.toFixed(2)}px)`; + divStyle.top = `${scaleFactorStr}${top.toFixed(2)}px)`; + } + divStyle.fontSize = `${scaleFactorStr}${(_TextLayer.#minFontSize * fontHeight).toFixed(2)}px)`; + divStyle.fontFamily = fontFamily; + textDivProperties.fontSize = fontHeight; + textDiv.setAttribute("role", "presentation"); + textDiv.textContent = geom.str; + textDiv.dir = geom.dir; + if (this.#fontInspectorEnabled) { + textDiv.dataset.fontName = style.fontSubstitutionLoadedName || geom.fontName; + } + if (angle !== 0) { + textDivProperties.angle = angle * (180 / Math.PI); + } + let shouldScaleText = false; + if (geom.str.length > 1) { + shouldScaleText = true; + } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) { + const absScaleX = Math.abs(geom.transform[0]), absScaleY = Math.abs(geom.transform[3]); + if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) { + shouldScaleText = true; + } + } + if (shouldScaleText) { + textDivProperties.canvasWidth = style.vertical ? geom.height : geom.width; + } + this.#textDivProperties.set(textDiv, textDivProperties); + this.#layoutTextParams.div = textDiv; + this.#layoutTextParams.properties = textDivProperties; + this.#layout(this.#layoutTextParams); + if (textDivProperties.hasText) { + this.#container.append(textDiv); + } + if (textDivProperties.hasEOL) { + const br = document.createElement("br"); + br.setAttribute("role", "presentation"); + this.#container.append(br); + } + } + #layout(params) { + const { + div, + properties, + ctx + } = params; + const { + style + } = div; + let transform = ""; + if (_TextLayer.#minFontSize > 1) { + transform = `scale(${1 / _TextLayer.#minFontSize})`; + } + if (properties.canvasWidth !== 0 && properties.hasText) { + const { + fontFamily + } = style; + const { + canvasWidth, + fontSize + } = properties; + _TextLayer.#ensureCtxFont(ctx, fontSize * this.#scale, fontFamily); + const { + width + } = ctx.measureText(div.textContent); + if (width > 0) { + transform = `scaleX(${canvasWidth * this.#scale / width}) ${transform}`; + } + } + if (properties.angle !== 0) { + transform = `rotate(${properties.angle}deg) ${transform}`; + } + if (transform.length > 0) { + style.transform = transform; + } + } + static cleanup() { + if (this.#pendingTextLayers.size > 0) { + return; + } + this.#ascentCache.clear(); + for (const { + canvas + } of this.#canvasContexts.values()) { + canvas.remove(); + } + this.#canvasContexts.clear(); + } + static #getCtx(lang = null) { + let ctx = this.#canvasContexts.get(lang ||= ""); + if (!ctx) { + const canvas = document.createElement("canvas"); + canvas.className = "hiddenCanvasElement"; + canvas.lang = lang; + document.body.append(canvas); + ctx = canvas.getContext("2d", { + alpha: false, + willReadFrequently: true + }); + this.#canvasContexts.set(lang, ctx); + this.#canvasCtxFonts.set(ctx, { + size: 0, + family: "" + }); + } + return ctx; + } + static #ensureCtxFont(ctx, size, family) { + const cached = this.#canvasCtxFonts.get(ctx); + if (size === cached.size && family === cached.family) { + return; + } + ctx.font = `${size}px ${family}`; + cached.size = size; + cached.family = family; + } + static #ensureMinFontSizeComputed() { + if (this.#minFontSize !== null) { + return; + } + const div = document.createElement("div"); + div.style.opacity = 0; + div.style.lineHeight = 1; + div.style.fontSize = "1px"; + div.style.position = "absolute"; + div.textContent = "X"; + document.body.append(div); + this.#minFontSize = div.getBoundingClientRect().height; + div.remove(); + } + static #getAscent(fontFamily, style, lang) { + const cachedAscent = this.#ascentCache.get(fontFamily); + if (cachedAscent) { + return cachedAscent; + } + const ctx = this.#getCtx(lang); + ctx.canvas.width = ctx.canvas.height = DEFAULT_FONT_SIZE; + this.#ensureCtxFont(ctx, DEFAULT_FONT_SIZE, fontFamily); + const metrics = ctx.measureText(""); + const ascent = metrics.fontBoundingBoxAscent; + const descent = Math.abs(metrics.fontBoundingBoxDescent); + ctx.canvas.width = ctx.canvas.height = 0; + let ratio = 0.8; + if (ascent) { + ratio = ascent / (ascent + descent); + } else { + if (util_FeatureTest.platform.isFirefox) { + warn("Enable the `dom.textMetrics.fontBoundingBox.enabled` preference in `about:config` to improve TextLayer rendering."); + } + if (style.ascent) { + ratio = style.ascent; + } else if (style.descent) { + ratio = 1 + style.descent; + } + } + this.#ascentCache.set(fontFamily, ratio); + return ratio; + } + }; + RENDERING_CANCELLED_TIMEOUT = 100; + PDFDocumentLoadingTask = class _PDFDocumentLoadingTask { + static #docId = 0; + _capability = Promise.withResolvers(); + _transport = null; + _worker = null; + docId = `d${_PDFDocumentLoadingTask.#docId++}`; + destroyed = false; + onPassword = null; + onProgress = null; + get promise() { + return this._capability.promise; + } + async destroy() { + this.destroyed = true; + try { + if (this._worker?.port) { + this._worker._pendingDestroy = true; + } + await this._transport?.destroy(); + } catch (ex) { + if (this._worker?.port) { + delete this._worker._pendingDestroy; + } + throw ex; + } + this._transport = null; + this._worker?.destroy(); + this._worker = null; + } + async getData() { + return this._transport.getData(); + } + }; + PDFDataRangeTransport = class { + #capability = Promise.withResolvers(); + #progressiveDoneListeners = []; + #progressiveReadListeners = []; + #progressListeners = []; + #rangeListeners = []; + constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) { + this.length = length; + this.initialData = initialData; + this.progressiveDone = progressiveDone; + this.contentDispositionFilename = contentDispositionFilename; + } + addRangeListener(listener) { + this.#rangeListeners.push(listener); + } + addProgressListener(listener) { + this.#progressListeners.push(listener); + } + addProgressiveReadListener(listener) { + this.#progressiveReadListeners.push(listener); + } + addProgressiveDoneListener(listener) { + this.#progressiveDoneListeners.push(listener); + } + onDataRange(begin, chunk) { + for (const listener of this.#rangeListeners) { + listener(begin, chunk); + } + } + onDataProgress(loaded, total) { + this.#capability.promise.then(() => { + for (const listener of this.#progressListeners) { + listener(loaded, total); + } + }); + } + onDataProgressiveRead(chunk) { + this.#capability.promise.then(() => { + for (const listener of this.#progressiveReadListeners) { + listener(chunk); + } + }); + } + onDataProgressiveDone() { + this.#capability.promise.then(() => { + for (const listener of this.#progressiveDoneListeners) { + listener(); + } + }); + } + transportReady() { + this.#capability.resolve(); + } + requestDataRange(begin, end) { + unreachable("Abstract method PDFDataRangeTransport.requestDataRange"); + } + abort() { + } + }; + PDFDocumentProxy = class { + constructor(pdfInfo, transport) { + this._pdfInfo = pdfInfo; + this._transport = transport; + } + get annotationStorage() { + return this._transport.annotationStorage; + } + get canvasFactory() { + return this._transport.canvasFactory; + } + get filterFactory() { + return this._transport.filterFactory; + } + get numPages() { + return this._pdfInfo.numPages; + } + get fingerprints() { + return this._pdfInfo.fingerprints; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + get allXfaHtml() { + return this._transport._htmlForXfa; + } + getPage(pageNumber) { + return this._transport.getPage(pageNumber); + } + getPageIndex(ref) { + return this._transport.getPageIndex(ref); + } + getDestinations() { + return this._transport.getDestinations(); + } + getDestination(id) { + return this._transport.getDestination(id); + } + getPageLabels() { + return this._transport.getPageLabels(); + } + getPageLayout() { + return this._transport.getPageLayout(); + } + getPageMode() { + return this._transport.getPageMode(); + } + getViewerPreferences() { + return this._transport.getViewerPreferences(); + } + getOpenAction() { + return this._transport.getOpenAction(); + } + getAttachments() { + return this._transport.getAttachments(); + } + getAnnotationsByType(types2, pageIndexesToSkip) { + return this._transport.getAnnotationsByType(types2, pageIndexesToSkip); + } + getJSActions() { + return this._transport.getDocJSActions(); + } + getOutline() { + return this._transport.getOutline(); + } + getOptionalContentConfig({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getOptionalContentConfig(renderingIntent); + } + getPermissions() { + return this._transport.getPermissions(); + } + getMetadata() { + return this._transport.getMetadata(); + } + getMarkInfo() { + return this._transport.getMarkInfo(); + } + getData() { + return this._transport.getData(); + } + saveDocument() { + return this._transport.saveDocument(); + } + getDownloadInfo() { + return this._transport.downloadInfoCapability.promise; + } + cleanup(keepLoadedFonts = false) { + return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa); + } + destroy() { + return this.loadingTask.destroy(); + } + cachedPageNumber(ref) { + return this._transport.cachedPageNumber(ref); + } + get loadingParams() { + return this._transport.loadingParams; + } + get loadingTask() { + return this._transport.loadingTask; + } + getFieldObjects() { + return this._transport.getFieldObjects(); + } + hasJSActions() { + return this._transport.hasJSActions(); + } + getCalculationOrderIds() { + return this._transport.getCalculationOrderIds(); + } + }; + PDFPageProxy = class { + #pendingCleanup = false; + constructor(pageIndex, pageInfo, transport, pdfBug = false) { + this._pageIndex = pageIndex; + this._pageInfo = pageInfo; + this._transport = transport; + this._stats = pdfBug ? new StatTimer() : null; + this._pdfBug = pdfBug; + this.commonObjs = transport.commonObjs; + this.objs = new PDFObjects(); + this._intentStates = /* @__PURE__ */ new Map(); + this.destroyed = false; + this.recordedBBoxes = null; + } + get pageNumber() { + return this._pageIndex + 1; + } + get rotate() { + return this._pageInfo.rotate; + } + get ref() { + return this._pageInfo.ref; + } + get userUnit() { + return this._pageInfo.userUnit; + } + get view() { + return this._pageInfo.view; + } + getViewport({ + scale, + rotation = this.rotate, + offsetX = 0, + offsetY = 0, + dontFlip = false + } = {}) { + return new PageViewport({ + viewBox: this.view, + userUnit: this.userUnit, + scale, + rotation, + offsetX, + offsetY, + dontFlip + }); + } + getAnnotations({ + intent = "display" + } = {}) { + const { + renderingIntent + } = this._transport.getRenderingIntent(intent); + return this._transport.getAnnotations(this._pageIndex, renderingIntent); + } + getJSActions() { + return this._transport.getPageJSActions(this._pageIndex); + } + get filterFactory() { + return this._transport.filterFactory; + } + get isPureXfa() { + return shadow(this, "isPureXfa", !!this._transport._htmlForXfa); + } + async getXfa() { + return this._transport._htmlForXfa?.children[this._pageIndex] || null; + } + render({ + canvasContext, + canvas = canvasContext.canvas, + viewport, + intent = "display", + annotationMode = AnnotationMode.ENABLE, + transform = null, + background = null, + optionalContentConfigPromise = null, + annotationCanvasMap = null, + pageColors = null, + printAnnotationStorage = null, + isEditing = false, + recordOperations = false, + operationsFilter = null + }) { + this._stats?.time("Overall"); + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing); + const { + renderingIntent, + cacheKey + } = intentArgs; + this.#pendingCleanup = false; + optionalContentConfigPromise ||= this._transport.getOptionalContentConfig(renderingIntent); + let intentState = this._intentStates.get(cacheKey); + if (!intentState) { + intentState = /* @__PURE__ */ Object.create(null); + this._intentStates.set(cacheKey, intentState); + } + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + const intentPrint = !!(renderingIntent & RenderingIntentFlag.PRINT); + if (!intentState.displayReadyCapability) { + intentState.displayReadyCapability = Promise.withResolvers(); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + const recordForDebugger = Boolean(this._pdfBug && globalThis.StepperManager?.enabled); + const shouldRecordOperations = !this.recordedBBoxes && (recordOperations || recordForDebugger); + const complete2 = (error) => { + intentState.renderTasks.delete(internalRenderTask); + if (shouldRecordOperations) { + const recordedBBoxes = internalRenderTask.gfx?.dependencyTracker.take(); + if (recordedBBoxes) { + if (internalRenderTask.stepper) { + internalRenderTask.stepper.setOperatorBBoxes(recordedBBoxes, internalRenderTask.gfx.dependencyTracker.takeDebugMetadata()); + } + if (recordOperations) { + this.recordedBBoxes = recordedBBoxes; + } + } + } + if (intentPrint) { + this.#pendingCleanup = true; + } + this.#tryCleanup(); + if (error) { + internalRenderTask.capability.reject(error); + this._abortOperatorList({ + intentState, + reason: error instanceof Error ? error : new Error(error) + }); + } else { + internalRenderTask.capability.resolve(); + } + if (this._stats) { + this._stats.timeEnd("Rendering"); + this._stats.timeEnd("Overall"); + if (globalThis.Stats?.enabled) { + globalThis.Stats.add(this.pageNumber, this._stats); + } + } + }; + const internalRenderTask = new InternalRenderTask({ + callback: complete2, + params: { + canvas, + canvasContext, + dependencyTracker: shouldRecordOperations ? new CanvasDependencyTracker(canvas, intentState.operatorList.length, recordForDebugger) : null, + viewport, + transform, + background + }, + objs: this.objs, + commonObjs: this.commonObjs, + annotationCanvasMap, + operatorList: intentState.operatorList, + pageIndex: this._pageIndex, + canvasFactory: this._transport.canvasFactory, + filterFactory: this._transport.filterFactory, + useRequestAnimationFrame: !intentPrint, + pdfBug: this._pdfBug, + pageColors, + enableHWA: this._transport.enableHWA, + operationsFilter + }); + (intentState.renderTasks ||= /* @__PURE__ */ new Set()).add(internalRenderTask); + const renderTask = internalRenderTask.task; + Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => { + if (this.destroyed) { + complete2(); + return; + } + this._stats?.time("Rendering"); + if (!(optionalContentConfig.renderingIntent & renderingIntent)) { + throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods."); + } + internalRenderTask.initializeGraphics({ + transparency, + optionalContentConfig + }); + internalRenderTask.operatorListChanged(); + }).catch(complete2); + return renderTask; + } + getOperatorList({ + intent = "display", + annotationMode = AnnotationMode.ENABLE, + printAnnotationStorage = null, + isEditing = false + } = {}) { + function operatorListChanged() { + if (intentState.operatorList.lastChunk) { + intentState.opListReadCapability.resolve(intentState.operatorList); + intentState.renderTasks.delete(opListTask); + } + } + const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, printAnnotationStorage, isEditing, true); + let intentState = this._intentStates.get(intentArgs.cacheKey); + if (!intentState) { + intentState = /* @__PURE__ */ Object.create(null); + this._intentStates.set(intentArgs.cacheKey, intentState); + } + let opListTask; + if (!intentState.opListReadCapability) { + opListTask = /* @__PURE__ */ Object.create(null); + opListTask.operatorListChanged = operatorListChanged; + intentState.opListReadCapability = Promise.withResolvers(); + (intentState.renderTasks ||= /* @__PURE__ */ new Set()).add(opListTask); + intentState.operatorList = { + fnArray: [], + argsArray: [], + lastChunk: false, + separateAnnots: null + }; + this._stats?.time("Page Request"); + this._pumpOperatorList(intentArgs); + } + return intentState.opListReadCapability.promise; + } + streamTextContent({ + includeMarkedContent = false, + disableNormalization = false + } = {}) { + const TEXT_CONTENT_CHUNK_SIZE = 100; + return this._transport.messageHandler.sendWithStream("GetTextContent", { + pageIndex: this._pageIndex, + includeMarkedContent: includeMarkedContent === true, + disableNormalization: disableNormalization === true + }, { + highWaterMark: TEXT_CONTENT_CHUNK_SIZE, + size(textContent) { + return textContent.items.length; + } + }); + } + getTextContent(params = {}) { + if (this._transport._htmlForXfa) { + return this.getXfa().then((xfa) => XfaText.textContent(xfa)); + } + const readableStream = this.streamTextContent(params); + return new Promise(function(resolve2, reject) { + function pump() { + reader.read().then(function({ + value, + done + }) { + if (done) { + resolve2(textContent); + return; + } + textContent.lang ??= value.lang; + Object.assign(textContent.styles, value.styles); + textContent.items.push(...value.items); + pump(); + }, reject); + } + const reader = readableStream.getReader(); + const textContent = { + items: [], + styles: /* @__PURE__ */ Object.create(null), + lang: null + }; + pump(); + }); + } + getStructTree() { + return this._transport.getStructTree(this._pageIndex); + } + _destroy() { + this.destroyed = true; + const waitOn = []; + for (const intentState of this._intentStates.values()) { + this._abortOperatorList({ + intentState, + reason: new Error("Page was destroyed."), + force: true + }); + if (intentState.opListReadCapability) { + continue; + } + for (const internalRenderTask of intentState.renderTasks) { + waitOn.push(internalRenderTask.completed); + internalRenderTask.cancel(); + } + } + this.objs.clear(); + this.#pendingCleanup = false; + return Promise.all(waitOn); + } + cleanup(resetStats = false) { + this.#pendingCleanup = true; + const success = this.#tryCleanup(); + if (resetStats && success) { + this._stats &&= new StatTimer(); + } + return success; + } + #tryCleanup() { + if (!this.#pendingCleanup || this.destroyed) { + return false; + } + for (const { + renderTasks, + operatorList + } of this._intentStates.values()) { + if (renderTasks.size > 0 || !operatorList.lastChunk) { + return false; + } + } + this._intentStates.clear(); + this.objs.clear(); + this.#pendingCleanup = false; + return true; + } + _startRenderPage(transparency, cacheKey) { + const intentState = this._intentStates.get(cacheKey); + if (!intentState) { + return; + } + this._stats?.timeEnd("Page Request"); + intentState.displayReadyCapability?.resolve(transparency); + } + _renderPageChunk(operatorListChunk, intentState) { + for (let i7 = 0, ii = operatorListChunk.length; i7 < ii; i7++) { + intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i7]); + intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i7]); + } + intentState.operatorList.lastChunk = operatorListChunk.lastChunk; + intentState.operatorList.separateAnnots = operatorListChunk.separateAnnots; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + if (operatorListChunk.lastChunk) { + this.#tryCleanup(); + } + } + _pumpOperatorList({ + renderingIntent, + cacheKey, + annotationStorageSerializable, + modifiedIds + }) { + const { + map: map3, + transfer + } = annotationStorageSerializable; + const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", { + pageIndex: this._pageIndex, + intent: renderingIntent, + cacheKey, + annotationStorage: map3, + modifiedIds + }, transfer); + const reader = readableStream.getReader(); + const intentState = this._intentStates.get(cacheKey); + intentState.streamReader = reader; + const pump = () => { + reader.read().then(({ + value, + done + }) => { + if (done) { + intentState.streamReader = null; + return; + } + if (this._transport.destroyed) { + return; + } + this._renderPageChunk(value, intentState); + pump(); + }, (reason) => { + intentState.streamReader = null; + if (this._transport.destroyed) { + return; + } + if (intentState.operatorList) { + intentState.operatorList.lastChunk = true; + for (const internalRenderTask of intentState.renderTasks) { + internalRenderTask.operatorListChanged(); + } + this.#tryCleanup(); + } + if (intentState.displayReadyCapability) { + intentState.displayReadyCapability.reject(reason); + } else if (intentState.opListReadCapability) { + intentState.opListReadCapability.reject(reason); + } else { + throw reason; + } + }); + }; + pump(); + } + _abortOperatorList({ + intentState, + reason, + force = false + }) { + if (!intentState.streamReader) { + return; + } + if (intentState.streamReaderCancelTimeout) { + clearTimeout(intentState.streamReaderCancelTimeout); + intentState.streamReaderCancelTimeout = null; + } + if (!force) { + if (intentState.renderTasks.size > 0) { + return; + } + if (reason instanceof RenderingCancelledException) { + let delay = RENDERING_CANCELLED_TIMEOUT; + if (reason.extraDelay > 0 && reason.extraDelay < 1e3) { + delay += reason.extraDelay; + } + intentState.streamReaderCancelTimeout = setTimeout(() => { + intentState.streamReaderCancelTimeout = null; + this._abortOperatorList({ + intentState, + reason, + force: true + }); + }, delay); + return; + } + } + intentState.streamReader.cancel(new AbortException(reason.message)).catch(() => { + }); + intentState.streamReader = null; + if (this._transport.destroyed) { + return; + } + for (const [curCacheKey, curIntentState] of this._intentStates) { + if (curIntentState === intentState) { + this._intentStates.delete(curCacheKey); + break; + } + } + this.cleanup(); + } + get stats() { + return this._stats; + } + }; + PDFWorker = class _PDFWorker { + #capability = Promise.withResolvers(); + #messageHandler = null; + #port = null; + #webWorker = null; + static #fakeWorkerId = 0; + static #isWorkerDisabled = false; + static #workerPorts = /* @__PURE__ */ new WeakMap(); + static { + if (isNodeJS) { + this.#isWorkerDisabled = true; + GlobalWorkerOptions.workerSrc ||= "./pdf.worker.mjs"; + } + this._isSameOrigin = (baseUrl, otherUrl) => { + const base = URL.parse(baseUrl); + if (!base?.origin || base.origin === "null") { + return false; + } + const other = new URL(otherUrl, base); + return base.origin === other.origin; + }; + this._createCDNWrapper = (url) => { + const wrapper = `await import("${url}");`; + return URL.createObjectURL(new Blob([wrapper], { + type: "text/javascript" + })); + }; + this.fromPort = (params) => { + deprecated("`PDFWorker.fromPort` - please use `PDFWorker.create` instead."); + if (!params?.port) { + throw new Error("PDFWorker.fromPort - invalid method signature."); + } + return this.create(params); + }; + } + constructor({ + name = null, + port: port2 = null, + verbosity: verbosity2 = getVerbosityLevel() + } = {}) { + this.name = name; + this.destroyed = false; + this.verbosity = verbosity2; + if (port2) { + if (_PDFWorker.#workerPorts.has(port2)) { + throw new Error("Cannot use more than one PDFWorker per port."); + } + _PDFWorker.#workerPorts.set(port2, this); + this.#initializeFromPort(port2); + } else { + this.#initialize(); + } + } + get promise() { + return this.#capability.promise; + } + #resolve() { + this.#capability.resolve(); + this.#messageHandler.send("configure", { + verbosity: this.verbosity + }); + } + get port() { + return this.#port; + } + get messageHandler() { + return this.#messageHandler; + } + #initializeFromPort(port2) { + this.#port = port2; + this.#messageHandler = new MessageHandler("main", "worker", port2); + this.#messageHandler.on("ready", () => { + }); + this.#resolve(); + } + #initialize() { + if (_PDFWorker.#isWorkerDisabled || _PDFWorker.#mainThreadWorkerMessageHandler) { + this.#setupFakeWorker(); + return; + } + let { + workerSrc + } = _PDFWorker; + try { + if (!_PDFWorker._isSameOrigin(window.location, workerSrc)) { + workerSrc = _PDFWorker._createCDNWrapper(new URL(workerSrc, window.location).href); + } + const worker = new Worker(workerSrc, { + type: "module" + }); + const messageHandler = new MessageHandler("main", "worker", worker); + const terminateEarly = () => { + ac.abort(); + messageHandler.destroy(); + worker.terminate(); + if (this.destroyed) { + this.#capability.reject(new Error("Worker was destroyed")); + } else { + this.#setupFakeWorker(); + } + }; + const ac = new AbortController(); + worker.addEventListener("error", () => { + if (!this.#webWorker) { + terminateEarly(); + } + }, { + signal: ac.signal + }); + messageHandler.on("test", (data) => { + ac.abort(); + if (this.destroyed || !data) { + terminateEarly(); + return; + } + this.#messageHandler = messageHandler; + this.#port = worker; + this.#webWorker = worker; + this.#resolve(); + }); + messageHandler.on("ready", (data) => { + ac.abort(); + if (this.destroyed) { + terminateEarly(); + return; + } + try { + sendTest(); + } catch { + this.#setupFakeWorker(); + } + }); + const sendTest = () => { + const testObj = new Uint8Array(); + messageHandler.send("test", testObj, [testObj.buffer]); + }; + sendTest(); + return; + } catch { + info("The worker has been disabled."); + } + this.#setupFakeWorker(); + } + #setupFakeWorker() { + if (!_PDFWorker.#isWorkerDisabled) { + warn("Setting up fake worker."); + _PDFWorker.#isWorkerDisabled = true; + } + _PDFWorker._setupFakeWorkerGlobal.then((WorkerMessageHandler) => { + if (this.destroyed) { + this.#capability.reject(new Error("Worker was destroyed")); + return; + } + const port2 = new LoopbackPort(); + this.#port = port2; + const id = `fake${_PDFWorker.#fakeWorkerId++}`; + const workerHandler = new MessageHandler(id + "_worker", id, port2); + WorkerMessageHandler.setup(workerHandler, port2); + this.#messageHandler = new MessageHandler(id, id + "_worker", port2); + this.#resolve(); + }).catch((reason) => { + this.#capability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`)); + }); + } + destroy() { + this.destroyed = true; + this.#webWorker?.terminate(); + this.#webWorker = null; + _PDFWorker.#workerPorts.delete(this.#port); + this.#port = null; + this.#messageHandler?.destroy(); + this.#messageHandler = null; + } + static create(params) { + const cachedPort = this.#workerPorts.get(params?.port); + if (cachedPort) { + if (cachedPort._pendingDestroy) { + throw new Error("PDFWorker.create - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls."); + } + return cachedPort; + } + return new _PDFWorker(params); + } + static get workerSrc() { + if (GlobalWorkerOptions.workerSrc) { + return GlobalWorkerOptions.workerSrc; + } + throw new Error('No "GlobalWorkerOptions.workerSrc" specified.'); + } + static get #mainThreadWorkerMessageHandler() { + try { + return globalThis.pdfjsWorker?.WorkerMessageHandler || null; + } catch { + return null; + } + } + static get _setupFakeWorkerGlobal() { + const loader = async () => { + if (this.#mainThreadWorkerMessageHandler) { + return this.#mainThreadWorkerMessageHandler; + } + const worker = await import( + /*webpackIgnore: true*/ + /*@vite-ignore*/ + this.workerSrc + ); + return worker.WorkerMessageHandler; + }; + return shadow(this, "_setupFakeWorkerGlobal", loader()); + } + }; + WorkerTransport = class { + #methodPromises = /* @__PURE__ */ new Map(); + #pageCache = /* @__PURE__ */ new Map(); + #pagePromises = /* @__PURE__ */ new Map(); + #pageRefCache = /* @__PURE__ */ new Map(); + #passwordCapability = null; + constructor(messageHandler, loadingTask, networkStream, params, factory, enableHWA) { + this.messageHandler = messageHandler; + this.loadingTask = loadingTask; + this.commonObjs = new PDFObjects(); + this.fontLoader = new FontLoader({ + ownerDocument: params.ownerDocument, + styleElement: params.styleElement + }); + this.loadingParams = params.loadingParams; + this._params = params; + this.canvasFactory = factory.canvasFactory; + this.filterFactory = factory.filterFactory; + this.cMapReaderFactory = factory.cMapReaderFactory; + this.standardFontDataFactory = factory.standardFontDataFactory; + this.wasmFactory = factory.wasmFactory; + this.destroyed = false; + this.destroyCapability = null; + this._networkStream = networkStream; + this._fullReader = null; + this._lastProgress = null; + this.downloadInfoCapability = Promise.withResolvers(); + this.enableHWA = enableHWA; + this.setupMessageHandler(); + } + #cacheSimpleMethod(name, data = null) { + const cachedPromise = this.#methodPromises.get(name); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise(name, data); + this.#methodPromises.set(name, promise); + return promise; + } + get annotationStorage() { + return shadow(this, "annotationStorage", new AnnotationStorage()); + } + getRenderingIntent(intent, annotationMode = AnnotationMode.ENABLE, printAnnotationStorage = null, isEditing = false, isOpList = false) { + let renderingIntent = RenderingIntentFlag.DISPLAY; + let annotationStorageSerializable = SerializableEmpty; + switch (intent) { + case "any": + renderingIntent = RenderingIntentFlag.ANY; + break; + case "display": + break; + case "print": + renderingIntent = RenderingIntentFlag.PRINT; + break; + default: + warn(`getRenderingIntent - invalid intent: ${intent}`); + } + const annotationStorage = renderingIntent & RenderingIntentFlag.PRINT && printAnnotationStorage instanceof PrintAnnotationStorage ? printAnnotationStorage : this.annotationStorage; + switch (annotationMode) { + case AnnotationMode.DISABLE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_DISABLE; + break; + case AnnotationMode.ENABLE: + break; + case AnnotationMode.ENABLE_FORMS: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_FORMS; + break; + case AnnotationMode.ENABLE_STORAGE: + renderingIntent += RenderingIntentFlag.ANNOTATIONS_STORAGE; + annotationStorageSerializable = annotationStorage.serializable; + break; + default: + warn(`getRenderingIntent - invalid annotationMode: ${annotationMode}`); + } + if (isEditing) { + renderingIntent += RenderingIntentFlag.IS_EDITING; + } + if (isOpList) { + renderingIntent += RenderingIntentFlag.OPLIST; + } + const { + ids: modifiedIds, + hash: modifiedIdsHash + } = annotationStorage.modifiedIds; + const cacheKeyBuf = [renderingIntent, annotationStorageSerializable.hash, modifiedIdsHash]; + return { + renderingIntent, + cacheKey: cacheKeyBuf.join("_"), + annotationStorageSerializable, + modifiedIds + }; + } + destroy() { + if (this.destroyCapability) { + return this.destroyCapability.promise; + } + this.destroyed = true; + this.destroyCapability = Promise.withResolvers(); + this.#passwordCapability?.reject(new Error("Worker was destroyed during onPassword callback")); + const waitOn = []; + for (const page of this.#pageCache.values()) { + waitOn.push(page._destroy()); + } + this.#pageCache.clear(); + this.#pagePromises.clear(); + this.#pageRefCache.clear(); + if (this.hasOwnProperty("annotationStorage")) { + this.annotationStorage.resetModified(); + } + const terminated = this.messageHandler.sendWithPromise("Terminate", null); + waitOn.push(terminated); + Promise.all(waitOn).then(() => { + this.commonObjs.clear(); + this.fontLoader.clear(); + this.#methodPromises.clear(); + this.filterFactory.destroy(); + TextLayer.cleanup(); + this._networkStream?.cancelAllRequests(new AbortException("Worker was terminated.")); + this.messageHandler?.destroy(); + this.messageHandler = null; + this.destroyCapability.resolve(); + }, this.destroyCapability.reject); + return this.destroyCapability.promise; + } + setupMessageHandler() { + const { + messageHandler, + loadingTask + } = this; + messageHandler.on("GetReader", (data, sink) => { + assert(this._networkStream, "GetReader - no `IPDFStream` instance available."); + this._fullReader = this._networkStream.getFullReader(); + this._fullReader.onProgress = (evt) => { + this._lastProgress = { + loaded: evt.loaded, + total: evt.total + }; + }; + sink.onPull = () => { + this._fullReader.read().then(function({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch((reason) => { + sink.error(reason); + }); + }; + sink.onCancel = (reason) => { + this._fullReader.cancel(reason); + sink.ready.catch((readyReason) => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("ReaderHeadersReady", async (data) => { + await this._fullReader.headersReady; + const { + isStreamingSupported, + isRangeSupported, + contentLength + } = this._fullReader; + if (!isStreamingSupported || !isRangeSupported) { + if (this._lastProgress) { + loadingTask.onProgress?.(this._lastProgress); + } + this._fullReader.onProgress = (evt) => { + loadingTask.onProgress?.({ + loaded: evt.loaded, + total: evt.total + }); + }; + } + return { + isStreamingSupported, + isRangeSupported, + contentLength + }; + }); + messageHandler.on("GetRangeReader", (data, sink) => { + assert(this._networkStream, "GetRangeReader - no `IPDFStream` instance available."); + const rangeReader = this._networkStream.getRangeReader(data.begin, data.end); + if (!rangeReader) { + sink.close(); + return; + } + sink.onPull = () => { + rangeReader.read().then(function({ + value, + done + }) { + if (done) { + sink.close(); + return; + } + assert(value instanceof ArrayBuffer, "GetRangeReader - expected an ArrayBuffer."); + sink.enqueue(new Uint8Array(value), 1, [value]); + }).catch((reason) => { + sink.error(reason); + }); + }; + sink.onCancel = (reason) => { + rangeReader.cancel(reason); + sink.ready.catch((readyReason) => { + if (this.destroyed) { + return; + } + throw readyReason; + }); + }; + }); + messageHandler.on("GetDoc", ({ + pdfInfo + }) => { + this._numPages = pdfInfo.numPages; + this._htmlForXfa = pdfInfo.htmlForXfa; + delete pdfInfo.htmlForXfa; + loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this)); + }); + messageHandler.on("DocException", (ex) => { + loadingTask._capability.reject(wrapReason(ex)); + }); + messageHandler.on("PasswordRequest", (ex) => { + this.#passwordCapability = Promise.withResolvers(); + try { + if (!loadingTask.onPassword) { + throw wrapReason(ex); + } + const updatePassword = (password) => { + if (password instanceof Error) { + this.#passwordCapability.reject(password); + } else { + this.#passwordCapability.resolve({ + password + }); + } + }; + loadingTask.onPassword(updatePassword, ex.code); + } catch (err) { + this.#passwordCapability.reject(err); + } + return this.#passwordCapability.promise; + }); + messageHandler.on("DataLoaded", (data) => { + loadingTask.onProgress?.({ + loaded: data.length, + total: data.length + }); + this.downloadInfoCapability.resolve(data); + }); + messageHandler.on("StartRenderPage", (data) => { + if (this.destroyed) { + return; + } + const page = this.#pageCache.get(data.pageIndex); + page._startRenderPage(data.transparency, data.cacheKey); + }); + messageHandler.on("commonobj", ([id, type, exportedData]) => { + if (this.destroyed) { + return null; + } + if (this.commonObjs.has(id)) { + return null; + } + switch (type) { + case "Font": + if ("error" in exportedData) { + const exportedError = exportedData.error; + warn(`Error during font loading: ${exportedError}`); + this.commonObjs.resolve(id, exportedError); + break; + } + const fontData = new FontInfo(exportedData); + const inspectFont = this._params.pdfBug && globalThis.FontInspector?.enabled ? (font2, url) => globalThis.FontInspector.fontAdded(font2, url) : null; + const font = new FontFaceObject(fontData, inspectFont, exportedData.extra, exportedData.charProcOperatorList); + this.fontLoader.bind(font).catch(() => messageHandler.sendWithPromise("FontFallback", { + id + })).finally(() => { + if (!font.fontExtraProperties && font.data) { + font.clearData(); + } + this.commonObjs.resolve(id, font); + }); + break; + case "CopyLocalImage": + const { + imageRef + } = exportedData; + assert(imageRef, "The imageRef must be defined."); + for (const pageProxy of this.#pageCache.values()) { + for (const [, data] of pageProxy.objs) { + if (data?.ref !== imageRef) { + continue; + } + if (!data.dataLen) { + return null; + } + this.commonObjs.resolve(id, structuredClone(data)); + return data.dataLen; + } + } + break; + case "FontPath": + case "Image": + this.commonObjs.resolve(id, exportedData); + break; + case "Pattern": + const pattern = new PatternInfo(exportedData); + this.commonObjs.resolve(id, pattern.getIR()); + break; + default: + throw new Error(`Got unknown common object type ${type}`); + } + return null; + }); + messageHandler.on("obj", ([id, pageIndex, type, imageData]) => { + if (this.destroyed) { + return; + } + const pageProxy = this.#pageCache.get(pageIndex); + if (pageProxy.objs.has(id)) { + return; + } + if (pageProxy._intentStates.size === 0) { + imageData?.bitmap?.close(); + return; + } + switch (type) { + case "Image": + case "Pattern": + pageProxy.objs.resolve(id, imageData); + break; + default: + throw new Error(`Got unknown object type ${type}`); + } + }); + messageHandler.on("DocProgress", (data) => { + if (this.destroyed) { + return; + } + loadingTask.onProgress?.({ + loaded: data.loaded, + total: data.total + }); + }); + messageHandler.on("FetchBinaryData", async (data) => { + if (this.destroyed) { + throw new Error("Worker was destroyed."); + } + const factory = this[data.type]; + if (!factory) { + throw new Error(`${data.type} not initialized, see the \`useWorkerFetch\` parameter.`); + } + return factory.fetch(data); + }); + } + getData() { + return this.messageHandler.sendWithPromise("GetData", null); + } + saveDocument() { + if (this.annotationStorage.size <= 0) { + warn("saveDocument called while `annotationStorage` is empty, please use the getData-method instead."); + } + const { + map: map3, + transfer + } = this.annotationStorage.serializable; + return this.messageHandler.sendWithPromise("SaveDocument", { + isPureXfa: !!this._htmlForXfa, + numPages: this._numPages, + annotationStorage: map3, + filename: this._fullReader?.filename ?? null + }, transfer).finally(() => { + this.annotationStorage.resetModified(); + }); + } + getPage(pageNumber) { + if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) { + return Promise.reject(new Error("Invalid page request.")); + } + const pageIndex = pageNumber - 1, cachedPromise = this.#pagePromises.get(pageIndex); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise("GetPage", { + pageIndex + }).then((pageInfo) => { + if (this.destroyed) { + throw new Error("Transport destroyed"); + } + if (pageInfo.refStr) { + this.#pageRefCache.set(pageInfo.refStr, pageNumber); + } + const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.pdfBug); + this.#pageCache.set(pageIndex, page); + return page; + }); + this.#pagePromises.set(pageIndex, promise); + return promise; + } + getPageIndex(ref) { + if (!isRefProxy(ref)) { + return Promise.reject(new Error("Invalid pageIndex request.")); + } + return this.messageHandler.sendWithPromise("GetPageIndex", { + num: ref.num, + gen: ref.gen + }); + } + getAnnotations(pageIndex, intent) { + return this.messageHandler.sendWithPromise("GetAnnotations", { + pageIndex, + intent + }); + } + getFieldObjects() { + return this.#cacheSimpleMethod("GetFieldObjects"); + } + hasJSActions() { + return this.#cacheSimpleMethod("HasJSActions"); + } + getCalculationOrderIds() { + return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null); + } + getDestinations() { + return this.messageHandler.sendWithPromise("GetDestinations", null); + } + getDestination(id) { + if (typeof id !== "string") { + return Promise.reject(new Error("Invalid destination request.")); + } + return this.messageHandler.sendWithPromise("GetDestination", { + id + }); + } + getPageLabels() { + return this.messageHandler.sendWithPromise("GetPageLabels", null); + } + getPageLayout() { + return this.messageHandler.sendWithPromise("GetPageLayout", null); + } + getPageMode() { + return this.messageHandler.sendWithPromise("GetPageMode", null); + } + getViewerPreferences() { + return this.messageHandler.sendWithPromise("GetViewerPreferences", null); + } + getOpenAction() { + return this.messageHandler.sendWithPromise("GetOpenAction", null); + } + getAttachments() { + return this.messageHandler.sendWithPromise("GetAttachments", null); + } + getAnnotationsByType(types2, pageIndexesToSkip) { + return this.messageHandler.sendWithPromise("GetAnnotationsByType", { + types: types2, + pageIndexesToSkip + }); + } + getDocJSActions() { + return this.#cacheSimpleMethod("GetDocJSActions"); + } + getPageJSActions(pageIndex) { + return this.messageHandler.sendWithPromise("GetPageJSActions", { + pageIndex + }); + } + getStructTree(pageIndex) { + return this.messageHandler.sendWithPromise("GetStructTree", { + pageIndex + }); + } + getOutline() { + return this.messageHandler.sendWithPromise("GetOutline", null); + } + getOptionalContentConfig(renderingIntent) { + return this.#cacheSimpleMethod("GetOptionalContentConfig").then((data) => new OptionalContentConfig(data, renderingIntent)); + } + getPermissions() { + return this.messageHandler.sendWithPromise("GetPermissions", null); + } + getMetadata() { + const name = "GetMetadata", cachedPromise = this.#methodPromises.get(name); + if (cachedPromise) { + return cachedPromise; + } + const promise = this.messageHandler.sendWithPromise(name, null).then((results) => ({ + info: results[0], + metadata: results[1] ? new Metadata(results[1]) : null, + contentDispositionFilename: this._fullReader?.filename ?? null, + contentLength: this._fullReader?.contentLength ?? null + })); + this.#methodPromises.set(name, promise); + return promise; + } + getMarkInfo() { + return this.messageHandler.sendWithPromise("GetMarkInfo", null); + } + async startCleanup(keepLoadedFonts = false) { + if (this.destroyed) { + return; + } + await this.messageHandler.sendWithPromise("Cleanup", null); + for (const page of this.#pageCache.values()) { + const cleanupSuccessful = page.cleanup(); + if (!cleanupSuccessful) { + throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`); + } + } + this.commonObjs.clear(); + if (!keepLoadedFonts) { + this.fontLoader.clear(); + } + this.#methodPromises.clear(); + this.filterFactory.destroy(true); + TextLayer.cleanup(); + } + cachedPageNumber(ref) { + if (!isRefProxy(ref)) { + return null; + } + const refStr = ref.gen === 0 ? `${ref.num}R` : `${ref.num}R${ref.gen}`; + return this.#pageRefCache.get(refStr) ?? null; + } + }; + RenderTask = class { + #internalRenderTask = null; + onContinue = null; + onError = null; + constructor(internalRenderTask) { + this.#internalRenderTask = internalRenderTask; + } + get promise() { + return this.#internalRenderTask.capability.promise; + } + cancel(extraDelay = 0) { + this.#internalRenderTask.cancel(null, extraDelay); + } + get separateAnnots() { + const { + separateAnnots + } = this.#internalRenderTask.operatorList; + if (!separateAnnots) { + return false; + } + const { + annotationCanvasMap + } = this.#internalRenderTask; + return separateAnnots.form || separateAnnots.canvas && annotationCanvasMap?.size > 0; + } + }; + InternalRenderTask = class _InternalRenderTask { + #rAF = null; + static #canvasInUse = /* @__PURE__ */ new WeakSet(); + constructor({ + callback: callback2, + params, + objs, + commonObjs, + annotationCanvasMap, + operatorList, + pageIndex, + canvasFactory, + filterFactory, + useRequestAnimationFrame = false, + pdfBug = false, + pageColors = null, + enableHWA = false, + operationsFilter = null + }) { + this.callback = callback2; + this.params = params; + this.objs = objs; + this.commonObjs = commonObjs; + this.annotationCanvasMap = annotationCanvasMap; + this.operatorListIdx = null; + this.operatorList = operatorList; + this._pageIndex = pageIndex; + this.canvasFactory = canvasFactory; + this.filterFactory = filterFactory; + this._pdfBug = pdfBug; + this.pageColors = pageColors; + this.running = false; + this.graphicsReadyCallback = null; + this.graphicsReady = false; + this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined"; + this.cancelled = false; + this.capability = Promise.withResolvers(); + this.task = new RenderTask(this); + this._cancelBound = this.cancel.bind(this); + this._continueBound = this._continue.bind(this); + this._scheduleNextBound = this._scheduleNext.bind(this); + this._nextBound = this._next.bind(this); + this._canvas = params.canvas; + this._canvasContext = params.canvas ? null : params.canvasContext; + this._enableHWA = enableHWA; + this._dependencyTracker = params.dependencyTracker; + this._operationsFilter = operationsFilter; + } + get completed() { + return this.capability.promise.catch(function() { + }); + } + initializeGraphics({ + transparency = false, + optionalContentConfig + }) { + if (this.cancelled) { + return; + } + if (this._canvas) { + if (_InternalRenderTask.#canvasInUse.has(this._canvas)) { + throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed."); + } + _InternalRenderTask.#canvasInUse.add(this._canvas); + } + if (this._pdfBug && globalThis.StepperManager?.enabled) { + this.stepper = globalThis.StepperManager.create(this._pageIndex); + this.stepper.init(this.operatorList); + this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); + } + const { + viewport, + transform, + background, + dependencyTracker + } = this.params; + const canvasContext = this._canvasContext || this._canvas.getContext("2d", { + alpha: false, + willReadFrequently: !this._enableHWA + }); + this.gfx = new CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, this.filterFactory, { + optionalContentConfig + }, this.annotationCanvasMap, this.pageColors, dependencyTracker); + this.gfx.beginDrawing({ + transform, + viewport, + transparency, + background + }); + this.operatorListIdx = 0; + this.graphicsReady = true; + this.graphicsReadyCallback?.(); + } + cancel(error = null, extraDelay = 0) { + this.running = false; + this.cancelled = true; + this.gfx?.endDrawing(); + if (this.#rAF) { + window.cancelAnimationFrame(this.#rAF); + this.#rAF = null; + } + _InternalRenderTask.#canvasInUse.delete(this._canvas); + error ||= new RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, extraDelay); + this.callback(error); + this.task.onError?.(error); + } + operatorListChanged() { + if (!this.graphicsReady) { + this.graphicsReadyCallback ||= this._continueBound; + return; + } + this.gfx.dependencyTracker?.growOperationsCount(this.operatorList.fnArray.length); + this.stepper?.updateOperatorList(this.operatorList); + if (this.running) { + return; + } + this._continue(); + } + _continue() { + this.running = true; + if (this.cancelled) { + return; + } + if (this.task.onContinue) { + this.task.onContinue(this._scheduleNextBound); + } else { + this._scheduleNext(); + } + } + _scheduleNext() { + if (this._useRequestAnimationFrame) { + this.#rAF = window.requestAnimationFrame(() => { + this.#rAF = null; + this._nextBound().catch(this._cancelBound); + }); + } else { + Promise.resolve().then(this._nextBound).catch(this._cancelBound); + } + } + async _next() { + if (this.cancelled) { + return; + } + this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper, this._operationsFilter); + if (this.operatorListIdx === this.operatorList.argsArray.length) { + this.running = false; + if (this.operatorList.lastChunk) { + this.gfx.endDrawing(); + _InternalRenderTask.#canvasInUse.delete(this._canvas); + this.callback(); + } + } + } + }; + version2 = "5.4.394"; + build = "2cc809ade"; + ColorPicker = class _ColorPicker { + #button = null; + #buttonSwatch = null; + #defaultColor; + #dropdown = null; + #dropdownWasFromKeyboard = false; + #isMainColorPicker = false; + #editor = null; + #eventBus; + #openDropdownAC = null; + #uiManager = null; + static #l10nColor = null; + static get _keyboardManager() { + return shadow(this, "_keyboardManager", new KeyboardManager([[["Escape", "mac+Escape"], _ColorPicker.prototype._hideDropdownFromKeyboard], [[" ", "mac+ "], _ColorPicker.prototype._colorSelectFromKeyboard], [["ArrowDown", "ArrowRight", "mac+ArrowDown", "mac+ArrowRight"], _ColorPicker.prototype._moveToNext], [["ArrowUp", "ArrowLeft", "mac+ArrowUp", "mac+ArrowLeft"], _ColorPicker.prototype._moveToPrevious], [["Home", "mac+Home"], _ColorPicker.prototype._moveToBeginning], [["End", "mac+End"], _ColorPicker.prototype._moveToEnd]])); + } + constructor({ + editor = null, + uiManager = null + }) { + if (editor) { + this.#isMainColorPicker = false; + this.#editor = editor; + } else { + this.#isMainColorPicker = true; + } + this.#uiManager = editor?._uiManager || uiManager; + this.#eventBus = this.#uiManager._eventBus; + this.#defaultColor = editor?.color?.toUpperCase() || this.#uiManager?.highlightColors.values().next().value || "#FFFF98"; + _ColorPicker.#l10nColor ||= Object.freeze({ + blue: "pdfjs-editor-colorpicker-blue", + green: "pdfjs-editor-colorpicker-green", + pink: "pdfjs-editor-colorpicker-pink", + red: "pdfjs-editor-colorpicker-red", + yellow: "pdfjs-editor-colorpicker-yellow" + }); + } + renderButton() { + const button = this.#button = document.createElement("button"); + button.className = "colorPicker"; + button.tabIndex = "0"; + button.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-button"); + button.ariaHasPopup = "true"; + if (this.#editor) { + button.ariaControls = `${this.#editor.id}_colorpicker_dropdown`; + } + const signal = this.#uiManager._signal; + button.addEventListener("click", this.#openDropdown.bind(this), { + signal + }); + button.addEventListener("keydown", this.#keyDown.bind(this), { + signal + }); + const swatch = this.#buttonSwatch = document.createElement("span"); + swatch.className = "swatch"; + swatch.ariaHidden = "true"; + swatch.style.backgroundColor = this.#defaultColor; + button.append(swatch); + return button; + } + renderMainDropdown() { + const dropdown = this.#dropdown = this.#getDropdownRoot(); + dropdown.ariaOrientation = "horizontal"; + dropdown.ariaLabelledBy = "highlightColorPickerLabel"; + return dropdown; + } + #getDropdownRoot() { + const div = document.createElement("div"); + const signal = this.#uiManager._signal; + div.addEventListener("contextmenu", noContextMenu, { + signal + }); + div.className = "dropdown"; + div.role = "listbox"; + div.ariaMultiSelectable = "false"; + div.ariaOrientation = "vertical"; + div.setAttribute("data-l10n-id", "pdfjs-editor-colorpicker-dropdown"); + if (this.#editor) { + div.id = `${this.#editor.id}_colorpicker_dropdown`; + } + for (const [name, color2] of this.#uiManager.highlightColors) { + const button = document.createElement("button"); + button.tabIndex = "0"; + button.role = "option"; + button.setAttribute("data-color", color2); + button.title = name; + button.setAttribute("data-l10n-id", _ColorPicker.#l10nColor[name]); + const swatch = document.createElement("span"); + button.append(swatch); + swatch.className = "swatch"; + swatch.style.backgroundColor = color2; + button.ariaSelected = color2 === this.#defaultColor; + button.addEventListener("click", this.#colorSelect.bind(this, color2), { + signal + }); + div.append(button); + } + div.addEventListener("keydown", this.#keyDown.bind(this), { + signal + }); + return div; + } + #colorSelect(color2, event) { + event.stopPropagation(); + this.#eventBus.dispatch("switchannotationeditorparams", { + source: this, + type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, + value: color2 + }); + this.updateColor(color2); + } + _colorSelectFromKeyboard(event) { + if (event.target === this.#button) { + this.#openDropdown(event); + return; + } + const color2 = event.target.getAttribute("data-color"); + if (!color2) { + return; + } + this.#colorSelect(color2, event); + } + _moveToNext(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + if (event.target === this.#button) { + this.#dropdown.firstChild?.focus(); + return; + } + event.target.nextSibling?.focus(); + } + _moveToPrevious(event) { + if (event.target === this.#dropdown?.firstChild || event.target === this.#button) { + if (this.#isDropdownVisible) { + this._hideDropdownFromKeyboard(); + } + return; + } + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + } + event.target.previousSibling?.focus(); + } + _moveToBeginning(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.firstChild?.focus(); + } + _moveToEnd(event) { + if (!this.#isDropdownVisible) { + this.#openDropdown(event); + return; + } + this.#dropdown.lastChild?.focus(); + } + #keyDown(event) { + _ColorPicker._keyboardManager.exec(this, event); + } + #openDropdown(event) { + if (this.#isDropdownVisible) { + this.hideDropdown(); + return; + } + this.#dropdownWasFromKeyboard = event.detail === 0; + if (!this.#openDropdownAC) { + this.#openDropdownAC = new AbortController(); + window.addEventListener("pointerdown", this.#pointerDown.bind(this), { + signal: this.#uiManager.combinedSignal(this.#openDropdownAC) + }); + } + this.#button.ariaExpanded = "true"; + if (this.#dropdown) { + this.#dropdown.classList.remove("hidden"); + return; + } + const root = this.#dropdown = this.#getDropdownRoot(); + this.#button.append(root); + } + #pointerDown(event) { + if (this.#dropdown?.contains(event.target)) { + return; + } + this.hideDropdown(); + } + hideDropdown() { + this.#dropdown?.classList.add("hidden"); + this.#button.ariaExpanded = "false"; + this.#openDropdownAC?.abort(); + this.#openDropdownAC = null; + } + get #isDropdownVisible() { + return this.#dropdown && !this.#dropdown.classList.contains("hidden"); + } + _hideDropdownFromKeyboard() { + if (this.#isMainColorPicker) { + return; + } + if (!this.#isDropdownVisible) { + this.#editor?.unselect(); + return; + } + this.hideDropdown(); + this.#button.focus({ + preventScroll: true, + focusVisible: this.#dropdownWasFromKeyboard + }); + } + updateColor(color2) { + if (this.#buttonSwatch) { + this.#buttonSwatch.style.backgroundColor = color2; + } + if (!this.#dropdown) { + return; + } + const i7 = this.#uiManager.highlightColors.values(); + for (const child of this.#dropdown.children) { + child.ariaSelected = i7.next().value === color2.toUpperCase(); + } + } + destroy() { + this.#button?.remove(); + this.#button = null; + this.#buttonSwatch = null; + this.#dropdown?.remove(); + this.#dropdown = null; + } + }; + BasicColorPicker = class _BasicColorPicker { + #input = null; + #editor = null; + #uiManager = null; + static #l10nColor = null; + constructor(editor) { + this.#editor = editor; + this.#uiManager = editor._uiManager; + _BasicColorPicker.#l10nColor ||= Object.freeze({ + freetext: "pdfjs-editor-color-picker-free-text-input", + ink: "pdfjs-editor-color-picker-ink-input" + }); + } + renderButton() { + if (this.#input) { + return this.#input; + } + const { + editorType, + colorType, + color: color2 + } = this.#editor; + const input = this.#input = document.createElement("input"); + input.type = "color"; + input.value = color2 || "#000000"; + input.className = "basicColorPicker"; + input.tabIndex = 0; + input.setAttribute("data-l10n-id", _BasicColorPicker.#l10nColor[editorType]); + input.addEventListener("input", () => { + this.#uiManager.updateParams(colorType, input.value); + }, { + signal: this.#uiManager._signal + }); + return input; + } + update(value) { + if (!this.#input) { + return; + } + this.#input.value = value; + } + destroy() { + this.#input?.remove(); + this.#input = null; + } + hideDropdown() { + } + }; + ColorConverters = class { + static CMYK_G([c6, y4, m4, k2]) { + return ["G", 1 - Math.min(1, 0.3 * c6 + 0.59 * m4 + 0.11 * y4 + k2)]; + } + static G_CMYK([g3]) { + return ["CMYK", 0, 0, 0, 1 - g3]; + } + static G_RGB([g3]) { + return ["RGB", g3, g3, g3]; + } + static G_rgb([g3]) { + g3 = scaleAndClamp(g3); + return [g3, g3, g3]; + } + static G_HTML([g3]) { + const G2 = makeColorComp(g3); + return `#${G2}${G2}${G2}`; + } + static RGB_G([r8, g3, b4]) { + return ["G", 0.3 * r8 + 0.59 * g3 + 0.11 * b4]; + } + static RGB_rgb(color2) { + return color2.map(scaleAndClamp); + } + static RGB_HTML(color2) { + return `#${color2.map(makeColorComp).join("")}`; + } + static T_HTML() { + return "#00000000"; + } + static T_rgb() { + return [null]; + } + static CMYK_RGB([c6, y4, m4, k2]) { + return ["RGB", 1 - Math.min(1, c6 + k2), 1 - Math.min(1, m4 + k2), 1 - Math.min(1, y4 + k2)]; + } + static CMYK_rgb([c6, y4, m4, k2]) { + return [scaleAndClamp(1 - Math.min(1, c6 + k2)), scaleAndClamp(1 - Math.min(1, m4 + k2)), scaleAndClamp(1 - Math.min(1, y4 + k2))]; + } + static CMYK_HTML(components) { + const rgb = this.CMYK_RGB(components).slice(1); + return this.RGB_HTML(rgb); + } + static RGB_CMYK([r8, g3, b4]) { + const c6 = 1 - r8; + const m4 = 1 - g3; + const y4 = 1 - b4; + const k2 = Math.min(c6, m4, y4); + return ["CMYK", c6, m4, y4, k2]; + } + }; + BaseSVGFactory = class { + create(width, height, skipDimensions = false) { + if (width <= 0 || height <= 0) { + throw new Error("Invalid SVG dimensions"); + } + const svg = this._createSVG("svg:svg"); + svg.setAttribute("version", "1.1"); + if (!skipDimensions) { + svg.setAttribute("width", `${width}px`); + svg.setAttribute("height", `${height}px`); + } + svg.setAttribute("preserveAspectRatio", "none"); + svg.setAttribute("viewBox", `0 0 ${width} ${height}`); + return svg; + } + createElement(type) { + if (typeof type !== "string") { + throw new Error("Invalid SVG element type"); + } + return this._createSVG(type); + } + _createSVG(type) { + unreachable("Abstract method `_createSVG` called."); + } + }; + DOMSVGFactory = class extends BaseSVGFactory { + _createSVG(type) { + return document.createElementNS(SVG_NS, type); + } + }; + annotation_layer_DEFAULT_FONT_SIZE = 9; + GetElementsByNameSet = /* @__PURE__ */ new WeakSet(); + TIMEZONE_OFFSET = (/* @__PURE__ */ new Date()).getTimezoneOffset() * 60 * 1e3; + AnnotationElementFactory = class { + static create(parameters) { + const subtype = parameters.data.annotationType; + switch (subtype) { + case AnnotationType.LINK: + return new LinkAnnotationElement(parameters); + case AnnotationType.TEXT: + return new TextAnnotationElement(parameters); + case AnnotationType.WIDGET: + const fieldType = parameters.data.fieldType; + switch (fieldType) { + case "Tx": + return new TextWidgetAnnotationElement(parameters); + case "Btn": + if (parameters.data.radioButton) { + return new RadioButtonWidgetAnnotationElement(parameters); + } else if (parameters.data.checkBox) { + return new CheckboxWidgetAnnotationElement(parameters); + } + return new PushButtonWidgetAnnotationElement(parameters); + case "Ch": + return new ChoiceWidgetAnnotationElement(parameters); + case "Sig": + return new SignatureWidgetAnnotationElement(parameters); + } + return new WidgetAnnotationElement(parameters); + case AnnotationType.POPUP: + return new PopupAnnotationElement(parameters); + case AnnotationType.FREETEXT: + return new FreeTextAnnotationElement(parameters); + case AnnotationType.LINE: + return new LineAnnotationElement(parameters); + case AnnotationType.SQUARE: + return new SquareAnnotationElement(parameters); + case AnnotationType.CIRCLE: + return new CircleAnnotationElement(parameters); + case AnnotationType.POLYLINE: + return new PolylineAnnotationElement(parameters); + case AnnotationType.CARET: + return new CaretAnnotationElement(parameters); + case AnnotationType.INK: + return new InkAnnotationElement(parameters); + case AnnotationType.POLYGON: + return new PolygonAnnotationElement(parameters); + case AnnotationType.HIGHLIGHT: + return new HighlightAnnotationElement(parameters); + case AnnotationType.UNDERLINE: + return new UnderlineAnnotationElement(parameters); + case AnnotationType.SQUIGGLY: + return new SquigglyAnnotationElement(parameters); + case AnnotationType.STRIKEOUT: + return new StrikeOutAnnotationElement(parameters); + case AnnotationType.STAMP: + return new StampAnnotationElement(parameters); + case AnnotationType.FILEATTACHMENT: + return new FileAttachmentAnnotationElement(parameters); + default: + return new AnnotationElement(parameters); + } + } + }; + AnnotationElement = class _AnnotationElement { + #updates = null; + #hasBorder = false; + #popupElement = null; + constructor(parameters, { + isRenderable = false, + ignoreBorder = false, + createQuadrilaterals = false + } = {}) { + this.isRenderable = isRenderable; + this.data = parameters.data; + this.layer = parameters.layer; + this.linkService = parameters.linkService; + this.downloadManager = parameters.downloadManager; + this.imageResourcesPath = parameters.imageResourcesPath; + this.renderForms = parameters.renderForms; + this.svgFactory = parameters.svgFactory; + this.annotationStorage = parameters.annotationStorage; + this.enableComment = parameters.enableComment; + this.enableScripting = parameters.enableScripting; + this.hasJSActions = parameters.hasJSActions; + this._fieldObjects = parameters.fieldObjects; + this.parent = parameters.parent; + this.hasOwnCommentButton = false; + if (isRenderable) { + this.contentElement = this.container = this._createContainer(ignoreBorder); + } + if (createQuadrilaterals) { + this._createQuadrilaterals(); + } + } + static _hasPopupData({ + contentsObj, + richText + }) { + return !!(contentsObj?.str || richText?.str); + } + get _isEditable() { + return this.data.isEditable; + } + get hasPopupData() { + return _AnnotationElement._hasPopupData(this.data) || this.enableComment && !!this.commentText; + } + get commentData() { + const { + data + } = this; + const editor = this.annotationStorage?.getEditor(data.id); + if (editor) { + return editor.getData(); + } + return data; + } + get hasCommentButton() { + return this.enableComment && this.hasPopupElement; + } + get commentButtonPosition() { + const editor = this.annotationStorage?.getEditor(this.data.id); + if (editor) { + return editor.commentButtonPositionInPage; + } + const { + quadPoints, + inkLists, + rect + } = this.data; + let maxX = -Infinity; + let maxY = -Infinity; + if (quadPoints?.length >= 8) { + for (let i7 = 0; i7 < quadPoints.length; i7 += 8) { + if (quadPoints[i7 + 1] > maxY) { + maxY = quadPoints[i7 + 1]; + maxX = quadPoints[i7 + 2]; + } else if (quadPoints[i7 + 1] === maxY) { + maxX = Math.max(maxX, quadPoints[i7 + 2]); + } + } + return [maxX, maxY]; + } + if (inkLists?.length >= 1) { + for (const inkList of inkLists) { + for (let i7 = 0, ii = inkList.length; i7 < ii; i7 += 2) { + if (inkList[i7 + 1] > maxY) { + maxY = inkList[i7 + 1]; + maxX = inkList[i7]; + } else if (inkList[i7 + 1] === maxY) { + maxX = Math.max(maxX, inkList[i7]); + } + } + } + if (maxX !== Infinity) { + return [maxX, maxY]; + } + } + if (rect) { + return [rect[2], rect[3]]; + } + return null; + } + _normalizePoint(point) { + const { + page: { + view + }, + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } = this.parent; + point[1] = view[3] - point[1] + view[1]; + point[0] = 100 * (point[0] - pageX) / pageWidth; + point[1] = 100 * (point[1] - pageY) / pageHeight; + return point; + } + get commentText() { + const { + data + } = this; + return this.annotationStorage.getRawValue(`${AnnotationEditorPrefix}${data.id}`)?.popup?.contents || data.contentsObj?.str || ""; + } + set commentText(text3) { + const { + data + } = this; + const popup = { + deleted: !text3, + contents: text3 || "" + }; + if (!this.annotationStorage.updateEditor(data.id, { + popup + })) { + this.annotationStorage.setValue(`${AnnotationEditorPrefix}${data.id}`, { + id: data.id, + annotationType: data.annotationType, + pageIndex: this.parent.page._pageIndex, + popup, + popupRef: data.popupRef, + modificationDate: /* @__PURE__ */ new Date() + }); + } + if (!text3) { + this.removePopup(); + } + } + removePopup() { + (this.#popupElement?.popup || this.popup)?.remove(); + this.#popupElement = this.popup = null; + } + updateEdited(params) { + if (!this.container) { + return; + } + if (params.rect) { + this.#updates ||= { + rect: this.data.rect.slice(0) + }; + } + const { + rect, + popup: newPopup + } = params; + if (rect) { + this.#setRectEdited(rect); + } + let popup = this.#popupElement?.popup || this.popup; + if (!popup && newPopup?.text) { + this._createPopup(newPopup); + popup = this.#popupElement.popup; + } + if (!popup) { + return; + } + popup.updateEdited(params); + if (newPopup?.deleted) { + popup.remove(); + this.#popupElement = null; + this.popup = null; + } + } + resetEdited() { + if (!this.#updates) { + return; + } + this.#setRectEdited(this.#updates.rect); + this.#popupElement?.popup.resetEdited(); + this.#updates = null; + } + #setRectEdited(rect) { + const { + container: { + style + }, + data: { + rect: currentRect, + rotation + }, + parent: { + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } + } = this; + currentRect?.splice(0, 4, ...rect); + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (pageHeight - rect[3] + pageY) / pageHeight}%`; + if (rotation === 0) { + style.width = `${100 * (rect[2] - rect[0]) / pageWidth}%`; + style.height = `${100 * (rect[3] - rect[1]) / pageHeight}%`; + } else { + this.setRotation(rotation); + } + } + _createContainer(ignoreBorder) { + const { + data, + parent: { + page, + viewport + } + } = this; + const container = document.createElement("section"); + container.setAttribute("data-annotation-id", data.id); + if (!(this instanceof WidgetAnnotationElement) && !(this instanceof LinkAnnotationElement)) { + container.tabIndex = 0; + } + const { + style + } = container; + style.zIndex = this.parent.zIndex; + this.parent.zIndex += 2; + if (data.alternativeText) { + container.title = data.alternativeText; + } + if (data.noRotate) { + container.classList.add("norotate"); + } + if (!data.rect || this instanceof PopupAnnotationElement) { + const { + rotation: rotation2 + } = data; + if (!data.hasOwnCanvas && rotation2 !== 0) { + this.setRotation(rotation2, container); + } + return container; + } + const { + width, + height + } = this; + if (!ignoreBorder && data.borderStyle.width > 0) { + style.borderWidth = `${data.borderStyle.width}px`; + const horizontalRadius = data.borderStyle.horizontalCornerRadius; + const verticalRadius = data.borderStyle.verticalCornerRadius; + if (horizontalRadius > 0 || verticalRadius > 0) { + const radius = `calc(${horizontalRadius}px * var(--total-scale-factor)) / calc(${verticalRadius}px * var(--total-scale-factor))`; + style.borderRadius = radius; + } else if (this instanceof RadioButtonWidgetAnnotationElement) { + const radius = `calc(${width}px * var(--total-scale-factor)) / calc(${height}px * var(--total-scale-factor))`; + style.borderRadius = radius; + } + switch (data.borderStyle.style) { + case AnnotationBorderStyleType.SOLID: + style.borderStyle = "solid"; + break; + case AnnotationBorderStyleType.DASHED: + style.borderStyle = "dashed"; + break; + case AnnotationBorderStyleType.BEVELED: + warn("Unimplemented border style: beveled"); + break; + case AnnotationBorderStyleType.INSET: + warn("Unimplemented border style: inset"); + break; + case AnnotationBorderStyleType.UNDERLINE: + style.borderBottomStyle = "solid"; + break; + default: + break; + } + const borderColor = data.borderColor || null; + if (borderColor) { + this.#hasBorder = true; + style.borderColor = Util.makeHexColor(borderColor[0] | 0, borderColor[1] | 0, borderColor[2] | 0); + } else { + style.borderWidth = 0; + } + } + const rect = Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]); + const { + pageWidth, + pageHeight, + pageX, + pageY + } = viewport.rawDims; + style.left = `${100 * (rect[0] - pageX) / pageWidth}%`; + style.top = `${100 * (rect[1] - pageY) / pageHeight}%`; + const { + rotation + } = data; + if (data.hasOwnCanvas || rotation === 0) { + style.width = `${100 * width / pageWidth}%`; + style.height = `${100 * height / pageHeight}%`; + } else { + this.setRotation(rotation, container); + } + return container; + } + setRotation(angle, container = this.container) { + if (!this.data.rect) { + return; + } + const { + pageWidth, + pageHeight + } = this.parent.viewport.rawDims; + let { + width, + height + } = this; + if (angle % 180 !== 0) { + [width, height] = [height, width]; + } + container.style.width = `${100 * width / pageWidth}%`; + container.style.height = `${100 * height / pageHeight}%`; + container.setAttribute("data-main-rotation", (360 - angle) % 360); + } + get _commonActions() { + const setColor = (jsName, styleName, event) => { + const color2 = event.detail[jsName]; + const colorType = color2[0]; + const colorArray = color2.slice(1); + event.target.style[styleName] = ColorConverters[`${colorType}_HTML`](colorArray); + this.annotationStorage.setValue(this.data.id, { + [styleName]: ColorConverters[`${colorType}_rgb`](colorArray) + }); + }; + return shadow(this, "_commonActions", { + display: (event) => { + const { + display + } = event.detail; + const hidden = display % 2 === 1; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noView: hidden, + noPrint: display === 1 || display === 2 + }); + }, + print: (event) => { + this.annotationStorage.setValue(this.data.id, { + noPrint: !event.detail.print + }); + }, + hidden: (event) => { + const { + hidden + } = event.detail; + this.container.style.visibility = hidden ? "hidden" : "visible"; + this.annotationStorage.setValue(this.data.id, { + noPrint: hidden, + noView: hidden + }); + }, + focus: (event) => { + setTimeout(() => event.target.focus({ + preventScroll: false + }), 0); + }, + userName: (event) => { + event.target.title = event.detail.userName; + }, + readonly: (event) => { + event.target.disabled = event.detail.readonly; + }, + required: (event) => { + this._setRequired(event.target, event.detail.required); + }, + bgColor: (event) => { + setColor("bgColor", "backgroundColor", event); + }, + fillColor: (event) => { + setColor("fillColor", "backgroundColor", event); + }, + fgColor: (event) => { + setColor("fgColor", "color", event); + }, + textColor: (event) => { + setColor("textColor", "color", event); + }, + borderColor: (event) => { + setColor("borderColor", "borderColor", event); + }, + strokeColor: (event) => { + setColor("strokeColor", "borderColor", event); + }, + rotation: (event) => { + const angle = event.detail.rotation; + this.setRotation(angle); + this.annotationStorage.setValue(this.data.id, { + rotation: angle + }); + } + }); + } + _dispatchEventFromSandbox(actions, jsEvent) { + const commonActions = this._commonActions; + for (const name of Object.keys(jsEvent.detail)) { + const action = actions[name] || commonActions[name]; + action?.(jsEvent); + } + } + _setDefaultPropertiesFromJS(element) { + if (!this.enableScripting) { + return; + } + const storedData = this.annotationStorage.getRawValue(this.data.id); + if (!storedData) { + return; + } + const commonActions = this._commonActions; + for (const [actionName, detail] of Object.entries(storedData)) { + const action = commonActions[actionName]; + if (action) { + const eventProxy = { + detail: { + [actionName]: detail + }, + target: element + }; + action(eventProxy); + delete storedData[actionName]; + } + } + } + _createQuadrilaterals() { + if (!this.container) { + return; + } + const { + quadPoints + } = this.data; + if (!quadPoints) { + return; + } + const [rectBlX, rectBlY, rectTrX, rectTrY] = this.data.rect.map((x2) => Math.fround(x2)); + if (quadPoints.length === 8) { + const [trX, trY, blX, blY] = quadPoints.subarray(2, 6); + if (rectTrX === trX && rectTrY === trY && rectBlX === blX && rectBlY === blY) { + return; + } + } + const { + style + } = this.container; + let svgBuffer; + if (this.#hasBorder) { + const { + borderColor, + borderWidth + } = style; + style.borderWidth = 0; + svgBuffer = ["url('data:image/svg+xml;utf8,", ``, ``]; + this.container.classList.add("hasBorder"); + } + const width = rectTrX - rectBlX; + const height = rectTrY - rectBlY; + const { + svgFactory + } = this; + const svg = svgFactory.createElement("svg"); + svg.classList.add("quadrilateralsContainer"); + svg.setAttribute("width", 0); + svg.setAttribute("height", 0); + svg.role = "none"; + const defs = svgFactory.createElement("defs"); + svg.append(defs); + const clipPath = svgFactory.createElement("clipPath"); + const id = `clippath_${this.data.id}`; + clipPath.setAttribute("id", id); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + defs.append(clipPath); + for (let i7 = 2, ii = quadPoints.length; i7 < ii; i7 += 8) { + const trX = quadPoints[i7]; + const trY = quadPoints[i7 + 1]; + const blX = quadPoints[i7 + 2]; + const blY = quadPoints[i7 + 3]; + const rect = svgFactory.createElement("rect"); + const x2 = (blX - rectBlX) / width; + const y4 = (rectTrY - trY) / height; + const rectWidth = (trX - blX) / width; + const rectHeight = (trY - blY) / height; + rect.setAttribute("x", x2); + rect.setAttribute("y", y4); + rect.setAttribute("width", rectWidth); + rect.setAttribute("height", rectHeight); + clipPath.append(rect); + svgBuffer?.push(``); + } + if (this.#hasBorder) { + svgBuffer.push(`')`); + style.backgroundImage = svgBuffer.join(""); + } + this.container.append(svg); + this.container.style.clipPath = `url(#${id})`; + } + _createPopup(popupData = null) { + const { + data + } = this; + let contentsObj, modificationDate; + if (popupData) { + contentsObj = { + str: popupData.text + }; + modificationDate = popupData.date; + } else { + contentsObj = data.contentsObj; + modificationDate = data.modificationDate; + } + this.#popupElement = new PopupAnnotationElement({ + data: { + color: data.color, + titleObj: data.titleObj, + modificationDate, + contentsObj, + richText: data.richText, + parentRect: data.rect, + borderStyle: 0, + id: `popup_${data.id}`, + rotation: data.rotation, + noRotate: true + }, + linkService: this.linkService, + parent: this.parent, + elements: [this] + }); + } + get hasPopupElement() { + return !!(this.#popupElement || this.popup || this.data.popupRef); + } + get extraPopupElement() { + return this.#popupElement; + } + render() { + unreachable("Abstract method `AnnotationElement.render` called"); + } + _getElementsByName(name, skipId = null) { + const fields = []; + if (this._fieldObjects) { + const fieldObj = this._fieldObjects[name]; + if (fieldObj) { + for (const { + page, + id, + exportValues + } of fieldObj) { + if (page === -1) { + continue; + } + if (id === skipId) { + continue; + } + const exportValue = typeof exportValues === "string" ? exportValues : null; + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (domElement && !GetElementsByNameSet.has(domElement)) { + warn(`_getElementsByName - element not allowed: ${id}`); + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + } + return fields; + } + for (const domElement of document.getElementsByName(name)) { + const { + exportValue + } = domElement; + const id = domElement.getAttribute("data-element-id"); + if (id === skipId) { + continue; + } + if (!GetElementsByNameSet.has(domElement)) { + continue; + } + fields.push({ + id, + exportValue, + domElement + }); + } + return fields; + } + show() { + if (this.container) { + this.container.hidden = false; + } + this.popup?.maybeShow(); + } + hide() { + if (this.container) { + this.container.hidden = true; + } + this.popup?.forceHide(); + } + getElementsToTriggerPopup() { + return this.container; + } + addHighlightArea() { + const triggers = this.getElementsToTriggerPopup(); + if (Array.isArray(triggers)) { + for (const element of triggers) { + element.classList.add("highlightArea"); + } + } else { + triggers.classList.add("highlightArea"); + } + } + _editOnDoubleClick() { + if (!this._isEditable) { + return; + } + const { + annotationEditorType: mode, + data: { + id: editId + } + } = this; + this.container.addEventListener("dblclick", () => { + this.linkService.eventBus?.dispatch("switchannotationeditormode", { + source: this, + mode, + editId, + mustEnterInEditMode: true + }); + }); + } + get width() { + return this.data.rect[2] - this.data.rect[0]; + } + get height() { + return this.data.rect[3] - this.data.rect[1]; + } + }; + EditorAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.editor = parameters.editor; + } + render() { + this.container.className = "editorAnnotation"; + return this.container; + } + createOrUpdatePopup() { + const { + editor + } = this; + if (!editor.hasComment) { + return; + } + this._createPopup(editor.comment); + } + get hasCommentButton() { + return this.enableComment && this.editor.hasComment; + } + get commentButtonPosition() { + return this.editor.commentButtonPositionInPage; + } + get commentText() { + return this.editor.comment.text; + } + set commentText(text3) { + this.editor.comment = text3; + if (!text3) { + this.removePopup(); + } + } + get commentData() { + return this.editor.getData(); + } + remove() { + this.parent.removeAnnotation(this.data.id); + this.container.remove(); + this.container = null; + this.removePopup(); + } + }; + LinkAnnotationElement = class extends AnnotationElement { + constructor(parameters, options = null) { + super(parameters, { + isRenderable: true, + ignoreBorder: !!options?.ignoreBorder, + createQuadrilaterals: true + }); + this.isTooltipOnly = parameters.data.isTooltipOnly; + } + render() { + const { + data, + linkService + } = this; + const link = document.createElement("a"); + link.setAttribute("data-element-id", data.id); + let isBound = false; + if (data.url) { + linkService.addLinkAttributes(link, data.url, data.newWindow); + isBound = true; + } else if (data.action) { + this._bindNamedAction(link, data.action, data.overlaidText); + isBound = true; + } else if (data.attachment) { + this.#bindAttachment(link, data.attachment, data.overlaidText, data.attachmentDest); + isBound = true; + } else if (data.setOCGState) { + this.#bindSetOCGState(link, data.setOCGState, data.overlaidText); + isBound = true; + } else if (data.dest) { + this._bindLink(link, data.dest, data.overlaidText); + isBound = true; + } else { + if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) { + this._bindJSAction(link, data); + isBound = true; + } + if (data.resetForm) { + this._bindResetFormAction(link, data.resetForm); + isBound = true; + } else if (this.isTooltipOnly && !isBound) { + this._bindLink(link, ""); + isBound = true; + } + } + this.container.classList.add("linkAnnotation"); + if (isBound) { + this.contentElement = link; + this.container.append(link); + } + return this.container; + } + #setInternalLink() { + this.container.setAttribute("data-internal-link", ""); + } + _bindLink(link, destination, overlaidText = "") { + link.href = this.linkService.getDestinationHash(destination); + link.onclick = () => { + if (destination) { + this.linkService.goToDestination(destination); + } + return false; + }; + if (destination || destination === "") { + this.#setInternalLink(); + } + if (overlaidText) { + link.title = overlaidText; + } + } + _bindNamedAction(link, action, overlaidText = "") { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeNamedAction(action); + return false; + }; + if (overlaidText) { + link.title = overlaidText; + } + this.#setInternalLink(); + } + #bindAttachment(link, attachment, overlaidText = "", dest = null) { + link.href = this.linkService.getAnchorUrl(""); + if (attachment.description) { + link.title = attachment.description; + } else if (overlaidText) { + link.title = overlaidText; + } + link.onclick = () => { + this.downloadManager?.openOrDownloadData(attachment.content, attachment.filename, dest); + return false; + }; + this.#setInternalLink(); + } + #bindSetOCGState(link, action, overlaidText = "") { + link.href = this.linkService.getAnchorUrl(""); + link.onclick = () => { + this.linkService.executeSetOCGState(action); + return false; + }; + if (overlaidText) { + link.title = overlaidText; + } + this.#setInternalLink(); + } + _bindJSAction(link, data) { + link.href = this.linkService.getAnchorUrl(""); + const map3 = /* @__PURE__ */ new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]); + for (const name of Object.keys(data.actions)) { + const jsName = map3.get(name); + if (!jsName) { + continue; + } + link[jsName] = () => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: data.id, + name + } + }); + return false; + }; + } + if (data.overlaidText) { + link.title = data.overlaidText; + } + if (!link.onclick) { + link.onclick = () => false; + } + this.#setInternalLink(); + } + _bindResetFormAction(link, resetForm) { + const otherClickAction = link.onclick; + if (!otherClickAction) { + link.href = this.linkService.getAnchorUrl(""); + } + this.#setInternalLink(); + if (!this._fieldObjects) { + warn(`_bindResetFormAction - "resetForm" action not supported, ensure that the \`fieldObjects\` parameter is provided.`); + if (!otherClickAction) { + link.onclick = () => false; + } + return; + } + link.onclick = () => { + otherClickAction?.(); + const { + fields: resetFormFields, + refs: resetFormRefs, + include + } = resetForm; + const allFields = []; + if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) { + const fieldIds = new Set(resetFormRefs); + for (const fieldName of resetFormFields) { + const fields = this._fieldObjects[fieldName] || []; + for (const { + id + } of fields) { + fieldIds.add(id); + } + } + for (const fields of Object.values(this._fieldObjects)) { + for (const field of fields) { + if (fieldIds.has(field.id) === include) { + allFields.push(field); + } + } + } + } else { + for (const fields of Object.values(this._fieldObjects)) { + allFields.push(...fields); + } + } + const storage2 = this.annotationStorage; + const allIds = []; + for (const field of allFields) { + const { + id + } = field; + allIds.push(id); + switch (field.type) { + case "text": { + const value = field.defaultValue || ""; + storage2.setValue(id, { + value + }); + break; + } + case "checkbox": + case "radiobutton": { + const value = field.defaultValue === field.exportValues; + storage2.setValue(id, { + value + }); + break; + } + case "combobox": + case "listbox": { + const value = field.defaultValue || ""; + storage2.setValue(id, { + value + }); + break; + } + default: + continue; + } + const domElement = document.querySelector(`[data-element-id="${id}"]`); + if (!domElement) { + continue; + } else if (!GetElementsByNameSet.has(domElement)) { + warn(`_bindResetFormAction - element not allowed: ${id}`); + continue; + } + domElement.dispatchEvent(new Event("resetform")); + } + if (this.enableScripting) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: "app", + ids: allIds, + name: "ResetForm" + } + }); + } + return false; + }; + } + }; + TextAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + } + render() { + this.container.classList.add("textAnnotation"); + const image = document.createElement("img"); + image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg"; + image.setAttribute("data-l10n-id", "pdfjs-text-annotation-type"); + image.setAttribute("data-l10n-args", JSON.stringify({ + type: this.data.name + })); + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.append(image); + return this.container; + } + }; + WidgetAnnotationElement = class extends AnnotationElement { + render() { + return this.container; + } + showElementAndHideCanvas(element) { + if (this.data.hasOwnCanvas) { + if (element.previousSibling?.nodeName === "CANVAS") { + element.previousSibling.hidden = true; + } + element.hidden = false; + } + } + _getKeyModifier(event) { + return util_FeatureTest.platform.isMac ? event.metaKey : event.ctrlKey; + } + _setEventListener(element, elementData, baseName, eventName, valueGetter) { + if (baseName.includes("mouse")) { + element.addEventListener(baseName, (event) => { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event), + shift: event.shiftKey, + modifier: this._getKeyModifier(event) + } + }); + }); + } else { + element.addEventListener(baseName, (event) => { + if (baseName === "blur") { + if (!elementData.focused || !event.relatedTarget) { + return; + } + elementData.focused = false; + } else if (baseName === "focus") { + if (elementData.focused) { + return; + } + elementData.focused = true; + } + if (!valueGetter) { + return; + } + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id: this.data.id, + name: eventName, + value: valueGetter(event) + } + }); + }); + } + } + _setEventListeners(element, elementData, names2, getter) { + for (const [baseName, eventName] of names2) { + if (eventName === "Action" || this.data.actions?.[eventName]) { + if (eventName === "Focus" || eventName === "Blur") { + elementData ||= { + focused: false + }; + } + this._setEventListener(element, elementData, baseName, eventName, getter); + if (eventName === "Focus" && !this.data.actions?.Blur) { + this._setEventListener(element, elementData, "blur", "Blur", null); + } else if (eventName === "Blur" && !this.data.actions?.Focus) { + this._setEventListener(element, elementData, "focus", "Focus", null); + } + } + } + } + _setBackgroundColor(element) { + const color2 = this.data.backgroundColor || null; + element.style.backgroundColor = color2 === null ? "transparent" : Util.makeHexColor(color2[0], color2[1], color2[2]); + } + _setTextStyle(element) { + const TEXT_ALIGNMENT = ["left", "center", "right"]; + const { + fontColor + } = this.data.defaultAppearanceData; + const fontSize = this.data.defaultAppearanceData.fontSize || annotation_layer_DEFAULT_FONT_SIZE; + const style = element.style; + let computedFontSize; + const BORDER_SIZE = 2; + const roundToOneDecimal = (x2) => Math.round(10 * x2) / 10; + if (this.data.multiLine) { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + const numberOfLines = Math.round(height / (LINE_FACTOR * fontSize)) || 1; + const lineHeight = height / numberOfLines; + computedFontSize = Math.min(fontSize, roundToOneDecimal(lineHeight / LINE_FACTOR)); + } else { + const height = Math.abs(this.data.rect[3] - this.data.rect[1] - BORDER_SIZE); + computedFontSize = Math.min(fontSize, roundToOneDecimal(height / LINE_FACTOR)); + } + style.fontSize = `calc(${computedFontSize}px * var(--total-scale-factor))`; + style.color = Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]); + if (this.data.textAlignment !== null) { + style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; + } + } + _setRequired(element, isRequired) { + if (isRequired) { + element.setAttribute("required", true); + } else { + element.removeAttribute("required"); + } + element.setAttribute("aria-required", isRequired); + } + }; + TextWidgetAnnotationElement = class extends WidgetAnnotationElement { + constructor(parameters) { + const isRenderable = parameters.renderForms || parameters.data.hasOwnCanvas || !parameters.data.hasAppearance && !!parameters.data.fieldValue; + super(parameters, { + isRenderable + }); + } + setPropertyOnSiblings(base, key, value, keyInStorage) { + const storage2 = this.annotationStorage; + for (const element of this._getElementsByName(base.name, base.id)) { + if (element.domElement) { + element.domElement[key] = value; + } + storage2.setValue(element.id, { + [keyInStorage]: value + }); + } + } + render() { + const storage2 = this.annotationStorage; + const id = this.data.id; + this.container.classList.add("textWidgetAnnotation"); + let element = null; + if (this.renderForms) { + const storedData = storage2.getValue(id, { + value: this.data.fieldValue + }); + let textContent = storedData.value || ""; + const maxLen = storage2.getValue(id, { + charLimit: this.data.maxLen + }).charLimit; + if (maxLen && textContent.length > maxLen) { + textContent = textContent.slice(0, maxLen); + } + let fieldFormattedValues = storedData.formattedValue || this.data.textContent?.join("\n") || null; + if (fieldFormattedValues && this.data.comb) { + fieldFormattedValues = fieldFormattedValues.replaceAll(/\s+/g, ""); + } + const elementData = { + userValue: textContent, + formattedValue: fieldFormattedValues, + lastCommittedValue: null, + commitKey: 1, + focused: false + }; + if (this.data.multiLine) { + element = document.createElement("textarea"); + element.textContent = fieldFormattedValues ?? textContent; + if (this.data.doNotScroll) { + element.style.overflowY = "hidden"; + } + } else { + element = document.createElement("input"); + element.type = this.data.password ? "password" : "text"; + element.setAttribute("value", fieldFormattedValues ?? textContent); + if (this.data.doNotScroll) { + element.style.overflowX = "hidden"; + } + } + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + GetElementsByNameSet.add(element); + this.contentElement = element; + element.setAttribute("data-element-id", id); + element.disabled = this.data.readOnly; + element.name = this.data.fieldName; + element.tabIndex = 0; + const { + datetimeFormat, + datetimeType, + timeStep + } = this.data; + const hasDateOrTime = !!datetimeType && this.enableScripting; + if (datetimeFormat) { + element.title = datetimeFormat; + } + this._setRequired(element, this.data.required); + if (maxLen) { + element.maxLength = maxLen; + } + element.addEventListener("input", (event) => { + storage2.setValue(id, { + value: event.target.value + }); + this.setPropertyOnSiblings(element, "value", event.target.value, "value"); + elementData.formattedValue = null; + }); + element.addEventListener("resetform", (event) => { + const defaultValue = this.data.defaultFieldValue ?? ""; + element.value = elementData.userValue = defaultValue; + elementData.formattedValue = null; + }); + let blurListener = (event) => { + const { + formattedValue + } = elementData; + if (formattedValue !== null && formattedValue !== void 0) { + event.target.value = formattedValue; + } + event.target.scrollLeft = 0; + }; + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("focus", (event) => { + if (elementData.focused) { + return; + } + const { + target + } = event; + if (hasDateOrTime) { + target.type = datetimeType; + if (timeStep) { + target.step = timeStep; + } + } + if (elementData.userValue) { + const value = elementData.userValue; + if (hasDateOrTime) { + if (datetimeType === "time") { + const date = new Date(value); + const parts = [date.getHours(), date.getMinutes(), date.getSeconds()]; + target.value = parts.map((v4) => v4.toString().padStart(2, "0")).join(":"); + } else { + target.value = new Date(value - TIMEZONE_OFFSET).toISOString().split(datetimeType === "date" ? "T" : ".", 1)[0]; + } + } else { + target.value = value; + } + } + elementData.lastCommittedValue = target.value; + elementData.commitKey = 1; + if (!this.data.actions?.Focus) { + elementData.focused = true; + } + }); + element.addEventListener("updatefromsandbox", (jsEvent) => { + this.showElementAndHideCanvas(jsEvent.target); + const actions = { + value(event) { + elementData.userValue = event.detail.value ?? ""; + if (!hasDateOrTime) { + storage2.setValue(id, { + value: elementData.userValue.toString() + }); + } + event.target.value = elementData.userValue; + }, + formattedValue(event) { + const { + formattedValue + } = event.detail; + elementData.formattedValue = formattedValue; + if (formattedValue !== null && formattedValue !== void 0 && event.target !== document.activeElement) { + event.target.value = formattedValue; + } + const data = { + formattedValue + }; + if (hasDateOrTime) { + data.value = formattedValue; + } + storage2.setValue(id, data); + }, + selRange(event) { + event.target.setSelectionRange(...event.detail.selRange); + }, + charLimit: (event) => { + const { + charLimit + } = event.detail; + const { + target + } = event; + if (charLimit === 0) { + target.removeAttribute("maxLength"); + return; + } + target.setAttribute("maxLength", charLimit); + let value = elementData.userValue; + if (!value || value.length <= charLimit) { + return; + } + value = value.slice(0, charLimit); + target.value = elementData.userValue = value; + storage2.setValue(id, { + value + }); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: 1, + selStart: target.selectionStart, + selEnd: target.selectionEnd + } + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + element.addEventListener("keydown", (event) => { + elementData.commitKey = 1; + let commitKey = -1; + if (event.key === "Escape") { + commitKey = 0; + } else if (event.key === "Enter" && !this.data.multiLine) { + commitKey = 2; + } else if (event.key === "Tab") { + elementData.commitKey = 3; + } + if (commitKey === -1) { + return; + } + const { + value + } = event.target; + if (elementData.lastCommittedValue === value) { + return; + } + elementData.lastCommittedValue = value; + elementData.userValue = value; + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + }); + const _blurListener = blurListener; + blurListener = null; + element.addEventListener("blur", (event) => { + if (!elementData.focused || !event.relatedTarget) { + return; + } + if (!this.data.actions?.Blur) { + elementData.focused = false; + } + const { + target + } = event; + let { + value + } = target; + if (hasDateOrTime) { + if (value && datetimeType === "time") { + const parts = value.split(":").map((v4) => parseInt(v4, 10)); + value = new Date(2e3, 0, 1, parts[0], parts[1], parts[2] || 0).valueOf(); + target.step = ""; + } else { + if (!value.includes("T")) { + value = `${value}T00:00`; + } + value = new Date(value).valueOf(); + } + target.type = "text"; + } + elementData.userValue = value; + if (elementData.lastCommittedValue !== value) { + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + willCommit: true, + commitKey: elementData.commitKey, + selStart: event.target.selectionStart, + selEnd: event.target.selectionEnd + } + }); + } + _blurListener(event); + }); + if (this.data.actions?.Keystroke) { + element.addEventListener("beforeinput", (event) => { + elementData.lastCommittedValue = null; + const { + data, + target + } = event; + const { + value, + selectionStart, + selectionEnd + } = target; + let selStart = selectionStart, selEnd = selectionEnd; + switch (event.inputType) { + case "deleteWordBackward": { + const match2 = value.substring(0, selectionStart).match(/\w*[^\w]*$/); + if (match2) { + selStart -= match2[0].length; + } + break; + } + case "deleteWordForward": { + const match2 = value.substring(selectionStart).match(/^[^\w]*\w*/); + if (match2) { + selEnd += match2[0].length; + } + break; + } + case "deleteContentBackward": + if (selectionStart === selectionEnd) { + selStart -= 1; + } + break; + case "deleteContentForward": + if (selectionStart === selectionEnd) { + selEnd += 1; + } + break; + } + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value, + change: data || "", + willCommit: false, + selStart, + selEnd + } + }); + }); + } + this._setEventListeners(element, elementData, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.value); + } + if (blurListener) { + element.addEventListener("blur", blurListener); + } + if (this.data.comb) { + const fieldWidth = this.data.rect[2] - this.data.rect[0]; + const combWidth = fieldWidth / maxLen; + element.classList.add("comb"); + element.style.letterSpacing = `calc(${combWidth}px * var(--total-scale-factor) - 1ch)`; + } + } else { + element = document.createElement("div"); + element.textContent = this.data.fieldValue; + element.style.verticalAlign = "middle"; + element.style.display = "table-cell"; + if (this.data.hasOwnCanvas) { + element.hidden = true; + } + } + this._setTextStyle(element); + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } + }; + SignatureWidgetAnnotationElement = class extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: !!parameters.data.hasOwnCanvas + }); + } + }; + CheckboxWidgetAnnotationElement = class extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + const storage2 = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage2.getValue(id, { + value: data.exportValue === data.fieldValue + }).value; + if (typeof value === "string") { + value = value !== "Off"; + storage2.setValue(id, { + value + }); + } + this.container.classList.add("buttonWidgetAnnotation", "checkBox"); + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "checkbox"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.setAttribute("exportValue", data.exportValue); + element.tabIndex = 0; + element.addEventListener("change", (event) => { + const { + name, + checked + } = event.target; + for (const checkbox of this._getElementsByName(name, id)) { + const curChecked = checked && checkbox.exportValue === data.exportValue; + if (checkbox.domElement) { + checkbox.domElement.checked = curChecked; + } + storage2.setValue(checkbox.id, { + value: curChecked + }); + } + storage2.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", (event) => { + const defaultValue = data.defaultFieldValue || "Off"; + event.target.checked = defaultValue === data.exportValue; + }); + if (this.enableScripting && this.hasJSActions) { + element.addEventListener("updatefromsandbox", (jsEvent) => { + const actions = { + value(event) { + event.target.checked = event.detail.value !== "Off"; + storage2.setValue(id, { + value: event.target.checked + }); + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.checked); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } + }; + RadioButtonWidgetAnnotationElement = class extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("buttonWidgetAnnotation", "radioButton"); + const storage2 = this.annotationStorage; + const data = this.data; + const id = data.id; + let value = storage2.getValue(id, { + value: data.fieldValue === data.buttonValue + }).value; + if (typeof value === "string") { + value = value !== data.buttonValue; + storage2.setValue(id, { + value + }); + } + if (value) { + for (const radio of this._getElementsByName(data.fieldName, id)) { + storage2.setValue(radio.id, { + value: false + }); + } + } + const element = document.createElement("input"); + GetElementsByNameSet.add(element); + element.setAttribute("data-element-id", id); + element.disabled = data.readOnly; + this._setRequired(element, this.data.required); + element.type = "radio"; + element.name = data.fieldName; + if (value) { + element.setAttribute("checked", true); + } + element.tabIndex = 0; + element.addEventListener("change", (event) => { + const { + name, + checked + } = event.target; + for (const radio of this._getElementsByName(name, id)) { + storage2.setValue(radio.id, { + value: false + }); + } + storage2.setValue(id, { + value: checked + }); + }); + element.addEventListener("resetform", (event) => { + const defaultValue = data.defaultFieldValue; + event.target.checked = defaultValue !== null && defaultValue !== void 0 && defaultValue === data.buttonValue; + }); + if (this.enableScripting && this.hasJSActions) { + const pdfButtonValue = data.buttonValue; + element.addEventListener("updatefromsandbox", (jsEvent) => { + const actions = { + value: (event) => { + const checked = pdfButtonValue === event.detail.value; + for (const radio of this._getElementsByName(event.target.name)) { + const curChecked = checked && radio.id === id; + if (radio.domElement) { + radio.domElement.checked = curChecked; + } + storage2.setValue(radio.id, { + value: curChecked + }); + } + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + this._setEventListeners(element, null, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], (event) => event.target.checked); + } + this._setBackgroundColor(element); + this._setDefaultPropertiesFromJS(element); + this.container.append(element); + return this.container; + } + }; + PushButtonWidgetAnnotationElement = class extends LinkAnnotationElement { + constructor(parameters) { + super(parameters, { + ignoreBorder: parameters.data.hasAppearance + }); + } + render() { + const container = super.render(); + container.classList.add("buttonWidgetAnnotation", "pushButton"); + const linkElement = container.lastChild; + if (this.enableScripting && this.hasJSActions && linkElement) { + this._setDefaultPropertiesFromJS(linkElement); + linkElement.addEventListener("updatefromsandbox", (jsEvent) => { + this._dispatchEventFromSandbox({}, jsEvent); + }); + } + return container; + } + }; + ChoiceWidgetAnnotationElement = class extends WidgetAnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: parameters.renderForms + }); + } + render() { + this.container.classList.add("choiceWidgetAnnotation"); + const storage2 = this.annotationStorage; + const id = this.data.id; + const storedData = storage2.getValue(id, { + value: this.data.fieldValue + }); + const selectElement = document.createElement("select"); + GetElementsByNameSet.add(selectElement); + selectElement.setAttribute("data-element-id", id); + selectElement.disabled = this.data.readOnly; + this._setRequired(selectElement, this.data.required); + selectElement.name = this.data.fieldName; + selectElement.tabIndex = 0; + let addAnEmptyEntry = this.data.combo && this.data.options.length > 0; + if (!this.data.combo) { + selectElement.size = this.data.options.length; + if (this.data.multiSelect) { + selectElement.multiple = true; + } + } + selectElement.addEventListener("resetform", (event) => { + const defaultValue = this.data.defaultFieldValue; + for (const option of selectElement.options) { + option.selected = option.value === defaultValue; + } + }); + for (const option of this.data.options) { + const optionElement = document.createElement("option"); + optionElement.textContent = option.displayValue; + optionElement.value = option.exportValue; + if (storedData.value.includes(option.exportValue)) { + optionElement.setAttribute("selected", true); + addAnEmptyEntry = false; + } + selectElement.append(optionElement); + } + let removeEmptyEntry = null; + if (addAnEmptyEntry) { + const noneOptionElement = document.createElement("option"); + noneOptionElement.value = " "; + noneOptionElement.setAttribute("hidden", true); + noneOptionElement.setAttribute("selected", true); + selectElement.prepend(noneOptionElement); + removeEmptyEntry = () => { + noneOptionElement.remove(); + selectElement.removeEventListener("input", removeEmptyEntry); + removeEmptyEntry = null; + }; + selectElement.addEventListener("input", removeEmptyEntry); + } + const getValue = (isExport) => { + const name = isExport ? "value" : "textContent"; + const { + options, + multiple + } = selectElement; + if (!multiple) { + return options.selectedIndex === -1 ? null : options[options.selectedIndex][name]; + } + return Array.prototype.filter.call(options, (option) => option.selected).map((option) => option[name]); + }; + let selectedValues = getValue(false); + const getItems = (event) => { + const options = event.target.options; + return Array.prototype.map.call(options, (option) => ({ + displayValue: option.textContent, + exportValue: option.value + })); + }; + if (this.enableScripting && this.hasJSActions) { + selectElement.addEventListener("updatefromsandbox", (jsEvent) => { + const actions = { + value(event) { + removeEmptyEntry?.(); + const value = event.detail.value; + const values2 = new Set(Array.isArray(value) ? value : [value]); + for (const option of selectElement.options) { + option.selected = values2.has(option.value); + } + storage2.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + multipleSelection(event) { + selectElement.multiple = true; + }, + remove(event) { + const options = selectElement.options; + const index2 = event.detail.remove; + options[index2].selected = false; + selectElement.remove(index2); + if (options.length > 0) { + const i7 = Array.prototype.findIndex.call(options, (option) => option.selected); + if (i7 === -1) { + options[0].selected = true; + } + } + storage2.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + clear(event) { + while (selectElement.length !== 0) { + selectElement.remove(0); + } + storage2.setValue(id, { + value: null, + items: [] + }); + selectedValues = getValue(false); + }, + insert(event) { + const { + index: index2, + displayValue, + exportValue + } = event.detail.insert; + const selectChild = selectElement.children[index2]; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + if (selectChild) { + selectChild.before(optionElement); + } else { + selectElement.append(optionElement); + } + storage2.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + items(event) { + const { + items + } = event.detail; + while (selectElement.length !== 0) { + selectElement.remove(0); + } + for (const item of items) { + const { + displayValue, + exportValue + } = item; + const optionElement = document.createElement("option"); + optionElement.textContent = displayValue; + optionElement.value = exportValue; + selectElement.append(optionElement); + } + if (selectElement.options.length > 0) { + selectElement.options[0].selected = true; + } + storage2.setValue(id, { + value: getValue(true), + items: getItems(event) + }); + selectedValues = getValue(false); + }, + indices(event) { + const indices = new Set(event.detail.indices); + for (const option of event.target.options) { + option.selected = indices.has(option.index); + } + storage2.setValue(id, { + value: getValue(true) + }); + selectedValues = getValue(false); + }, + editable(event) { + event.target.disabled = !event.detail.editable; + } + }; + this._dispatchEventFromSandbox(actions, jsEvent); + }); + selectElement.addEventListener("input", (event) => { + const exportValue = getValue(true); + const change = getValue(false); + storage2.setValue(id, { + value: exportValue + }); + event.preventDefault(); + this.linkService.eventBus?.dispatch("dispatcheventinsandbox", { + source: this, + detail: { + id, + name: "Keystroke", + value: selectedValues, + change, + changeEx: exportValue, + willCommit: false, + commitKey: 1, + keyDown: false + } + }); + }); + this._setEventListeners(selectElement, null, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"], ["input", "Validate"]], (event) => event.target.value); + } else { + selectElement.addEventListener("input", function(event) { + storage2.setValue(id, { + value: getValue(true) + }); + }); + } + if (this.data.combo) { + this._setTextStyle(selectElement); + } else { + } + this._setBackgroundColor(selectElement); + this._setDefaultPropertiesFromJS(selectElement); + this.container.append(selectElement); + return this.container; + } + }; + PopupAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + const { + data, + elements: elements2, + parent + } = parameters; + const hasCommentManager = !!parent._commentManager; + super(parameters, { + isRenderable: !hasCommentManager && AnnotationElement._hasPopupData(data) + }); + this.elements = elements2; + if (hasCommentManager && AnnotationElement._hasPopupData(data)) { + const popup = this.popup = this.#createPopup(); + for (const element of elements2) { + element.popup = popup; + } + } else { + this.popup = null; + } + } + #createPopup() { + return new PopupElement({ + container: this.container, + color: this.data.color, + titleObj: this.data.titleObj, + modificationDate: this.data.modificationDate || this.data.creationDate, + contentsObj: this.data.contentsObj, + richText: this.data.richText, + rect: this.data.rect, + parentRect: this.data.parentRect || null, + parent: this.parent, + elements: this.elements, + open: this.data.open, + commentManager: this.parent._commentManager + }); + } + render() { + const { + container + } = this; + container.classList.add("popupAnnotation"); + container.role = "comment"; + const popup = this.popup = this.#createPopup(); + const elementIds = []; + for (const element of this.elements) { + element.popup = popup; + element.container.ariaHasPopup = "dialog"; + elementIds.push(element.data.id); + element.addHighlightArea(); + } + this.container.setAttribute("aria-controls", elementIds.map((id) => `${AnnotationPrefix}${id}`).join(",")); + return this.container; + } + }; + PopupElement = class { + #commentManager = null; + #boundKeyDown = this.#keyDown.bind(this); + #boundHide = this.#hide.bind(this); + #boundShow = this.#show.bind(this); + #boundToggle = this.#toggle.bind(this); + #color = null; + #container = null; + #contentsObj = null; + #dateObj = null; + #elements = null; + #parent = null; + #parentRect = null; + #pinned = false; + #popup = null; + #popupAbortController = null; + #position = null; + #commentButton = null; + #commentButtonPosition = null; + #popupPosition = null; + #rect = null; + #richText = null; + #titleObj = null; + #updates = null; + #wasVisible = false; + #firstElement = null; + #commentText = null; + constructor({ + container, + color: color2, + elements: elements2, + titleObj, + modificationDate, + contentsObj, + richText, + parent, + rect, + parentRect, + open: open2, + commentManager = null + }) { + this.#container = container; + this.#titleObj = titleObj; + this.#contentsObj = contentsObj; + this.#richText = richText; + this.#parent = parent; + this.#color = color2; + this.#rect = rect; + this.#parentRect = parentRect; + this.#elements = elements2; + this.#commentManager = commentManager; + this.#firstElement = elements2[0]; + this.#dateObj = PDFDateString.toDateObject(modificationDate); + this.trigger = elements2.flatMap((e9) => e9.getElementsToTriggerPopup()); + if (!commentManager) { + this.#addEventListeners(); + this.#container.hidden = true; + if (open2) { + this.#toggle(); + } + } + } + #addEventListeners() { + if (this.#popupAbortController) { + return; + } + this.#popupAbortController = new AbortController(); + const { + signal + } = this.#popupAbortController; + for (const element of this.trigger) { + element.addEventListener("click", this.#boundToggle, { + signal + }); + element.addEventListener("pointerenter", this.#boundShow, { + signal + }); + element.addEventListener("pointerleave", this.#boundHide, { + signal + }); + element.classList.add("popupTriggerArea"); + } + for (const element of this.#elements) { + element.container?.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + } + } + #setCommentButtonPosition() { + const element = this.#elements.find((e9) => e9.hasCommentButton); + if (!element) { + return; + } + this.#commentButtonPosition = element._normalizePoint(element.commentButtonPosition); + } + renderCommentButton() { + if (this.#commentButton) { + if (!this.#commentButton.parentNode) { + this.#firstElement.container.after(this.#commentButton); + } + return; + } + if (!this.#commentButtonPosition) { + this.#setCommentButtonPosition(); + } + if (!this.#commentButtonPosition) { + return; + } + const { + signal + } = this.#popupAbortController = new AbortController(); + const hasOwnButton = this.#firstElement.hasOwnCommentButton; + const togglePopup = () => { + this.#commentManager.toggleCommentPopup(this, true, void 0, !hasOwnButton); + }; + const showPopup = () => { + this.#commentManager.toggleCommentPopup(this, false, true, !hasOwnButton); + }; + const hidePopup = () => { + this.#commentManager.toggleCommentPopup(this, false, false); + }; + if (!hasOwnButton) { + const button = this.#commentButton = document.createElement("button"); + button.className = "annotationCommentButton"; + const parentContainer = this.#firstElement.container; + button.style.zIndex = parentContainer.style.zIndex + 1; + button.tabIndex = 0; + button.ariaHasPopup = "dialog"; + button.ariaControls = "commentPopup"; + button.setAttribute("data-l10n-id", "pdfjs-show-comment-button"); + this.#updateColor(); + this.#updateCommentButtonPosition(); + button.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + button.addEventListener("click", togglePopup, { + signal + }); + button.addEventListener("pointerenter", showPopup, { + signal + }); + button.addEventListener("pointerleave", hidePopup, { + signal + }); + parentContainer.after(button); + } else { + this.#commentButton = this.#firstElement.container; + for (const element of this.trigger) { + element.ariaHasPopup = "dialog"; + element.ariaControls = "commentPopup"; + element.addEventListener("keydown", this.#boundKeyDown, { + signal + }); + element.addEventListener("click", togglePopup, { + signal + }); + element.addEventListener("pointerenter", showPopup, { + signal + }); + element.addEventListener("pointerleave", hidePopup, { + signal + }); + element.classList.add("popupTriggerArea"); + } + } + } + #updateCommentButtonPosition() { + if (this.#firstElement.extraPopupElement && !this.#firstElement.editor) { + return; + } + if (!this.#commentButton) { + this.renderCommentButton(); + } + const [x2, y4] = this.#commentButtonPosition; + const { + style + } = this.#commentButton; + style.left = `calc(${x2}%)`; + style.top = `calc(${y4}% - var(--comment-button-dim))`; + } + #updateColor() { + if (this.#firstElement.extraPopupElement) { + return; + } + if (!this.#commentButton) { + this.renderCommentButton(); + } + this.#commentButton.style.backgroundColor = this.commentButtonColor || ""; + } + get commentButtonColor() { + const { + color: color2, + opacity + } = this.#firstElement.commentData; + if (!color2) { + return null; + } + return this.#parent._commentManager.makeCommentColor(color2, opacity); + } + focusCommentButton() { + setTimeout(() => { + this.#commentButton?.focus(); + }, 0); + } + getData() { + const { + richText, + color: color2, + opacity, + creationDate, + modificationDate + } = this.#firstElement.commentData; + return { + contentsObj: { + str: this.comment + }, + richText, + color: color2, + opacity, + creationDate, + modificationDate + }; + } + get elementBeforePopup() { + return this.#commentButton; + } + get comment() { + this.#commentText ||= this.#firstElement.commentText; + return this.#commentText; + } + set comment(text3) { + if (text3 === this.comment) { + return; + } + this.#firstElement.commentText = this.#commentText = text3; + } + focus() { + this.#firstElement.container?.focus(); + } + get parentBoundingClientRect() { + return this.#firstElement.layer.getBoundingClientRect(); + } + setCommentButtonStates({ + selected, + hasPopup + }) { + if (!this.#commentButton) { + return; + } + this.#commentButton.classList.toggle("selected", selected); + this.#commentButton.ariaExpanded = hasPopup; + } + setSelectedCommentButton(selected) { + this.#commentButton.classList.toggle("selected", selected); + } + get commentPopupPosition() { + if (this.#popupPosition) { + return this.#popupPosition; + } + const { + x: x2, + y: y4, + height + } = this.#commentButton.getBoundingClientRect(); + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = this.#firstElement.layer.getBoundingClientRect(); + return [(x2 - parentX) / parentWidth, (y4 + height - parentY) / parentHeight]; + } + set commentPopupPosition(pos) { + this.#popupPosition = pos; + } + hasDefaultPopupPosition() { + return this.#popupPosition === null; + } + get commentButtonPosition() { + return this.#commentButtonPosition; + } + get commentButtonWidth() { + return this.#commentButton.getBoundingClientRect().width / this.parentBoundingClientRect.width; + } + editComment(options) { + const [posX, posY] = this.#popupPosition || this.commentButtonPosition.map((x2) => x2 / 100); + const parentDimensions = this.parentBoundingClientRect; + const { + x: parentX, + y: parentY, + width: parentWidth, + height: parentHeight + } = parentDimensions; + this.#commentManager.showDialog(null, this, parentX + posX * parentWidth, parentY + posY * parentHeight, { + ...options, + parentDimensions + }); + } + render() { + if (this.#popup) { + return; + } + const popup = this.#popup = document.createElement("div"); + popup.className = "popup"; + if (this.#color) { + const baseColor = popup.style.outlineColor = Util.makeHexColor(...this.#color); + popup.style.backgroundColor = `color-mix(in srgb, ${baseColor} 30%, white)`; + } + const header = document.createElement("span"); + header.className = "header"; + if (this.#titleObj?.str) { + const title = document.createElement("span"); + title.className = "title"; + header.append(title); + ({ + dir: title.dir, + str: title.textContent + } = this.#titleObj); + } + popup.append(header); + if (this.#dateObj) { + const modificationDate = document.createElement("time"); + modificationDate.className = "popupDate"; + modificationDate.setAttribute("data-l10n-id", "pdfjs-annotation-date-time-string"); + modificationDate.setAttribute("data-l10n-args", JSON.stringify({ + dateObj: this.#dateObj.valueOf() + })); + modificationDate.dateTime = this.#dateObj.toISOString(); + header.append(modificationDate); + } + renderRichText({ + html: this.#html || this.#contentsObj.str, + dir: this.#contentsObj?.dir, + className: "popupContent" + }, popup); + this.#container.append(popup); + } + get #html() { + const richText = this.#richText; + const contentsObj = this.#contentsObj; + if (richText?.str && (!contentsObj?.str || contentsObj.str === richText.str)) { + return this.#richText.html || null; + } + return null; + } + get #fontSize() { + return this.#html?.attributes?.style?.fontSize || 0; + } + get #fontColor() { + return this.#html?.attributes?.style?.color || null; + } + #makePopupContent(text3) { + const popupLines = []; + const popupContent = { + str: text3, + html: { + name: "div", + attributes: { + dir: "auto" + }, + children: [{ + name: "p", + children: popupLines + }] + } + }; + const lineAttributes = { + style: { + color: this.#fontColor, + fontSize: this.#fontSize ? `calc(${this.#fontSize}px * var(--total-scale-factor))` : "" + } + }; + for (const line of text3.split("\n")) { + popupLines.push({ + name: "span", + value: line, + attributes: lineAttributes + }); + } + return popupContent; + } + #keyDown(event) { + if (event.altKey || event.shiftKey || event.ctrlKey || event.metaKey) { + return; + } + if (event.key === "Enter" || event.key === "Escape" && this.#pinned) { + this.#toggle(); + } + } + updateEdited({ + rect, + popup, + deleted + }) { + if (this.#commentManager) { + if (deleted) { + this.remove(); + this.#commentText = null; + } else if (popup) { + if (popup.deleted) { + this.remove(); + } else { + this.#updateColor(); + this.#commentText = popup.text; + } + } + if (rect) { + this.#commentButtonPosition = null; + this.#setCommentButtonPosition(); + this.#updateCommentButtonPosition(); + } + return; + } + if (deleted || popup?.deleted) { + this.remove(); + return; + } + this.#addEventListeners(); + this.#updates ||= { + contentsObj: this.#contentsObj, + richText: this.#richText + }; + if (rect) { + this.#position = null; + } + if (popup && popup.text) { + this.#richText = this.#makePopupContent(popup.text); + this.#dateObj = PDFDateString.toDateObject(popup.date); + this.#contentsObj = null; + } + this.#popup?.remove(); + this.#popup = null; + } + resetEdited() { + if (!this.#updates) { + return; + } + ({ + contentsObj: this.#contentsObj, + richText: this.#richText + } = this.#updates); + this.#updates = null; + this.#popup?.remove(); + this.#popup = null; + this.#position = null; + } + remove() { + this.#popupAbortController?.abort(); + this.#popupAbortController = null; + this.#popup?.remove(); + this.#popup = null; + this.#wasVisible = false; + this.#pinned = false; + this.#commentButton?.remove(); + this.#commentButton = null; + if (this.trigger) { + for (const element of this.trigger) { + element.classList.remove("popupTriggerArea"); + } + } + } + #setPosition() { + if (this.#position !== null) { + return; + } + const { + page: { + view + }, + viewport: { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } + } = this.#parent; + let useParentRect = !!this.#parentRect; + let rect = useParentRect ? this.#parentRect : this.#rect; + for (const element of this.#elements) { + if (!rect || Util.intersect(element.data.rect, rect) !== null) { + rect = element.data.rect; + useParentRect = true; + break; + } + } + const normalizedRect = Util.normalizeRect([rect[0], view[3] - rect[1] + view[1], rect[2], view[3] - rect[3] + view[1]]); + const HORIZONTAL_SPACE_AFTER_ANNOTATION = 5; + const parentWidth = useParentRect ? rect[2] - rect[0] + HORIZONTAL_SPACE_AFTER_ANNOTATION : 0; + const popupLeft = normalizedRect[0] + parentWidth; + const popupTop = normalizedRect[1]; + this.#position = [100 * (popupLeft - pageX) / pageWidth, 100 * (popupTop - pageY) / pageHeight]; + const { + style + } = this.#container; + style.left = `${this.#position[0]}%`; + style.top = `${this.#position[1]}%`; + } + #toggle() { + if (this.#commentManager) { + this.#commentManager.toggleCommentPopup(this, false); + return; + } + this.#pinned = !this.#pinned; + if (this.#pinned) { + this.#show(); + this.#container.addEventListener("click", this.#boundToggle); + this.#container.addEventListener("keydown", this.#boundKeyDown); + } else { + this.#hide(); + this.#container.removeEventListener("click", this.#boundToggle); + this.#container.removeEventListener("keydown", this.#boundKeyDown); + } + } + #show() { + if (!this.#popup) { + this.render(); + } + if (!this.isVisible) { + this.#setPosition(); + this.#container.hidden = false; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) + 1e3; + } else if (this.#pinned) { + this.#container.classList.add("focused"); + } + } + #hide() { + this.#container.classList.remove("focused"); + if (this.#pinned || !this.isVisible) { + return; + } + this.#container.hidden = true; + this.#container.style.zIndex = parseInt(this.#container.style.zIndex) - 1e3; + } + forceHide() { + this.#wasVisible = this.isVisible; + if (!this.#wasVisible) { + return; + } + this.#container.hidden = true; + } + maybeShow() { + if (this.#commentManager) { + return; + } + this.#addEventListeners(); + if (!this.#wasVisible) { + return; + } + if (!this.#popup) { + this.#show(); + } + this.#wasVisible = false; + this.#container.hidden = false; + } + get isVisible() { + if (this.#commentManager) { + return false; + } + return this.#container.hidden === false; + } + }; + FreeTextAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.textContent = parameters.data.textContent; + this.textPosition = parameters.data.textPosition; + this.annotationEditorType = AnnotationEditorType.FREETEXT; + } + render() { + this.container.classList.add("freeTextAnnotation"); + if (this.textContent) { + const content = this.contentElement = document.createElement("div"); + content.classList.add("annotationTextContent"); + content.setAttribute("role", "comment"); + for (const line of this.textContent) { + const lineSpan = document.createElement("span"); + lineSpan.textContent = line; + content.append(lineSpan); + } + this.container.append(content); + } + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } + }; + LineAnnotationElement = class extends AnnotationElement { + #line = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("lineAnnotation"); + const { + data, + width, + height + } = this; + const svg = this.svgFactory.create(width, height, true); + const line = this.#line = this.svgFactory.createElement("svg:line"); + line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]); + line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]); + line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]); + line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]); + line.setAttribute("stroke-width", data.borderStyle.width || 1); + line.setAttribute("stroke", "transparent"); + line.setAttribute("fill", "transparent"); + svg.append(line); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#line; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + }; + SquareAnnotationElement = class extends AnnotationElement { + #square = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("squareAnnotation"); + const { + data, + width, + height + } = this; + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const square = this.#square = this.svgFactory.createElement("svg:rect"); + square.setAttribute("x", borderWidth / 2); + square.setAttribute("y", borderWidth / 2); + square.setAttribute("width", width - borderWidth); + square.setAttribute("height", height - borderWidth); + square.setAttribute("stroke-width", borderWidth || 1); + square.setAttribute("stroke", "transparent"); + square.setAttribute("fill", "transparent"); + svg.append(square); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#square; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + }; + CircleAnnotationElement = class extends AnnotationElement { + #circle = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("circleAnnotation"); + const { + data, + width, + height + } = this; + const svg = this.svgFactory.create(width, height, true); + const borderWidth = data.borderStyle.width; + const circle = this.#circle = this.svgFactory.createElement("svg:ellipse"); + circle.setAttribute("cx", width / 2); + circle.setAttribute("cy", height / 2); + circle.setAttribute("rx", width / 2 - borderWidth / 2); + circle.setAttribute("ry", height / 2 - borderWidth / 2); + circle.setAttribute("stroke-width", borderWidth || 1); + circle.setAttribute("stroke", "transparent"); + circle.setAttribute("fill", "transparent"); + svg.append(circle); + this.container.append(svg); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#circle; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + }; + PolylineAnnotationElement = class extends AnnotationElement { + #polyline = null; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "polylineAnnotation"; + this.svgElementName = "svg:polyline"; + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + vertices, + borderStyle, + popupRef + }, + width, + height + } = this; + if (!vertices) { + return this.container; + } + const svg = this.svgFactory.create(width, height, true); + let points = []; + for (let i7 = 0, ii = vertices.length; i7 < ii; i7 += 2) { + const x2 = vertices[i7] - rect[0]; + const y4 = rect[3] - vertices[i7 + 1]; + points.push(`${x2},${y4}`); + } + points = points.join(" "); + const polyline = this.#polyline = this.svgFactory.createElement(this.svgElementName); + polyline.setAttribute("points", points); + polyline.setAttribute("stroke-width", borderStyle.width || 1); + polyline.setAttribute("stroke", "transparent"); + polyline.setAttribute("fill", "transparent"); + svg.append(polyline); + this.container.append(svg); + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + getElementsToTriggerPopup() { + return this.#polyline; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + }; + PolygonAnnotationElement = class extends PolylineAnnotationElement { + constructor(parameters) { + super(parameters); + this.containerClassName = "polygonAnnotation"; + this.svgElementName = "svg:polygon"; + } + }; + CaretAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + } + render() { + this.container.classList.add("caretAnnotation"); + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + return this.container; + } + }; + InkAnnotationElement = class extends AnnotationElement { + #polylinesGroupElement = null; + #polylines = []; + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.containerClassName = "inkAnnotation"; + this.svgElementName = "svg:polyline"; + this.annotationEditorType = this.data.it === "InkHighlight" ? AnnotationEditorType.HIGHLIGHT : AnnotationEditorType.INK; + } + #getTransform(rotation, rect) { + switch (rotation) { + case 90: + return { + transform: `rotate(90) translate(${-rect[0]},${rect[1]}) scale(1,-1)`, + width: rect[3] - rect[1], + height: rect[2] - rect[0] + }; + case 180: + return { + transform: `rotate(180) translate(${-rect[2]},${rect[1]}) scale(1,-1)`, + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; + case 270: + return { + transform: `rotate(270) translate(${-rect[2]},${rect[3]}) scale(1,-1)`, + width: rect[3] - rect[1], + height: rect[2] - rect[0] + }; + default: + return { + transform: `translate(${-rect[0]},${rect[3]}) scale(1,-1)`, + width: rect[2] - rect[0], + height: rect[3] - rect[1] + }; + } + } + render() { + this.container.classList.add(this.containerClassName); + const { + data: { + rect, + rotation, + inkLists, + borderStyle, + popupRef + } + } = this; + const { + transform, + width, + height + } = this.#getTransform(rotation, rect); + const svg = this.svgFactory.create(width, height, true); + const g3 = this.#polylinesGroupElement = this.svgFactory.createElement("svg:g"); + svg.append(g3); + g3.setAttribute("stroke-width", borderStyle.width || 1); + g3.setAttribute("stroke-linecap", "round"); + g3.setAttribute("stroke-linejoin", "round"); + g3.setAttribute("stroke-miterlimit", 10); + g3.setAttribute("stroke", "transparent"); + g3.setAttribute("fill", "transparent"); + g3.setAttribute("transform", transform); + for (let i7 = 0, ii = inkLists.length; i7 < ii; i7++) { + const polyline = this.svgFactory.createElement(this.svgElementName); + this.#polylines.push(polyline); + polyline.setAttribute("points", inkLists[i7].join(",")); + g3.append(polyline); + } + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.append(svg); + this._editOnDoubleClick(); + return this.container; + } + updateEdited(params) { + super.updateEdited(params); + const { + thickness, + points, + rect + } = params; + const g3 = this.#polylinesGroupElement; + if (thickness >= 0) { + g3.setAttribute("stroke-width", thickness || 1); + } + if (points) { + for (let i7 = 0, ii = this.#polylines.length; i7 < ii; i7++) { + this.#polylines[i7].setAttribute("points", points[i7].join(",")); + } + } + if (rect) { + const { + transform, + width, + height + } = this.#getTransform(this.data.rotation, rect); + const root = g3.parentElement; + root.setAttribute("viewBox", `0 0 ${width} ${height}`); + g3.setAttribute("transform", transform); + } + } + getElementsToTriggerPopup() { + return this.#polylines; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + }; + HighlightAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + this.annotationEditorType = AnnotationEditorType.HIGHLIGHT; + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("highlightAnnotation"); + this._editOnDoubleClick(); + if (overlaidText) { + const mark = document.createElement("mark"); + mark.classList.add("overlaidText"); + mark.textContent = overlaidText; + this.container.append(mark); + } + return this.container; + } + }; + UnderlineAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("underlineAnnotation"); + if (overlaidText) { + const underline = document.createElement("u"); + underline.classList.add("overlaidText"); + underline.textContent = overlaidText; + this.container.append(underline); + } + return this.container; + } + }; + SquigglyAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("squigglyAnnotation"); + if (overlaidText) { + const underline = document.createElement("u"); + underline.classList.add("overlaidText"); + underline.textContent = overlaidText; + this.container.append(underline); + } + return this.container; + } + }; + StrikeOutAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true, + createQuadrilaterals: true + }); + } + render() { + const { + data: { + overlaidText, + popupRef + } + } = this; + if (!popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this.container.classList.add("strikeoutAnnotation"); + if (overlaidText) { + const strikeout = document.createElement("s"); + strikeout.classList.add("overlaidText"); + strikeout.textContent = overlaidText; + this.container.append(strikeout); + } + return this.container; + } + }; + StampAnnotationElement = class extends AnnotationElement { + constructor(parameters) { + super(parameters, { + isRenderable: true, + ignoreBorder: true + }); + this.annotationEditorType = AnnotationEditorType.STAMP; + } + render() { + this.container.classList.add("stampAnnotation"); + this.container.setAttribute("role", "img"); + if (!this.data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } + this._editOnDoubleClick(); + return this.container; + } + }; + FileAttachmentAnnotationElement = class extends AnnotationElement { + #trigger = null; + constructor(parameters) { + super(parameters, { + isRenderable: true + }); + const { + file + } = this.data; + this.filename = file.filename; + this.content = file.content; + this.linkService.eventBus?.dispatch("fileattachmentannotation", { + source: this, + ...file + }); + } + render() { + this.container.classList.add("fileAttachmentAnnotation"); + const { + container, + data + } = this; + let trigger; + if (data.hasAppearance || data.fillAlpha === 0) { + trigger = document.createElement("div"); + } else { + trigger = document.createElement("img"); + trigger.src = `${this.imageResourcesPath}annotation-${/paperclip/i.test(data.name) ? "paperclip" : "pushpin"}.svg`; + if (data.fillAlpha && data.fillAlpha < 1) { + trigger.style = `filter: opacity(${Math.round(data.fillAlpha * 100)}%);`; + } + } + trigger.addEventListener("dblclick", this.#download.bind(this)); + this.#trigger = trigger; + const { + isMac + } = util_FeatureTest.platform; + container.addEventListener("keydown", (evt) => { + if (evt.key === "Enter" && (isMac ? evt.metaKey : evt.ctrlKey)) { + this.#download(); + } + }); + if (!data.popupRef && this.hasPopupData) { + this.hasOwnCommentButton = true; + this._createPopup(); + } else { + trigger.classList.add("popupTriggerArea"); + } + container.append(trigger); + return container; + } + getElementsToTriggerPopup() { + return this.#trigger; + } + addHighlightArea() { + this.container.classList.add("highlightArea"); + } + #download() { + this.downloadManager?.openOrDownloadData(this.content, this.filename); + } + }; + AnnotationLayer = class _AnnotationLayer { + #accessibilityManager = null; + #annotationCanvasMap = null; + #annotationStorage = null; + #editableAnnotations = /* @__PURE__ */ new Map(); + #structTreeLayer = null; + #linkService = null; + #elements = []; + #hasAriaAttributesFromStructTree = false; + constructor({ + div, + accessibilityManager, + annotationCanvasMap, + annotationEditorUIManager, + page, + viewport, + structTreeLayer, + commentManager, + linkService, + annotationStorage + }) { + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationCanvasMap = annotationCanvasMap; + this.#structTreeLayer = structTreeLayer || null; + this.#linkService = linkService || null; + this.#annotationStorage = annotationStorage || new AnnotationStorage(); + this.page = page; + this.viewport = viewport; + this.zIndex = 0; + this._annotationEditorUIManager = annotationEditorUIManager; + this._commentManager = commentManager || null; + } + hasEditableAnnotations() { + return this.#editableAnnotations.size > 0; + } + async render(params) { + const { + annotations + } = params; + const layer = this.div; + setLayerDimensions(layer, this.viewport); + const popupToElements = /* @__PURE__ */ new Map(); + const popupAnnotations = []; + const elementParams = { + data: null, + layer, + linkService: this.#linkService, + downloadManager: params.downloadManager, + imageResourcesPath: params.imageResourcesPath || "", + renderForms: params.renderForms !== false, + svgFactory: new DOMSVGFactory(), + annotationStorage: this.#annotationStorage, + enableComment: params.enableComment === true, + enableScripting: params.enableScripting === true, + hasJSActions: params.hasJSActions, + fieldObjects: params.fieldObjects, + parent: this, + elements: null + }; + for (const data of annotations) { + if (data.noHTML) { + continue; + } + const isPopupAnnotation = data.annotationType === AnnotationType.POPUP; + if (!isPopupAnnotation) { + if (data.rect[2] === data.rect[0] || data.rect[3] === data.rect[1]) { + continue; + } + } else { + const elements2 = popupToElements.get(data.id); + if (!elements2) { + continue; + } + if (!this._commentManager) { + popupAnnotations.push(data); + continue; + } + elementParams.elements = elements2; + } + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + if (!isPopupAnnotation) { + this.#elements.push(element); + if (data.popupRef) { + const elements2 = popupToElements.get(data.popupRef); + if (!elements2) { + popupToElements.set(data.popupRef, [element]); + } else { + elements2.push(element); + } + } + } + const rendered = element.render(); + if (data.hidden) { + rendered.style.visibility = "hidden"; + } + if (element._isEditable) { + this.#editableAnnotations.set(element.data.id, element); + this._annotationEditorUIManager?.renderAnnotationElement(element); + } + } + await this.#addElementsToDOM(); + for (const data of popupAnnotations) { + const elements2 = elementParams.elements = popupToElements.get(data.id); + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + const rendered = element.render(); + element.contentElement.id = `${AnnotationPrefix}${data.id}`; + if (data.hidden) { + rendered.style.visibility = "hidden"; + } + elements2.at(-1).container.after(rendered); + } + this.#setAnnotationCanvasMap(); + } + async #addElementsToDOM() { + if (this.#elements.length === 0) { + return; + } + this.div.replaceChildren(); + const promises = []; + if (!this.#hasAriaAttributesFromStructTree) { + this.#hasAriaAttributesFromStructTree = true; + for (const { + contentElement, + data: { + id + } + } of this.#elements) { + const annotationId = contentElement.id = `${AnnotationPrefix}${id}`; + promises.push(this.#structTreeLayer?.getAriaAttributes(annotationId).then((ariaAttributes) => { + if (ariaAttributes) { + for (const [key, value] of ariaAttributes) { + contentElement.setAttribute(key, value); + } + } + })); + } + } + this.#elements.sort(({ + data: { + rect: [a0, a1, a22, a3] + } + }, { + data: { + rect: [b0, b1, b22, b32] + } + }) => { + if (a0 === a22 && a1 === a3) { + return 1; + } + if (b0 === b22 && b1 === b32) { + return -1; + } + const top1 = a3; + const bot1 = a1; + const mid1 = (a1 + a3) / 2; + const top2 = b32; + const bot2 = b1; + const mid2 = (b1 + b32) / 2; + if (mid1 >= top2 && mid2 <= bot1) { + return -1; + } + if (mid2 >= top1 && mid1 <= bot2) { + return 1; + } + const centerX1 = (a0 + a22) / 2; + const centerX2 = (b0 + b22) / 2; + return centerX1 - centerX2; + }); + const fragment2 = document.createDocumentFragment(); + for (const element of this.#elements) { + fragment2.append(element.container); + if (this._commentManager) { + (element.extraPopupElement?.popup || element.popup)?.renderCommentButton(); + } else if (element.extraPopupElement) { + fragment2.append(element.extraPopupElement.render()); + } + } + this.div.append(fragment2); + await Promise.all(promises); + if (this.#accessibilityManager) { + for (const element of this.#elements) { + this.#accessibilityManager.addPointerInTextLayer(element.contentElement, false); + } + } + } + async addLinkAnnotations(annotations) { + const elementParams = { + data: null, + layer: this.div, + linkService: this.#linkService, + svgFactory: new DOMSVGFactory(), + parent: this + }; + for (const data of annotations) { + data.borderStyle ||= _AnnotationLayer._defaultBorderStyle; + elementParams.data = data; + const element = AnnotationElementFactory.create(elementParams); + if (!element.isRenderable) { + continue; + } + element.render(); + element.contentElement.id = `${AnnotationPrefix}${data.id}`; + this.#elements.push(element); + } + await this.#addElementsToDOM(); + } + update({ + viewport + }) { + const layer = this.div; + this.viewport = viewport; + setLayerDimensions(layer, { + rotation: viewport.rotation + }); + this.#setAnnotationCanvasMap(); + layer.hidden = false; + } + #setAnnotationCanvasMap() { + if (!this.#annotationCanvasMap) { + return; + } + const layer = this.div; + for (const [id, canvas] of this.#annotationCanvasMap) { + const element = layer.querySelector(`[data-annotation-id="${id}"]`); + if (!element) { + continue; + } + canvas.className = "annotationContent"; + const { + firstChild + } = element; + if (!firstChild) { + element.append(canvas); + } else if (firstChild.nodeName === "CANVAS") { + firstChild.replaceWith(canvas); + } else if (!firstChild.classList.contains("annotationContent")) { + firstChild.before(canvas); + } else { + firstChild.after(canvas); + } + const editableAnnotation = this.#editableAnnotations.get(id); + if (!editableAnnotation) { + continue; + } + if (editableAnnotation._hasNoCanvas) { + this._annotationEditorUIManager?.setMissingCanvas(id, element.id, canvas); + editableAnnotation._hasNoCanvas = false; + } else { + editableAnnotation.canvas = canvas; + } + } + this.#annotationCanvasMap.clear(); + } + getEditableAnnotations() { + return Array.from(this.#editableAnnotations.values()); + } + getEditableAnnotation(id) { + return this.#editableAnnotations.get(id); + } + addFakeAnnotation(editor) { + const { + div + } = this; + const { + id, + rotation + } = editor; + const element = new EditorAnnotationElement({ + data: { + id, + rect: editor.getPDFRect(), + rotation + }, + editor, + layer: div, + parent: this, + enableComment: !!this._commentManager, + linkService: this.#linkService, + annotationStorage: this.#annotationStorage + }); + element.render(); + element.contentElement.id = `${AnnotationPrefix}${id}`; + element.createOrUpdatePopup(); + this.#elements.push(element); + return element; + } + removeAnnotation(id) { + const index2 = this.#elements.findIndex((el) => el.data.id === id); + if (index2 < 0) { + return; + } + const [element] = this.#elements.splice(index2, 1); + this.#accessibilityManager?.removePointerInTextLayer(element.contentElement); + } + updateFakeAnnotations(editors) { + if (editors.length === 0) { + return; + } + for (const editor of editors) { + editor.updateFakeAnnotationElement(this); + } + this.#addElementsToDOM(); + } + togglePointerEvents(enabled = false) { + this.div.classList.toggle("disabled", !enabled); + } + static get _defaultBorderStyle() { + return shadow(this, "_defaultBorderStyle", Object.freeze({ + width: 1, + rawWidth: 1, + style: AnnotationBorderStyleType.SOLID, + dashArray: [3], + horizontalCornerRadius: 0, + verticalCornerRadius: 0 + })); + } + }; + EOL_PATTERN = /\r\n?|\n/g; + FreeTextEditor = class _FreeTextEditor extends AnnotationEditor { + #content = ""; + #editorDivId = `${this.id}-editor`; + #editModeAC = null; + #fontSize; + _colorPicker = null; + static _freeTextDefaultContent = ""; + static _internalPadding = 0; + static _defaultColor = null; + static _defaultFontSize = 10; + static get _keyboardManager() { + const proto = _FreeTextEditor.prototype; + const arrowChecker = (self2) => self2.isEmpty(); + const small = AnnotationEditorUIManager.TRANSLATE_SMALL; + const big = AnnotationEditorUIManager.TRANSLATE_BIG; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ctrl+s", "mac+meta+s", "ctrl+p", "mac+meta+p"], proto.commitOrRemove, { + bubbles: true + }], [["ctrl+Enter", "mac+meta+Enter", "Escape", "mac+Escape"], proto.commitOrRemove], [["ArrowLeft", "mac+ArrowLeft"], proto._translateEmpty, { + args: [-small, 0], + checker: arrowChecker + }], [["ctrl+ArrowLeft", "mac+shift+ArrowLeft"], proto._translateEmpty, { + args: [-big, 0], + checker: arrowChecker + }], [["ArrowRight", "mac+ArrowRight"], proto._translateEmpty, { + args: [small, 0], + checker: arrowChecker + }], [["ctrl+ArrowRight", "mac+shift+ArrowRight"], proto._translateEmpty, { + args: [big, 0], + checker: arrowChecker + }], [["ArrowUp", "mac+ArrowUp"], proto._translateEmpty, { + args: [0, -small], + checker: arrowChecker + }], [["ctrl+ArrowUp", "mac+shift+ArrowUp"], proto._translateEmpty, { + args: [0, -big], + checker: arrowChecker + }], [["ArrowDown", "mac+ArrowDown"], proto._translateEmpty, { + args: [0, small], + checker: arrowChecker + }], [["ctrl+ArrowDown", "mac+shift+ArrowDown"], proto._translateEmpty, { + args: [0, big], + checker: arrowChecker + }]])); + } + static _type = "freetext"; + static _editorType = AnnotationEditorType.FREETEXT; + constructor(params) { + super({ + ...params, + name: "freeTextEditor" + }); + this.color = params.color || _FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor; + this.#fontSize = params.fontSize || _FreeTextEditor._defaultFontSize; + if (!this.annotationElementId) { + this._uiManager.a11yAlert("pdfjs-editor-freetext-added-alert"); + } + this.canAddComment = false; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + const style = getComputedStyle(document.documentElement); + this._internalPadding = parseFloat(style.getPropertyValue("--freetext-padding")); + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + _FreeTextEditor._defaultFontSize = value; + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + _FreeTextEditor._defaultColor = value; + break; + } + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.FREETEXT_SIZE: + this.#updateFontSize(value); + break; + case AnnotationEditorParamsType.FREETEXT_COLOR: + this.#updateColor(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, _FreeTextEditor._defaultFontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, _FreeTextEditor._defaultColor || AnnotationEditor._defaultLineColor]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.FREETEXT_SIZE, this.#fontSize], [AnnotationEditorParamsType.FREETEXT_COLOR, this.color]]; + } + get toolbarButtons() { + this._colorPicker ||= new BasicColorPicker(this); + return [["colorPicker", this._colorPicker]]; + } + get colorType() { + return AnnotationEditorParamsType.FREETEXT_COLOR; + } + #updateFontSize(fontSize) { + const setFontsize = (size) => { + this.editorDiv.style.fontSize = `calc(${size}px * var(--total-scale-factor))`; + this.translate(0, -(size - this.#fontSize) * this.parentScale); + this.#fontSize = size; + this.#setEditorDimensions(); + }; + const savedFontsize = this.#fontSize; + this.addCommands({ + cmd: setFontsize.bind(this, fontSize), + undo: setFontsize.bind(this, savedFontsize), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_SIZE, + overwriteIfSameType: true, + keepUndo: true + }); + } + onUpdatedColor() { + this.editorDiv.style.color = this.color; + this._colorPicker?.update(this.color); + super.onUpdatedColor(); + } + #updateColor(color2) { + const setColor = (col) => { + this.color = col; + this.onUpdatedColor(); + }; + const savedColor = this.color; + this.addCommands({ + cmd: setColor.bind(this, color2), + undo: setColor.bind(this, savedColor), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.FREETEXT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + } + _translateEmpty(x2, y4) { + this._uiManager.translateSelectedEditors(x2, y4, true); + } + getInitialTranslation() { + const scale = this.parentScale; + return [-_FreeTextEditor._internalPadding * scale, -(_FreeTextEditor._internalPadding + this.#fontSize) * scale]; + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + enableEditMode() { + if (!super.enableEditMode()) { + return false; + } + this.overlayDiv.classList.remove("enabled"); + this.editorDiv.contentEditable = true; + this._isDraggable = false; + this.div.removeAttribute("aria-activedescendant"); + this.#editModeAC = new AbortController(); + const signal = this._uiManager.combinedSignal(this.#editModeAC); + this.editorDiv.addEventListener("keydown", this.editorDivKeydown.bind(this), { + signal + }); + this.editorDiv.addEventListener("focus", this.editorDivFocus.bind(this), { + signal + }); + this.editorDiv.addEventListener("blur", this.editorDivBlur.bind(this), { + signal + }); + this.editorDiv.addEventListener("input", this.editorDivInput.bind(this), { + signal + }); + this.editorDiv.addEventListener("paste", this.editorDivPaste.bind(this), { + signal + }); + return true; + } + disableEditMode() { + if (!super.disableEditMode()) { + return false; + } + this.overlayDiv.classList.add("enabled"); + this.editorDiv.contentEditable = false; + this.div.setAttribute("aria-activedescendant", this.#editorDivId); + this._isDraggable = true; + this.#editModeAC?.abort(); + this.#editModeAC = null; + this.div.focus({ + preventScroll: true + }); + this.isEditing = false; + this.parent.div.classList.add("freetextEditing"); + return true; + } + focusin(event) { + if (!this._focusEventsAllowed) { + return; + } + super.focusin(event); + if (event.target !== this.editorDiv) { + this.editorDiv.focus(); + } + } + onceAdded(focus) { + if (this.width) { + return; + } + this.enableEditMode(); + if (focus) { + this.editorDiv.focus(); + } + if (this._initialOptions?.isCentered) { + this.center(); + } + this._initialOptions = null; + } + isEmpty() { + return !this.editorDiv || this.editorDiv.innerText.trim() === ""; + } + remove() { + this.isEditing = false; + if (this.parent) { + this.parent.setEditingState(true); + this.parent.div.classList.add("freetextEditing"); + } + super.remove(); + } + #extractText() { + const buffer = []; + this.editorDiv.normalize(); + let prevChild = null; + for (const child of this.editorDiv.childNodes) { + if (prevChild?.nodeType === Node.TEXT_NODE && child.nodeName === "BR") { + continue; + } + buffer.push(_FreeTextEditor.#getNodeContent(child)); + prevChild = child; + } + return buffer.join("\n"); + } + #setEditorDimensions() { + const [parentWidth, parentHeight] = this.parentDimensions; + let rect; + if (this.isAttachedToDOM) { + rect = this.div.getBoundingClientRect(); + } else { + const { + currentLayer, + div + } = this; + const savedDisplay = div.style.display; + const savedVisibility = div.classList.contains("hidden"); + div.classList.remove("hidden"); + div.style.display = "hidden"; + currentLayer.div.append(this.div); + rect = div.getBoundingClientRect(); + div.remove(); + div.style.display = savedDisplay; + div.classList.toggle("hidden", savedVisibility); + } + if (this.rotation % 180 === this.parentRotation % 180) { + this.width = rect.width / parentWidth; + this.height = rect.height / parentHeight; + } else { + this.width = rect.height / parentWidth; + this.height = rect.width / parentHeight; + } + this.fixAndSetPosition(); + } + commit() { + if (!this.isInEditMode()) { + return; + } + super.commit(); + this.disableEditMode(); + const savedText = this.#content; + const newText = this.#content = this.#extractText().trimEnd(); + if (savedText === newText) { + return; + } + const setText = (text3) => { + this.#content = text3; + if (!text3) { + this.remove(); + return; + } + this.#setContent(); + this._uiManager.rebuild(this); + this.#setEditorDimensions(); + }; + this.addCommands({ + cmd: () => { + setText(newText); + }, + undo: () => { + setText(savedText); + }, + mustExec: false + }); + this.#setEditorDimensions(); + } + shouldGetKeyboardEvents() { + return this.isInEditMode(); + } + enterInEditMode() { + this.enableEditMode(); + this.editorDiv.focus(); + } + keydown(event) { + if (event.target === this.div && event.key === "Enter") { + this.enterInEditMode(); + event.preventDefault(); + } + } + editorDivKeydown(event) { + _FreeTextEditor._keyboardManager.exec(this, event); + } + editorDivFocus(event) { + this.isEditing = true; + } + editorDivBlur(event) { + this.isEditing = false; + } + editorDivInput(event) { + this.parent.div.classList.toggle("freetextEditing", this.isEmpty()); + } + disableEditing() { + this.editorDiv.setAttribute("role", "comment"); + this.editorDiv.removeAttribute("aria-multiline"); + } + enableEditing() { + this.editorDiv.setAttribute("role", "textbox"); + this.editorDiv.setAttribute("aria-multiline", true); + } + get canChangeContent() { + return true; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this._isCopy || this.annotationElementId) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.editorDiv = document.createElement("div"); + this.editorDiv.className = "internal"; + this.editorDiv.setAttribute("id", this.#editorDivId); + this.editorDiv.setAttribute("data-l10n-id", "pdfjs-free-text2"); + this.editorDiv.setAttribute("data-l10n-attrs", "default-content"); + this.enableEditing(); + this.editorDiv.contentEditable = true; + const { + style + } = this.editorDiv; + style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`; + style.color = this.color; + this.div.append(this.editorDiv); + this.overlayDiv = document.createElement("div"); + this.overlayDiv.classList.add("overlay", "enabled"); + this.div.append(this.overlayDiv); + if (this._isCopy || this.annotationElementId) { + const [parentWidth, parentHeight] = this.parentDimensions; + if (this.annotationElementId) { + const { + position + } = this._initialData; + let [tx, ty] = this.getInitialTranslation(); + [tx, ty] = this.pageTranslationToScreen(tx, ty); + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + let posX, posY; + switch (this.rotation) { + case 0: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY + this.height - (position[1] - pageY) / pageHeight; + break; + case 90: + posX = baseX + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [ty, -tx]; + break; + case 180: + posX = baseX - this.width + (position[0] - pageX) / pageWidth; + posY = baseY - (position[1] - pageY) / pageHeight; + [tx, ty] = [-tx, -ty]; + break; + case 270: + posX = baseX + (position[0] - pageX - this.height * pageHeight) / pageWidth; + posY = baseY + (position[1] - pageY - this.width * pageWidth) / pageHeight; + [tx, ty] = [-ty, tx]; + break; + } + this.setAt(posX * parentWidth, posY * parentHeight, tx, ty); + } else { + this._moveAfterPaste(baseX, baseY); + } + this.#setContent(); + this._isDraggable = true; + this.editorDiv.contentEditable = false; + } else { + this._isDraggable = false; + this.editorDiv.contentEditable = true; + } + return this.div; + } + static #getNodeContent(node) { + return (node.nodeType === Node.TEXT_NODE ? node.nodeValue : node.innerText).replaceAll(EOL_PATTERN, ""); + } + editorDivPaste(event) { + const clipboardData = event.clipboardData || window.clipboardData; + const { + types: types2 + } = clipboardData; + if (types2.length === 1 && types2[0] === "text/plain") { + return; + } + event.preventDefault(); + const paste = _FreeTextEditor.#deserializeContent(clipboardData.getData("text") || "").replaceAll(EOL_PATTERN, "\n"); + if (!paste) { + return; + } + const selection = window.getSelection(); + if (!selection.rangeCount) { + return; + } + this.editorDiv.normalize(); + selection.deleteFromDocument(); + const range2 = selection.getRangeAt(0); + if (!paste.includes("\n")) { + range2.insertNode(document.createTextNode(paste)); + this.editorDiv.normalize(); + selection.collapseToStart(); + return; + } + const { + startContainer, + startOffset + } = range2; + const bufferBefore = []; + const bufferAfter = []; + if (startContainer.nodeType === Node.TEXT_NODE) { + const parent = startContainer.parentElement; + bufferAfter.push(startContainer.nodeValue.slice(startOffset).replaceAll(EOL_PATTERN, "")); + if (parent !== this.editorDiv) { + let buffer = bufferBefore; + for (const child of this.editorDiv.childNodes) { + if (child === parent) { + buffer = bufferAfter; + continue; + } + buffer.push(_FreeTextEditor.#getNodeContent(child)); + } + } + bufferBefore.push(startContainer.nodeValue.slice(0, startOffset).replaceAll(EOL_PATTERN, "")); + } else if (startContainer === this.editorDiv) { + let buffer = bufferBefore; + let i7 = 0; + for (const child of this.editorDiv.childNodes) { + if (i7++ === startOffset) { + buffer = bufferAfter; + } + buffer.push(_FreeTextEditor.#getNodeContent(child)); + } + } + this.#content = `${bufferBefore.join("\n")}${paste}${bufferAfter.join("\n")}`; + this.#setContent(); + const newRange = new Range(); + let beforeLength = Math.sumPrecise(bufferBefore.map((line) => line.length)); + for (const { + firstChild + } of this.editorDiv.childNodes) { + if (firstChild.nodeType === Node.TEXT_NODE) { + const length = firstChild.nodeValue.length; + if (beforeLength <= length) { + newRange.setStart(firstChild, beforeLength); + newRange.setEnd(firstChild, beforeLength); + break; + } + beforeLength -= length; + } + } + selection.removeAllRanges(); + selection.addRange(newRange); + } + #setContent() { + this.editorDiv.replaceChildren(); + if (!this.#content) { + return; + } + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + this.editorDiv.append(div); + } + } + #serializeContent() { + return this.#content.replaceAll("\xA0", " "); + } + static #deserializeContent(content) { + return content.replaceAll(" ", "\xA0"); + } + get contentDiv() { + return this.editorDiv; + } + getPDFRect() { + const padding = _FreeTextEditor._internalPadding * this.parentScale; + return this.getRect(padding, padding); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof FreeTextAnnotationElement) { + const { + data: { + defaultAppearanceData: { + fontSize, + fontColor + }, + rect, + rotation, + id, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + textContent, + textPosition, + parent: { + page: { + pageNumber + } + } + } = data; + if (!textContent || textContent.length === 0) { + return null; + } + initialData = data = { + annotationType: AnnotationEditorType.FREETEXT, + color: Array.from(fontColor), + fontSize, + value: textContent.join("\n"), + position: textPosition, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + comment: contentsObj?.str || null, + richText, + creationDate, + modificationDate + }; + } + const editor = await super.deserialize(data, parent, uiManager); + editor.#fontSize = data.fontSize; + editor.color = Util.makeHexColor(...data.color); + editor.#content = _FreeTextEditor.#deserializeContent(data.value); + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const color2 = AnnotationEditor._colorManager.convert(this.isAttachedToDOM ? getComputedStyle(this.editorDiv).color : this.color); + const serialized = Object.assign(super.serialize(isForCopying), { + color: color2, + fontSize: this.#fontSize, + value: this.#serializeContent() + }); + this.addComment(serialized); + if (isForCopying) { + serialized.isCopy = true; + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + value, + fontSize, + color: color2, + pageIndex + } = this._initialData; + return this.hasEditedComment || this._hasBeenMoved || serialized.value !== value || serialized.fontSize !== fontSize || serialized.color.some((c6, i7) => c6 !== color2[i7]) || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + const content = super.renderAnnotationElement(annotation); + if (!content) { + return null; + } + const { + style + } = content; + style.fontSize = `calc(${this.#fontSize}px * var(--total-scale-factor))`; + style.color = this.color; + content.replaceChildren(); + for (const line of this.#content.split("\n")) { + const div = document.createElement("div"); + div.append(line ? document.createTextNode(line) : document.createElement("br")); + content.append(div); + } + annotation.updateEdited({ + rect: this.getPDFRect(), + popup: this._uiManager.hasCommentManager() || this.hasEditedComment ? this.comment : { + text: this.#content + } + }); + return content; + } + resetAnnotationElement(annotation) { + super.resetAnnotationElement(annotation); + annotation.resetEdited(); + } + }; + Outline = class { + static PRECISION = 1e-4; + toSVGPath() { + unreachable("Abstract method `toSVGPath` must be implemented."); + } + get box() { + unreachable("Abstract getter `box` must be implemented."); + } + serialize(_bbox, _rotation) { + unreachable("Abstract method `serialize` must be implemented."); + } + static _rescale(src, tx, ty, sx, sy, dest) { + dest ||= new Float32Array(src.length); + for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) { + dest[i7] = tx + src[i7] * sx; + dest[i7 + 1] = ty + src[i7 + 1] * sy; + } + return dest; + } + static _rescaleAndSwap(src, tx, ty, sx, sy, dest) { + dest ||= new Float32Array(src.length); + for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) { + dest[i7] = tx + src[i7 + 1] * sx; + dest[i7 + 1] = ty + src[i7] * sy; + } + return dest; + } + static _translate(src, tx, ty, dest) { + dest ||= new Float32Array(src.length); + for (let i7 = 0, ii = src.length; i7 < ii; i7 += 2) { + dest[i7] = tx + src[i7]; + dest[i7 + 1] = ty + src[i7 + 1]; + } + return dest; + } + static svgRound(x2) { + return Math.round(x2 * 1e4); + } + static _normalizePoint(x2, y4, parentWidth, parentHeight, rotation) { + switch (rotation) { + case 90: + return [1 - y4 / parentWidth, x2 / parentHeight]; + case 180: + return [1 - x2 / parentWidth, 1 - y4 / parentHeight]; + case 270: + return [y4 / parentWidth, 1 - x2 / parentHeight]; + default: + return [x2 / parentWidth, y4 / parentHeight]; + } + } + static _normalizePagePoint(x2, y4, rotation) { + switch (rotation) { + case 90: + return [1 - y4, x2]; + case 180: + return [1 - x2, 1 - y4]; + case 270: + return [y4, 1 - x2]; + default: + return [x2, y4]; + } + } + static createBezierPoints(x1, y1, x2, y22, x3, y32) { + return [(x1 + 5 * x2) / 6, (y1 + 5 * y22) / 6, (5 * x2 + x3) / 6, (5 * y22 + y32) / 6, (x2 + x3) / 2, (y22 + y32) / 2]; + } + }; + FreeDrawOutliner = class _FreeDrawOutliner { + #box; + #bottom = []; + #innerMargin; + #isLTR; + #top = []; + #last = new Float32Array(18); + #lastX; + #lastY; + #min; + #min_dist; + #scaleFactor; + #thickness; + #points = []; + static #MIN_DIST = 8; + static #MIN_DIFF = 2; + static #MIN = _FreeDrawOutliner.#MIN_DIST + _FreeDrawOutliner.#MIN_DIFF; + constructor({ + x: x2, + y: y4 + }, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + this.#box = box; + this.#thickness = thickness * scaleFactor; + this.#isLTR = isLTR; + this.#last.set([NaN, NaN, NaN, NaN, x2, y4], 6); + this.#innerMargin = innerMargin; + this.#min_dist = _FreeDrawOutliner.#MIN_DIST * scaleFactor; + this.#min = _FreeDrawOutliner.#MIN * scaleFactor; + this.#scaleFactor = scaleFactor; + this.#points.push(x2, y4); + } + isEmpty() { + return isNaN(this.#last[8]); + } + #getLastCoords() { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [x2, y4, width, height] = this.#box; + return [(this.#lastX + (lastTop[0] - lastBottom[0]) / 2 - x2) / width, (this.#lastY + (lastTop[1] - lastBottom[1]) / 2 - y4) / height, (this.#lastX + (lastBottom[0] - lastTop[0]) / 2 - x2) / width, (this.#lastY + (lastBottom[1] - lastTop[1]) / 2 - y4) / height]; + } + add({ + x: x2, + y: y4 + }) { + this.#lastX = x2; + this.#lastY = y4; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + let [x1, y1, x22, y22] = this.#last.subarray(8, 12); + const diffX = x2 - x22; + const diffY = y4 - y22; + const d4 = Math.hypot(diffX, diffY); + if (d4 < this.#min) { + return false; + } + const diffD = d4 - this.#min_dist; + const K2 = diffD / d4; + const shiftX = K2 * diffX; + const shiftY = K2 * diffY; + let x0 = x1; + let y0 = y1; + x1 = x22; + y1 = y22; + x22 += shiftX; + y22 += shiftY; + this.#points?.push(x2, y4); + const nX = -shiftY / diffD; + const nY = shiftX / diffD; + const thX = nX * this.#thickness; + const thY = nY * this.#thickness; + this.#last.set(this.#last.subarray(2, 8), 0); + this.#last.set([x22 + thX, y22 + thY], 4); + this.#last.set(this.#last.subarray(14, 18), 12); + this.#last.set([x22 - thX, y22 - thY], 16); + if (isNaN(this.#last[6])) { + if (this.#top.length === 0) { + this.#last.set([x1 + thX, y1 + thY], 2); + this.#top.push(NaN, NaN, NaN, NaN, (x1 + thX - layerX) / layerWidth, (y1 + thY - layerY) / layerHeight); + this.#last.set([x1 - thX, y1 - thY], 14); + this.#bottom.push(NaN, NaN, NaN, NaN, (x1 - thX - layerX) / layerWidth, (y1 - thY - layerY) / layerHeight); + } + this.#last.set([x0, y0, x1, y1, x22, y22], 6); + return !this.isEmpty(); + } + this.#last.set([x0, y0, x1, y1, x22, y22], 6); + const angle = Math.abs(Math.atan2(y0 - y1, x0 - x1) - Math.atan2(shiftY, shiftX)); + if (angle < Math.PI / 2) { + [x1, y1, x22, y22] = this.#last.subarray(2, 6); + this.#top.push(NaN, NaN, NaN, NaN, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight); + [x1, y1, x0, y0] = this.#last.subarray(14, 18); + this.#bottom.push(NaN, NaN, NaN, NaN, ((x0 + x1) / 2 - layerX) / layerWidth, ((y0 + y1) / 2 - layerY) / layerHeight); + return true; + } + [x0, y0, x1, y1, x22, y22] = this.#last.subarray(0, 6); + this.#top.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x22) / 6 - layerX) / layerWidth, ((5 * y1 + y22) / 6 - layerY) / layerHeight, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight); + [x22, y22, x1, y1, x0, y0] = this.#last.subarray(12, 18); + this.#bottom.push(((x0 + 5 * x1) / 6 - layerX) / layerWidth, ((y0 + 5 * y1) / 6 - layerY) / layerHeight, ((5 * x1 + x22) / 6 - layerX) / layerWidth, ((5 * y1 + y22) / 6 - layerY) / layerHeight, ((x1 + x22) / 2 - layerX) / layerWidth, ((y1 + y22) / 2 - layerY) / layerHeight); + return true; + } + toSVGPath() { + if (this.isEmpty()) { + return ""; + } + const top = this.#top; + const bottom = this.#bottom; + if (isNaN(this.#last[6]) && !this.isEmpty()) { + return this.#toSVGPathTwoPoints(); + } + const buffer = []; + buffer.push(`M${top[4]} ${top[5]}`); + for (let i7 = 6; i7 < top.length; i7 += 6) { + if (isNaN(top[i7])) { + buffer.push(`L${top[i7 + 4]} ${top[i7 + 5]}`); + } else { + buffer.push(`C${top[i7]} ${top[i7 + 1]} ${top[i7 + 2]} ${top[i7 + 3]} ${top[i7 + 4]} ${top[i7 + 5]}`); + } + } + this.#toSVGPathEnd(buffer); + for (let i7 = bottom.length - 6; i7 >= 6; i7 -= 6) { + if (isNaN(bottom[i7])) { + buffer.push(`L${bottom[i7 + 4]} ${bottom[i7 + 5]}`); + } else { + buffer.push(`C${bottom[i7]} ${bottom[i7 + 1]} ${bottom[i7 + 2]} ${bottom[i7 + 3]} ${bottom[i7 + 4]} ${bottom[i7 + 5]}`); + } + } + this.#toSVGPathStart(buffer); + return buffer.join(" "); + } + #toSVGPathTwoPoints() { + const [x2, y4, width, height] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + return `M${(this.#last[2] - x2) / width} ${(this.#last[3] - y4) / height} L${(this.#last[4] - x2) / width} ${(this.#last[5] - y4) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(this.#last[16] - x2) / width} ${(this.#last[17] - y4) / height} L${(this.#last[14] - x2) / width} ${(this.#last[15] - y4) / height} Z`; + } + #toSVGPathStart(buffer) { + const bottom = this.#bottom; + buffer.push(`L${bottom[4]} ${bottom[5]} Z`); + } + #toSVGPathEnd(buffer) { + const [x2, y4, width, height] = this.#box; + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + buffer.push(`L${(lastTop[0] - x2) / width} ${(lastTop[1] - y4) / height} L${lastTopX} ${lastTopY} L${lastBottomX} ${lastBottomY} L${(lastBottom[0] - x2) / width} ${(lastBottom[1] - y4) / height}`); + } + newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { + return new FreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR); + } + getOutlines() { + const top = this.#top; + const bottom = this.#bottom; + const last = this.#last; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const points = new Float32Array((this.#points?.length ?? 0) + 2); + for (let i7 = 0, ii = points.length - 2; i7 < ii; i7 += 2) { + points[i7] = (this.#points[i7] - layerX) / layerWidth; + points[i7 + 1] = (this.#points[i7 + 1] - layerY) / layerHeight; + } + points[points.length - 2] = (this.#lastX - layerX) / layerWidth; + points[points.length - 1] = (this.#lastY - layerY) / layerHeight; + if (isNaN(last[6]) && !this.isEmpty()) { + return this.#getOutlineTwoPoints(points); + } + const outline = new Float32Array(this.#top.length + 24 + this.#bottom.length); + let N3 = top.length; + for (let i7 = 0; i7 < N3; i7 += 2) { + if (isNaN(top[i7])) { + outline[i7] = outline[i7 + 1] = NaN; + continue; + } + outline[i7] = top[i7]; + outline[i7 + 1] = top[i7 + 1]; + } + N3 = this.#getOutlineEnd(outline, N3); + for (let i7 = bottom.length - 6; i7 >= 6; i7 -= 6) { + for (let j3 = 0; j3 < 6; j3 += 2) { + if (isNaN(bottom[i7 + j3])) { + outline[N3] = outline[N3 + 1] = NaN; + N3 += 2; + continue; + } + outline[N3] = bottom[i7 + j3]; + outline[N3 + 1] = bottom[i7 + j3 + 1]; + N3 += 2; + } + } + this.#getOutlineStart(outline, N3); + return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + #getOutlineTwoPoints(points) { + const last = this.#last; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + const outline = new Float32Array(36); + outline.set([NaN, NaN, NaN, NaN, (last[2] - layerX) / layerWidth, (last[3] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[4] - layerX) / layerWidth, (last[5] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (last[16] - layerX) / layerWidth, (last[17] - layerY) / layerHeight, NaN, NaN, NaN, NaN, (last[14] - layerX) / layerWidth, (last[15] - layerY) / layerHeight], 0); + return this.newFreeDrawOutline(outline, points, this.#box, this.#scaleFactor, this.#innerMargin, this.#isLTR); + } + #getOutlineStart(outline, pos) { + const bottom = this.#bottom; + outline.set([NaN, NaN, NaN, NaN, bottom[4], bottom[5]], pos); + return pos += 6; + } + #getOutlineEnd(outline, pos) { + const lastTop = this.#last.subarray(4, 6); + const lastBottom = this.#last.subarray(16, 18); + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const [lastTopX, lastTopY, lastBottomX, lastBottomY] = this.#getLastCoords(); + outline.set([NaN, NaN, NaN, NaN, (lastTop[0] - layerX) / layerWidth, (lastTop[1] - layerY) / layerHeight, NaN, NaN, NaN, NaN, lastTopX, lastTopY, NaN, NaN, NaN, NaN, lastBottomX, lastBottomY, NaN, NaN, NaN, NaN, (lastBottom[0] - layerX) / layerWidth, (lastBottom[1] - layerY) / layerHeight], pos); + return pos += 24; + } + }; + FreeDrawOutline = class extends Outline { + #box; + #bbox = new Float32Array(4); + #innerMargin; + #isLTR; + #points; + #scaleFactor; + #outline; + constructor(outline, points, box, scaleFactor, innerMargin, isLTR) { + super(); + this.#outline = outline; + this.#points = points; + this.#box = box; + this.#scaleFactor = scaleFactor; + this.#innerMargin = innerMargin; + this.#isLTR = isLTR; + this.firstPoint = [NaN, NaN]; + this.lastPoint = [NaN, NaN]; + this.#computeMinMax(isLTR); + const [x2, y4, width, height] = this.#bbox; + for (let i7 = 0, ii = outline.length; i7 < ii; i7 += 2) { + outline[i7] = (outline[i7] - x2) / width; + outline[i7 + 1] = (outline[i7 + 1] - y4) / height; + } + for (let i7 = 0, ii = points.length; i7 < ii; i7 += 2) { + points[i7] = (points[i7] - x2) / width; + points[i7 + 1] = (points[i7 + 1] - y4) / height; + } + } + toSVGPath() { + const buffer = [`M${this.#outline[4]} ${this.#outline[5]}`]; + for (let i7 = 6, ii = this.#outline.length; i7 < ii; i7 += 6) { + if (isNaN(this.#outline[i7])) { + buffer.push(`L${this.#outline[i7 + 4]} ${this.#outline[i7 + 5]}`); + continue; + } + buffer.push(`C${this.#outline[i7]} ${this.#outline[i7 + 1]} ${this.#outline[i7 + 2]} ${this.#outline[i7 + 3]} ${this.#outline[i7 + 4]} ${this.#outline[i7 + 5]}`); + } + buffer.push("Z"); + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], rotation) { + const width = trX - blX; + const height = trY - blY; + let outline; + let points; + switch (rotation) { + case 0: + outline = Outline._rescale(this.#outline, blX, trY, width, -height); + points = Outline._rescale(this.#points, blX, trY, width, -height); + break; + case 90: + outline = Outline._rescaleAndSwap(this.#outline, blX, blY, width, height); + points = Outline._rescaleAndSwap(this.#points, blX, blY, width, height); + break; + case 180: + outline = Outline._rescale(this.#outline, trX, blY, -width, height); + points = Outline._rescale(this.#points, trX, blY, -width, height); + break; + case 270: + outline = Outline._rescaleAndSwap(this.#outline, trX, trY, -width, -height); + points = Outline._rescaleAndSwap(this.#points, trX, trY, -width, -height); + break; + } + return { + outline: Array.from(outline), + points: [Array.from(points)] + }; + } + #computeMinMax(isLTR) { + const outline = this.#outline; + let lastX = outline[4]; + let lastY = outline[5]; + const minMax = [lastX, lastY, lastX, lastY]; + let firstPointX = lastX; + let firstPointY = lastY; + let lastPointX = lastX; + let lastPointY = lastY; + const ltrCallback = isLTR ? Math.max : Math.min; + const bezierBbox = new Float32Array(4); + for (let i7 = 6, ii = outline.length; i7 < ii; i7 += 6) { + const x2 = outline[i7 + 4], y4 = outline[i7 + 5]; + if (isNaN(outline[i7])) { + Util.pointBoundingBox(x2, y4, minMax); + if (firstPointY > y4) { + firstPointX = x2; + firstPointY = y4; + } else if (firstPointY === y4) { + firstPointX = ltrCallback(firstPointX, x2); + } + if (lastPointY < y4) { + lastPointX = x2; + lastPointY = y4; + } else if (lastPointY === y4) { + lastPointX = ltrCallback(lastPointX, x2); + } + } else { + bezierBbox[0] = bezierBbox[1] = Infinity; + bezierBbox[2] = bezierBbox[3] = -Infinity; + Util.bezierBoundingBox(lastX, lastY, ...outline.slice(i7, i7 + 6), bezierBbox); + Util.rectBoundingBox(bezierBbox[0], bezierBbox[1], bezierBbox[2], bezierBbox[3], minMax); + if (firstPointY > bezierBbox[1]) { + firstPointX = bezierBbox[0]; + firstPointY = bezierBbox[1]; + } else if (firstPointY === bezierBbox[1]) { + firstPointX = ltrCallback(firstPointX, bezierBbox[0]); + } + if (lastPointY < bezierBbox[3]) { + lastPointX = bezierBbox[2]; + lastPointY = bezierBbox[3]; + } else if (lastPointY === bezierBbox[3]) { + lastPointX = ltrCallback(lastPointX, bezierBbox[2]); + } + } + lastX = x2; + lastY = y4; + } + const bbox = this.#bbox; + bbox[0] = minMax[0] - this.#innerMargin; + bbox[1] = minMax[1] - this.#innerMargin; + bbox[2] = minMax[2] - minMax[0] + 2 * this.#innerMargin; + bbox[3] = minMax[3] - minMax[1] + 2 * this.#innerMargin; + this.firstPoint = [firstPointX, firstPointY]; + this.lastPoint = [lastPointX, lastPointY]; + } + get box() { + return this.#bbox; + } + newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + return new FreeDrawOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); + } + getNewOutline(thickness, innerMargin) { + const [x2, y4, width, height] = this.#bbox; + const [layerX, layerY, layerWidth, layerHeight] = this.#box; + const sx = width * layerWidth; + const sy = height * layerHeight; + const tx = x2 * layerWidth + layerX; + const ty = y4 * layerHeight + layerY; + const outliner = this.newOutliner({ + x: this.#points[0] * sx + tx, + y: this.#points[1] * sy + ty + }, this.#box, this.#scaleFactor, thickness, this.#isLTR, innerMargin ?? this.#innerMargin); + for (let i7 = 2; i7 < this.#points.length; i7 += 2) { + outliner.add({ + x: this.#points[i7] * sx + tx, + y: this.#points[i7 + 1] * sy + ty + }); + } + return outliner.getOutlines(); + } + }; + HighlightOutliner = class { + #box; + #firstPoint; + #lastPoint; + #verticalEdges = []; + #intervals = []; + constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) { + const minMax = [Infinity, Infinity, -Infinity, -Infinity]; + const NUMBER_OF_DIGITS = 4; + const EPSILON2 = 10 ** -NUMBER_OF_DIGITS; + for (const { + x: x2, + y: y4, + width, + height + } of boxes) { + const x1 = Math.floor((x2 - borderWidth) / EPSILON2) * EPSILON2; + const x22 = Math.ceil((x2 + width + borderWidth) / EPSILON2) * EPSILON2; + const y1 = Math.floor((y4 - borderWidth) / EPSILON2) * EPSILON2; + const y22 = Math.ceil((y4 + height + borderWidth) / EPSILON2) * EPSILON2; + const left = [x1, y1, y22, true]; + const right = [x22, y1, y22, false]; + this.#verticalEdges.push(left, right); + Util.rectBoundingBox(x1, y1, x22, y22, minMax); + } + const bboxWidth = minMax[2] - minMax[0] + 2 * innerMargin; + const bboxHeight = minMax[3] - minMax[1] + 2 * innerMargin; + const shiftedMinX = minMax[0] - innerMargin; + const shiftedMinY = minMax[1] - innerMargin; + let firstPointX = isLTR ? -Infinity : Infinity; + let firstPointY = Infinity; + const lastEdge = this.#verticalEdges.at(isLTR ? -1 : -2); + const lastPoint = [lastEdge[0], lastEdge[2]]; + for (const edge of this.#verticalEdges) { + const [x2, y1, y22, left] = edge; + if (!left && isLTR) { + if (y1 < firstPointY) { + firstPointY = y1; + firstPointX = x2; + } else if (y1 === firstPointY) { + firstPointX = Math.max(firstPointX, x2); + } + } else if (left && !isLTR) { + if (y1 < firstPointY) { + firstPointY = y1; + firstPointX = x2; + } else if (y1 === firstPointY) { + firstPointX = Math.min(firstPointX, x2); + } + } + edge[0] = (x2 - shiftedMinX) / bboxWidth; + edge[1] = (y1 - shiftedMinY) / bboxHeight; + edge[2] = (y22 - shiftedMinY) / bboxHeight; + } + this.#box = new Float32Array([shiftedMinX, shiftedMinY, bboxWidth, bboxHeight]); + this.#firstPoint = [firstPointX, firstPointY]; + this.#lastPoint = lastPoint; + } + getOutlines() { + this.#verticalEdges.sort((a3, b4) => a3[0] - b4[0] || a3[1] - b4[1] || a3[2] - b4[2]); + const outlineVerticalEdges = []; + for (const edge of this.#verticalEdges) { + if (edge[3]) { + outlineVerticalEdges.push(...this.#breakEdge(edge)); + this.#insert(edge); + } else { + this.#remove(edge); + outlineVerticalEdges.push(...this.#breakEdge(edge)); + } + } + return this.#getOutlines(outlineVerticalEdges); + } + #getOutlines(outlineVerticalEdges) { + const edges = []; + const allEdges = /* @__PURE__ */ new Set(); + for (const edge of outlineVerticalEdges) { + const [x2, y1, y22] = edge; + edges.push([x2, y1, edge], [x2, y22, edge]); + } + edges.sort((a3, b4) => a3[1] - b4[1] || a3[0] - b4[0]); + for (let i7 = 0, ii = edges.length; i7 < ii; i7 += 2) { + const edge1 = edges[i7][2]; + const edge2 = edges[i7 + 1][2]; + edge1.push(edge2); + edge2.push(edge1); + allEdges.add(edge1); + allEdges.add(edge2); + } + const outlines = []; + let outline; + while (allEdges.size > 0) { + const edge = allEdges.values().next().value; + let [x2, y1, y22, edge1, edge2] = edge; + allEdges.delete(edge); + let lastPointX = x2; + let lastPointY = y1; + outline = [x2, y22]; + outlines.push(outline); + while (true) { + let e9; + if (allEdges.has(edge1)) { + e9 = edge1; + } else if (allEdges.has(edge2)) { + e9 = edge2; + } else { + break; + } + allEdges.delete(e9); + [x2, y1, y22, edge1, edge2] = e9; + if (lastPointX !== x2) { + outline.push(lastPointX, lastPointY, x2, lastPointY === y1 ? y1 : y22); + lastPointX = x2; + } + lastPointY = lastPointY === y1 ? y22 : y1; + } + outline.push(lastPointX, lastPointY); + } + return new HighlightOutline(outlines, this.#box, this.#firstPoint, this.#lastPoint); + } + #binarySearch(y4) { + const array = this.#intervals; + let start = 0; + let end = array.length - 1; + while (start <= end) { + const middle = start + end >> 1; + const y1 = array[middle][0]; + if (y1 === y4) { + return middle; + } + if (y1 < y4) { + start = middle + 1; + } else { + end = middle - 1; + } + } + return end + 1; + } + #insert([, y1, y22]) { + const index2 = this.#binarySearch(y1); + this.#intervals.splice(index2, 0, [y1, y22]); + } + #remove([, y1, y22]) { + const index2 = this.#binarySearch(y1); + for (let i7 = index2; i7 < this.#intervals.length; i7++) { + const [start, end] = this.#intervals[i7]; + if (start !== y1) { + break; + } + if (start === y1 && end === y22) { + this.#intervals.splice(i7, 1); + return; + } + } + for (let i7 = index2 - 1; i7 >= 0; i7--) { + const [start, end] = this.#intervals[i7]; + if (start !== y1) { + break; + } + if (start === y1 && end === y22) { + this.#intervals.splice(i7, 1); + return; + } + } + } + #breakEdge(edge) { + const [x2, y1, y22] = edge; + const results = [[x2, y1, y22]]; + const index2 = this.#binarySearch(y22); + for (let i7 = 0; i7 < index2; i7++) { + const [start, end] = this.#intervals[i7]; + for (let j3 = 0, jj = results.length; j3 < jj; j3++) { + const [, y32, y4] = results[j3]; + if (end <= y32 || y4 <= start) { + continue; + } + if (y32 >= start) { + if (y4 > end) { + results[j3][1] = end; + } else { + if (jj === 1) { + return []; + } + results.splice(j3, 1); + j3--; + jj--; + } + continue; + } + results[j3][2] = start; + if (y4 > end) { + results.push([x2, end, y4]); + } + } + } + return results; + } + }; + HighlightOutline = class extends Outline { + #box; + #outlines; + constructor(outlines, box, firstPoint, lastPoint) { + super(); + this.#outlines = outlines; + this.#box = box; + this.firstPoint = firstPoint; + this.lastPoint = lastPoint; + } + toSVGPath() { + const buffer = []; + for (const polygon of this.#outlines) { + let [prevX, prevY] = polygon; + buffer.push(`M${prevX} ${prevY}`); + for (let i7 = 2; i7 < polygon.length; i7 += 2) { + const x2 = polygon[i7]; + const y4 = polygon[i7 + 1]; + if (x2 === prevX) { + buffer.push(`V${y4}`); + prevY = y4; + } else if (y4 === prevY) { + buffer.push(`H${x2}`); + prevX = x2; + } + } + buffer.push("Z"); + } + return buffer.join(" "); + } + serialize([blX, blY, trX, trY], _rotation) { + const outlines = []; + const width = trX - blX; + const height = trY - blY; + for (const outline of this.#outlines) { + const points = new Array(outline.length); + for (let i7 = 0; i7 < outline.length; i7 += 2) { + points[i7] = blX + outline[i7] * width; + points[i7 + 1] = trY - outline[i7 + 1] * height; + } + outlines.push(points); + } + return outlines; + } + get box() { + return this.#box; + } + get classNamesForOutlining() { + return ["highlightOutline"]; + } + }; + FreeHighlightOutliner = class extends FreeDrawOutliner { + newFreeDrawOutline(outline, points, box, scaleFactor, innerMargin, isLTR) { + return new FreeHighlightOutline(outline, points, box, scaleFactor, innerMargin, isLTR); + } + }; + FreeHighlightOutline = class extends FreeDrawOutline { + newOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin = 0) { + return new FreeHighlightOutliner(point, box, scaleFactor, thickness, isLTR, innerMargin); + } + }; + HighlightEditor = class _HighlightEditor extends AnnotationEditor { + #anchorNode = null; + #anchorOffset = 0; + #boxes; + #clipPathId = null; + #colorPicker = null; + #focusOutlines = null; + #focusNode = null; + #focusOffset = 0; + #highlightDiv = null; + #highlightOutlines = null; + #id = null; + #isFreeHighlight = false; + #firstPoint = null; + #lastPoint = null; + #outlineId = null; + #text = ""; + #thickness; + #methodOfCreation = ""; + static _defaultColor = null; + static _defaultOpacity = 1; + static _defaultThickness = 12; + static _type = "highlight"; + static _editorType = AnnotationEditorType.HIGHLIGHT; + static _freeHighlightId = -1; + static _freeHighlight = null; + static _freeHighlightClipId = ""; + static get _keyboardManager() { + const proto = _HighlightEditor.prototype; + return shadow(this, "_keyboardManager", new KeyboardManager([[["ArrowLeft", "mac+ArrowLeft"], proto._moveCaret, { + args: [0] + }], [["ArrowRight", "mac+ArrowRight"], proto._moveCaret, { + args: [1] + }], [["ArrowUp", "mac+ArrowUp"], proto._moveCaret, { + args: [2] + }], [["ArrowDown", "mac+ArrowDown"], proto._moveCaret, { + args: [3] + }]])); + } + constructor(params) { + super({ + ...params, + name: "highlightEditor" + }); + this.color = params.color || _HighlightEditor._defaultColor; + this.#thickness = params.thickness || _HighlightEditor._defaultThickness; + this.opacity = params.opacity || _HighlightEditor._defaultOpacity; + this.#boxes = params.boxes || null; + this.#methodOfCreation = params.methodOfCreation || ""; + this.#text = params.text || ""; + this._isDraggable = false; + this.defaultL10nId = "pdfjs-editor-highlight-editor"; + if (params.highlightId > -1) { + this.#isFreeHighlight = true; + this.#createFreeOutlines(params); + this.#addToDrawLayer(); + } else if (this.#boxes) { + this.#anchorNode = params.anchorNode; + this.#anchorOffset = params.anchorOffset; + this.#focusNode = params.focusNode; + this.#focusOffset = params.focusOffset; + this.#createOutlines(); + this.#addToDrawLayer(); + this.rotate(this.rotation); + } + if (!this.annotationElementId) { + this._uiManager.a11yAlert("pdfjs-editor-highlight-added-alert"); + } + } + get telemetryInitialData() { + return { + action: "added", + type: this.#isFreeHighlight ? "free_highlight" : "highlight", + color: this._uiManager.getNonHCMColorName(this.color), + thickness: this.#thickness, + methodOfCreation: this.#methodOfCreation + }; + } + get telemetryFinalData() { + return { + type: "highlight", + color: this._uiManager.getNonHCMColorName(this.color) + }; + } + static computeTelemetryFinalData(data) { + return { + numberOfColors: data.get("color").size + }; + } + #createOutlines() { + const outliner = new HighlightOutliner(this.#boxes, 1e-3); + this.#highlightOutlines = outliner.getOutlines(); + [this.x, this.y, this.width, this.height] = this.#highlightOutlines.box; + const outlinerForOutline = new HighlightOutliner(this.#boxes, 25e-4, 1e-3, this._uiManager.direction === "ltr"); + this.#focusOutlines = outlinerForOutline.getOutlines(); + const { + firstPoint + } = this.#highlightOutlines; + this.#firstPoint = [(firstPoint[0] - this.x) / this.width, (firstPoint[1] - this.y) / this.height]; + const { + lastPoint + } = this.#focusOutlines; + this.#lastPoint = [(lastPoint[0] - this.x) / this.width, (lastPoint[1] - this.y) / this.height]; + } + #createFreeOutlines({ + highlightOutlines, + highlightId, + clipPathId + }) { + this.#highlightOutlines = highlightOutlines; + const extraThickness = 1.5; + this.#focusOutlines = highlightOutlines.getNewOutline(this.#thickness / 2 + extraThickness, 25e-4); + if (highlightId >= 0) { + this.#id = highlightId; + this.#clipPathId = clipPathId; + this.parent.drawLayer.finalizeDraw(highlightId, { + bbox: highlightOutlines.box, + path: { + d: highlightOutlines.toSVGPath() + } + }); + this.#outlineId = this.parent.drawLayer.drawOutline({ + rootClass: { + highlightOutline: true, + free: true + }, + bbox: this.#focusOutlines.box, + path: { + d: this.#focusOutlines.toSVGPath() + } + }, true); + } else if (this.parent) { + const angle = this.parent.viewport.rotation; + this.parent.drawLayer.updateProperties(this.#id, { + bbox: _HighlightEditor.#rotateBbox(this.#highlightOutlines.box, (angle - this.rotation + 360) % 360), + path: { + d: highlightOutlines.toSVGPath() + } + }); + this.parent.drawLayer.updateProperties(this.#outlineId, { + bbox: _HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), + path: { + d: this.#focusOutlines.toSVGPath() + } + }); + } + const [x2, y4, width, height] = highlightOutlines.box; + switch (this.rotation) { + case 0: + this.x = x2; + this.y = y4; + this.width = width; + this.height = height; + break; + case 90: { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = y4; + this.y = 1 - x2; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + case 180: + this.x = 1 - x2; + this.y = 1 - y4; + this.width = width; + this.height = height; + break; + case 270: { + const [pageWidth, pageHeight] = this.parentDimensions; + this.x = 1 - y4; + this.y = x2; + this.width = width * pageHeight / pageWidth; + this.height = height * pageWidth / pageHeight; + break; + } + } + const { + firstPoint + } = highlightOutlines; + this.#firstPoint = [(firstPoint[0] - x2) / width, (firstPoint[1] - y4) / height]; + const { + lastPoint + } = this.#focusOutlines; + this.#lastPoint = [(lastPoint[0] - x2) / width, (lastPoint[1] - y4) / height]; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + _HighlightEditor._defaultColor ||= uiManager.highlightColors?.values().next().value || "#fff066"; + } + static updateDefaultParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_COLOR: + _HighlightEditor._defaultColor = value; + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + _HighlightEditor._defaultThickness = value; + break; + } + } + translateInPage(x2, y4) { + } + get toolbarPosition() { + return this.#lastPoint; + } + get commentButtonPosition() { + return this.#firstPoint; + } + updateParams(type, value) { + switch (type) { + case AnnotationEditorParamsType.HIGHLIGHT_COLOR: + this.#updateColor(value); + break; + case AnnotationEditorParamsType.HIGHLIGHT_THICKNESS: + this.#updateThickness(value); + break; + } + } + static get defaultPropertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, _HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, _HighlightEditor._defaultThickness]]; + } + get propertiesToUpdate() { + return [[AnnotationEditorParamsType.HIGHLIGHT_COLOR, this.color || _HighlightEditor._defaultColor], [AnnotationEditorParamsType.HIGHLIGHT_THICKNESS, this.#thickness || _HighlightEditor._defaultThickness], [AnnotationEditorParamsType.HIGHLIGHT_FREE, this.#isFreeHighlight]]; + } + onUpdatedColor() { + this.parent?.drawLayer.updateProperties(this.#id, { + root: { + fill: this.color, + "fill-opacity": this.opacity + } + }); + this.#colorPicker?.updateColor(this.color); + super.onUpdatedColor(); + } + #updateColor(color2) { + const setColorAndOpacity = (col, opa) => { + this.color = col; + this.opacity = opa; + this.onUpdatedColor(); + }; + const savedColor = this.color; + const savedOpacity = this.opacity; + this.addCommands({ + cmd: setColorAndOpacity.bind(this, color2, _HighlightEditor._defaultOpacity), + undo: setColorAndOpacity.bind(this, savedColor, savedOpacity), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.HIGHLIGHT_COLOR, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "color_changed", + color: this._uiManager.getNonHCMColorName(color2) + }, true); + } + #updateThickness(thickness) { + const savedThickness = this.#thickness; + const setThickness = (th) => { + this.#thickness = th; + this.#changeThickness(th); + }; + this.addCommands({ + cmd: setThickness.bind(this, thickness), + undo: setThickness.bind(this, savedThickness), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type: AnnotationEditorParamsType.INK_THICKNESS, + overwriteIfSameType: true, + keepUndo: true + }); + this._reportTelemetry({ + action: "thickness_changed", + thickness + }, true); + } + get toolbarButtons() { + if (this._uiManager.highlightColors) { + const colorPicker = this.#colorPicker = new ColorPicker({ + editor: this + }); + return [["colorPicker", colorPicker]]; + } + return super.toolbarButtons; + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + fixAndSetPosition() { + return super.fixAndSetPosition(this.#getRotation()); + } + getBaseTranslation() { + return [0, 0]; + } + getRect(tx, ty) { + return super.getRect(tx, ty, this.#getRotation()); + } + onceAdded(focus) { + if (!this.annotationElementId) { + this.parent.addUndoableEditor(this); + } + if (focus) { + this.div.focus(); + } + } + remove() { + this.#cleanDrawLayer(); + this._reportTelemetry({ + action: "deleted" + }); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this.#cleanDrawLayer(); + } else if (parent) { + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + this.show(this._isVisible); + if (mustBeSelected) { + this.select(); + } + } + #changeThickness(thickness) { + if (!this.#isFreeHighlight) { + return; + } + this.#createFreeOutlines({ + highlightOutlines: this.#highlightOutlines.getNewOutline(thickness / 2) + }); + this.fixAndSetPosition(); + this.setDims(); + } + #cleanDrawLayer() { + if (this.#id === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this.#id); + this.#id = null; + this.parent.drawLayer.remove(this.#outlineId); + this.#outlineId = null; + } + #addToDrawLayer(parent = this.parent) { + if (this.#id !== null) { + return; + } + ({ + id: this.#id, + clipPathId: this.#clipPathId + } = parent.drawLayer.draw({ + bbox: this.#highlightOutlines.box, + root: { + viewBox: "0 0 1 1", + fill: this.color, + "fill-opacity": this.opacity + }, + rootClass: { + highlight: true, + free: this.#isFreeHighlight + }, + path: { + d: this.#highlightOutlines.toSVGPath() + } + }, false, true)); + this.#outlineId = parent.drawLayer.drawOutline({ + rootClass: { + highlightOutline: true, + free: this.#isFreeHighlight + }, + bbox: this.#focusOutlines.box, + path: { + d: this.#focusOutlines.toSVGPath() + } + }, this.#isFreeHighlight); + if (this.#highlightDiv) { + this.#highlightDiv.style.clipPath = this.#clipPathId; + } + } + static #rotateBbox([x2, y4, width, height], angle) { + switch (angle) { + case 90: + return [1 - y4 - height, x2, height, width]; + case 180: + return [1 - x2 - width, 1 - y4 - height, width, height]; + case 270: + return [y4, 1 - x2 - width, height, width]; + } + return [x2, y4, width, height]; + } + rotate(angle) { + const { + drawLayer + } = this.parent; + let box; + if (this.#isFreeHighlight) { + angle = (angle - this.rotation + 360) % 360; + box = _HighlightEditor.#rotateBbox(this.#highlightOutlines.box, angle); + } else { + box = _HighlightEditor.#rotateBbox([this.x, this.y, this.width, this.height], angle); + } + drawLayer.updateProperties(this.#id, { + bbox: box, + root: { + "data-main-rotation": angle + } + }); + drawLayer.updateProperties(this.#outlineId, { + bbox: _HighlightEditor.#rotateBbox(this.#focusOutlines.box, angle), + root: { + "data-main-rotation": angle + } + }); + } + render() { + if (this.div) { + return this.div; + } + const div = super.render(); + if (this.#text) { + div.setAttribute("aria-label", this.#text); + div.setAttribute("role", "mark"); + } + if (this.#isFreeHighlight) { + div.classList.add("free"); + } else { + this.div.addEventListener("keydown", this.#keydown.bind(this), { + signal: this._uiManager._signal + }); + } + const highlightDiv = this.#highlightDiv = document.createElement("div"); + div.append(highlightDiv); + highlightDiv.setAttribute("aria-hidden", "true"); + highlightDiv.className = "internal"; + highlightDiv.style.clipPath = this.#clipPathId; + this.setDims(); + bindEvents(this, this.#highlightDiv, ["pointerover", "pointerleave"]); + this.enableEditing(); + return div; + } + pointerover() { + if (!this.isSelected) { + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: true + } + }); + } + } + pointerleave() { + if (!this.isSelected) { + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: false + } + }); + } + } + #keydown(event) { + _HighlightEditor._keyboardManager.exec(this, event); + } + _moveCaret(direction) { + this.parent.unselect(this); + switch (direction) { + case 0: + case 2: + this.#setCaret(true); + break; + case 1: + case 3: + this.#setCaret(false); + break; + } + } + #setCaret(start) { + if (!this.#anchorNode) { + return; + } + const selection = window.getSelection(); + if (start) { + selection.setPosition(this.#anchorNode, this.#anchorOffset); + } else { + selection.setPosition(this.#focusNode, this.#focusOffset); + } + } + select() { + super.select(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hovered: false, + selected: true + } + }); + } + unselect() { + super.unselect(); + if (!this.#outlineId) { + return; + } + this.parent?.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + selected: false + } + }); + if (!this.#isFreeHighlight) { + this.#setCaret(false); + } + } + get _mustFixPosition() { + return !this.#isFreeHighlight; + } + show(visible = this._isVisible) { + super.show(visible); + if (this.parent) { + this.parent.drawLayer.updateProperties(this.#id, { + rootClass: { + hidden: !visible + } + }); + this.parent.drawLayer.updateProperties(this.#outlineId, { + rootClass: { + hidden: !visible + } + }); + } + } + #getRotation() { + return this.#isFreeHighlight ? this.rotation : 0; + } + #serializeBoxes() { + if (this.#isFreeHighlight) { + return null; + } + const [pageWidth, pageHeight] = this.pageDimensions; + const [pageX, pageY] = this.pageTranslation; + const boxes = this.#boxes; + const quadPoints = new Float32Array(boxes.length * 8); + let i7 = 0; + for (const { + x: x2, + y: y4, + width, + height + } of boxes) { + const sx = x2 * pageWidth + pageX; + const sy = (1 - y4) * pageHeight + pageY; + quadPoints[i7] = quadPoints[i7 + 4] = sx; + quadPoints[i7 + 1] = quadPoints[i7 + 3] = sy; + quadPoints[i7 + 2] = quadPoints[i7 + 6] = sx + width * pageWidth; + quadPoints[i7 + 5] = quadPoints[i7 + 7] = sy - height * pageHeight; + i7 += 8; + } + return quadPoints; + } + #serializeOutlines(rect) { + return this.#highlightOutlines.serialize(rect, this.#getRotation()); + } + static startHighlighting(parent, isLTR, { + target: textLayer, + x: x2, + y: y4 + }) { + const { + x: layerX, + y: layerY, + width: parentWidth, + height: parentHeight + } = textLayer.getBoundingClientRect(); + const ac = new AbortController(); + const signal = parent.combinedSignal(ac); + const pointerUpCallback = (e9) => { + ac.abort(); + this.#endHighlight(parent, e9); + }; + window.addEventListener("blur", pointerUpCallback, { + signal + }); + window.addEventListener("pointerup", pointerUpCallback, { + signal + }); + window.addEventListener("pointerdown", stopEvent, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + textLayer.addEventListener("pointermove", this.#highlightMove.bind(this, parent), { + signal + }); + this._freeHighlight = new FreeHighlightOutliner({ + x: x2, + y: y4 + }, [layerX, layerY, parentWidth, parentHeight], parent.scale, this._defaultThickness / 2, isLTR, 1e-3); + ({ + id: this._freeHighlightId, + clipPathId: this._freeHighlightClipId + } = parent.drawLayer.draw({ + bbox: [0, 0, 1, 1], + root: { + viewBox: "0 0 1 1", + fill: this._defaultColor, + "fill-opacity": this._defaultOpacity + }, + rootClass: { + highlight: true, + free: true + }, + path: { + d: this._freeHighlight.toSVGPath() + } + }, true, true)); + } + static #highlightMove(parent, event) { + if (this._freeHighlight.add(event)) { + parent.drawLayer.updateProperties(this._freeHighlightId, { + path: { + d: this._freeHighlight.toSVGPath() + } + }); + } + } + static #endHighlight(parent, event) { + if (!this._freeHighlight.isEmpty()) { + parent.createAndAddNewEditor(event, false, { + highlightId: this._freeHighlightId, + highlightOutlines: this._freeHighlight.getOutlines(), + clipPathId: this._freeHighlightClipId, + methodOfCreation: "main_toolbar" + }); + } else { + parent.drawLayer.remove(this._freeHighlightId); + } + this._freeHighlightId = -1; + this._freeHighlight = null; + this._freeHighlightClipId = ""; + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof HighlightAnnotationElement) { + const { + data: { + quadPoints: quadPoints2, + rect, + rotation, + id, + color: color3, + opacity: opacity2, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color3), + opacity: opacity2, + quadPoints: quadPoints2, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } else if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists: inkLists2, + rect, + rotation, + id, + color: color3, + borderStyle: { + rawWidth: thickness + }, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.HIGHLIGHT, + color: Array.from(color3), + thickness, + inkLists: inkLists2, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } + const { + color: color2, + quadPoints, + inkLists, + opacity + } = data; + const editor = await super.deserialize(data, parent, uiManager); + editor.color = Util.makeHexColor(...color2); + editor.opacity = opacity || 1; + if (inkLists) { + editor.#thickness = data.thickness; + } + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + const [pageWidth, pageHeight] = editor.pageDimensions; + const [pageX, pageY] = editor.pageTranslation; + if (quadPoints) { + const boxes = editor.#boxes = []; + for (let i7 = 0; i7 < quadPoints.length; i7 += 8) { + boxes.push({ + x: (quadPoints[i7] - pageX) / pageWidth, + y: 1 - (quadPoints[i7 + 1] - pageY) / pageHeight, + width: (quadPoints[i7 + 2] - quadPoints[i7]) / pageWidth, + height: (quadPoints[i7 + 1] - quadPoints[i7 + 5]) / pageHeight + }); + } + editor.#createOutlines(); + editor.#addToDrawLayer(); + editor.rotate(editor.rotation); + } else if (inkLists) { + editor.#isFreeHighlight = true; + const points = inkLists[0]; + const point = { + x: points[0] - pageX, + y: pageHeight - (points[1] - pageY) + }; + const outliner = new FreeHighlightOutliner(point, [0, 0, pageWidth, pageHeight], 1, editor.#thickness / 2, true, 1e-3); + for (let i7 = 0, ii = points.length; i7 < ii; i7 += 2) { + point.x = points[i7] - pageX; + point.y = pageHeight - (points[i7 + 1] - pageY); + outliner.add(point); + } + const { + id, + clipPathId + } = parent.drawLayer.draw({ + bbox: [0, 0, 1, 1], + root: { + viewBox: "0 0 1 1", + fill: editor.color, + "fill-opacity": editor._defaultOpacity + }, + rootClass: { + highlight: true, + free: true + }, + path: { + d: outliner.toSVGPath() + } + }, true, true); + editor.#createFreeOutlines({ + highlightOutlines: outliner.getOutlines(), + highlightId: id, + clipPathId + }); + editor.#addToDrawLayer(); + editor.rotate(editor.parentRotation); + } + return editor; + } + serialize(isForCopying = false) { + if (this.isEmpty() || isForCopying) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const color2 = AnnotationEditor._colorManager.convert(this._uiManager.getNonHCMColor(this.color)); + const serialized = super.serialize(isForCopying); + Object.assign(serialized, { + color: color2, + opacity: this.opacity, + thickness: this.#thickness, + quadPoints: this.#serializeBoxes(), + outlines: this.#serializeOutlines(serialized.rect) + }); + this.addComment(serialized); + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color: color2 + } = this._initialData; + return this.hasEditedComment || serialized.color.some((c6, i7) => c6 !== color2[i7]); + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + annotation.updateEdited({ + rect: this.getPDFRect(), + popup: this.comment + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } + }; + DrawingOptions = class { + #svgProperties = /* @__PURE__ */ Object.create(null); + updateProperty(name, value) { + this[name] = value; + this.updateSVGProperty(name, value); + } + updateProperties(properties) { + if (!properties) { + return; + } + for (const [name, value] of Object.entries(properties)) { + if (!name.startsWith("_")) { + this.updateProperty(name, value); + } + } + } + updateSVGProperty(name, value) { + this.#svgProperties[name] = value; + } + toSVGProperties() { + const root = this.#svgProperties; + this.#svgProperties = /* @__PURE__ */ Object.create(null); + return { + root + }; + } + reset() { + this.#svgProperties = /* @__PURE__ */ Object.create(null); + } + updateAll(options = this) { + this.updateProperties(options); + } + clone() { + unreachable("Not implemented"); + } + }; + DrawingEditor = class _DrawingEditor extends AnnotationEditor { + #drawOutlines = null; + #mustBeCommitted; + _colorPicker = null; + _drawId = null; + static _currentDrawId = -1; + static _currentParent = null; + static #currentDraw = null; + static #currentDrawingAC = null; + static #currentDrawingOptions = null; + static _INNER_MARGIN = 3; + constructor(params) { + super(params); + this.#mustBeCommitted = params.mustBeCommitted || false; + this._addOutlines(params); + } + onUpdatedColor() { + this._colorPicker?.update(this.color); + super.onUpdatedColor(); + } + _addOutlines(params) { + if (params.drawOutlines) { + this.#createDrawOutlines(params); + this.#addToDrawLayer(); + } + } + #createDrawOutlines({ + drawOutlines, + drawId, + drawingOptions + }) { + this.#drawOutlines = drawOutlines; + this._drawingOptions ||= drawingOptions; + if (!this.annotationElementId) { + this._uiManager.a11yAlert(`pdfjs-editor-${this.editorType}-added-alert`); + } + if (drawId >= 0) { + this._drawId = drawId; + this.parent.drawLayer.finalizeDraw(drawId, drawOutlines.defaultProperties); + } else { + this._drawId = this.#createDrawing(drawOutlines, this.parent); + } + this.#updateBbox(drawOutlines.box); + } + #createDrawing(drawOutlines, parent) { + const { + id + } = parent.drawLayer.draw(_DrawingEditor._mergeSVGProperties(this._drawingOptions.toSVGProperties(), drawOutlines.defaultSVGProperties), false, false); + return id; + } + static _mergeSVGProperties(p1, p22) { + const p1Keys = new Set(Object.keys(p1)); + for (const [key, value] of Object.entries(p22)) { + if (p1Keys.has(key)) { + Object.assign(p1[key], value); + } else { + p1[key] = value; + } + } + return p1; + } + static getDefaultDrawingOptions(_options) { + unreachable("Not implemented"); + } + static get typesMap() { + unreachable("Not implemented"); + } + static get isDrawer() { + return true; + } + static get supportMultipleDrawings() { + return false; + } + static updateDefaultParams(type, value) { + const propertyName = this.typesMap.get(type); + if (propertyName) { + this._defaultDrawingOptions.updateProperty(propertyName, value); + } + if (this._currentParent) { + _DrawingEditor.#currentDraw.updateProperty(propertyName, value); + this._currentParent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); + } + } + updateParams(type, value) { + const propertyName = this.constructor.typesMap.get(type); + if (propertyName) { + this._updateProperty(type, propertyName, value); + } + } + static get defaultPropertiesToUpdate() { + const properties = []; + const options = this._defaultDrawingOptions; + for (const [type, name] of this.typesMap) { + properties.push([type, options[name]]); + } + return properties; + } + get propertiesToUpdate() { + const properties = []; + const { + _drawingOptions + } = this; + for (const [type, name] of this.constructor.typesMap) { + properties.push([type, _drawingOptions[name]]); + } + return properties; + } + _updateProperty(type, name, value) { + const options = this._drawingOptions; + const savedValue = options[name]; + const setter = (val2) => { + options.updateProperty(name, val2); + const bbox = this.#drawOutlines.updateProperty(name, val2); + if (bbox) { + this.#updateBbox(bbox); + } + this.parent?.drawLayer.updateProperties(this._drawId, options.toSVGProperties()); + if (type === this.colorType) { + this.onUpdatedColor(); + } + }; + this.addCommands({ + cmd: setter.bind(this, value), + undo: setter.bind(this, savedValue), + post: this._uiManager.updateUI.bind(this._uiManager, this), + mustExec: true, + type, + overwriteIfSameType: true, + keepUndo: true + }); + } + _onResizing() { + this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizingSVGProperties(this.#convertToDrawSpace()), { + bbox: this.#rotateBox() + })); + } + _onResized() { + this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathResizedSVGProperties(this.#convertToDrawSpace()), { + bbox: this.#rotateBox() + })); + } + _onTranslating(_x2, _y2) { + this.parent?.drawLayer.updateProperties(this._drawId, { + bbox: this.#rotateBox() + }); + } + _onTranslated() { + this.parent?.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties(this.#drawOutlines.getPathTranslatedSVGProperties(this.#convertToDrawSpace(), this.parentDimensions), { + bbox: this.#rotateBox() + })); + } + _onStartDragging() { + this.parent?.drawLayer.updateProperties(this._drawId, { + rootClass: { + moving: true + } + }); + } + _onStopDragging() { + this.parent?.drawLayer.updateProperties(this._drawId, { + rootClass: { + moving: false + } + }); + } + commit() { + super.commit(); + this.disableEditMode(); + this.disableEditing(); + } + disableEditing() { + super.disableEditing(); + this.div.classList.toggle("disabled", true); + } + enableEditing() { + super.enableEditing(); + this.div.classList.toggle("disabled", false); + } + getBaseTranslation() { + return [0, 0]; + } + get isResizable() { + return true; + } + onceAdded(focus) { + if (!this.annotationElementId) { + this.parent.addUndoableEditor(this); + } + this._isDraggable = true; + if (this.#mustBeCommitted) { + this.#mustBeCommitted = false; + this.commit(); + this.parent.setSelected(this); + if (focus && this.isOnScreen) { + this.div.focus(); + } + } + } + remove() { + this.#cleanDrawLayer(); + super.remove(); + } + rebuild() { + if (!this.parent) { + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + this.#addToDrawLayer(); + this.#updateBbox(this.#drawOutlines.box); + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + setParent(parent) { + let mustBeSelected = false; + if (this.parent && !parent) { + this._uiManager.removeShouldRescale(this); + this.#cleanDrawLayer(); + } else if (parent) { + this._uiManager.addShouldRescale(this); + this.#addToDrawLayer(parent); + mustBeSelected = !this.parent && this.div?.classList.contains("selectedEditor"); + } + super.setParent(parent); + if (mustBeSelected) { + this.select(); + } + } + #cleanDrawLayer() { + if (this._drawId === null || !this.parent) { + return; + } + this.parent.drawLayer.remove(this._drawId); + this._drawId = null; + this._drawingOptions.reset(); + } + #addToDrawLayer(parent = this.parent) { + if (this._drawId !== null && this.parent === parent) { + return; + } + if (this._drawId !== null) { + this.parent.drawLayer.updateParent(this._drawId, parent.drawLayer); + return; + } + this._drawingOptions.updateAll(); + this._drawId = this.#createDrawing(this.#drawOutlines, parent); + } + #convertToParentSpace([x2, y4, width, height]) { + const { + parentDimensions: [pW, pH], + rotation + } = this; + switch (rotation) { + case 90: + return [y4, 1 - x2, width * (pH / pW), height * (pW / pH)]; + case 180: + return [1 - x2, 1 - y4, width, height]; + case 270: + return [1 - y4, x2, width * (pH / pW), height * (pW / pH)]; + default: + return [x2, y4, width, height]; + } + } + #convertToDrawSpace() { + const { + x: x2, + y: y4, + width, + height, + parentDimensions: [pW, pH], + rotation + } = this; + switch (rotation) { + case 90: + return [1 - y4, x2, width * (pW / pH), height * (pH / pW)]; + case 180: + return [1 - x2, 1 - y4, width, height]; + case 270: + return [y4, 1 - x2, width * (pW / pH), height * (pH / pW)]; + default: + return [x2, y4, width, height]; + } + } + #updateBbox(bbox) { + [this.x, this.y, this.width, this.height] = this.#convertToParentSpace(bbox); + if (this.div) { + this.fixAndSetPosition(); + this.setDims(); + } + this._onResized(); + } + #rotateBox() { + const { + x: x2, + y: y4, + width, + height, + rotation, + parentRotation, + parentDimensions: [pW, pH] + } = this; + switch ((rotation * 4 + parentRotation) / 90) { + case 1: + return [1 - y4 - height, x2, height, width]; + case 2: + return [1 - x2 - width, 1 - y4 - height, width, height]; + case 3: + return [y4, 1 - x2 - width, height, width]; + case 4: + return [x2, y4 - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; + case 5: + return [1 - y4, x2, width * (pW / pH), height * (pH / pW)]; + case 6: + return [1 - x2 - height * (pH / pW), 1 - y4, height * (pH / pW), width * (pW / pH)]; + case 7: + return [y4 - width * (pW / pH), 1 - x2 - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; + case 8: + return [x2 - width, y4 - height, width, height]; + case 9: + return [1 - y4, x2 - width, height, width]; + case 10: + return [1 - x2, 1 - y4, width, height]; + case 11: + return [y4 - height, 1 - x2, height, width]; + case 12: + return [x2 - height * (pH / pW), y4, height * (pH / pW), width * (pW / pH)]; + case 13: + return [1 - y4 - width * (pW / pH), x2 - height * (pH / pW), width * (pW / pH), height * (pH / pW)]; + case 14: + return [1 - x2, 1 - y4 - width * (pW / pH), height * (pH / pW), width * (pW / pH)]; + case 15: + return [y4, 1 - x2, width * (pW / pH), height * (pH / pW)]; + default: + return [x2, y4, width, height]; + } + } + rotate() { + if (!this.parent) { + return; + } + this.parent.drawLayer.updateProperties(this._drawId, _DrawingEditor._mergeSVGProperties({ + bbox: this.#rotateBox() + }, this.#drawOutlines.updateRotation((this.parentRotation - this.rotation + 360) % 360))); + } + onScaleChanging() { + if (!this.parent) { + return; + } + this.#updateBbox(this.#drawOutlines.updateParentDimensions(this.parentDimensions, this.parent.scale)); + } + static onScaleChangingWhenDrawing() { + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this._isCopy) { + baseX = this.x; + baseY = this.y; + } + const div = super.render(); + div.classList.add("draw"); + const drawDiv = document.createElement("div"); + div.append(drawDiv); + drawDiv.setAttribute("aria-hidden", "true"); + drawDiv.className = "internal"; + this.setDims(); + this._uiManager.addShouldRescale(this); + this.disableEditing(); + if (this._isCopy) { + this._moveAfterPaste(baseX, baseY); + } + return div; + } + static createDrawerInstance(_x2, _y2, _parentWidth, _parentHeight, _rotation) { + unreachable("Not implemented"); + } + static startDrawing(parent, uiManager, _isLTR, event) { + const { + target, + offsetX: x2, + offsetY: y4, + pointerId, + pointerType + } = event; + if (CurrentPointers.isInitializedAndDifferentPointerType(pointerType)) { + return; + } + const { + viewport: { + rotation + } + } = parent; + const { + width: parentWidth, + height: parentHeight + } = target.getBoundingClientRect(); + const ac = _DrawingEditor.#currentDrawingAC = new AbortController(); + const signal = parent.combinedSignal(ac); + CurrentPointers.setPointer(pointerType, pointerId); + window.addEventListener("pointerup", (e9) => { + if (CurrentPointers.isSamePointerIdOrRemove(e9.pointerId)) { + this._endDraw(e9); + } + }, { + signal + }); + window.addEventListener("pointercancel", (e9) => { + if (CurrentPointers.isSamePointerIdOrRemove(e9.pointerId)) { + this._currentParent.endDrawingSession(); + } + }, { + signal + }); + window.addEventListener("pointerdown", (e9) => { + if (!CurrentPointers.isSamePointerType(e9.pointerType)) { + return; + } + CurrentPointers.initializeAndAddPointerId(e9.pointerId); + if (_DrawingEditor.#currentDraw.isCancellable()) { + _DrawingEditor.#currentDraw.removeLastElement(); + if (_DrawingEditor.#currentDraw.isEmpty()) { + this._currentParent.endDrawingSession(true); + } else { + this._endDraw(null); + } + } + }, { + capture: true, + passive: false, + signal + }); + window.addEventListener("contextmenu", noContextMenu, { + signal + }); + target.addEventListener("pointermove", this._drawMove.bind(this), { + signal + }); + target.addEventListener("touchmove", (e9) => { + if (CurrentPointers.isSameTimeStamp(e9.timeStamp)) { + stopEvent(e9); + } + }, { + signal + }); + parent.toggleDrawing(); + uiManager._editorUndoBar?.hide(); + if (_DrawingEditor.#currentDraw) { + parent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.startNew(x2, y4, parentWidth, parentHeight, rotation)); + return; + } + uiManager.updateUIForDefaultProperties(this); + _DrawingEditor.#currentDraw = this.createDrawerInstance(x2, y4, parentWidth, parentHeight, rotation); + _DrawingEditor.#currentDrawingOptions = this.getDefaultDrawingOptions(); + this._currentParent = parent; + ({ + id: this._currentDrawId + } = parent.drawLayer.draw(this._mergeSVGProperties(_DrawingEditor.#currentDrawingOptions.toSVGProperties(), _DrawingEditor.#currentDraw.defaultSVGProperties), true, false)); + } + static _drawMove(event) { + CurrentPointers.isSameTimeStamp(event.timeStamp); + if (!_DrawingEditor.#currentDraw) { + return; + } + const { + offsetX, + offsetY, + pointerId + } = event; + if (!CurrentPointers.isSamePointerId(pointerId)) { + return; + } + if (CurrentPointers.isUsingMultiplePointers()) { + this._endDraw(event); + return; + } + this._currentParent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.add(offsetX, offsetY)); + CurrentPointers.setTimeStamp(event.timeStamp); + stopEvent(event); + } + static _cleanup(all) { + if (all) { + this._currentDrawId = -1; + this._currentParent = null; + _DrawingEditor.#currentDraw = null; + _DrawingEditor.#currentDrawingOptions = null; + CurrentPointers.clearPointerType(); + CurrentPointers.clearTimeStamp(); + } + if (_DrawingEditor.#currentDrawingAC) { + _DrawingEditor.#currentDrawingAC.abort(); + _DrawingEditor.#currentDrawingAC = null; + CurrentPointers.clearPointerIds(); + } + } + static _endDraw(event) { + const parent = this._currentParent; + if (!parent) { + return; + } + parent.toggleDrawing(true); + this._cleanup(false); + if (event?.target === parent.div) { + parent.drawLayer.updateProperties(this._currentDrawId, _DrawingEditor.#currentDraw.end(event.offsetX, event.offsetY)); + } + if (this.supportMultipleDrawings) { + const draw2 = _DrawingEditor.#currentDraw; + const drawId = this._currentDrawId; + const lastElement = draw2.getLastElement(); + parent.addCommands({ + cmd: () => { + parent.drawLayer.updateProperties(drawId, draw2.setLastElement(lastElement)); + }, + undo: () => { + parent.drawLayer.updateProperties(drawId, draw2.removeLastElement()); + }, + mustExec: false, + type: AnnotationEditorParamsType.DRAW_STEP + }); + return; + } + this.endDrawing(false); + } + static endDrawing(isAborted3) { + const parent = this._currentParent; + if (!parent) { + return null; + } + parent.toggleDrawing(true); + parent.cleanUndoStack(AnnotationEditorParamsType.DRAW_STEP); + if (!_DrawingEditor.#currentDraw.isEmpty()) { + const { + pageDimensions: [pageWidth, pageHeight], + scale + } = parent; + const editor = parent.createAndAddNewEditor({ + offsetX: 0, + offsetY: 0 + }, false, { + drawId: this._currentDrawId, + drawOutlines: _DrawingEditor.#currentDraw.getOutlines(pageWidth * scale, pageHeight * scale, scale, this._INNER_MARGIN), + drawingOptions: _DrawingEditor.#currentDrawingOptions, + mustBeCommitted: !isAborted3 + }); + this._cleanup(true); + return editor; + } + parent.drawLayer.remove(this._currentDrawId); + this._cleanup(true); + return null; + } + createDrawingOptions(_data) { + } + static deserializeDraw(_pageX, _pageY, _pageWidth, _pageHeight, _innerWidth, _data) { + unreachable("Not implemented"); + } + static async deserialize(data, parent, uiManager) { + const { + rawDims: { + pageWidth, + pageHeight, + pageX, + pageY + } + } = parent.viewport; + const drawOutlines = this.deserializeDraw(pageX, pageY, pageWidth, pageHeight, this._INNER_MARGIN, data); + const editor = await super.deserialize(data, parent, uiManager); + editor.createDrawingOptions(data); + editor.#createDrawOutlines({ + drawOutlines + }); + editor.#addToDrawLayer(); + editor.onScaleChanging(); + editor.rotate(); + return editor; + } + serializeDraw(isForCopying) { + const [pageX, pageY] = this.pageTranslation; + const [pageWidth, pageHeight] = this.pageDimensions; + return this.#drawOutlines.serialize([pageX, pageY, pageWidth, pageHeight], isForCopying); + } + renderAnnotationElement(annotation) { + annotation.updateEdited({ + rect: this.getPDFRect() + }); + return null; + } + static canCreateNewEmptyEditor() { + return false; + } + }; + InkDrawOutliner = class { + #last = new Float64Array(6); + #line; + #lines; + #rotation; + #thickness; + #points; + #lastSVGPath = ""; + #lastIndex = 0; + #outlines = new InkDrawOutline(); + #parentWidth; + #parentHeight; + constructor(x2, y4, parentWidth, parentHeight, rotation, thickness) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#rotation = rotation; + this.#thickness = thickness; + [x2, y4] = this.#normalizePoint(x2, y4); + const line = this.#line = [NaN, NaN, NaN, NaN, x2, y4]; + this.#points = [x2, y4]; + this.#lines = [{ + line, + points: this.#points + }]; + this.#last.set(line, 0); + } + updateProperty(name, value) { + if (name === "stroke-width") { + this.#thickness = value; + } + } + #normalizePoint(x2, y4) { + return Outline._normalizePoint(x2, y4, this.#parentWidth, this.#parentHeight, this.#rotation); + } + isEmpty() { + return !this.#lines || this.#lines.length === 0; + } + isCancellable() { + return this.#points.length <= 10; + } + add(x2, y4) { + [x2, y4] = this.#normalizePoint(x2, y4); + const [x1, y1, x22, y22] = this.#last.subarray(2, 6); + const diffX = x2 - x22; + const diffY = y4 - y22; + const d4 = Math.hypot(this.#parentWidth * diffX, this.#parentHeight * diffY); + if (d4 <= 2) { + return null; + } + this.#points.push(x2, y4); + if (isNaN(x1)) { + this.#last.set([x22, y22, x2, y4], 2); + this.#line.push(NaN, NaN, NaN, NaN, x2, y4); + return { + path: { + d: this.toSVGPath() + } + }; + } + if (isNaN(this.#last[0])) { + this.#line.splice(6, 6); + } + this.#last.set([x1, y1, x22, y22, x2, y4], 0); + this.#line.push(...Outline.createBezierPoints(x1, y1, x22, y22, x2, y4)); + return { + path: { + d: this.toSVGPath() + } + }; + } + end(x2, y4) { + const change = this.add(x2, y4); + if (change) { + return change; + } + if (this.#points.length === 2) { + return { + path: { + d: this.toSVGPath() + } + }; + } + return null; + } + startNew(x2, y4, parentWidth, parentHeight, rotation) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#rotation = rotation; + [x2, y4] = this.#normalizePoint(x2, y4); + const line = this.#line = [NaN, NaN, NaN, NaN, x2, y4]; + this.#points = [x2, y4]; + const last = this.#lines.at(-1); + if (last) { + last.line = new Float32Array(last.line); + last.points = new Float32Array(last.points); + } + this.#lines.push({ + line, + points: this.#points + }); + this.#last.set(line, 0); + this.#lastIndex = 0; + this.toSVGPath(); + return null; + } + getLastElement() { + return this.#lines.at(-1); + } + setLastElement(element) { + if (!this.#lines) { + return this.#outlines.setLastElement(element); + } + this.#lines.push(element); + this.#line = element.line; + this.#points = element.points; + this.#lastIndex = 0; + return { + path: { + d: this.toSVGPath() + } + }; + } + removeLastElement() { + if (!this.#lines) { + return this.#outlines.removeLastElement(); + } + this.#lines.pop(); + this.#lastSVGPath = ""; + for (let i7 = 0, ii = this.#lines.length; i7 < ii; i7++) { + const { + line, + points + } = this.#lines[i7]; + this.#line = line; + this.#points = points; + this.#lastIndex = 0; + this.toSVGPath(); + } + return { + path: { + d: this.#lastSVGPath + } + }; + } + toSVGPath() { + const firstX = Outline.svgRound(this.#line[4]); + const firstY = Outline.svgRound(this.#line[5]); + if (this.#points.length === 2) { + this.#lastSVGPath = `${this.#lastSVGPath} M ${firstX} ${firstY} Z`; + return this.#lastSVGPath; + } + if (this.#points.length <= 6) { + const i7 = this.#lastSVGPath.lastIndexOf("M"); + this.#lastSVGPath = `${this.#lastSVGPath.slice(0, i7)} M ${firstX} ${firstY}`; + this.#lastIndex = 6; + } + if (this.#points.length === 4) { + const secondX = Outline.svgRound(this.#line[10]); + const secondY = Outline.svgRound(this.#line[11]); + this.#lastSVGPath = `${this.#lastSVGPath} L ${secondX} ${secondY}`; + this.#lastIndex = 12; + return this.#lastSVGPath; + } + const buffer = []; + if (this.#lastIndex === 0) { + buffer.push(`M ${firstX} ${firstY}`); + this.#lastIndex = 6; + } + for (let i7 = this.#lastIndex, ii = this.#line.length; i7 < ii; i7 += 6) { + const [c1x, c1y, c2x, c2y, x2, y4] = this.#line.slice(i7, i7 + 6).map(Outline.svgRound); + buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x2} ${y4}`); + } + this.#lastSVGPath += buffer.join(" "); + this.#lastIndex = this.#line.length; + return this.#lastSVGPath; + } + getOutlines(parentWidth, parentHeight, scale, innerMargin) { + const last = this.#lines.at(-1); + last.line = new Float32Array(last.line); + last.points = new Float32Array(last.points); + this.#outlines.build(this.#lines, parentWidth, parentHeight, scale, this.#rotation, this.#thickness, innerMargin); + this.#last = null; + this.#line = null; + this.#lines = null; + this.#lastSVGPath = null; + return this.#outlines; + } + get defaultSVGProperties() { + return { + root: { + viewBox: "0 0 10000 10000" + }, + rootClass: { + draw: true + }, + bbox: [0, 0, 1, 1] + }; + } + }; + InkDrawOutline = class extends Outline { + #bbox; + #currentRotation = 0; + #innerMargin; + #lines; + #parentWidth; + #parentHeight; + #parentScale; + #rotation; + #thickness; + build(lines, parentWidth, parentHeight, parentScale, rotation, thickness, innerMargin) { + this.#parentWidth = parentWidth; + this.#parentHeight = parentHeight; + this.#parentScale = parentScale; + this.#rotation = rotation; + this.#thickness = thickness; + this.#innerMargin = innerMargin ?? 0; + this.#lines = lines; + this.#computeBbox(); + } + get thickness() { + return this.#thickness; + } + setLastElement(element) { + this.#lines.push(element); + return { + path: { + d: this.toSVGPath() + } + }; + } + removeLastElement() { + this.#lines.pop(); + return { + path: { + d: this.toSVGPath() + } + }; + } + toSVGPath() { + const buffer = []; + for (const { + line + } of this.#lines) { + buffer.push(`M${Outline.svgRound(line[4])} ${Outline.svgRound(line[5])}`); + if (line.length === 6) { + buffer.push("Z"); + continue; + } + if (line.length === 12 && isNaN(line[6])) { + buffer.push(`L${Outline.svgRound(line[10])} ${Outline.svgRound(line[11])}`); + continue; + } + for (let i7 = 6, ii = line.length; i7 < ii; i7 += 6) { + const [c1x, c1y, c2x, c2y, x2, y4] = line.subarray(i7, i7 + 6).map(Outline.svgRound); + buffer.push(`C${c1x} ${c1y} ${c2x} ${c2y} ${x2} ${y4}`); + } + } + return buffer.join(""); + } + serialize([pageX, pageY, pageWidth, pageHeight], isForCopying) { + const serializedLines = []; + const serializedPoints = []; + const [x2, y4, width, height] = this.#getBBoxWithNoMargin(); + let tx, ty, sx, sy, x1, y1, x22, y22, rescaleFn; + switch (this.#rotation) { + case 0: + rescaleFn = Outline._rescale; + tx = pageX; + ty = pageY + pageHeight; + sx = pageWidth; + sy = -pageHeight; + x1 = pageX + x2 * pageWidth; + y1 = pageY + (1 - y4 - height) * pageHeight; + x22 = pageX + (x2 + width) * pageWidth; + y22 = pageY + (1 - y4) * pageHeight; + break; + case 90: + rescaleFn = Outline._rescaleAndSwap; + tx = pageX; + ty = pageY; + sx = pageWidth; + sy = pageHeight; + x1 = pageX + y4 * pageWidth; + y1 = pageY + x2 * pageHeight; + x22 = pageX + (y4 + height) * pageWidth; + y22 = pageY + (x2 + width) * pageHeight; + break; + case 180: + rescaleFn = Outline._rescale; + tx = pageX + pageWidth; + ty = pageY; + sx = -pageWidth; + sy = pageHeight; + x1 = pageX + (1 - x2 - width) * pageWidth; + y1 = pageY + y4 * pageHeight; + x22 = pageX + (1 - x2) * pageWidth; + y22 = pageY + (y4 + height) * pageHeight; + break; + case 270: + rescaleFn = Outline._rescaleAndSwap; + tx = pageX + pageWidth; + ty = pageY + pageHeight; + sx = -pageWidth; + sy = -pageHeight; + x1 = pageX + (1 - y4 - height) * pageWidth; + y1 = pageY + (1 - x2 - width) * pageHeight; + x22 = pageX + (1 - y4) * pageWidth; + y22 = pageY + (1 - x2) * pageHeight; + break; + } + for (const { + line, + points + } of this.#lines) { + serializedLines.push(rescaleFn(line, tx, ty, sx, sy, isForCopying ? new Array(line.length) : null)); + serializedPoints.push(rescaleFn(points, tx, ty, sx, sy, isForCopying ? new Array(points.length) : null)); + } + return { + lines: serializedLines, + points: serializedPoints, + rect: [x1, y1, x22, y22] + }; + } + static deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, { + paths: { + lines, + points + }, + rotation, + thickness + }) { + const newLines = []; + let tx, ty, sx, sy, rescaleFn; + switch (rotation) { + case 0: + rescaleFn = Outline._rescale; + tx = -pageX / pageWidth; + ty = pageY / pageHeight + 1; + sx = 1 / pageWidth; + sy = -1 / pageHeight; + break; + case 90: + rescaleFn = Outline._rescaleAndSwap; + tx = -pageY / pageHeight; + ty = -pageX / pageWidth; + sx = 1 / pageHeight; + sy = 1 / pageWidth; + break; + case 180: + rescaleFn = Outline._rescale; + tx = pageX / pageWidth + 1; + ty = -pageY / pageHeight; + sx = -1 / pageWidth; + sy = 1 / pageHeight; + break; + case 270: + rescaleFn = Outline._rescaleAndSwap; + tx = pageY / pageHeight + 1; + ty = pageX / pageWidth + 1; + sx = -1 / pageHeight; + sy = -1 / pageWidth; + break; + } + if (!lines) { + lines = []; + for (const point of points) { + const len = point.length; + if (len === 2) { + lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1]])); + continue; + } + if (len === 4) { + lines.push(new Float32Array([NaN, NaN, NaN, NaN, point[0], point[1], NaN, NaN, NaN, NaN, point[2], point[3]])); + continue; + } + const line = new Float32Array(3 * (len - 2)); + lines.push(line); + let [x1, y1, x2, y22] = point.subarray(0, 4); + line.set([NaN, NaN, NaN, NaN, x1, y1], 0); + for (let i7 = 4; i7 < len; i7 += 2) { + const x3 = point[i7]; + const y4 = point[i7 + 1]; + line.set(Outline.createBezierPoints(x1, y1, x2, y22, x3, y4), (i7 - 2) * 3); + [x1, y1, x2, y22] = [x2, y22, x3, y4]; + } + } + } + for (let i7 = 0, ii = lines.length; i7 < ii; i7++) { + newLines.push({ + line: rescaleFn(lines[i7].map((x2) => x2 ?? NaN), tx, ty, sx, sy), + points: rescaleFn(points[i7].map((x2) => x2 ?? NaN), tx, ty, sx, sy) + }); + } + const outlines = new this.prototype.constructor(); + outlines.build(newLines, pageWidth, pageHeight, 1, rotation, thickness, innerMargin); + return outlines; + } + #getMarginComponents(thickness = this.#thickness) { + const margin = this.#innerMargin + thickness / 2 * this.#parentScale; + return this.#rotation % 180 === 0 ? [margin / this.#parentWidth, margin / this.#parentHeight] : [margin / this.#parentHeight, margin / this.#parentWidth]; + } + #getBBoxWithNoMargin() { + const [x2, y4, width, height] = this.#bbox; + const [marginX, marginY] = this.#getMarginComponents(0); + return [x2 + marginX, y4 + marginY, width - 2 * marginX, height - 2 * marginY]; + } + #computeBbox() { + const bbox = this.#bbox = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]); + for (const { + line + } of this.#lines) { + if (line.length <= 12) { + for (let i7 = 4, ii = line.length; i7 < ii; i7 += 6) { + Util.pointBoundingBox(line[i7], line[i7 + 1], bbox); + } + continue; + } + let lastX = line[4], lastY = line[5]; + for (let i7 = 6, ii = line.length; i7 < ii; i7 += 6) { + const [c1x, c1y, c2x, c2y, x2, y4] = line.subarray(i7, i7 + 6); + Util.bezierBoundingBox(lastX, lastY, c1x, c1y, c2x, c2y, x2, y4, bbox); + lastX = x2; + lastY = y4; + } + } + const [marginX, marginY] = this.#getMarginComponents(); + bbox[0] = MathClamp(bbox[0] - marginX, 0, 1); + bbox[1] = MathClamp(bbox[1] - marginY, 0, 1); + bbox[2] = MathClamp(bbox[2] + marginX, 0, 1); + bbox[3] = MathClamp(bbox[3] + marginY, 0, 1); + bbox[2] -= bbox[0]; + bbox[3] -= bbox[1]; + } + get box() { + return this.#bbox; + } + updateProperty(name, value) { + if (name === "stroke-width") { + return this.#updateThickness(value); + } + return null; + } + #updateThickness(thickness) { + const [oldMarginX, oldMarginY] = this.#getMarginComponents(); + this.#thickness = thickness; + const [newMarginX, newMarginY] = this.#getMarginComponents(); + const [diffMarginX, diffMarginY] = [newMarginX - oldMarginX, newMarginY - oldMarginY]; + const bbox = this.#bbox; + bbox[0] -= diffMarginX; + bbox[1] -= diffMarginY; + bbox[2] += 2 * diffMarginX; + bbox[3] += 2 * diffMarginY; + return bbox; + } + updateParentDimensions([width, height], scale) { + const [oldMarginX, oldMarginY] = this.#getMarginComponents(); + this.#parentWidth = width; + this.#parentHeight = height; + this.#parentScale = scale; + const [newMarginX, newMarginY] = this.#getMarginComponents(); + const diffMarginX = newMarginX - oldMarginX; + const diffMarginY = newMarginY - oldMarginY; + const bbox = this.#bbox; + bbox[0] -= diffMarginX; + bbox[1] -= diffMarginY; + bbox[2] += 2 * diffMarginX; + bbox[3] += 2 * diffMarginY; + return bbox; + } + updateRotation(rotation) { + this.#currentRotation = rotation; + return { + path: { + transform: this.rotationTransform + } + }; + } + get viewBox() { + return this.#bbox.map(Outline.svgRound).join(" "); + } + get defaultProperties() { + const [x2, y4] = this.#bbox; + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(x2)} ${Outline.svgRound(y4)}` + } + }; + } + get rotationTransform() { + const [, , width, height] = this.#bbox; + let a3 = 0, b4 = 0, c6 = 0, d4 = 0, e9 = 0, f4 = 0; + switch (this.#currentRotation) { + case 90: + b4 = height / width; + c6 = -width / height; + e9 = width; + break; + case 180: + a3 = -1; + d4 = -1; + e9 = width; + f4 = height; + break; + case 270: + b4 = -height / width; + c6 = width / height; + f4 = height; + break; + default: + return ""; + } + return `matrix(${a3} ${b4} ${c6} ${d4} ${Outline.svgRound(e9)} ${Outline.svgRound(f4)})`; + } + getPathResizingSVGProperties([newX, newY, newWidth, newHeight]) { + const [marginX, marginY] = this.#getMarginComponents(); + const [x2, y4, width, height] = this.#bbox; + if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { + const tx = newX + newWidth / 2 - (x2 + width / 2); + const ty = newY + newHeight / 2 - (y4 + height / 2); + return { + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: `${this.rotationTransform} translate(${tx} ${ty})` + } + }; + } + const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); + const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); + const s2x = width / newWidth; + const s2y = height / newHeight; + return { + path: { + "transform-origin": `${Outline.svgRound(x2)} ${Outline.svgRound(y4)}`, + transform: `${this.rotationTransform} scale(${s2x} ${s2y}) translate(${Outline.svgRound(marginX)} ${Outline.svgRound(marginY)}) scale(${s1x} ${s1y}) translate(${Outline.svgRound(-marginX)} ${Outline.svgRound(-marginY)})` + } + }; + } + getPathResizedSVGProperties([newX, newY, newWidth, newHeight]) { + const [marginX, marginY] = this.#getMarginComponents(); + const bbox = this.#bbox; + const [x2, y4, width, height] = bbox; + bbox[0] = newX; + bbox[1] = newY; + bbox[2] = newWidth; + bbox[3] = newHeight; + if (Math.abs(width - marginX) <= Outline.PRECISION || Math.abs(height - marginY) <= Outline.PRECISION) { + const tx2 = newX + newWidth / 2 - (x2 + width / 2); + const ty2 = newY + newHeight / 2 - (y4 + height / 2); + for (const { + line, + points + } of this.#lines) { + Outline._translate(line, tx2, ty2, line); + Outline._translate(points, tx2, ty2, points); + } + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: this.rotationTransform || null, + d: this.toSVGPath() + } + }; + } + const s1x = (newWidth - 2 * marginX) / (width - 2 * marginX); + const s1y = (newHeight - 2 * marginY) / (height - 2 * marginY); + const tx = -s1x * (x2 + marginX) + newX + marginX; + const ty = -s1y * (y4 + marginY) + newY + marginY; + if (s1x !== 1 || s1y !== 1 || tx !== 0 || ty !== 0) { + for (const { + line, + points + } of this.#lines) { + Outline._rescale(line, tx, ty, s1x, s1y, line); + Outline._rescale(points, tx, ty, s1x, s1y, points); + } + } + return { + root: { + viewBox: this.viewBox + }, + path: { + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}`, + transform: this.rotationTransform || null, + d: this.toSVGPath() + } + }; + } + getPathTranslatedSVGProperties([newX, newY], parentDimensions) { + const [newParentWidth, newParentHeight] = parentDimensions; + const bbox = this.#bbox; + const tx = newX - bbox[0]; + const ty = newY - bbox[1]; + if (this.#parentWidth === newParentWidth && this.#parentHeight === newParentHeight) { + for (const { + line, + points + } of this.#lines) { + Outline._translate(line, tx, ty, line); + Outline._translate(points, tx, ty, points); + } + } else { + const sx = this.#parentWidth / newParentWidth; + const sy = this.#parentHeight / newParentHeight; + this.#parentWidth = newParentWidth; + this.#parentHeight = newParentHeight; + for (const { + line, + points + } of this.#lines) { + Outline._rescale(line, tx, ty, sx, sy, line); + Outline._rescale(points, tx, ty, sx, sy, points); + } + bbox[2] *= sx; + bbox[3] *= sy; + } + bbox[0] = newX; + bbox[1] = newY; + return { + root: { + viewBox: this.viewBox + }, + path: { + d: this.toSVGPath(), + "transform-origin": `${Outline.svgRound(newX)} ${Outline.svgRound(newY)}` + } + }; + } + get defaultSVGProperties() { + const bbox = this.#bbox; + return { + root: { + viewBox: this.viewBox + }, + rootClass: { + draw: true + }, + path: { + d: this.toSVGPath(), + "transform-origin": `${Outline.svgRound(bbox[0])} ${Outline.svgRound(bbox[1])}`, + transform: this.rotationTransform || null + }, + bbox + }; + } + }; + InkDrawingOptions = class _InkDrawingOptions extends DrawingOptions { + constructor(viewerParameters) { + super(); + this._viewParameters = viewerParameters; + super.updateProperties({ + fill: "none", + stroke: AnnotationEditor._defaultLineColor, + "stroke-opacity": 1, + "stroke-width": 1, + "stroke-linecap": "round", + "stroke-linejoin": "round", + "stroke-miterlimit": 10 + }); + } + updateSVGProperty(name, value) { + if (name === "stroke-width") { + value ??= this["stroke-width"]; + value *= this._viewParameters.realScale; + } + super.updateSVGProperty(name, value); + } + clone() { + const clone3 = new _InkDrawingOptions(this._viewParameters); + clone3.updateAll(this); + return clone3; + } + }; + InkEditor = class _InkEditor extends DrawingEditor { + static _type = "ink"; + static _editorType = AnnotationEditorType.INK; + static _defaultDrawingOptions = null; + constructor(params) { + super({ + ...params, + name: "inkEditor" + }); + this._willKeepAspectRatio = true; + this.defaultL10nId = "pdfjs-editor-ink-editor"; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + this._defaultDrawingOptions = new InkDrawingOptions(uiManager.viewParameters); + } + static getDefaultDrawingOptions(options) { + const clone3 = this._defaultDrawingOptions.clone(); + clone3.updateProperties(options); + return clone3; + } + static get supportMultipleDrawings() { + return true; + } + static get typesMap() { + return shadow(this, "typesMap", /* @__PURE__ */ new Map([[AnnotationEditorParamsType.INK_THICKNESS, "stroke-width"], [AnnotationEditorParamsType.INK_COLOR, "stroke"], [AnnotationEditorParamsType.INK_OPACITY, "stroke-opacity"]])); + } + static createDrawerInstance(x2, y4, parentWidth, parentHeight, rotation) { + return new InkDrawOutliner(x2, y4, parentWidth, parentHeight, rotation, this._defaultDrawingOptions["stroke-width"]); + } + static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { + return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + if (data instanceof InkAnnotationElement) { + const { + data: { + inkLists, + rect, + rotation, + id, + color: color2, + opacity, + borderStyle: { + rawWidth: thickness + }, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + parent: { + page: { + pageNumber + } + } + } = data; + initialData = data = { + annotationType: AnnotationEditorType.INK, + color: Array.from(color2), + thickness, + opacity, + paths: { + points: inkLists + }, + boxes: null, + pageIndex: pageNumber - 1, + rect: rect.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } + const editor = await super.deserialize(data, parent, uiManager); + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + return editor; + } + get toolbarButtons() { + this._colorPicker ||= new BasicColorPicker(this); + return [["colorPicker", this._colorPicker]]; + } + get colorType() { + return AnnotationEditorParamsType.INK_COLOR; + } + get color() { + return this._drawingOptions.stroke; + } + get opacity() { + return this._drawingOptions["stroke-opacity"]; + } + onScaleChanging() { + if (!this.parent) { + return; + } + super.onScaleChanging(); + const { + _drawId, + _drawingOptions, + parent + } = this; + _drawingOptions.updateSVGProperty("stroke-width"); + parent.drawLayer.updateProperties(_drawId, _drawingOptions.toSVGProperties()); + } + static onScaleChangingWhenDrawing() { + const parent = this._currentParent; + if (!parent) { + return; + } + super.onScaleChangingWhenDrawing(); + this._defaultDrawingOptions.updateSVGProperty("stroke-width"); + parent.drawLayer.updateProperties(this._currentDrawId, this._defaultDrawingOptions.toSVGProperties()); + } + createDrawingOptions({ + color: color2, + thickness, + opacity + }) { + this._drawingOptions = _InkEditor.getDefaultDrawingOptions({ + stroke: Util.makeHexColor(...color2), + "stroke-width": thickness, + "stroke-opacity": opacity + }); + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const { + lines, + points + } = this.serializeDraw(isForCopying); + const { + _drawingOptions: { + stroke, + "stroke-opacity": opacity, + "stroke-width": thickness + } + } = this; + const serialized = Object.assign(super.serialize(isForCopying), { + color: AnnotationEditor._colorManager.convert(stroke), + opacity, + thickness, + paths: { + lines, + points + } + }); + this.addComment(serialized); + if (isForCopying) { + serialized.isCopy = true; + return serialized; + } + if (this.annotationElementId && !this.#hasElementChanged(serialized)) { + return null; + } + serialized.id = this.annotationElementId; + return serialized; + } + #hasElementChanged(serialized) { + const { + color: color2, + thickness, + opacity, + pageIndex + } = this._initialData; + return this.hasEditedComment || this._hasBeenMoved || this._hasBeenResized || serialized.color.some((c6, i7) => c6 !== color2[i7]) || serialized.thickness !== thickness || serialized.opacity !== opacity || serialized.pageIndex !== pageIndex; + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + const { + points, + rect + } = this.serializeDraw(false); + annotation.updateEdited({ + rect, + thickness: this._drawingOptions["stroke-width"], + points, + popup: this.comment + }); + return null; + } + }; + ContourDrawOutline = class extends InkDrawOutline { + toSVGPath() { + let path6 = super.toSVGPath(); + if (!path6.endsWith("Z")) { + path6 += "Z"; + } + return path6; + } + }; + BASE_HEADER_LENGTH = 8; + POINTS_PROPERTIES_NUMBER = 3; + SignatureExtractor = class { + static #PARAMETERS = { + maxDim: 512, + sigmaSFactor: 0.02, + sigmaR: 25, + kernelSize: 16 + }; + static #neighborIndexToId(i0, j0, i7, j3) { + i7 -= i0; + j3 -= j0; + if (i7 === 0) { + return j3 > 0 ? 0 : 4; + } + if (i7 === 1) { + return j3 + 6; + } + return 2 - j3; + } + static #neighborIdToIndex = new Int32Array([0, 1, -1, 1, -1, 0, -1, -1, 0, -1, 1, -1, 1, 0, 1, 1]); + static #clockwiseNonZero(buf, width, i0, j0, i7, j3, offset) { + const id = this.#neighborIndexToId(i0, j0, i7, j3); + for (let k2 = 0; k2 < 8; k2++) { + const kk = (-k2 + id - offset + 16) % 8; + const shiftI = this.#neighborIdToIndex[2 * kk]; + const shiftJ = this.#neighborIdToIndex[2 * kk + 1]; + if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) { + return kk; + } + } + return -1; + } + static #counterClockwiseNonZero(buf, width, i0, j0, i7, j3, offset) { + const id = this.#neighborIndexToId(i0, j0, i7, j3); + for (let k2 = 0; k2 < 8; k2++) { + const kk = (k2 + id + offset + 16) % 8; + const shiftI = this.#neighborIdToIndex[2 * kk]; + const shiftJ = this.#neighborIdToIndex[2 * kk + 1]; + if (buf[(i0 + shiftI) * width + (j0 + shiftJ)] !== 0) { + return kk; + } + } + return -1; + } + static #findContours(buf, width, height, threshold) { + const N3 = buf.length; + const types2 = new Int32Array(N3); + for (let i7 = 0; i7 < N3; i7++) { + types2[i7] = buf[i7] <= threshold ? 1 : 0; + } + for (let i7 = 1; i7 < height - 1; i7++) { + types2[i7 * width] = types2[i7 * width + width - 1] = 0; + } + for (let i7 = 0; i7 < width; i7++) { + types2[i7] = types2[width * height - 1 - i7] = 0; + } + let nbd = 1; + let lnbd; + const contours = []; + for (let i7 = 1; i7 < height - 1; i7++) { + lnbd = 1; + for (let j3 = 1; j3 < width - 1; j3++) { + const ij = i7 * width + j3; + const pix = types2[ij]; + if (pix === 0) { + continue; + } + let i22 = i7; + let j22 = j3; + if (pix === 1 && types2[ij - 1] === 0) { + nbd += 1; + j22 -= 1; + } else if (pix >= 1 && types2[ij + 1] === 0) { + nbd += 1; + j22 += 1; + if (pix > 1) { + lnbd = pix; + } + } else { + if (pix !== 1) { + lnbd = Math.abs(pix); + } + continue; + } + const points = [j3, i7]; + const isHole = j22 === j3 + 1; + const contour = { + isHole, + points, + id: nbd, + parent: 0 + }; + contours.push(contour); + let contour0; + for (const c6 of contours) { + if (c6.id === lnbd) { + contour0 = c6; + break; + } + } + if (!contour0) { + contour.parent = isHole ? lnbd : 0; + } else if (contour0.isHole) { + contour.parent = isHole ? contour0.parent : lnbd; + } else { + contour.parent = isHole ? lnbd : contour0.parent; + } + const k2 = this.#clockwiseNonZero(types2, width, i7, j3, i22, j22, 0); + if (k2 === -1) { + types2[ij] = -nbd; + if (types2[ij] !== 1) { + lnbd = Math.abs(types2[ij]); + } + continue; + } + let shiftI = this.#neighborIdToIndex[2 * k2]; + let shiftJ = this.#neighborIdToIndex[2 * k2 + 1]; + const i1 = i7 + shiftI; + const j1 = j3 + shiftJ; + i22 = i1; + j22 = j1; + let i32 = i7; + let j32 = j3; + while (true) { + const kk = this.#counterClockwiseNonZero(types2, width, i32, j32, i22, j22, 1); + shiftI = this.#neighborIdToIndex[2 * kk]; + shiftJ = this.#neighborIdToIndex[2 * kk + 1]; + const i42 = i32 + shiftI; + const j4 = j32 + shiftJ; + points.push(j4, i42); + const ij3 = i32 * width + j32; + if (types2[ij3 + 1] === 0) { + types2[ij3] = -nbd; + } else if (types2[ij3] === 1) { + types2[ij3] = nbd; + } + if (i42 === i7 && j4 === j3 && i32 === i1 && j32 === j1) { + if (types2[ij] !== 1) { + lnbd = Math.abs(types2[ij]); + } + break; + } else { + i22 = i32; + j22 = j32; + i32 = i42; + j32 = j4; + } + } + } + } + return contours; + } + static #douglasPeuckerHelper(points, start, end, output) { + if (end - start <= 4) { + for (let i7 = start; i7 < end - 2; i7 += 2) { + output.push(points[i7], points[i7 + 1]); + } + return; + } + const ax = points[start]; + const ay = points[start + 1]; + const abx = points[end - 4] - ax; + const aby = points[end - 3] - ay; + const dist = Math.hypot(abx, aby); + const nabx = abx / dist; + const naby = aby / dist; + const aa = nabx * ay - naby * ax; + const m4 = aby / abx; + const invS = 1 / dist; + const phi = Math.atan(m4); + const cosPhi = Math.cos(phi); + const sinPhi = Math.sin(phi); + const tmax = invS * (Math.abs(cosPhi) + Math.abs(sinPhi)); + const poly = invS * (1 - tmax + tmax ** 2); + const partialPhi = Math.max(Math.atan(Math.abs(sinPhi + cosPhi) * poly), Math.atan(Math.abs(sinPhi - cosPhi) * poly)); + let dmax = 0; + let index2 = start; + for (let i7 = start + 2; i7 < end - 2; i7 += 2) { + const d4 = Math.abs(aa - nabx * points[i7 + 1] + naby * points[i7]); + if (d4 > dmax) { + index2 = i7; + dmax = d4; + } + } + if (dmax > (dist * partialPhi) ** 2) { + this.#douglasPeuckerHelper(points, start, index2 + 2, output); + this.#douglasPeuckerHelper(points, index2, end, output); + } else { + output.push(ax, ay); + } + } + static #douglasPeucker(points) { + const output = []; + const len = points.length; + this.#douglasPeuckerHelper(points, 0, len, output); + output.push(points[len - 2], points[len - 1]); + return output.length <= 4 ? null : output; + } + static #bilateralFilter(buf, width, height, sigmaS, sigmaR, kernelSize) { + const kernel = new Float32Array(kernelSize ** 2); + const sigmaS2 = -2 * sigmaS ** 2; + const halfSize = kernelSize >> 1; + for (let i7 = 0; i7 < kernelSize; i7++) { + const x2 = (i7 - halfSize) ** 2; + for (let j3 = 0; j3 < kernelSize; j3++) { + kernel[i7 * kernelSize + j3] = Math.exp((x2 + (j3 - halfSize) ** 2) / sigmaS2); + } + } + const rangeValues = new Float32Array(256); + const sigmaR2 = -2 * sigmaR ** 2; + for (let i7 = 0; i7 < 256; i7++) { + rangeValues[i7] = Math.exp(i7 ** 2 / sigmaR2); + } + const N3 = buf.length; + const out = new Uint8Array(N3); + const histogram = new Uint32Array(256); + for (let i7 = 0; i7 < height; i7++) { + for (let j3 = 0; j3 < width; j3++) { + const ij = i7 * width + j3; + const center = buf[ij]; + let sum = 0; + let norm2 = 0; + for (let k2 = 0; k2 < kernelSize; k2++) { + const y4 = i7 + k2 - halfSize; + if (y4 < 0 || y4 >= height) { + continue; + } + for (let l5 = 0; l5 < kernelSize; l5++) { + const x2 = j3 + l5 - halfSize; + if (x2 < 0 || x2 >= width) { + continue; + } + const neighbour = buf[y4 * width + x2]; + const w3 = kernel[k2 * kernelSize + l5] * rangeValues[Math.abs(neighbour - center)]; + sum += neighbour * w3; + norm2 += w3; + } + } + const pix = out[ij] = Math.round(sum / norm2); + histogram[pix]++; + } + } + return [out, histogram]; + } + static #getHistogram(buf) { + const histogram = new Uint32Array(256); + for (const g3 of buf) { + histogram[g3]++; + } + return histogram; + } + static #toUint8(buf) { + const N3 = buf.length; + const out = new Uint8ClampedArray(N3 >> 2); + let max = -Infinity; + let min = Infinity; + for (let i7 = 0, ii = out.length; i7 < ii; i7++) { + const pix = out[i7] = buf[i7 << 2]; + max = Math.max(max, pix); + min = Math.min(min, pix); + } + const ratio = 255 / (max - min); + for (let i7 = 0, ii = out.length; i7 < ii; i7++) { + out[i7] = (out[i7] - min) * ratio; + } + return out; + } + static #guessThreshold(histogram) { + let i7; + let M4 = -Infinity; + let L3 = -Infinity; + const min = histogram.findIndex((v4) => v4 !== 0); + let pos = min; + let spos = min; + for (i7 = min; i7 < 256; i7++) { + const v4 = histogram[i7]; + if (v4 > M4) { + if (i7 - pos > L3) { + L3 = i7 - pos; + spos = i7 - 1; + } + M4 = v4; + pos = i7; + } + } + for (i7 = spos - 1; i7 >= 0; i7--) { + if (histogram[i7] > histogram[i7 + 1]) { + break; + } + } + return i7; + } + static #getGrayPixels(bitmap) { + const originalBitmap = bitmap; + const { + width, + height + } = bitmap; + const { + maxDim + } = this.#PARAMETERS; + let newWidth = width; + let newHeight = height; + if (width > maxDim || height > maxDim) { + let prevWidth = width; + let prevHeight = height; + let steps2 = Math.log2(Math.max(width, height) / maxDim); + const isteps = Math.floor(steps2); + steps2 = steps2 === isteps ? isteps - 1 : isteps; + for (let i7 = 0; i7 < steps2; i7++) { + newWidth = Math.ceil(prevWidth / 2); + newHeight = Math.ceil(prevHeight / 2); + const offscreen2 = new OffscreenCanvas(newWidth, newHeight); + const ctx2 = offscreen2.getContext("2d"); + ctx2.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); + prevWidth = newWidth; + prevHeight = newHeight; + if (bitmap !== originalBitmap) { + bitmap.close(); + } + bitmap = offscreen2.transferToImageBitmap(); + } + const ratio = Math.min(maxDim / newWidth, maxDim / newHeight); + newWidth = Math.round(newWidth * ratio); + newHeight = Math.round(newHeight * ratio); + } + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d", { + willReadFrequently: true + }); + ctx.fillStyle = "white"; + ctx.fillRect(0, 0, newWidth, newHeight); + ctx.filter = "grayscale(1)"; + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newWidth, newHeight); + const grayImage = ctx.getImageData(0, 0, newWidth, newHeight).data; + const uint8Buf = this.#toUint8(grayImage); + return [uint8Buf, newWidth, newHeight]; + } + static extractContoursFromText(text3, { + fontFamily, + fontStyle, + fontWeight + }, pageWidth, pageHeight, rotation, innerMargin) { + let canvas = new OffscreenCanvas(1, 1); + let ctx = canvas.getContext("2d", { + alpha: false + }); + const fontSize = 200; + const font = ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`; + const { + actualBoundingBoxLeft, + actualBoundingBoxRight, + actualBoundingBoxAscent, + actualBoundingBoxDescent, + fontBoundingBoxAscent, + fontBoundingBoxDescent, + width + } = ctx.measureText(text3); + const SCALE = 1.5; + const canvasWidth = Math.ceil(Math.max(Math.abs(actualBoundingBoxLeft) + Math.abs(actualBoundingBoxRight) || 0, width) * SCALE); + const canvasHeight = Math.ceil(Math.max(Math.abs(actualBoundingBoxAscent) + Math.abs(actualBoundingBoxDescent) || fontSize, Math.abs(fontBoundingBoxAscent) + Math.abs(fontBoundingBoxDescent) || fontSize) * SCALE); + canvas = new OffscreenCanvas(canvasWidth, canvasHeight); + ctx = canvas.getContext("2d", { + alpha: true, + willReadFrequently: true + }); + ctx.font = font; + ctx.filter = "grayscale(1)"; + ctx.fillStyle = "white"; + ctx.fillRect(0, 0, canvasWidth, canvasHeight); + ctx.fillStyle = "black"; + ctx.fillText(text3, canvasWidth * (SCALE - 1) / 2, canvasHeight * (3 - SCALE) / 2); + const uint8Buf = this.#toUint8(ctx.getImageData(0, 0, canvasWidth, canvasHeight).data); + const histogram = this.#getHistogram(uint8Buf); + const threshold = this.#guessThreshold(histogram); + const contourList = this.#findContours(uint8Buf, canvasWidth, canvasHeight, threshold); + return this.processDrawnLines({ + lines: { + curves: contourList, + width: canvasWidth, + height: canvasHeight + }, + pageWidth, + pageHeight, + rotation, + innerMargin, + mustSmooth: true, + areContours: true + }); + } + static process(bitmap, pageWidth, pageHeight, rotation, innerMargin) { + const [uint8Buf, width, height] = this.#getGrayPixels(bitmap); + const [buffer, histogram] = this.#bilateralFilter(uint8Buf, width, height, Math.hypot(width, height) * this.#PARAMETERS.sigmaSFactor, this.#PARAMETERS.sigmaR, this.#PARAMETERS.kernelSize); + const threshold = this.#guessThreshold(histogram); + const contourList = this.#findContours(buffer, width, height, threshold); + return this.processDrawnLines({ + lines: { + curves: contourList, + width, + height + }, + pageWidth, + pageHeight, + rotation, + innerMargin, + mustSmooth: true, + areContours: true + }); + } + static processDrawnLines({ + lines, + pageWidth, + pageHeight, + rotation, + innerMargin, + mustSmooth, + areContours + }) { + if (rotation % 180 !== 0) { + [pageWidth, pageHeight] = [pageHeight, pageWidth]; + } + const { + curves, + width, + height + } = lines; + const thickness = lines.thickness ?? 0; + const linesAndPoints = []; + const ratio = Math.min(pageWidth / width, pageHeight / height); + const xScale = ratio / pageWidth; + const yScale = ratio / pageHeight; + const newCurves = []; + for (const { + points + } of curves) { + const reducedPoints = mustSmooth ? this.#douglasPeucker(points) : points; + if (!reducedPoints) { + continue; + } + newCurves.push(reducedPoints); + const len = reducedPoints.length; + const newPoints = new Float32Array(len); + const line = new Float32Array(3 * (len === 2 ? 2 : len - 2)); + linesAndPoints.push({ + line, + points: newPoints + }); + if (len === 2) { + newPoints[0] = reducedPoints[0] * xScale; + newPoints[1] = reducedPoints[1] * yScale; + line.set([NaN, NaN, NaN, NaN, newPoints[0], newPoints[1]], 0); + continue; + } + let [x1, y1, x2, y22] = reducedPoints; + x1 *= xScale; + y1 *= yScale; + x2 *= xScale; + y22 *= yScale; + newPoints.set([x1, y1, x2, y22], 0); + line.set([NaN, NaN, NaN, NaN, x1, y1], 0); + for (let i7 = 4; i7 < len; i7 += 2) { + const x3 = newPoints[i7] = reducedPoints[i7] * xScale; + const y4 = newPoints[i7 + 1] = reducedPoints[i7 + 1] * yScale; + line.set(Outline.createBezierPoints(x1, y1, x2, y22, x3, y4), (i7 - 2) * 3); + [x1, y1, x2, y22] = [x2, y22, x3, y4]; + } + } + if (linesAndPoints.length === 0) { + return null; + } + const outline = areContours ? new ContourDrawOutline() : new InkDrawOutline(); + outline.build(linesAndPoints, pageWidth, pageHeight, 1, rotation, areContours ? 0 : thickness, innerMargin); + return { + outline, + newCurves, + areContours, + thickness, + width, + height + }; + } + static async compressSignature({ + outlines, + areContours, + thickness, + width, + height + }) { + let minDiff = Infinity; + let maxDiff = -Infinity; + let outlinesLength = 0; + for (const points of outlines) { + outlinesLength += points.length; + for (let i7 = 2, ii = points.length; i7 < ii; i7++) { + const dx = points[i7] - points[i7 - 2]; + minDiff = Math.min(minDiff, dx); + maxDiff = Math.max(maxDiff, dx); + } + } + let bufferType; + if (minDiff >= -128 && maxDiff <= 127) { + bufferType = Int8Array; + } else if (minDiff >= -32768 && maxDiff <= 32767) { + bufferType = Int16Array; + } else { + bufferType = Int32Array; + } + const len = outlines.length; + const headerLength = BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * len; + const header = new Uint32Array(headerLength); + let offset = 0; + header[offset++] = headerLength * Uint32Array.BYTES_PER_ELEMENT + (outlinesLength - 2 * len) * bufferType.BYTES_PER_ELEMENT; + header[offset++] = 0; + header[offset++] = width; + header[offset++] = height; + header[offset++] = areContours ? 0 : 1; + header[offset++] = Math.max(0, Math.floor(thickness ?? 0)); + header[offset++] = len; + header[offset++] = bufferType.BYTES_PER_ELEMENT; + for (const points of outlines) { + header[offset++] = points.length - 2; + header[offset++] = points[0]; + header[offset++] = points[1]; + } + const cs = new CompressionStream("deflate-raw"); + const writer = cs.writable.getWriter(); + await writer.ready; + writer.write(header); + const BufferCtor = bufferType.prototype.constructor; + for (const points of outlines) { + const diffs = new BufferCtor(points.length - 2); + for (let i7 = 2, ii = points.length; i7 < ii; i7++) { + diffs[i7 - 2] = points[i7] - points[i7 - 2]; + } + writer.write(diffs); + } + writer.close(); + const buf = await new Response(cs.readable).arrayBuffer(); + const bytes = new Uint8Array(buf); + return toBase64Util(bytes); + } + static async decompressSignature(signatureData) { + try { + const bytes = fromBase64Util(signatureData); + const { + readable, + writable + } = new DecompressionStream("deflate-raw"); + const writer = writable.getWriter(); + await writer.ready; + writer.write(bytes).then(async () => { + await writer.ready; + await writer.close(); + }).catch(() => { + }); + let data = null; + let offset = 0; + for await (const chunk of readable) { + data ||= new Uint8Array(new Uint32Array(chunk.buffer, 0, 4)[0]); + data.set(chunk, offset); + offset += chunk.length; + } + const header = new Uint32Array(data.buffer, 0, data.length >> 2); + const version6 = header[1]; + if (version6 !== 0) { + throw new Error(`Invalid version: ${version6}`); + } + const width = header[2]; + const height = header[3]; + const areContours = header[4] === 0; + const thickness = header[5]; + const numberOfDrawings = header[6]; + const bufferType = header[7]; + const outlines = []; + const diffsOffset = (BASE_HEADER_LENGTH + POINTS_PROPERTIES_NUMBER * numberOfDrawings) * Uint32Array.BYTES_PER_ELEMENT; + let diffs; + switch (bufferType) { + case Int8Array.BYTES_PER_ELEMENT: + diffs = new Int8Array(data.buffer, diffsOffset); + break; + case Int16Array.BYTES_PER_ELEMENT: + diffs = new Int16Array(data.buffer, diffsOffset); + break; + case Int32Array.BYTES_PER_ELEMENT: + diffs = new Int32Array(data.buffer, diffsOffset); + break; + } + offset = 0; + for (let i7 = 0; i7 < numberOfDrawings; i7++) { + const len = header[POINTS_PROPERTIES_NUMBER * i7 + BASE_HEADER_LENGTH]; + const points = new Float32Array(len + 2); + outlines.push(points); + for (let j3 = 0; j3 < POINTS_PROPERTIES_NUMBER - 1; j3++) { + points[j3] = header[POINTS_PROPERTIES_NUMBER * i7 + BASE_HEADER_LENGTH + j3 + 1]; + } + for (let j3 = 0; j3 < len; j3++) { + points[j3 + 2] = points[j3] + diffs[offset++]; + } + } + return { + areContours, + thickness, + outlines, + width, + height + }; + } catch (e9) { + warn(`decompressSignature: ${e9}`); + return null; + } + } + }; + SignatureOptions = class _SignatureOptions extends DrawingOptions { + constructor() { + super(); + super.updateProperties({ + fill: AnnotationEditor._defaultLineColor, + "stroke-width": 0 + }); + } + clone() { + const clone3 = new _SignatureOptions(); + clone3.updateAll(this); + return clone3; + } + }; + DrawnSignatureOptions = class _DrawnSignatureOptions extends InkDrawingOptions { + constructor(viewerParameters) { + super(viewerParameters); + super.updateProperties({ + stroke: AnnotationEditor._defaultLineColor, + "stroke-width": 1 + }); + } + clone() { + const clone3 = new _DrawnSignatureOptions(this._viewParameters); + clone3.updateAll(this); + return clone3; + } + }; + SignatureEditor = class _SignatureEditor extends DrawingEditor { + #isExtracted = false; + #description = null; + #signatureData = null; + #signatureUUID = null; + static _type = "signature"; + static _editorType = AnnotationEditorType.SIGNATURE; + static _defaultDrawingOptions = null; + constructor(params) { + super({ + ...params, + mustBeCommitted: true, + name: "signatureEditor" + }); + this._willKeepAspectRatio = true; + this.#signatureData = params.signatureData || null; + this.#description = null; + this.defaultL10nId = "pdfjs-editor-signature-editor1"; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + this._defaultDrawingOptions = new SignatureOptions(); + this._defaultDrawnSignatureOptions = new DrawnSignatureOptions(uiManager.viewParameters); + } + static getDefaultDrawingOptions(options) { + const clone3 = this._defaultDrawingOptions.clone(); + clone3.updateProperties(options); + return clone3; + } + static get supportMultipleDrawings() { + return false; + } + static get typesMap() { + return shadow(this, "typesMap", /* @__PURE__ */ new Map()); + } + static get isDrawer() { + return false; + } + get telemetryFinalData() { + return { + type: "signature", + hasDescription: !!this.#description + }; + } + static computeTelemetryFinalData(data) { + const hasDescriptionStats = data.get("hasDescription"); + return { + hasAltText: hasDescriptionStats.get(true) ?? 0, + hasNoAltText: hasDescriptionStats.get(false) ?? 0 + }; + } + get isResizable() { + return true; + } + onScaleChanging() { + if (this._drawId === null) { + return; + } + super.onScaleChanging(); + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + const { + _isCopy + } = this; + if (_isCopy) { + this._isCopy = false; + baseX = this.x; + baseY = this.y; + } + super.render(); + if (this._drawId === null) { + if (this.#signatureData) { + const { + lines, + mustSmooth, + areContours, + description, + uuid, + heightInPage + } = this.#signatureData; + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + const outline = SignatureExtractor.processDrawnLines({ + lines, + pageWidth, + pageHeight, + rotation, + innerMargin: _SignatureEditor._INNER_MARGIN, + mustSmooth, + areContours + }); + this.addSignature(outline, heightInPage, description, uuid); + } else { + this.div.setAttribute("data-l10n-args", JSON.stringify({ + description: "" + })); + this.div.hidden = true; + this._uiManager.getSignature(this); + } + } else { + this.div.setAttribute("data-l10n-args", JSON.stringify({ + description: this.#description || "" + })); + } + if (_isCopy) { + this._isCopy = true; + this._moveAfterPaste(baseX, baseY); + } + return this.div; + } + setUuid(uuid) { + this.#signatureUUID = uuid; + this.addEditToolbar(); + } + getUuid() { + return this.#signatureUUID; + } + get description() { + return this.#description; + } + set description(description) { + this.#description = description; + if (!this.div) { + return; + } + this.div.setAttribute("data-l10n-args", JSON.stringify({ + description + })); + super.addEditToolbar().then((toolbar) => { + toolbar?.updateEditSignatureButton(description); + }); + } + getSignaturePreview() { + const { + newCurves, + areContours, + thickness, + width, + height + } = this.#signatureData; + const maxDim = Math.max(width, height); + const outlineData = SignatureExtractor.processDrawnLines({ + lines: { + curves: newCurves.map((points) => ({ + points + })), + thickness, + width, + height + }, + pageWidth: maxDim, + pageHeight: maxDim, + rotation: 0, + innerMargin: 0, + mustSmooth: false, + areContours + }); + return { + areContours, + outline: outlineData.outline + }; + } + get toolbarButtons() { + if (this._uiManager.signatureManager) { + return [["editSignature", this._uiManager.signatureManager]]; + } + return super.toolbarButtons; + } + addSignature(data, heightInPage, description, uuid) { + const { + x: savedX, + y: savedY + } = this; + const { + outline + } = this.#signatureData = data; + this.#isExtracted = outline instanceof ContourDrawOutline; + this.description = description; + let drawingOptions; + if (this.#isExtracted) { + drawingOptions = _SignatureEditor.getDefaultDrawingOptions(); + } else { + drawingOptions = _SignatureEditor._defaultDrawnSignatureOptions.clone(); + drawingOptions.updateProperties({ + "stroke-width": outline.thickness + }); + } + this._addOutlines({ + drawOutlines: outline, + drawingOptions + }); + const [, pageHeight] = this.pageDimensions; + let newHeight = heightInPage / pageHeight; + newHeight = newHeight >= 1 ? 0.5 : newHeight; + this.width *= newHeight / this.height; + if (this.width >= 1) { + newHeight *= 0.9 / this.width; + this.width = 0.9; + } + this.height = newHeight; + this.setDims(); + this.x = savedX; + this.y = savedY; + this.center(); + this._onResized(); + this.onScaleChanging(); + this.rotate(); + this._uiManager.addToAnnotationStorage(this); + this.setUuid(uuid); + this._reportTelemetry({ + action: "pdfjs.signature.inserted", + data: { + hasBeenSaved: !!uuid, + hasDescription: !!description + } + }); + this.div.hidden = false; + } + getFromImage(bitmap) { + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + return SignatureExtractor.process(bitmap, pageWidth, pageHeight, rotation, _SignatureEditor._INNER_MARGIN); + } + getFromText(text3, fontInfo) { + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + return SignatureExtractor.extractContoursFromText(text3, fontInfo, pageWidth, pageHeight, rotation, _SignatureEditor._INNER_MARGIN); + } + getDrawnSignature(curves) { + const { + rawDims: { + pageWidth, + pageHeight + }, + rotation + } = this.parent.viewport; + return SignatureExtractor.processDrawnLines({ + lines: curves, + pageWidth, + pageHeight, + rotation, + innerMargin: _SignatureEditor._INNER_MARGIN, + mustSmooth: false, + areContours: false + }); + } + createDrawingOptions({ + areContours, + thickness + }) { + if (areContours) { + this._drawingOptions = _SignatureEditor.getDefaultDrawingOptions(); + } else { + this._drawingOptions = _SignatureEditor._defaultDrawnSignatureOptions.clone(); + this._drawingOptions.updateProperties({ + "stroke-width": thickness + }); + } + } + serialize(isForCopying = false) { + if (this.isEmpty()) { + return null; + } + const { + lines, + points + } = this.serializeDraw(isForCopying); + const { + _drawingOptions: { + "stroke-width": thickness + } + } = this; + const serialized = Object.assign(super.serialize(isForCopying), { + isSignature: true, + areContours: this.#isExtracted, + color: [0, 0, 0], + thickness: this.#isExtracted ? 0 : thickness + }); + this.addComment(serialized); + if (isForCopying) { + serialized.paths = { + lines, + points + }; + serialized.uuid = this.#signatureUUID; + serialized.isCopy = true; + } else { + serialized.lines = lines; + } + if (this.#description) { + serialized.accessibilityData = { + type: "Figure", + alt: this.#description + }; + } + return serialized; + } + static deserializeDraw(pageX, pageY, pageWidth, pageHeight, innerMargin, data) { + if (data.areContours) { + return ContourDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + return InkDrawOutline.deserialize(pageX, pageY, pageWidth, pageHeight, innerMargin, data); + } + static async deserialize(data, parent, uiManager) { + const editor = await super.deserialize(data, parent, uiManager); + editor.#isExtracted = data.areContours; + editor.description = data.accessibilityData?.alt || ""; + editor.#signatureUUID = data.uuid; + return editor; + } + }; + StampEditor = class extends AnnotationEditor { + #bitmap = null; + #bitmapId = null; + #bitmapPromise = null; + #bitmapUrl = null; + #bitmapFile = null; + #bitmapFileName = ""; + #canvas = null; + #missingCanvas = false; + #resizeTimeoutId = null; + #isSvg = false; + #hasBeenAddedInUndoStack = false; + static _type = "stamp"; + static _editorType = AnnotationEditorType.STAMP; + constructor(params) { + super({ + ...params, + name: "stampEditor" + }); + this.#bitmapUrl = params.bitmapUrl; + this.#bitmapFile = params.bitmapFile; + this.defaultL10nId = "pdfjs-editor-stamp-editor"; + } + static initialize(l10n, uiManager) { + AnnotationEditor.initialize(l10n, uiManager); + } + static isHandlingMimeForPasting(mime) { + return SupportedImageMimeTypes.includes(mime); + } + static paste(item, parent) { + parent.pasteEditor({ + mode: AnnotationEditorType.STAMP + }, { + bitmapFile: item.getAsFile() + }); + } + altTextFinish() { + if (this._uiManager.useNewAltTextFlow) { + this.div.hidden = false; + } + super.altTextFinish(); + } + get telemetryFinalData() { + return { + type: "stamp", + hasAltText: !!this.altTextData?.altText + }; + } + static computeTelemetryFinalData(data) { + const hasAltTextStats = data.get("hasAltText"); + return { + hasAltText: hasAltTextStats.get(true) ?? 0, + hasNoAltText: hasAltTextStats.get(false) ?? 0 + }; + } + #getBitmapFetched(data, fromId = false) { + if (!data) { + this.remove(); + return; + } + this.#bitmap = data.bitmap; + if (!fromId) { + this.#bitmapId = data.id; + this.#isSvg = data.isSvg; + } + if (data.file) { + this.#bitmapFileName = data.file.name; + } + this.#createCanvas(); + } + #getBitmapDone() { + this.#bitmapPromise = null; + this._uiManager.enableWaiting(false); + if (!this.#canvas) { + return; + } + if (this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this.addEditToolbar().then(() => { + this._editToolbar.hide(); + this._uiManager.editAltText(this, true); + }); + return; + } + if (!this._uiManager.useNewAltTextWhenAddingImage && this._uiManager.useNewAltTextFlow && this.#bitmap) { + this._reportTelemetry({ + action: "pdfjs.image.image_added", + data: { + alt_text_modal: false, + alt_text_type: "empty" + } + }); + try { + this.mlGuessAltText(); + } catch { + } + } + this.div.focus(); + } + async mlGuessAltText(imageData = null, updateAltTextData = true) { + if (this.hasAltTextData()) { + return null; + } + const { + mlManager + } = this._uiManager; + if (!mlManager) { + throw new Error("No ML."); + } + if (!await mlManager.isEnabledFor("altText")) { + throw new Error("ML isn't enabled for alt text."); + } + const { + data, + width, + height + } = imageData || this.copyCanvas(null, null, true).imageData; + const response = await mlManager.guess({ + name: "altText", + request: { + data, + width, + height, + channels: data.length / (width * height) + } + }); + if (!response) { + throw new Error("No response from the AI service."); + } + if (response.error) { + throw new Error("Error from the AI service."); + } + if (response.cancel) { + return null; + } + if (!response.output) { + throw new Error("No valid response from the AI service."); + } + const altText = response.output; + await this.setGuessedAltText(altText); + if (updateAltTextData && !this.hasAltTextData()) { + this.altTextData = { + alt: altText, + decorative: false + }; + } + return altText; + } + #getBitmap() { + if (this.#bitmapId) { + this._uiManager.enableWaiting(true); + this._uiManager.imageManager.getFromId(this.#bitmapId).then((data) => this.#getBitmapFetched(data, true)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapUrl) { + const url = this.#bitmapUrl; + this.#bitmapUrl = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromUrl(url).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + if (this.#bitmapFile) { + const file = this.#bitmapFile; + this.#bitmapFile = null; + this._uiManager.enableWaiting(true); + this.#bitmapPromise = this._uiManager.imageManager.getFromFile(file).then((data) => this.#getBitmapFetched(data)).finally(() => this.#getBitmapDone()); + return; + } + const input = document.createElement("input"); + input.type = "file"; + input.accept = SupportedImageMimeTypes.join(","); + const signal = this._uiManager._signal; + this.#bitmapPromise = new Promise((resolve2) => { + input.addEventListener("change", async () => { + if (!input.files || input.files.length === 0) { + this.remove(); + } else { + this._uiManager.enableWaiting(true); + const data = await this._uiManager.imageManager.getFromFile(input.files[0]); + this._reportTelemetry({ + action: "pdfjs.image.image_selected", + data: { + alt_text_modal: this._uiManager.useNewAltTextFlow + } + }); + this.#getBitmapFetched(data); + } + resolve2(); + }, { + signal + }); + input.addEventListener("cancel", () => { + this.remove(); + resolve2(); + }, { + signal + }); + }).finally(() => this.#getBitmapDone()); + input.click(); + } + remove() { + if (this.#bitmapId) { + this.#bitmap = null; + this._uiManager.imageManager.deleteId(this.#bitmapId); + this.#canvas?.remove(); + this.#canvas = null; + if (this.#resizeTimeoutId) { + clearTimeout(this.#resizeTimeoutId); + this.#resizeTimeoutId = null; + } + } + super.remove(); + } + rebuild() { + if (!this.parent) { + if (this.#bitmapId) { + this.#getBitmap(); + } + return; + } + super.rebuild(); + if (this.div === null) { + return; + } + if (this.#bitmapId && this.#canvas === null) { + this.#getBitmap(); + } + if (!this.isAttachedToDOM) { + this.parent.add(this); + } + } + onceAdded(focus) { + this._isDraggable = true; + if (focus) { + this.div.focus(); + } + } + isEmpty() { + return !(this.#bitmapPromise || this.#bitmap || this.#bitmapUrl || this.#bitmapFile || this.#bitmapId || this.#missingCanvas); + } + get toolbarButtons() { + return [["altText", this.createAltText()]]; + } + get isResizable() { + return true; + } + render() { + if (this.div) { + return this.div; + } + let baseX, baseY; + if (this._isCopy) { + baseX = this.x; + baseY = this.y; + } + super.render(); + this.div.hidden = true; + this.createAltText(); + if (!this.#missingCanvas) { + if (this.#bitmap) { + this.#createCanvas(); + } else { + this.#getBitmap(); + } + } + if (this._isCopy) { + this._moveAfterPaste(baseX, baseY); + } + this._uiManager.addShouldRescale(this); + return this.div; + } + setCanvas(annotationElementId, canvas) { + const { + id: bitmapId, + bitmap + } = this._uiManager.imageManager.getFromCanvas(annotationElementId, canvas); + canvas.remove(); + if (bitmapId && this._uiManager.imageManager.isValidId(bitmapId)) { + this.#bitmapId = bitmapId; + if (bitmap) { + this.#bitmap = bitmap; + } + this.#missingCanvas = false; + this.#createCanvas(); + } + } + _onResized() { + this.onScaleChanging(); + } + onScaleChanging() { + if (!this.parent) { + return; + } + if (this.#resizeTimeoutId !== null) { + clearTimeout(this.#resizeTimeoutId); + } + const TIME_TO_WAIT = 200; + this.#resizeTimeoutId = setTimeout(() => { + this.#resizeTimeoutId = null; + this.#drawBitmap(); + }, TIME_TO_WAIT); + } + #createCanvas() { + const { + div + } = this; + let { + width, + height + } = this.#bitmap; + const [pageWidth, pageHeight] = this.pageDimensions; + const MAX_RATIO = 0.75; + if (this.width) { + width = this.width * pageWidth; + height = this.height * pageHeight; + } else if (width > MAX_RATIO * pageWidth || height > MAX_RATIO * pageHeight) { + const factor = Math.min(MAX_RATIO * pageWidth / width, MAX_RATIO * pageHeight / height); + width *= factor; + height *= factor; + } + this._uiManager.enableWaiting(false); + const canvas = this.#canvas = document.createElement("canvas"); + canvas.setAttribute("role", "img"); + this.addContainer(canvas); + this.width = width / pageWidth; + this.height = height / pageHeight; + this.setDims(); + if (this._initialOptions?.isCentered) { + this.center(); + } else { + this.fixAndSetPosition(); + } + this._initialOptions = null; + if (!this._uiManager.useNewAltTextWhenAddingImage || !this._uiManager.useNewAltTextFlow || this.annotationElementId) { + div.hidden = false; + } + this.#drawBitmap(); + if (!this.#hasBeenAddedInUndoStack) { + this.parent.addUndoableEditor(this); + this.#hasBeenAddedInUndoStack = true; + } + this._reportTelemetry({ + action: "inserted_image" + }); + if (this.#bitmapFileName) { + this.div.setAttribute("aria-description", this.#bitmapFileName); + } + if (!this.annotationElementId) { + this._uiManager.a11yAlert("pdfjs-editor-stamp-added-alert"); + } + } + copyCanvas(maxDataDimension, maxPreviewDimension, createImageData = false) { + if (!maxDataDimension) { + maxDataDimension = 224; + } + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + const outputScale = new OutputScale(); + let bitmap = this.#bitmap; + let width = bitmapWidth, height = bitmapHeight; + let canvas = null; + if (maxPreviewDimension) { + if (bitmapWidth > maxPreviewDimension || bitmapHeight > maxPreviewDimension) { + const ratio = Math.min(maxPreviewDimension / bitmapWidth, maxPreviewDimension / bitmapHeight); + width = Math.floor(bitmapWidth * ratio); + height = Math.floor(bitmapHeight * ratio); + } + canvas = document.createElement("canvas"); + const scaledWidth = canvas.width = Math.ceil(width * outputScale.sx); + const scaledHeight = canvas.height = Math.ceil(height * outputScale.sy); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(scaledWidth, scaledHeight); + } + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + let white = "white", black = "#cfcfd8"; + if (this._uiManager.hcmFilter !== "none") { + black = "black"; + } else if (ColorScheme.isDarkMode) { + white = "#8f8f9d"; + black = "#42414d"; + } + const boxDim = 15; + const boxDimWidth = boxDim * outputScale.sx; + const boxDimHeight = boxDim * outputScale.sy; + const pattern = new OffscreenCanvas(boxDimWidth * 2, boxDimHeight * 2); + const patternCtx = pattern.getContext("2d"); + patternCtx.fillStyle = white; + patternCtx.fillRect(0, 0, boxDimWidth * 2, boxDimHeight * 2); + patternCtx.fillStyle = black; + patternCtx.fillRect(0, 0, boxDimWidth, boxDimHeight); + patternCtx.fillRect(boxDimWidth, boxDimHeight, boxDimWidth, boxDimHeight); + ctx.fillStyle = ctx.createPattern(pattern, "repeat"); + ctx.fillRect(0, 0, scaledWidth, scaledHeight); + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + let imageData = null; + if (createImageData) { + let dataWidth, dataHeight; + if (outputScale.symmetric && bitmap.width < maxDataDimension && bitmap.height < maxDataDimension) { + dataWidth = bitmap.width; + dataHeight = bitmap.height; + } else { + bitmap = this.#bitmap; + if (bitmapWidth > maxDataDimension || bitmapHeight > maxDataDimension) { + const ratio = Math.min(maxDataDimension / bitmapWidth, maxDataDimension / bitmapHeight); + dataWidth = Math.floor(bitmapWidth * ratio); + dataHeight = Math.floor(bitmapHeight * ratio); + if (!this.#isSvg) { + bitmap = this.#scaleBitmap(dataWidth, dataHeight); + } + } + } + const offscreen = new OffscreenCanvas(dataWidth, dataHeight); + const offscreenCtx = offscreen.getContext("2d", { + willReadFrequently: true + }); + offscreenCtx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, dataWidth, dataHeight); + imageData = { + width: dataWidth, + height: dataHeight, + data: offscreenCtx.getImageData(0, 0, dataWidth, dataHeight).data + }; + } + return { + canvas, + width, + height, + imageData + }; + } + #scaleBitmap(width, height) { + const { + width: bitmapWidth, + height: bitmapHeight + } = this.#bitmap; + let newWidth = bitmapWidth; + let newHeight = bitmapHeight; + let bitmap = this.#bitmap; + while (newWidth > 2 * width || newHeight > 2 * height) { + const prevWidth = newWidth; + const prevHeight = newHeight; + if (newWidth > 2 * width) { + newWidth = newWidth >= 16384 ? Math.floor(newWidth / 2) - 1 : Math.ceil(newWidth / 2); + } + if (newHeight > 2 * height) { + newHeight = newHeight >= 16384 ? Math.floor(newHeight / 2) - 1 : Math.ceil(newHeight / 2); + } + const offscreen = new OffscreenCanvas(newWidth, newHeight); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(bitmap, 0, 0, prevWidth, prevHeight, 0, 0, newWidth, newHeight); + bitmap = offscreen.transferToImageBitmap(); + } + return bitmap; + } + #drawBitmap() { + const [parentWidth, parentHeight] = this.parentDimensions; + const { + width, + height + } = this; + const outputScale = new OutputScale(); + const scaledWidth = Math.ceil(width * parentWidth * outputScale.sx); + const scaledHeight = Math.ceil(height * parentHeight * outputScale.sy); + const canvas = this.#canvas; + if (!canvas || canvas.width === scaledWidth && canvas.height === scaledHeight) { + return; + } + canvas.width = scaledWidth; + canvas.height = scaledHeight; + const bitmap = this.#isSvg ? this.#bitmap : this.#scaleBitmap(scaledWidth, scaledHeight); + const ctx = canvas.getContext("2d"); + ctx.filter = this._uiManager.hcmFilter; + ctx.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, scaledWidth, scaledHeight); + } + #serializeBitmap(toUrl) { + if (toUrl) { + if (this.#isSvg) { + const url = this._uiManager.imageManager.getSvgUrl(this.#bitmapId); + if (url) { + return url; + } + } + const canvas = document.createElement("canvas"); + ({ + width: canvas.width, + height: canvas.height + } = this.#bitmap); + const ctx = canvas.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0); + return canvas.toDataURL(); + } + if (this.#isSvg) { + const [pageWidth, pageHeight] = this.pageDimensions; + const width = Math.round(this.width * pageWidth * PixelsPerInch.PDF_TO_CSS_UNITS); + const height = Math.round(this.height * pageHeight * PixelsPerInch.PDF_TO_CSS_UNITS); + const offscreen = new OffscreenCanvas(width, height); + const ctx = offscreen.getContext("2d"); + ctx.drawImage(this.#bitmap, 0, 0, this.#bitmap.width, this.#bitmap.height, 0, 0, width, height); + return offscreen.transferToImageBitmap(); + } + return structuredClone(this.#bitmap); + } + static async deserialize(data, parent, uiManager) { + let initialData = null; + let missingCanvas = false; + if (data instanceof StampAnnotationElement) { + const { + data: { + rect: rect2, + rotation, + id, + structParent, + popupRef, + richText, + contentsObj, + creationDate, + modificationDate + }, + container, + parent: { + page: { + pageNumber + } + }, + canvas + } = data; + let bitmapId2, bitmap2; + if (canvas) { + delete data.canvas; + ({ + id: bitmapId2, + bitmap: bitmap2 + } = uiManager.imageManager.getFromCanvas(container.id, canvas)); + canvas.remove(); + } else { + missingCanvas = true; + data._hasNoCanvas = true; + } + const altText = (await parent._structTree.getAriaAttributes(`${AnnotationPrefix}${id}`))?.get("aria-label") || ""; + initialData = data = { + annotationType: AnnotationEditorType.STAMP, + bitmapId: bitmapId2, + bitmap: bitmap2, + pageIndex: pageNumber - 1, + rect: rect2.slice(0), + rotation, + annotationElementId: id, + id, + deleted: false, + accessibilityData: { + decorative: false, + altText + }, + isSvg: false, + structParent, + popupRef, + richText, + comment: contentsObj?.str || null, + creationDate, + modificationDate + }; + } + const editor = await super.deserialize(data, parent, uiManager); + const { + rect, + bitmap, + bitmapUrl, + bitmapId, + isSvg, + accessibilityData + } = data; + if (missingCanvas) { + uiManager.addMissingCanvas(data.id, editor); + editor.#missingCanvas = true; + } else if (bitmapId && uiManager.imageManager.isValidId(bitmapId)) { + editor.#bitmapId = bitmapId; + if (bitmap) { + editor.#bitmap = bitmap; + } + } else { + editor.#bitmapUrl = bitmapUrl; + } + editor.#isSvg = isSvg; + const [parentWidth, parentHeight] = editor.pageDimensions; + editor.width = (rect[2] - rect[0]) / parentWidth; + editor.height = (rect[3] - rect[1]) / parentHeight; + if (accessibilityData) { + editor.altTextData = accessibilityData; + } + editor._initialData = initialData; + if (data.comment) { + editor.setCommentData(data); + } + editor.#hasBeenAddedInUndoStack = !!initialData; + return editor; + } + serialize(isForCopying = false, context = null) { + if (this.isEmpty()) { + return null; + } + if (this.deleted) { + return this.serializeDeleted(); + } + const serialized = Object.assign(super.serialize(isForCopying), { + bitmapId: this.#bitmapId, + isSvg: this.#isSvg + }); + this.addComment(serialized); + if (isForCopying) { + serialized.bitmapUrl = this.#serializeBitmap(true); + serialized.accessibilityData = this.serializeAltText(true); + serialized.isCopy = true; + return serialized; + } + const { + decorative, + altText + } = this.serializeAltText(false); + if (!decorative && altText) { + serialized.accessibilityData = { + type: "Figure", + alt: altText + }; + } + if (this.annotationElementId) { + const changes = this.#hasElementChanged(serialized); + if (changes.isSame) { + return null; + } + if (changes.isSameAltText) { + delete serialized.accessibilityData; + } else { + serialized.accessibilityData.structParent = this._initialData.structParent ?? -1; + } + serialized.id = this.annotationElementId; + delete serialized.bitmapId; + return serialized; + } + if (context === null) { + return serialized; + } + context.stamps ||= /* @__PURE__ */ new Map(); + const area = this.#isSvg ? (serialized.rect[2] - serialized.rect[0]) * (serialized.rect[3] - serialized.rect[1]) : null; + if (!context.stamps.has(this.#bitmapId)) { + context.stamps.set(this.#bitmapId, { + area, + serialized + }); + serialized.bitmap = this.#serializeBitmap(false); + } else if (this.#isSvg) { + const prevData = context.stamps.get(this.#bitmapId); + if (area > prevData.area) { + prevData.area = area; + prevData.serialized.bitmap.close(); + prevData.serialized.bitmap = this.#serializeBitmap(false); + } + } + return serialized; + } + #hasElementChanged(serialized) { + const { + pageIndex, + accessibilityData: { + altText + } + } = this._initialData; + const isSamePageIndex = serialized.pageIndex === pageIndex; + const isSameAltText = (serialized.accessibilityData?.alt || "") === altText; + return { + isSame: !this.hasEditedComment && !this._hasBeenMoved && !this._hasBeenResized && isSamePageIndex && isSameAltText, + isSameAltText + }; + } + renderAnnotationElement(annotation) { + if (this.deleted) { + annotation.hide(); + return null; + } + annotation.updateEdited({ + rect: this.getPDFRect(), + popup: this.comment + }); + return null; + } + }; + AnnotationEditorLayer = class _AnnotationEditorLayer { + #accessibilityManager; + #allowClick = false; + #annotationLayer = null; + #clickAC = null; + #editorFocusTimeoutId = null; + #editors = /* @__PURE__ */ new Map(); + #hadPointerDown = false; + #isDisabling = false; + #isEnabling = false; + #drawingAC = null; + #focusedElement = null; + #textLayer = null; + #textSelectionAC = null; + #textLayerDblClickAC = null; + #lastPointerDownTimestamp = -1; + #uiManager; + static _initialized = false; + static #editorTypes = new Map([FreeTextEditor, InkEditor, StampEditor, HighlightEditor, SignatureEditor].map((type) => [type._editorType, type])); + constructor({ + uiManager, + pageIndex, + div, + structTreeLayer, + accessibilityManager, + annotationLayer, + drawLayer, + textLayer, + viewport, + l10n + }) { + const editorTypes = [..._AnnotationEditorLayer.#editorTypes.values()]; + if (!_AnnotationEditorLayer._initialized) { + _AnnotationEditorLayer._initialized = true; + for (const editorType of editorTypes) { + editorType.initialize(l10n, uiManager); + } + } + uiManager.registerEditorTypes(editorTypes); + this.#uiManager = uiManager; + this.pageIndex = pageIndex; + this.div = div; + this.#accessibilityManager = accessibilityManager; + this.#annotationLayer = annotationLayer; + this.viewport = viewport; + this.#textLayer = textLayer; + this.drawLayer = drawLayer; + this._structTree = structTreeLayer; + this.#uiManager.addLayer(this); + } + get isEmpty() { + return this.#editors.size === 0; + } + get isInvisible() { + return this.isEmpty && this.#uiManager.getMode() === AnnotationEditorType.NONE; + } + updateToolbar(options) { + this.#uiManager.updateToolbar(options); + } + updateMode(mode = this.#uiManager.getMode()) { + this.#cleanup(); + switch (mode) { + case AnnotationEditorType.NONE: + this.div.classList.toggle("nonEditing", true); + this.disableTextSelection(); + this.togglePointerEvents(false); + this.toggleAnnotationLayerPointerEvents(true); + this.disableClick(); + return; + case AnnotationEditorType.INK: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + break; + case AnnotationEditorType.HIGHLIGHT: + this.enableTextSelection(); + this.togglePointerEvents(false); + this.disableClick(); + break; + default: + this.disableTextSelection(); + this.togglePointerEvents(true); + this.enableClick(); + } + this.toggleAnnotationLayerPointerEvents(false); + const { + classList + } = this.div; + classList.toggle("nonEditing", false); + if (mode === AnnotationEditorType.POPUP) { + classList.toggle("commentEditing", true); + } else { + classList.toggle("commentEditing", false); + for (const editorType of _AnnotationEditorLayer.#editorTypes.values()) { + classList.toggle(`${editorType._type}Editing`, mode === editorType._editorType); + } + } + this.div.hidden = false; + } + hasTextLayer(textLayer) { + return textLayer === this.#textLayer?.div; + } + setEditingState(isEditing) { + this.#uiManager.setEditingState(isEditing); + } + addCommands(params) { + this.#uiManager.addCommands(params); + } + cleanUndoStack(type) { + this.#uiManager.cleanUndoStack(type); + } + toggleDrawing(enabled = false) { + this.div.classList.toggle("drawing", !enabled); + } + togglePointerEvents(enabled = false) { + this.div.classList.toggle("disabled", !enabled); + } + toggleAnnotationLayerPointerEvents(enabled = false) { + this.#annotationLayer?.togglePointerEvents(enabled); + } + get #allEditorsIterator() { + return this.#editors.size !== 0 ? this.#editors.values() : this.#uiManager.getEditors(this.pageIndex); + } + async enable() { + this.#isEnabling = true; + this.div.tabIndex = 0; + this.togglePointerEvents(true); + this.div.classList.toggle("nonEditing", false); + this.#textLayerDblClickAC?.abort(); + this.#textLayerDblClickAC = null; + const annotationElementIds = /* @__PURE__ */ new Set(); + for (const editor of this.#allEditorsIterator) { + editor.enableEditing(); + editor.show(true); + if (editor.annotationElementId) { + this.#uiManager.removeChangedExistingAnnotation(editor); + annotationElementIds.add(editor.annotationElementId); + } + } + const annotationLayer = this.#annotationLayer; + if (annotationLayer) { + for (const editable of annotationLayer.getEditableAnnotations()) { + editable.hide(); + if (this.#uiManager.isDeletedAnnotationElement(editable.data.id)) { + continue; + } + if (annotationElementIds.has(editable.data.id)) { + continue; + } + const editor = await this.deserialize(editable); + if (!editor) { + continue; + } + this.addOrRebuild(editor); + editor.enableEditing(); + } + } + this.#isEnabling = false; + this.#uiManager._eventBus.dispatch("editorsrendered", { + source: this, + pageNumber: this.pageIndex + 1 + }); + } + disable() { + this.#isDisabling = true; + this.div.tabIndex = -1; + this.togglePointerEvents(false); + this.div.classList.toggle("nonEditing", true); + if (this.#textLayer && !this.#textLayerDblClickAC) { + this.#textLayerDblClickAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#textLayerDblClickAC); + this.#textLayer.div.addEventListener("pointerdown", (e9) => { + const DBL_CLICK_THRESHOLD = 500; + const { + clientX, + clientY, + timeStamp + } = e9; + const lastPointerDownTimestamp = this.#lastPointerDownTimestamp; + if (timeStamp - lastPointerDownTimestamp > DBL_CLICK_THRESHOLD) { + this.#lastPointerDownTimestamp = timeStamp; + return; + } + this.#lastPointerDownTimestamp = -1; + const { + classList: classList2 + } = this.div; + classList2.toggle("getElements", true); + const elements2 = document.elementsFromPoint(clientX, clientY); + classList2.toggle("getElements", false); + if (!this.div.contains(elements2[0])) { + return; + } + let id; + const regex = new RegExp(`^${AnnotationEditorPrefix}[0-9]+$`); + for (const element of elements2) { + if (regex.test(element.id)) { + id = element.id; + break; + } + } + if (!id) { + return; + } + const editor = this.#editors.get(id); + if (editor?.annotationElementId === null) { + e9.stopPropagation(); + e9.preventDefault(); + editor.dblclick(e9); + } + }, { + signal, + capture: true + }); + } + const annotationLayer = this.#annotationLayer; + const needFakeAnnotation = []; + if (annotationLayer) { + const changedAnnotations = /* @__PURE__ */ new Map(); + const resetAnnotations = /* @__PURE__ */ new Map(); + for (const editor of this.#allEditorsIterator) { + editor.disableEditing(); + if (!editor.annotationElementId) { + needFakeAnnotation.push(editor); + continue; + } + if (editor.serialize() !== null) { + changedAnnotations.set(editor.annotationElementId, editor); + continue; + } else { + resetAnnotations.set(editor.annotationElementId, editor); + } + this.getEditableAnnotation(editor.annotationElementId)?.show(); + editor.remove(); + } + const editables = annotationLayer.getEditableAnnotations(); + for (const editable of editables) { + const { + id + } = editable.data; + if (this.#uiManager.isDeletedAnnotationElement(id)) { + editable.updateEdited({ + deleted: true + }); + continue; + } + let editor = resetAnnotations.get(id); + if (editor) { + editor.resetAnnotationElement(editable); + editor.show(false); + editable.show(); + continue; + } + editor = changedAnnotations.get(id); + if (editor) { + this.#uiManager.addChangedExistingAnnotation(editor); + if (editor.renderAnnotationElement(editable)) { + editor.show(false); + } + } + editable.show(); + } + } + this.#cleanup(); + if (this.isEmpty) { + this.div.hidden = true; + } + const { + classList + } = this.div; + for (const editorType of _AnnotationEditorLayer.#editorTypes.values()) { + classList.remove(`${editorType._type}Editing`); + } + this.disableTextSelection(); + this.toggleAnnotationLayerPointerEvents(true); + annotationLayer?.updateFakeAnnotations(needFakeAnnotation); + this.#isDisabling = false; + } + getEditableAnnotation(id) { + return this.#annotationLayer?.getEditableAnnotation(id) || null; + } + setActiveEditor(editor) { + const currentActive = this.#uiManager.getActive(); + if (currentActive === editor) { + return; + } + this.#uiManager.setActiveEditor(editor); + } + enableTextSelection() { + this.div.tabIndex = -1; + if (this.#textLayer?.div && !this.#textSelectionAC) { + this.#textSelectionAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#textSelectionAC); + this.#textLayer.div.addEventListener("pointerdown", this.#textLayerPointerDown.bind(this), { + signal + }); + this.#textLayer.div.classList.add("highlighting"); + } + } + disableTextSelection() { + this.div.tabIndex = 0; + if (this.#textLayer?.div && this.#textSelectionAC) { + this.#textSelectionAC.abort(); + this.#textSelectionAC = null; + this.#textLayer.div.classList.remove("highlighting"); + } + } + #textLayerPointerDown(event) { + this.#uiManager.unselectAll(); + const { + target + } = event; + if (target === this.#textLayer.div || (target.getAttribute("role") === "img" || target.classList.contains("endOfContent")) && this.#textLayer.div.contains(target)) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + this.#uiManager.showAllEditors("highlight", true, true); + this.#textLayer.div.classList.add("free"); + this.toggleDrawing(); + HighlightEditor.startHighlighting(this, this.#uiManager.direction === "ltr", { + target: this.#textLayer.div, + x: event.x, + y: event.y + }); + this.#textLayer.div.addEventListener("pointerup", () => { + this.#textLayer.div.classList.remove("free"); + this.toggleDrawing(true); + }, { + once: true, + signal: this.#uiManager._signal + }); + event.preventDefault(); + } + } + enableClick() { + if (this.#clickAC) { + return; + } + this.#clickAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#clickAC); + this.div.addEventListener("pointerdown", this.pointerdown.bind(this), { + signal + }); + const pointerup = this.pointerup.bind(this); + this.div.addEventListener("pointerup", pointerup, { + signal + }); + this.div.addEventListener("pointercancel", pointerup, { + signal + }); + } + disableClick() { + this.#clickAC?.abort(); + this.#clickAC = null; + } + attach(editor) { + this.#editors.set(editor.id, editor); + const { + annotationElementId + } = editor; + if (annotationElementId && this.#uiManager.isDeletedAnnotationElement(annotationElementId)) { + this.#uiManager.removeDeletedAnnotationElement(editor); + } + } + detach(editor) { + this.#editors.delete(editor.id); + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + if (!this.#isDisabling && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor); + } + } + remove(editor) { + this.detach(editor); + this.#uiManager.removeEditor(editor); + editor.div.remove(); + editor.isAttachedToDOM = false; + } + changeParent(editor) { + if (editor.parent === this) { + return; + } + if (editor.parent && editor.annotationElementId) { + this.#uiManager.addDeletedAnnotationElement(editor.annotationElementId); + AnnotationEditor.deleteAnnotationElement(editor); + editor.annotationElementId = null; + } + this.attach(editor); + editor.parent?.detach(editor); + editor.setParent(this); + if (editor.div && editor.isAttachedToDOM) { + editor.div.remove(); + this.div.append(editor.div); + } + } + add(editor) { + if (editor.parent === this && editor.isAttachedToDOM) { + return; + } + this.changeParent(editor); + this.#uiManager.addEditor(editor); + this.attach(editor); + if (!editor.isAttachedToDOM) { + const div = editor.render(); + this.div.append(div); + editor.isAttachedToDOM = true; + } + editor.fixAndSetPosition(); + editor.onceAdded(!this.#isEnabling); + this.#uiManager.addToAnnotationStorage(editor); + editor._reportTelemetry(editor.telemetryInitialData); + } + moveEditorInDOM(editor) { + if (!editor.isAttachedToDOM) { + return; + } + const { + activeElement + } = document; + if (editor.div.contains(activeElement) && !this.#editorFocusTimeoutId) { + editor._focusEventsAllowed = false; + this.#editorFocusTimeoutId = setTimeout(() => { + this.#editorFocusTimeoutId = null; + if (!editor.div.contains(document.activeElement)) { + editor.div.addEventListener("focusin", () => { + editor._focusEventsAllowed = true; + }, { + once: true, + signal: this.#uiManager._signal + }); + activeElement.focus(); + } else { + editor._focusEventsAllowed = true; + } + }, 0); + } + editor._structTreeParentId = this.#accessibilityManager?.moveElementInDOM(this.div, editor.div, editor.contentDiv, true); + } + addOrRebuild(editor) { + if (editor.needsToBeRebuilt()) { + editor.parent ||= this; + editor.rebuild(); + editor.show(); + } else { + this.add(editor); + } + } + addUndoableEditor(editor) { + const cmd = () => editor._uiManager.rebuild(editor); + const undo = () => { + editor.remove(); + }; + this.addCommands({ + cmd, + undo, + mustExec: false + }); + } + getEditorByUID(uid2) { + for (const editor of this.#editors.values()) { + if (editor.uid === uid2) { + return editor; + } + } + return null; + } + getNextId() { + return this.#uiManager.getId(); + } + get #currentEditorType() { + return _AnnotationEditorLayer.#editorTypes.get(this.#uiManager.getMode()); + } + combinedSignal(ac) { + return this.#uiManager.combinedSignal(ac); + } + #createNewEditor(params) { + const editorType = this.#currentEditorType; + return editorType ? new editorType.prototype.constructor(params) : null; + } + canCreateNewEmptyEditor() { + return this.#currentEditorType?.canCreateNewEmptyEditor(); + } + async pasteEditor(options, params) { + this.updateToolbar(options); + await this.#uiManager.updateMode(options.mode); + const { + offsetX, + offsetY + } = this.#getCenterPoint(); + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: offsetX, + y: offsetY, + uiManager: this.#uiManager, + isCentered: true, + ...params + }); + if (editor) { + this.add(editor); + } + } + async deserialize(data) { + return await _AnnotationEditorLayer.#editorTypes.get(data.annotationType ?? data.annotationEditorType)?.deserialize(data, this, this.#uiManager) || null; + } + createAndAddNewEditor(event, isCentered, data = {}) { + const id = this.getNextId(); + const editor = this.#createNewEditor({ + parent: this, + id, + x: event.offsetX, + y: event.offsetY, + uiManager: this.#uiManager, + isCentered, + ...data + }); + if (editor) { + this.add(editor); + } + return editor; + } + get boundingClientRect() { + return this.div.getBoundingClientRect(); + } + #getCenterPoint() { + const { + x: x2, + y: y4, + width, + height + } = this.boundingClientRect; + const tlX = Math.max(0, x2); + const tlY = Math.max(0, y4); + const brX = Math.min(window.innerWidth, x2 + width); + const brY = Math.min(window.innerHeight, y4 + height); + const centerX = (tlX + brX) / 2 - x2; + const centerY = (tlY + brY) / 2 - y4; + const [offsetX, offsetY] = this.viewport.rotation % 180 === 0 ? [centerX, centerY] : [centerY, centerX]; + return { + offsetX, + offsetY + }; + } + addNewEditor(data = {}) { + this.createAndAddNewEditor(this.#getCenterPoint(), true, data); + } + setSelected(editor) { + this.#uiManager.setSelected(editor); + } + toggleSelected(editor) { + this.#uiManager.toggleSelected(editor); + } + unselect(editor) { + this.#uiManager.unselect(editor); + } + pointerup(event) { + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + if (!this.#hadPointerDown) { + return; + } + this.#hadPointerDown = false; + if (this.#currentEditorType?.isDrawer && this.#currentEditorType.supportMultipleDrawings) { + return; + } + if (!this.#allowClick) { + this.#allowClick = true; + return; + } + const currentMode = this.#uiManager.getMode(); + if (currentMode === AnnotationEditorType.STAMP || currentMode === AnnotationEditorType.SIGNATURE) { + this.#uiManager.unselectAll(); + return; + } + this.createAndAddNewEditor(event, false); + } + pointerdown(event) { + if (this.#uiManager.getMode() === AnnotationEditorType.HIGHLIGHT) { + this.enableTextSelection(); + } + if (this.#hadPointerDown) { + this.#hadPointerDown = false; + return; + } + const { + isMac + } = util_FeatureTest.platform; + if (event.button !== 0 || event.ctrlKey && isMac) { + return; + } + if (event.target !== this.div) { + return; + } + this.#hadPointerDown = true; + if (this.#currentEditorType?.isDrawer) { + this.startDrawingSession(event); + return; + } + const editor = this.#uiManager.getActive(); + this.#allowClick = !editor || editor.isEmpty(); + } + startDrawingSession(event) { + this.div.focus({ + preventScroll: true + }); + if (this.#drawingAC) { + this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); + return; + } + this.#uiManager.setCurrentDrawingSession(this); + this.#drawingAC = new AbortController(); + const signal = this.#uiManager.combinedSignal(this.#drawingAC); + this.div.addEventListener("blur", ({ + relatedTarget + }) => { + if (relatedTarget && !this.div.contains(relatedTarget)) { + this.#focusedElement = null; + this.commitOrRemove(); + } + }, { + signal + }); + this.#currentEditorType.startDrawing(this, this.#uiManager, false, event); + } + pause(on) { + if (on) { + const { + activeElement + } = document; + if (this.div.contains(activeElement)) { + this.#focusedElement = activeElement; + } + return; + } + if (this.#focusedElement) { + setTimeout(() => { + this.#focusedElement?.focus(); + this.#focusedElement = null; + }, 0); + } + } + endDrawingSession(isAborted3 = false) { + if (!this.#drawingAC) { + return null; + } + this.#uiManager.setCurrentDrawingSession(null); + this.#drawingAC.abort(); + this.#drawingAC = null; + this.#focusedElement = null; + return this.#currentEditorType.endDrawing(isAborted3); + } + findNewParent(editor, x2, y4) { + const layer = this.#uiManager.findParent(x2, y4); + if (layer === null || layer === this) { + return false; + } + layer.changeParent(editor); + return true; + } + commitOrRemove() { + if (this.#drawingAC) { + this.endDrawingSession(); + return true; + } + return false; + } + onScaleChanging() { + if (!this.#drawingAC) { + return; + } + this.#currentEditorType.onScaleChangingWhenDrawing(this); + } + destroy() { + this.commitOrRemove(); + if (this.#uiManager.getActive()?.parent === this) { + this.#uiManager.commitOrRemove(); + this.#uiManager.setActiveEditor(null); + } + if (this.#editorFocusTimeoutId) { + clearTimeout(this.#editorFocusTimeoutId); + this.#editorFocusTimeoutId = null; + } + for (const editor of this.#editors.values()) { + this.#accessibilityManager?.removePointerInTextLayer(editor.contentDiv); + editor.setParent(null); + editor.isAttachedToDOM = false; + editor.div.remove(); + } + this.div = null; + this.#editors.clear(); + this.#uiManager.removeLayer(this); + } + #cleanup() { + for (const editor of this.#editors.values()) { + if (editor.isEmpty()) { + editor.remove(); + } + } + } + render({ + viewport + }) { + this.viewport = viewport; + setLayerDimensions(this.div, viewport); + for (const editor of this.#uiManager.getEditors(this.pageIndex)) { + this.add(editor); + editor.rebuild(); + } + this.updateMode(); + } + update({ + viewport + }) { + this.#uiManager.commitOrRemove(); + this.#cleanup(); + const oldRotation = this.viewport.rotation; + const rotation = viewport.rotation; + this.viewport = viewport; + setLayerDimensions(this.div, { + rotation + }); + if (oldRotation !== rotation) { + for (const editor of this.#editors.values()) { + editor.rotate(rotation); + } + } + } + get pageDimensions() { + const { + pageWidth, + pageHeight + } = this.viewport.rawDims; + return [pageWidth, pageHeight]; + } + get scale() { + return this.#uiManager.viewParameters.realScale; + } + }; + DrawLayer = class _DrawLayer { + #parent = null; + #mapping = /* @__PURE__ */ new Map(); + #toUpdate = /* @__PURE__ */ new Map(); + static #id = 0; + constructor({ + pageIndex + }) { + this.pageIndex = pageIndex; + } + setParent(parent) { + if (!this.#parent) { + this.#parent = parent; + return; + } + if (this.#parent !== parent) { + if (this.#mapping.size > 0) { + for (const root of this.#mapping.values()) { + root.remove(); + parent.append(root); + } + } + this.#parent = parent; + } + } + static get _svgFactory() { + return shadow(this, "_svgFactory", new DOMSVGFactory()); + } + static #setBox(element, [x2, y4, width, height]) { + const { + style + } = element; + style.top = `${100 * y4}%`; + style.left = `${100 * x2}%`; + style.width = `${100 * width}%`; + style.height = `${100 * height}%`; + } + #createSVG() { + const svg = _DrawLayer._svgFactory.create(1, 1, true); + this.#parent.append(svg); + svg.setAttribute("aria-hidden", true); + return svg; + } + #createClipPath(defs, pathId) { + const clipPath = _DrawLayer._svgFactory.createElement("clipPath"); + defs.append(clipPath); + const clipPathId = `clip_${pathId}`; + clipPath.setAttribute("id", clipPathId); + clipPath.setAttribute("clipPathUnits", "objectBoundingBox"); + const clipPathUse = _DrawLayer._svgFactory.createElement("use"); + clipPath.append(clipPathUse); + clipPathUse.setAttribute("href", `#${pathId}`); + clipPathUse.classList.add("clip"); + return clipPathId; + } + #updateProperties(element, properties) { + for (const [key, value] of Object.entries(properties)) { + if (value === null) { + element.removeAttribute(key); + } else { + element.setAttribute(key, value); + } + } + } + draw(properties, isPathUpdatable = false, hasClip = false) { + const id = _DrawLayer.#id++; + const root = this.#createSVG(); + const defs = _DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path6 = _DrawLayer._svgFactory.createElement("path"); + defs.append(path6); + const pathId = `path_p${this.pageIndex}_${id}`; + path6.setAttribute("id", pathId); + path6.setAttribute("vector-effect", "non-scaling-stroke"); + if (isPathUpdatable) { + this.#toUpdate.set(id, path6); + } + const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null; + const use = _DrawLayer._svgFactory.createElement("use"); + root.append(use); + use.setAttribute("href", `#${pathId}`); + this.updateProperties(root, properties); + this.#mapping.set(id, root); + return { + id, + clipPathId: `url(#${clipPathId})` + }; + } + drawOutline(properties, mustRemoveSelfIntersections) { + const id = _DrawLayer.#id++; + const root = this.#createSVG(); + const defs = _DrawLayer._svgFactory.createElement("defs"); + root.append(defs); + const path6 = _DrawLayer._svgFactory.createElement("path"); + defs.append(path6); + const pathId = `path_p${this.pageIndex}_${id}`; + path6.setAttribute("id", pathId); + path6.setAttribute("vector-effect", "non-scaling-stroke"); + let maskId; + if (mustRemoveSelfIntersections) { + const mask = _DrawLayer._svgFactory.createElement("mask"); + defs.append(mask); + maskId = `mask_p${this.pageIndex}_${id}`; + mask.setAttribute("id", maskId); + mask.setAttribute("maskUnits", "objectBoundingBox"); + const rect = _DrawLayer._svgFactory.createElement("rect"); + mask.append(rect); + rect.setAttribute("width", "1"); + rect.setAttribute("height", "1"); + rect.setAttribute("fill", "white"); + const use = _DrawLayer._svgFactory.createElement("use"); + mask.append(use); + use.setAttribute("href", `#${pathId}`); + use.setAttribute("stroke", "none"); + use.setAttribute("fill", "black"); + use.setAttribute("fill-rule", "nonzero"); + use.classList.add("mask"); + } + const use1 = _DrawLayer._svgFactory.createElement("use"); + root.append(use1); + use1.setAttribute("href", `#${pathId}`); + if (maskId) { + use1.setAttribute("mask", `url(#${maskId})`); + } + const use2 = use1.cloneNode(); + root.append(use2); + use1.classList.add("mainOutline"); + use2.classList.add("secondaryOutline"); + this.updateProperties(root, properties); + this.#mapping.set(id, root); + return id; + } + finalizeDraw(id, properties) { + this.#toUpdate.delete(id); + this.updateProperties(id, properties); + } + updateProperties(elementOrId, properties) { + if (!properties) { + return; + } + const { + root, + bbox, + rootClass, + path: path6 + } = properties; + const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId; + if (!element) { + return; + } + if (root) { + this.#updateProperties(element, root); + } + if (bbox) { + _DrawLayer.#setBox(element, bbox); + } + if (rootClass) { + const { + classList + } = element; + for (const [className, value] of Object.entries(rootClass)) { + classList.toggle(className, value); + } + } + if (path6) { + const defs = element.firstChild; + const pathElement = defs.firstChild; + this.#updateProperties(pathElement, path6); + } + } + updateParent(id, layer) { + if (layer === this) { + return; + } + const root = this.#mapping.get(id); + if (!root) { + return; + } + layer.#parent.append(root); + this.#mapping.delete(id); + layer.#mapping.set(id, root); + } + remove(id) { + this.#toUpdate.delete(id); + if (this.#parent === null) { + return; + } + this.#mapping.get(id).remove(); + this.#mapping.delete(id); + } + destroy() { + this.#parent = null; + for (const root of this.#mapping.values()) { + root.remove(); + } + this.#mapping.clear(); + this.#toUpdate.clear(); + } + }; + { + globalThis._pdfjsTestingUtils = { + HighlightOutliner + }; + } + globalThis.pdfjsLib = { + AbortException, + AnnotationEditorLayer, + AnnotationEditorParamsType, + AnnotationEditorType, + AnnotationEditorUIManager, + AnnotationLayer, + AnnotationMode, + AnnotationType, + applyOpacity, + build, + ColorPicker, + createValidAbsoluteUrl, + CSSConstants, + DOMSVGFactory, + DrawLayer, + FeatureTest: util_FeatureTest, + fetchData, + findContrastColor, + getDocument, + getFilenameFromUrl, + getPdfFilenameFromUrl, + getRGB, + getUuid, + getXfaPageViewport, + GlobalWorkerOptions, + ImageKind: util_ImageKind, + InvalidPDFException, + isDataScheme, + isPdfFile, + isValidExplicitDest, + MathClamp, + noContextMenu, + normalizeUnicode, + OPS, + OutputScale, + PasswordResponses, + PDFDataRangeTransport, + PDFDateString, + PDFWorker, + PermissionFlag, + PixelsPerInch, + RenderingCancelledException, + renderRichText, + ResponseException, + setLayerDimensions, + shadow, + SignatureExtractor, + stopEvent, + SupportedImageMimeTypes, + TextLayer, + TouchManager, + updateUrlHash, + Util, + VerbosityLevel, + version: version2, + XfaLayer + }; + } +}); + +// ../pi-mono/node_modules/xlsx/xlsx.mjs +function reset_ansi() { + set_ansi(1252); +} +function reset_cp() { + set_cp(1200); + reset_ansi(); +} +function char_codes(data) { + var o9 = []; + for (var i7 = 0, len = data.length; i7 < len; ++i7) o9[i7] = data.charCodeAt(i7); + return o9; +} +function utf16leread(data) { + var o9 = []; + for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data.charCodeAt(2 * i7) + (data.charCodeAt(2 * i7 + 1) << 8)); + return o9.join(""); +} +function utf16lereadu(data) { + var o9 = []; + for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data[2 * i7] + (data[2 * i7 + 1] << 8)); + return o9.join(""); +} +function utf16beread(data) { + var o9 = []; + for (var i7 = 0; i7 < data.length >> 1; ++i7) o9[i7] = String.fromCharCode(data.charCodeAt(2 * i7 + 1) + (data.charCodeAt(2 * i7) << 8)); + return o9.join(""); +} +function Base64_encode(input) { + var o9 = ""; + var c1 = 0, c22 = 0, c32 = 0, e1 = 0, e22 = 0, e32 = 0, e42 = 0; + for (var i7 = 0; i7 < input.length; ) { + c1 = input.charCodeAt(i7++); + e1 = c1 >> 2; + c22 = input.charCodeAt(i7++); + e22 = (c1 & 3) << 4 | c22 >> 4; + c32 = input.charCodeAt(i7++); + e32 = (c22 & 15) << 2 | c32 >> 6; + e42 = c32 & 63; + if (isNaN(c22)) { + e32 = e42 = 64; + } else if (isNaN(c32)) { + e42 = 64; + } + o9 += Base64_map.charAt(e1) + Base64_map.charAt(e22) + Base64_map.charAt(e32) + Base64_map.charAt(e42); + } + return o9; +} +function Base64_decode(input) { + var o9 = ""; + var c1 = 0, c22 = 0, c32 = 0, e1 = 0, e22 = 0, e32 = 0, e42 = 0; + if (input.slice(0, 5) == "data:") { + var i7 = input.slice(0, 1024).indexOf(";base64,"); + if (i7 > -1) + input = input.slice(i7 + 8); + } + input = input.replace(/[^\w\+\/\=]/g, ""); + for (var i7 = 0; i7 < input.length; ) { + e1 = Base64_map.indexOf(input.charAt(i7++)); + e22 = Base64_map.indexOf(input.charAt(i7++)); + c1 = e1 << 2 | e22 >> 4; + o9 += String.fromCharCode(c1); + e32 = Base64_map.indexOf(input.charAt(i7++)); + c22 = (e22 & 15) << 4 | e32 >> 2; + if (e32 !== 64) { + o9 += String.fromCharCode(c22); + } + e42 = Base64_map.indexOf(input.charAt(i7++)); + c32 = (e32 & 3) << 6 | e42; + if (e42 !== 64) { + o9 += String.fromCharCode(c32); + } + } + return o9; +} +function new_raw_buf(len) { + if (has_buf) return Buffer.alloc ? Buffer.alloc(len) : new Buffer(len); + return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len); +} +function new_unsafe_buf(len) { + if (has_buf) return Buffer.allocUnsafe ? Buffer.allocUnsafe(len) : new Buffer(len); + return typeof Uint8Array != "undefined" ? new Uint8Array(len) : new Array(len); +} +function a2s(data) { + if (Array.isArray(data)) return data.map(function(c6) { + return String.fromCharCode(c6); + }).join(""); + var o9 = []; + for (var i7 = 0; i7 < data.length; ++i7) o9[i7] = String.fromCharCode(data[i7]); + return o9.join(""); +} +function ab2a(data) { + if (typeof ArrayBuffer == "undefined") throw new Error("Unsupported"); + if (data instanceof ArrayBuffer) return ab2a(new Uint8Array(data)); + var o9 = new Array(data.length); + for (var i7 = 0; i7 < data.length; ++i7) o9[i7] = data[i7]; + return o9; +} +function utf8decode(content) { + var out = [], widx = 0, L3 = content.length + 250; + var o9 = new_raw_buf(content.length + 255); + for (var ridx = 0; ridx < content.length; ++ridx) { + var c6 = content.charCodeAt(ridx); + if (c6 < 128) o9[widx++] = c6; + else if (c6 < 2048) { + o9[widx++] = 192 | c6 >> 6 & 31; + o9[widx++] = 128 | c6 & 63; + } else if (c6 >= 55296 && c6 < 57344) { + c6 = (c6 & 1023) + 64; + var d4 = content.charCodeAt(++ridx) & 1023; + o9[widx++] = 240 | c6 >> 8 & 7; + o9[widx++] = 128 | c6 >> 2 & 63; + o9[widx++] = 128 | d4 >> 6 & 15 | (c6 & 3) << 4; + o9[widx++] = 128 | d4 & 63; + } else { + o9[widx++] = 224 | c6 >> 12 & 15; + o9[widx++] = 128 | c6 >> 6 & 63; + o9[widx++] = 128 | c6 & 63; + } + if (widx > L3) { + out.push(o9.slice(0, widx)); + widx = 0; + o9 = new_raw_buf(65535); + L3 = 65530; + } + } + out.push(o9.slice(0, widx)); + return bconcat(out); +} +function _strrev(x2) { + var o9 = "", i7 = x2.length - 1; + while (i7 >= 0) o9 += x2.charAt(i7--); + return o9; +} +function pad0(v4, d4) { + var t6 = "" + v4; + return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6; +} +function pad_(v4, d4) { + var t6 = "" + v4; + return t6.length >= d4 ? t6 : fill(" ", d4 - t6.length) + t6; +} +function rpad_(v4, d4) { + var t6 = "" + v4; + return t6.length >= d4 ? t6 : t6 + fill(" ", d4 - t6.length); +} +function pad0r1(v4, d4) { + var t6 = "" + Math.round(v4); + return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6; +} +function pad0r2(v4, d4) { + var t6 = "" + v4; + return t6.length >= d4 ? t6 : fill("0", d4 - t6.length) + t6; +} +function pad0r(v4, d4) { + if (v4 > p2_32 || v4 < -p2_32) return pad0r1(v4, d4); + var i7 = Math.round(v4); + return pad0r2(i7, d4); +} +function SSF_isgeneral(s6, i7) { + i7 = i7 || 0; + return s6.length >= 7 + i7 && (s6.charCodeAt(i7) | 32) === 103 && (s6.charCodeAt(i7 + 1) | 32) === 101 && (s6.charCodeAt(i7 + 2) | 32) === 110 && (s6.charCodeAt(i7 + 3) | 32) === 101 && (s6.charCodeAt(i7 + 4) | 32) === 114 && (s6.charCodeAt(i7 + 5) | 32) === 97 && (s6.charCodeAt(i7 + 6) | 32) === 108; +} +function SSF_init_table(t6) { + if (!t6) t6 = {}; + t6[0] = "General"; + t6[1] = "0"; + t6[2] = "0.00"; + t6[3] = "#,##0"; + t6[4] = "#,##0.00"; + t6[9] = "0%"; + t6[10] = "0.00%"; + t6[11] = "0.00E+00"; + t6[12] = "# ?/?"; + t6[13] = "# ??/??"; + t6[14] = "m/d/yy"; + t6[15] = "d-mmm-yy"; + t6[16] = "d-mmm"; + t6[17] = "mmm-yy"; + t6[18] = "h:mm AM/PM"; + t6[19] = "h:mm:ss AM/PM"; + t6[20] = "h:mm"; + t6[21] = "h:mm:ss"; + t6[22] = "m/d/yy h:mm"; + t6[37] = "#,##0 ;(#,##0)"; + t6[38] = "#,##0 ;[Red](#,##0)"; + t6[39] = "#,##0.00;(#,##0.00)"; + t6[40] = "#,##0.00;[Red](#,##0.00)"; + t6[45] = "mm:ss"; + t6[46] = "[h]:mm:ss"; + t6[47] = "mmss.0"; + t6[48] = "##0.0E+0"; + t6[49] = "@"; + t6[56] = '"\u4E0A\u5348/\u4E0B\u5348 "hh"\u6642"mm"\u5206"ss"\u79D2 "'; + return t6; +} +function SSF_frac(x2, D4, mixed) { + var sgn = x2 < 0 ? -1 : 1; + var B3 = x2 * sgn; + var P_2 = 0, P_1 = 1, P3 = 0; + var Q_2 = 1, Q_1 = 0, Q2 = 0; + var A2 = Math.floor(B3); + while (Q_1 < D4) { + A2 = Math.floor(B3); + P3 = A2 * P_1 + P_2; + Q2 = A2 * Q_1 + Q_2; + if (B3 - A2 < 5e-8) break; + B3 = 1 / (B3 - A2); + P_2 = P_1; + P_1 = P3; + Q_2 = Q_1; + Q_1 = Q2; + } + if (Q2 > D4) { + if (Q_1 > D4) { + Q2 = Q_2; + P3 = P_2; + } else { + Q2 = Q_1; + P3 = P_1; + } + } + if (!mixed) return [0, sgn * P3, Q2]; + var q2 = Math.floor(sgn * P3 / Q2); + return [q2, sgn * P3 - q2 * Q2, Q2]; +} +function SSF_normalize_xl_unsafe(v4) { + var s6 = v4.toPrecision(16); + if (s6.indexOf("e") > -1) { + var m4 = s6.slice(0, s6.indexOf("e")); + m4 = m4.indexOf(".") > -1 ? m4.slice(0, m4.slice(0, 2) == "0." ? 17 : 16) : m4.slice(0, 15) + fill("0", m4.length - 15); + return m4 + s6.slice(s6.indexOf("e")); + } + var n7 = s6.indexOf(".") > -1 ? s6.slice(0, s6.slice(0, 2) == "0." ? 17 : 16) : s6.slice(0, 15) + fill("0", s6.length - 15); + return Number(n7); +} +function SSF_parse_date_code(v4, opts, b22) { + if (v4 > 2958465 || v4 < 0) return null; + v4 = SSF_normalize_xl_unsafe(v4); + var date = v4 | 0, time = Math.floor(86400 * (v4 - date)), dow = 0; + var dout = []; + var out = { D: date, T: time, u: 86400 * (v4 - date) - time, y: 0, m: 0, d: 0, H: 0, M: 0, S: 0, q: 0 }; + if (Math.abs(out.u) < 1e-6) out.u = 0; + if (opts && opts.date1904) date += 1462; + if (out.u > 0.9999) { + out.u = 0; + if (++time == 86400) { + out.T = time = 0; + ++date; + ++out.D; + } + } + if (date === 60) { + dout = b22 ? [1317, 10, 29] : [1900, 2, 29]; + dow = 3; + } else if (date === 0) { + dout = b22 ? [1317, 8, 29] : [1900, 1, 0]; + dow = 6; + } else { + if (date > 60) --date; + var d4 = new Date(1900, 0, 1); + d4.setDate(d4.getDate() + date - 1); + dout = [d4.getFullYear(), d4.getMonth() + 1, d4.getDate()]; + dow = d4.getDay(); + if (date < 60) dow = (dow + 6) % 7; + if (b22) dow = SSF_fix_hijri(d4, dout); + } + out.y = dout[0]; + out.m = dout[1]; + out.d = dout[2]; + out.S = time % 60; + time = Math.floor(time / 60); + out.M = time % 60; + time = Math.floor(time / 60); + out.H = time; + out.q = dow; + return out; +} +function SSF_strip_decimal(o9) { + return o9.indexOf(".") == -1 ? o9 : o9.replace(/(?:\.0*|(\.\d*[1-9])0+)$/, "$1"); +} +function SSF_normalize_exp(o9) { + if (o9.indexOf("E") == -1) return o9; + return o9.replace(/(?:\.0*|(\.\d*[1-9])0+)[Ee]/, "$1E").replace(/(E[+-])(\d)$/, "$10$2"); +} +function SSF_small_exp(v4) { + var w3 = v4 < 0 ? 12 : 11; + var o9 = SSF_strip_decimal(v4.toFixed(12)); + if (o9.length <= w3) return o9; + o9 = v4.toPrecision(10); + if (o9.length <= w3) return o9; + return v4.toExponential(5); +} +function SSF_large_exp(v4) { + var o9 = SSF_strip_decimal(v4.toFixed(11)); + return o9.length > (v4 < 0 ? 12 : 11) || o9 === "0" || o9 === "-0" ? v4.toPrecision(6) : o9; +} +function SSF_general_num(v4) { + if (!isFinite(v4)) return isNaN(v4) ? "#NUM!" : "#DIV/0!"; + var V3 = Math.floor(Math.log(Math.abs(v4)) * Math.LOG10E), o9; + if (V3 >= -4 && V3 <= -1) o9 = v4.toPrecision(10 + V3); + else if (Math.abs(V3) <= 9) o9 = SSF_small_exp(v4); + else if (V3 === 10) o9 = v4.toFixed(10).substr(0, 12); + else o9 = SSF_large_exp(v4); + return SSF_strip_decimal(SSF_normalize_exp(o9.toUpperCase())); +} +function SSF_general(v4, opts) { + switch (typeof v4) { + case "string": + return v4; + case "boolean": + return v4 ? "TRUE" : "FALSE"; + case "number": + return (v4 | 0) === v4 ? v4.toString(10) : SSF_general_num(v4); + case "undefined": + return ""; + case "object": + if (v4 == null) return ""; + if (v4 instanceof Date) return SSF_format(14, datenum(v4, opts && opts.date1904), opts); + } + throw new Error("unsupported value in General format: " + v4); +} +function SSF_fix_hijri(date, o9) { + o9[0] -= 581; + var dow = date.getDay(); + if (date < 60) dow = (dow + 6) % 7; + return dow; +} +function SSF_write_date(type, fmt, val2, ss0) { + var o9 = "", ss = 0, tt = 0, y4 = val2.y, out, outl = 0; + switch (type) { + case 98: + y4 = val2.y + 543; + /* falls through */ + case 121: + switch (fmt.length) { + case 1: + case 2: + out = y4 % 100; + outl = 2; + break; + default: + out = y4 % 1e4; + outl = 4; + break; + } + break; + case 109: + switch (fmt.length) { + case 1: + case 2: + out = val2.m; + outl = fmt.length; + break; + case 3: + return months[val2.m - 1][1]; + case 5: + return months[val2.m - 1][0]; + default: + return months[val2.m - 1][2]; + } + break; + case 100: + switch (fmt.length) { + case 1: + case 2: + out = val2.d; + outl = fmt.length; + break; + case 3: + return days[val2.q][0]; + default: + return days[val2.q][1]; + } + break; + case 104: + switch (fmt.length) { + case 1: + case 2: + out = 1 + (val2.H + 11) % 12; + outl = fmt.length; + break; + default: + throw "bad hour format: " + fmt; + } + break; + case 72: + switch (fmt.length) { + case 1: + case 2: + out = val2.H; + outl = fmt.length; + break; + default: + throw "bad hour format: " + fmt; + } + break; + case 77: + switch (fmt.length) { + case 1: + case 2: + out = val2.M; + outl = fmt.length; + break; + default: + throw "bad minute format: " + fmt; + } + break; + case 115: + if (fmt != "s" && fmt != "ss" && fmt != ".0" && fmt != ".00" && fmt != ".000") throw "bad second format: " + fmt; + if (val2.u === 0 && (fmt == "s" || fmt == "ss")) return pad0(val2.S, fmt.length); + if (ss0 >= 2) tt = ss0 === 3 ? 1e3 : 100; + else tt = ss0 === 1 ? 10 : 1; + ss = Math.round(tt * (val2.S + val2.u)); + if (ss >= 60 * tt) ss = 0; + if (fmt === "s") return ss === 0 ? "0" : "" + ss / tt; + o9 = pad0(ss, 2 + ss0); + if (fmt === "ss") return o9.substr(0, 2); + return "." + o9.substr(2, fmt.length - 1); + case 90: + switch (fmt) { + case "[h]": + case "[hh]": + out = val2.D * 24 + val2.H; + break; + case "[m]": + case "[mm]": + out = (val2.D * 24 + val2.H) * 60 + val2.M; + break; + case "[s]": + case "[ss]": + out = ((val2.D * 24 + val2.H) * 60 + val2.M) * 60 + (ss0 == 0 ? Math.round(val2.S + val2.u) : val2.S); + break; + default: + throw "bad abstime format: " + fmt; + } + outl = fmt.length === 3 ? 1 : 2; + break; + case 101: + out = y4; + outl = 1; + break; + } + var outstr = outl > 0 ? pad0(out, outl) : ""; + return outstr; +} +function commaify(s6) { + var w3 = 3; + if (s6.length <= w3) return s6; + var j3 = s6.length % w3, o9 = s6.substr(0, j3); + for (; j3 != s6.length; j3 += w3) o9 += (o9.length > 0 ? "," : "") + s6.substr(j3, w3); + return o9; +} +function write_num_pct(type, fmt, val2) { + var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length; + return write_num(type, sfmt, val2 * Math.pow(10, 2 * mul)) + fill("%", mul); +} +function write_num_cm(type, fmt, val2) { + var idx = fmt.length - 1; + while (fmt.charCodeAt(idx - 1) === 44) --idx; + return write_num(type, fmt.substr(0, idx), val2 / Math.pow(10, 3 * (fmt.length - idx))); +} +function write_num_exp(fmt, val2) { + var o9; + var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1; + if (fmt.match(/^#+0.0E\+0$/)) { + if (val2 == 0) return "0.0E+0"; + else if (val2 < 0) return "-" + write_num_exp(fmt, -val2); + var period = fmt.indexOf("."); + if (period === -1) period = fmt.indexOf("E"); + var ee = Math.floor(Math.log(val2) * Math.LOG10E) % period; + if (ee < 0) ee += period; + o9 = (val2 / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period); + if (o9.indexOf("e") === -1) { + var fakee = Math.floor(Math.log(val2) * Math.LOG10E); + if (o9.indexOf(".") === -1) o9 = o9.charAt(0) + "." + o9.substr(1) + "E+" + (fakee - o9.length + ee); + else o9 += "E+" + (fakee - ee); + while (o9.substr(0, 2) === "0.") { + o9 = o9.charAt(0) + o9.substr(2, period) + "." + o9.substr(2 + period); + o9 = o9.replace(/^0+([1-9])/, "$1").replace(/^0+\./, "0."); + } + o9 = o9.replace(/\+-/, "-"); + } + o9 = o9.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $22, $32) { + return $1 + $22 + $32.substr(0, (period + ee) % period) + "." + $32.substr(ee) + "E"; + }); + } else o9 = val2.toExponential(idx); + if (fmt.match(/E\+00$/) && o9.match(/e[+-]\d$/)) o9 = o9.substr(0, o9.length - 1) + "0" + o9.charAt(o9.length - 1); + if (fmt.match(/E\-/) && o9.match(/e\+/)) o9 = o9.replace(/e\+/, "e"); + return o9.replace("e", "E"); +} +function write_num_f1(r8, aval, sign2) { + var den = parseInt(r8[4], 10), rr = Math.round(aval * den), base = Math.floor(rr / den); + var myn = rr - base * den, myd = den; + return sign2 + (base === 0 ? "" : "" + base) + " " + (myn === 0 ? fill(" ", r8[1].length + 1 + r8[4].length) : pad_(myn, r8[1].length) + r8[2] + "/" + r8[3] + pad0(myd, r8[4].length)); +} +function write_num_f2(r8, aval, sign2) { + return sign2 + (aval === 0 ? "" : "" + aval) + fill(" ", r8[1].length + 2 + r8[4].length); +} +function hashq(str2) { + var o9 = "", cc; + for (var i7 = 0; i7 != str2.length; ++i7) switch (cc = str2.charCodeAt(i7)) { + case 35: + break; + case 63: + o9 += " "; + break; + case 48: + o9 += "0"; + break; + default: + o9 += String.fromCharCode(cc); + } + return o9; +} +function rnd(val2, d4) { + var dd = Math.pow(10, d4); + return "" + Math.round(val2 * dd) / dd; +} +function dec(val2, d4) { + var _frac = val2 - Math.floor(val2), dd = Math.pow(10, d4); + if (d4 < ("" + Math.round(_frac * dd)).length) return 0; + return Math.round(_frac * dd); +} +function carry(val2, d4) { + if (d4 < ("" + Math.round((val2 - Math.floor(val2)) * Math.pow(10, d4))).length) { + return 1; + } + return 0; +} +function flr(val2) { + if (val2 < 2147483647 && val2 > -2147483648) return "" + (val2 >= 0 ? val2 | 0 : val2 - 1 | 0); + return "" + Math.floor(val2); +} +function write_num_flt(type, fmt, val2) { + if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) { + var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, ""); + if (val2 >= 0) return write_num_flt("n", ffmt, val2); + return "(" + write_num_flt("n", ffmt, -val2) + ")"; + } + if (fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm(type, fmt, val2); + if (fmt.indexOf("%") !== -1) return write_num_pct(type, fmt, val2); + if (fmt.indexOf("E") !== -1) return write_num_exp(fmt, val2); + if (fmt.charCodeAt(0) === 36) return "$" + write_num_flt(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val2); + var o9; + var r8, ri, ff, aval = Math.abs(val2), sign2 = val2 < 0 ? "-" : ""; + if (fmt.match(/^00+$/)) return sign2 + pad0r(aval, fmt.length); + if (fmt.match(/^[#?]+$/)) { + o9 = pad0r(val2, 0); + if (o9 === "0") o9 = ""; + return o9.length > fmt.length ? o9 : hashq(fmt.substr(0, fmt.length - o9.length)) + o9; + } + if (r8 = fmt.match(frac1)) return write_num_f1(r8, aval, sign2); + if (fmt.match(/^#+0+$/)) return sign2 + pad0r(aval, fmt.length - fmt.indexOf("0")); + if (r8 = fmt.match(dec1)) { + o9 = rnd(val2, r8[1].length).replace(/^([^\.]+)$/, "$1." + hashq(r8[1])).replace(/\.$/, "." + hashq(r8[1])).replace(/\.(\d*)$/, function($$, $1) { + return "." + $1 + fill("0", hashq( + /*::(*/ + r8[1] + ).length - $1.length); + }); + return fmt.indexOf("0.") !== -1 ? o9 : o9.replace(/^0\./, "."); + } + fmt = fmt.replace(/^#+([0.])/, "$1"); + if (r8 = fmt.match(/^(0*)\.(#*)$/)) { + return sign2 + rnd(aval, r8[2].length).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r8[1].length ? "0." : "."); + } + if (r8 = fmt.match(/^#{1,3},##0(\.?)$/)) return sign2 + commaify(pad0r(aval, 0)); + if (r8 = fmt.match(/^#,##0\.([#0]*0)$/)) { + return val2 < 0 ? "-" + write_num_flt(type, fmt, -val2) : commaify("" + (Math.floor(val2) + carry(val2, r8[1].length))) + "." + pad0(dec(val2, r8[1].length), r8[1].length); + } + if (r8 = fmt.match(/^#,#*,#0/)) return write_num_flt(type, fmt.replace(/^#,#*,/, ""), val2); + if (r8 = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) { + o9 = _strrev(write_num_flt(type, fmt.replace(/[\\-]/g, ""), val2)); + ri = 0; + return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x3) { + return ri < o9.length ? o9.charAt(ri++) : x3 === "0" ? "0" : ""; + })); + } + if (fmt.match(phone)) { + o9 = write_num_flt(type, "##########", val2); + return "(" + o9.substr(0, 3) + ") " + o9.substr(3, 3) + "-" + o9.substr(6); + } + var oa = ""; + if (r8 = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) { + ri = Math.min( + /*::String(*/ + r8[4].length, + 7 + ); + ff = SSF_frac(aval, Math.pow(10, ri) - 1, false); + o9 = "" + sign2; + oa = write_num( + "n", + /*::String(*/ + r8[1], + ff[1] + ); + if (oa.charAt(oa.length - 1) == " ") oa = oa.substr(0, oa.length - 1) + "0"; + o9 += oa + /*::String(*/ + r8[2] + "/" + /*::String(*/ + r8[3]; + oa = rpad_(ff[2], ri); + if (oa.length < r8[4].length) oa = hashq(r8[4].substr(r8[4].length - oa.length)) + oa; + o9 += oa; + return o9; + } + if (r8 = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) { + ri = Math.min(Math.max(r8[1].length, r8[4].length), 7); + ff = SSF_frac(aval, Math.pow(10, ri) - 1, true); + return sign2 + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r8[2] + "/" + r8[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r8[2].length + r8[3].length)); + } + if (r8 = fmt.match(/^[#0?]+$/)) { + o9 = pad0r(val2, 0); + if (fmt.length <= o9.length) return o9; + return hashq(fmt.substr(0, fmt.length - o9.length)) + o9; + } + if (r8 = fmt.match(/^([#0?]+)\.([#0]+)$/)) { + o9 = "" + val2.toFixed(Math.min(r8[2].length, 10)).replace(/([^0])0+$/, "$1"); + ri = o9.indexOf("."); + var lres = fmt.indexOf(".") - ri, rres = fmt.length - o9.length - lres; + return hashq(fmt.substr(0, lres) + o9 + fmt.substr(fmt.length - rres)); + } + if (r8 = fmt.match(/^00,000\.([#0]*0)$/)) { + ri = dec(val2, r8[1].length); + return val2 < 0 ? "-" + write_num_flt(type, fmt, -val2) : commaify(flr(val2)).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) { + return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$; + }) + "." + pad0(ri, r8[1].length); + } + switch (fmt) { + case "###,##0.00": + return write_num_flt(type, "#,##0.00", val2); + case "###,###": + case "##,###": + case "#,###": + var x2 = commaify(pad0r(aval, 0)); + return x2 !== "0" ? sign2 + x2 : ""; + case "###,###.00": + return write_num_flt(type, "###,##0.00", val2).replace(/^0\./, "."); + case "#,###.00": + return write_num_flt(type, "#,##0.00", val2).replace(/^0\./, "."); + default: + } + throw new Error("unsupported format |" + fmt + "|"); +} +function write_num_cm2(type, fmt, val2) { + var idx = fmt.length - 1; + while (fmt.charCodeAt(idx - 1) === 44) --idx; + return write_num(type, fmt.substr(0, idx), val2 / Math.pow(10, 3 * (fmt.length - idx))); +} +function write_num_pct2(type, fmt, val2) { + var sfmt = fmt.replace(pct1, ""), mul = fmt.length - sfmt.length; + return write_num(type, sfmt, val2 * Math.pow(10, 2 * mul)) + fill("%", mul); +} +function write_num_exp2(fmt, val2) { + var o9; + var idx = fmt.indexOf("E") - fmt.indexOf(".") - 1; + if (fmt.match(/^#+0.0E\+0$/)) { + if (val2 == 0) return "0.0E+0"; + else if (val2 < 0) return "-" + write_num_exp2(fmt, -val2); + var period = fmt.indexOf("."); + if (period === -1) period = fmt.indexOf("E"); + var ee = Math.floor(Math.log(val2) * Math.LOG10E) % period; + if (ee < 0) ee += period; + o9 = (val2 / Math.pow(10, ee)).toPrecision(idx + 1 + (period + ee) % period); + if (!o9.match(/[Ee]/)) { + var fakee = Math.floor(Math.log(val2) * Math.LOG10E); + if (o9.indexOf(".") === -1) o9 = o9.charAt(0) + "." + o9.substr(1) + "E+" + (fakee - o9.length + ee); + else o9 += "E+" + (fakee - ee); + o9 = o9.replace(/\+-/, "-"); + } + o9 = o9.replace(/^([+-]?)(\d*)\.(\d*)[Ee]/, function($$, $1, $22, $32) { + return $1 + $22 + $32.substr(0, (period + ee) % period) + "." + $32.substr(ee) + "E"; + }); + } else o9 = val2.toExponential(idx); + if (fmt.match(/E\+00$/) && o9.match(/e[+-]\d$/)) o9 = o9.substr(0, o9.length - 1) + "0" + o9.charAt(o9.length - 1); + if (fmt.match(/E\-/) && o9.match(/e\+/)) o9 = o9.replace(/e\+/, "e"); + return o9.replace("e", "E"); +} +function write_num_int(type, fmt, val2) { + if (type.charCodeAt(0) === 40 && !fmt.match(closeparen)) { + var ffmt = fmt.replace(/\( */, "").replace(/ \)/, "").replace(/\)/, ""); + if (val2 >= 0) return write_num_int("n", ffmt, val2); + return "(" + write_num_int("n", ffmt, -val2) + ")"; + } + if (fmt.charCodeAt(fmt.length - 1) === 44) return write_num_cm2(type, fmt, val2); + if (fmt.indexOf("%") !== -1) return write_num_pct2(type, fmt, val2); + if (fmt.indexOf("E") !== -1) return write_num_exp2(fmt, val2); + if (fmt.charCodeAt(0) === 36) return "$" + write_num_int(type, fmt.substr(fmt.charAt(1) == " " ? 2 : 1), val2); + var o9; + var r8, ri, ff, aval = Math.abs(val2), sign2 = val2 < 0 ? "-" : ""; + if (fmt.match(/^00+$/)) return sign2 + pad0(aval, fmt.length); + if (fmt.match(/^[#?]+$/)) { + o9 = "" + val2; + if (val2 === 0) o9 = ""; + return o9.length > fmt.length ? o9 : hashq(fmt.substr(0, fmt.length - o9.length)) + o9; + } + if (r8 = fmt.match(frac1)) return write_num_f2(r8, aval, sign2); + if (fmt.match(/^#+0+$/)) return sign2 + pad0(aval, fmt.length - fmt.indexOf("0")); + if (r8 = fmt.match(dec1)) { + o9 = ("" + val2).replace(/^([^\.]+)$/, "$1." + hashq(r8[1])).replace(/\.$/, "." + hashq(r8[1])); + o9 = o9.replace(/\.(\d*)$/, function($$, $1) { + return "." + $1 + fill("0", hashq(r8[1]).length - $1.length); + }); + return fmt.indexOf("0.") !== -1 ? o9 : o9.replace(/^0\./, "."); + } + fmt = fmt.replace(/^#+([0.])/, "$1"); + if (r8 = fmt.match(/^(0*)\.(#*)$/)) { + return sign2 + ("" + aval).replace(/\.(\d*[1-9])0*$/, ".$1").replace(/^(-?\d*)$/, "$1.").replace(/^0\./, r8[1].length ? "0." : "."); + } + if (r8 = fmt.match(/^#{1,3},##0(\.?)$/)) return sign2 + commaify("" + aval); + if (r8 = fmt.match(/^#,##0\.([#0]*0)$/)) { + return val2 < 0 ? "-" + write_num_int(type, fmt, -val2) : commaify("" + val2) + "." + fill("0", r8[1].length); + } + if (r8 = fmt.match(/^#,#*,#0/)) return write_num_int(type, fmt.replace(/^#,#*,/, ""), val2); + if (r8 = fmt.match(/^([0#]+)(\\?-([0#]+))+$/)) { + o9 = _strrev(write_num_int(type, fmt.replace(/[\\-]/g, ""), val2)); + ri = 0; + return _strrev(_strrev(fmt.replace(/\\/g, "")).replace(/[0#]/g, function(x3) { + return ri < o9.length ? o9.charAt(ri++) : x3 === "0" ? "0" : ""; + })); + } + if (fmt.match(phone)) { + o9 = write_num_int(type, "##########", val2); + return "(" + o9.substr(0, 3) + ") " + o9.substr(3, 3) + "-" + o9.substr(6); + } + var oa = ""; + if (r8 = fmt.match(/^([#0?]+)( ?)\/( ?)([#0?]+)/)) { + ri = Math.min( + /*::String(*/ + r8[4].length, + 7 + ); + ff = SSF_frac(aval, Math.pow(10, ri) - 1, false); + o9 = "" + sign2; + oa = write_num( + "n", + /*::String(*/ + r8[1], + ff[1] + ); + if (oa.charAt(oa.length - 1) == " ") oa = oa.substr(0, oa.length - 1) + "0"; + o9 += oa + /*::String(*/ + r8[2] + "/" + /*::String(*/ + r8[3]; + oa = rpad_(ff[2], ri); + if (oa.length < r8[4].length) oa = hashq(r8[4].substr(r8[4].length - oa.length)) + oa; + o9 += oa; + return o9; + } + if (r8 = fmt.match(/^# ([#0?]+)( ?)\/( ?)([#0?]+)/)) { + ri = Math.min(Math.max(r8[1].length, r8[4].length), 7); + ff = SSF_frac(aval, Math.pow(10, ri) - 1, true); + return sign2 + (ff[0] || (ff[1] ? "" : "0")) + " " + (ff[1] ? pad_(ff[1], ri) + r8[2] + "/" + r8[3] + rpad_(ff[2], ri) : fill(" ", 2 * ri + 1 + r8[2].length + r8[3].length)); + } + if (r8 = fmt.match(/^[#0?]+$/)) { + o9 = "" + val2; + if (fmt.length <= o9.length) return o9; + return hashq(fmt.substr(0, fmt.length - o9.length)) + o9; + } + if (r8 = fmt.match(/^([#0]+)\.([#0]+)$/)) { + o9 = "" + val2.toFixed(Math.min(r8[2].length, 10)).replace(/([^0])0+$/, "$1"); + ri = o9.indexOf("."); + var lres = fmt.indexOf(".") - ri, rres = fmt.length - o9.length - lres; + return hashq(fmt.substr(0, lres) + o9 + fmt.substr(fmt.length - rres)); + } + if (r8 = fmt.match(/^00,000\.([#0]*0)$/)) { + return val2 < 0 ? "-" + write_num_int(type, fmt, -val2) : commaify("" + val2).replace(/^\d,\d{3}$/, "0$&").replace(/^\d*$/, function($$) { + return "00," + ($$.length < 3 ? pad0(0, 3 - $$.length) : "") + $$; + }) + "." + pad0(0, r8[1].length); + } + switch (fmt) { + case "###,###": + case "##,###": + case "#,###": + var x2 = commaify("" + aval); + return x2 !== "0" ? sign2 + x2 : ""; + default: + if (fmt.match(/\.[0#?]*$/)) return write_num_int(type, fmt.slice(0, fmt.lastIndexOf(".")), val2) + hashq(fmt.slice(fmt.lastIndexOf("."))); + } + throw new Error("unsupported format |" + fmt + "|"); +} +function write_num(type, fmt, val2) { + return (val2 | 0) === val2 ? write_num_int(type, fmt, val2) : write_num_flt(type, fmt, val2); +} +function SSF_split_fmt(fmt) { + var out = []; + var in_str = false; + for (var i7 = 0, j3 = 0; i7 < fmt.length; ++i7) switch ( + /*cc=*/ + fmt.charCodeAt(i7) + ) { + case 34: + in_str = !in_str; + break; + case 95: + case 42: + case 92: + ++i7; + break; + case 59: + out[out.length] = fmt.substr(j3, i7 - j3); + j3 = i7 + 1; + } + out[out.length] = fmt.substr(j3); + if (in_str === true) throw new Error("Format |" + fmt + "| unterminated string "); + return out; +} +function fmt_is_date(fmt) { + var i7 = 0, c6 = "", o9 = ""; + while (i7 < fmt.length) { + switch (c6 = fmt.charAt(i7)) { + case "G": + if (SSF_isgeneral(fmt, i7)) i7 += 6; + i7++; + break; + case '"': + for ( + ; + /*cc=*/ + fmt.charCodeAt(++i7) !== 34 && i7 < fmt.length; + ) { + } + ++i7; + break; + case "\\": + i7 += 2; + break; + case "_": + i7 += 2; + break; + case "@": + ++i7; + break; + case "B": + case "b": + if (fmt.charAt(i7 + 1) === "1" || fmt.charAt(i7 + 1) === "2") return true; + /* falls through */ + case "M": + case "D": + case "Y": + case "H": + case "S": + case "E": + /* falls through */ + case "m": + case "d": + case "y": + case "h": + case "s": + case "e": + case "g": + return true; + case "A": + case "a": + case "\u4E0A": + if (fmt.substr(i7, 3).toUpperCase() === "A/P") return true; + if (fmt.substr(i7, 5).toUpperCase() === "AM/PM") return true; + if (fmt.substr(i7, 5).toUpperCase() === "\u4E0A\u5348/\u4E0B\u5348") return true; + ++i7; + break; + case "[": + o9 = c6; + while (fmt.charAt(i7++) !== "]" && i7 < fmt.length) o9 += fmt.charAt(i7); + if (o9.match(SSF_abstime)) return true; + break; + case ".": + /* falls through */ + case "0": + case "#": + while (i7 < fmt.length && ("0#?.,E+-%".indexOf(c6 = fmt.charAt(++i7)) > -1 || c6 == "\\" && fmt.charAt(i7 + 1) == "-" && "0#".indexOf(fmt.charAt(i7 + 2)) > -1)) { + } + break; + case "?": + while (fmt.charAt(++i7) === c6) { + } + break; + case "*": + ++i7; + if (fmt.charAt(i7) == " " || fmt.charAt(i7) == "*") ++i7; + break; + case "(": + case ")": + ++i7; + break; + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + while (i7 < fmt.length && "0123456789".indexOf(fmt.charAt(++i7)) > -1) { + } + break; + case " ": + ++i7; + break; + default: + ++i7; + break; + } + } + return false; +} +function eval_fmt(fmt, v4, opts, flen) { + var out = [], o9 = "", i7 = 0, c6 = "", lst = "t", dt, j3, cc; + var hr = "H"; + while (i7 < fmt.length) { + switch (c6 = fmt.charAt(i7)) { + case "G": + if (!SSF_isgeneral(fmt, i7)) throw new Error("unrecognized character " + c6 + " in " + fmt); + out[out.length] = { t: "G", v: "General" }; + i7 += 7; + break; + case '"': + for (o9 = ""; (cc = fmt.charCodeAt(++i7)) !== 34 && i7 < fmt.length; ) o9 += String.fromCharCode(cc); + out[out.length] = { t: "t", v: o9 }; + ++i7; + break; + case "\\": + var w3 = fmt.charAt(++i7), t6 = w3 === "(" || w3 === ")" ? w3 : "t"; + out[out.length] = { t: t6, v: w3 }; + ++i7; + break; + case "_": + out[out.length] = { t: "t", v: " " }; + i7 += 2; + break; + case "@": + out[out.length] = { t: "T", v: v4 }; + ++i7; + break; + case "B": + case "b": + if (fmt.charAt(i7 + 1) === "1" || fmt.charAt(i7 + 1) === "2") { + if (dt == null) { + dt = SSF_parse_date_code(v4, opts, fmt.charAt(i7 + 1) === "2"); + if (dt == null) return ""; + } + out[out.length] = { t: "X", v: fmt.substr(i7, 2) }; + lst = c6; + i7 += 2; + break; + } + /* falls through */ + case "M": + case "D": + case "Y": + case "H": + case "S": + case "E": + c6 = c6.toLowerCase(); + /* falls through */ + case "m": + case "d": + case "y": + case "h": + case "s": + case "e": + case "g": + if (v4 < 0) return ""; + if (dt == null) { + dt = SSF_parse_date_code(v4, opts); + if (dt == null) return ""; + } + o9 = c6; + while (++i7 < fmt.length && fmt.charAt(i7).toLowerCase() === c6) o9 += c6; + if (c6 === "m" && lst.toLowerCase() === "h") c6 = "M"; + if (c6 === "h") c6 = hr; + out[out.length] = { t: c6, v: o9 }; + lst = c6; + break; + case "A": + case "a": + case "\u4E0A": + var q2 = { t: c6, v: c6 }; + if (dt == null) dt = SSF_parse_date_code(v4, opts); + if (fmt.substr(i7, 3).toUpperCase() === "A/P") { + if (dt != null) q2.v = dt.H >= 12 ? fmt.charAt(i7 + 2) : c6; + q2.t = "T"; + hr = "h"; + i7 += 3; + } else if (fmt.substr(i7, 5).toUpperCase() === "AM/PM") { + if (dt != null) q2.v = dt.H >= 12 ? "PM" : "AM"; + q2.t = "T"; + i7 += 5; + hr = "h"; + } else if (fmt.substr(i7, 5).toUpperCase() === "\u4E0A\u5348/\u4E0B\u5348") { + if (dt != null) q2.v = dt.H >= 12 ? "\u4E0B\u5348" : "\u4E0A\u5348"; + q2.t = "T"; + i7 += 5; + hr = "h"; + } else { + q2.t = "t"; + ++i7; + } + if (dt == null && q2.t === "T") return ""; + out[out.length] = q2; + lst = c6; + break; + case "[": + o9 = c6; + while (fmt.charAt(i7++) !== "]" && i7 < fmt.length) o9 += fmt.charAt(i7); + if (o9.slice(-1) !== "]") throw 'unterminated "[" block: |' + o9 + "|"; + if (o9.match(SSF_abstime)) { + if (dt == null) { + dt = SSF_parse_date_code(v4, opts); + if (dt == null) return ""; + } + out[out.length] = { t: "Z", v: o9.toLowerCase() }; + lst = o9.charAt(1); + } else if (o9.indexOf("$") > -1) { + o9 = (o9.match(/\$([^-\[\]]*)/) || [])[1] || "$"; + if (!fmt_is_date(fmt)) out[out.length] = { t: "t", v: o9 }; + } + break; + /* Numbers */ + case ".": + if (dt != null) { + o9 = c6; + while (++i7 < fmt.length && (c6 = fmt.charAt(i7)) === "0") o9 += c6; + out[out.length] = { t: "s", v: o9 }; + break; + } + /* falls through */ + case "0": + case "#": + o9 = c6; + while (++i7 < fmt.length && "0#?.,E+-%".indexOf(c6 = fmt.charAt(i7)) > -1) o9 += c6; + out[out.length] = { t: "n", v: o9 }; + break; + case "?": + o9 = c6; + while (fmt.charAt(++i7) === c6) o9 += c6; + out[out.length] = { t: c6, v: o9 }; + lst = c6; + break; + case "*": + ++i7; + if (fmt.charAt(i7) == " " || fmt.charAt(i7) == "*") ++i7; + break; + // ** + case "(": + case ")": + out[out.length] = { t: flen === 1 ? "t" : c6, v: c6 }; + ++i7; + break; + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + o9 = c6; + while (i7 < fmt.length && "0123456789".indexOf(fmt.charAt(++i7)) > -1) o9 += fmt.charAt(i7); + out[out.length] = { t: "D", v: o9 }; + break; + case " ": + out[out.length] = { t: c6, v: c6 }; + ++i7; + break; + case "$": + out[out.length] = { t: "t", v: "$" }; + ++i7; + break; + default: + if (",$-+/():!^&'~{}<>=\u20ACacfijklopqrtuvwxzP".indexOf(c6) === -1) throw new Error("unrecognized character " + c6 + " in " + fmt); + out[out.length] = { t: "t", v: c6 }; + ++i7; + break; + } + } + var bt = 0, ss0 = 0, ssm; + for (i7 = out.length - 1, lst = "t"; i7 >= 0; --i7) { + switch (out[i7].t) { + case "h": + case "H": + out[i7].t = hr; + lst = "h"; + if (bt < 1) bt = 1; + break; + case "s": + if (ssm = out[i7].v.match(/\.0+$/)) { + ss0 = Math.max(ss0, ssm[0].length - 1); + bt = 4; + } + if (bt < 3) bt = 3; + /* falls through */ + case "d": + case "y": + case "e": + lst = out[i7].t; + break; + case "M": + lst = out[i7].t; + if (bt < 2) bt = 2; + break; + case "m": + if (lst === "s") { + out[i7].t = "M"; + if (bt < 2) bt = 2; + } + break; + case "X": + break; + case "Z": + if (bt < 1 && out[i7].v.match(/[Hh]/)) bt = 1; + if (bt < 2 && out[i7].v.match(/[Mm]/)) bt = 2; + if (bt < 3 && out[i7].v.match(/[Ss]/)) bt = 3; + } + } + var _dt; + switch (bt) { + case 0: + break; + case 1: + case 2: + case 3: + if (dt.u >= 0.5) { + dt.u = 0; + ++dt.S; + } + if (dt.S >= 60) { + dt.S = 0; + ++dt.M; + } + if (dt.M >= 60) { + dt.M = 0; + ++dt.H; + } + if (dt.H >= 24) { + dt.H = 0; + ++dt.D; + _dt = SSF_parse_date_code(dt.D); + _dt.u = dt.u; + _dt.S = dt.S; + _dt.M = dt.M; + _dt.H = dt.H; + dt = _dt; + } + break; + case 4: + switch (ss0) { + case 1: + dt.u = Math.round(dt.u * 10) / 10; + break; + case 2: + dt.u = Math.round(dt.u * 100) / 100; + break; + case 3: + dt.u = Math.round(dt.u * 1e3) / 1e3; + break; + } + if (dt.u >= 1) { + dt.u = 0; + ++dt.S; + } + if (dt.S >= 60) { + dt.S = 0; + ++dt.M; + } + if (dt.M >= 60) { + dt.M = 0; + ++dt.H; + } + if (dt.H >= 24) { + dt.H = 0; + ++dt.D; + _dt = SSF_parse_date_code(dt.D); + _dt.u = dt.u; + _dt.S = dt.S; + _dt.M = dt.M; + _dt.H = dt.H; + dt = _dt; + } + break; + } + var nstr = "", jj; + for (i7 = 0; i7 < out.length; ++i7) { + switch (out[i7].t) { + case "t": + case "T": + case " ": + case "D": + break; + case "X": + out[i7].v = ""; + out[i7].t = ";"; + break; + case "d": + case "m": + case "y": + case "h": + case "H": + case "M": + case "s": + case "e": + case "b": + case "Z": + out[i7].v = SSF_write_date(out[i7].t.charCodeAt(0), out[i7].v, dt, ss0); + out[i7].t = "t"; + break; + case "n": + case "?": + jj = i7 + 1; + while (out[jj] != null && ((c6 = out[jj].t) === "?" || c6 === "D" || (c6 === " " || c6 === "t") && out[jj + 1] != null && (out[jj + 1].t === "?" || out[jj + 1].t === "t" && out[jj + 1].v === "/") || out[i7].t === "(" && (c6 === " " || c6 === "n" || c6 === ")") || c6 === "t" && (out[jj].v === "/" || out[jj].v === " " && out[jj + 1] != null && out[jj + 1].t == "?"))) { + out[i7].v += out[jj].v; + out[jj] = { v: "", t: ";" }; + ++jj; + } + nstr += out[i7].v; + i7 = jj - 1; + break; + case "G": + out[i7].t = "t"; + out[i7].v = SSF_general(v4, opts); + break; + } + } + var vv = "", myv, ostr; + if (nstr.length > 0) { + if (nstr.charCodeAt(0) == 40) { + myv = v4 < 0 && nstr.charCodeAt(0) === 45 ? -v4 : v4; + ostr = write_num("n", nstr, myv); + } else { + myv = v4 < 0 && flen > 1 ? -v4 : v4; + ostr = write_num("n", nstr, myv); + if (myv < 0 && out[0] && out[0].t == "t") { + ostr = ostr.substr(1); + out[0].v = "-" + out[0].v; + } + } + jj = ostr.length - 1; + var decpt = out.length; + for (i7 = 0; i7 < out.length; ++i7) if (out[i7] != null && out[i7].t != "t" && out[i7].v.indexOf(".") > -1) { + decpt = i7; + break; + } + var lasti = out.length; + if (decpt === out.length && ostr.indexOf("E") === -1) { + for (i7 = out.length - 1; i7 >= 0; --i7) { + if (out[i7] == null || "n?".indexOf(out[i7].t) === -1) continue; + if (jj >= out[i7].v.length - 1) { + jj -= out[i7].v.length; + out[i7].v = ostr.substr(jj + 1, out[i7].v.length); + } else if (jj < 0) out[i7].v = ""; + else { + out[i7].v = ostr.substr(0, jj + 1); + jj = -1; + } + out[i7].t = "t"; + lasti = i7; + } + if (jj >= 0 && lasti < out.length) out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v; + } else if (decpt !== out.length && ostr.indexOf("E") === -1) { + jj = ostr.indexOf(".") - 1; + for (i7 = decpt; i7 >= 0; --i7) { + if (out[i7] == null || "n?".indexOf(out[i7].t) === -1) continue; + j3 = out[i7].v.indexOf(".") > -1 && i7 === decpt ? out[i7].v.indexOf(".") - 1 : out[i7].v.length - 1; + vv = out[i7].v.substr(j3 + 1); + for (; j3 >= 0; --j3) { + if (jj >= 0 && (out[i7].v.charAt(j3) === "0" || out[i7].v.charAt(j3) === "#")) vv = ostr.charAt(jj--) + vv; + } + out[i7].v = vv; + out[i7].t = "t"; + lasti = i7; + } + if (jj >= 0 && lasti < out.length) out[lasti].v = ostr.substr(0, jj + 1) + out[lasti].v; + jj = ostr.indexOf(".") + 1; + for (i7 = decpt; i7 < out.length; ++i7) { + if (out[i7] == null || "n?(".indexOf(out[i7].t) === -1 && i7 !== decpt) continue; + j3 = out[i7].v.indexOf(".") > -1 && i7 === decpt ? out[i7].v.indexOf(".") + 1 : 0; + vv = out[i7].v.substr(0, j3); + for (; j3 < out[i7].v.length; ++j3) { + if (jj < ostr.length) vv += ostr.charAt(jj++); + } + out[i7].v = vv; + out[i7].t = "t"; + lasti = i7; + } + } + } + for (i7 = 0; i7 < out.length; ++i7) if (out[i7] != null && "n?".indexOf(out[i7].t) > -1) { + myv = flen > 1 && v4 < 0 && i7 > 0 && out[i7 - 1].v === "-" ? -v4 : v4; + out[i7].v = write_num(out[i7].t, out[i7].v, myv); + out[i7].t = "t"; + } + var retval = ""; + for (i7 = 0; i7 !== out.length; ++i7) if (out[i7] != null) retval += out[i7].v; + return retval; +} +function chkcond(v4, rr) { + if (rr == null) return false; + var thresh = parseFloat(rr[2]); + switch (rr[1]) { + case "=": + if (v4 == thresh) return true; + break; + case ">": + if (v4 > thresh) return true; + break; + case "<": + if (v4 < thresh) return true; + break; + case "<>": + if (v4 != thresh) return true; + break; + case ">=": + if (v4 >= thresh) return true; + break; + case "<=": + if (v4 <= thresh) return true; + break; + } + return false; +} +function choose_fmt(f4, v4) { + var fmt = SSF_split_fmt(f4); + var l5 = fmt.length, lat = fmt[l5 - 1].indexOf("@"); + if (l5 < 4 && lat > -1) --l5; + if (fmt.length > 4) throw new Error("cannot find right format for |" + fmt.join("|") + "|"); + if (typeof v4 !== "number") return [4, fmt.length === 4 || lat > -1 ? fmt[fmt.length - 1] : "@"]; + if (typeof v4 === "number" && !isFinite(v4)) v4 = 0; + switch (fmt.length) { + case 1: + fmt = lat > -1 ? ["General", "General", "General", fmt[0]] : [fmt[0], fmt[0], fmt[0], "@"]; + break; + case 2: + fmt = lat > -1 ? [fmt[0], fmt[0], fmt[0], fmt[1]] : [fmt[0], fmt[1], fmt[0], "@"]; + break; + case 3: + fmt = lat > -1 ? [fmt[0], fmt[1], fmt[0], fmt[2]] : [fmt[0], fmt[1], fmt[2], "@"]; + break; + case 4: + break; + } + var ff = v4 > 0 ? fmt[0] : v4 < 0 ? fmt[1] : fmt[2]; + if (fmt[0].indexOf("[") === -1 && fmt[1].indexOf("[") === -1) return [l5, ff]; + if (fmt[0].match(/\[[=<>]/) != null || fmt[1].match(/\[[=<>]/) != null) { + var m1 = fmt[0].match(cfregex2); + var m22 = fmt[1].match(cfregex2); + return chkcond(v4, m1) ? [l5, fmt[0]] : chkcond(v4, m22) ? [l5, fmt[1]] : [l5, fmt[m1 != null && m22 != null ? 2 : 1]]; + } + return [l5, ff]; +} +function SSF_format(fmt, v4, o9) { + if (o9 == null) o9 = {}; + var sfmt = ""; + switch (typeof fmt) { + case "string": + if (fmt == "m/d/yy" && o9.dateNF) sfmt = o9.dateNF; + else sfmt = fmt; + break; + case "number": + if (fmt == 14 && o9.dateNF) sfmt = o9.dateNF; + else sfmt = (o9.table != null ? o9.table : table_fmt)[fmt]; + if (sfmt == null) sfmt = o9.table && o9.table[SSF_default_map[fmt]] || table_fmt[SSF_default_map[fmt]]; + if (sfmt == null) sfmt = SSF_default_str[fmt] || "General"; + break; + } + if (SSF_isgeneral(sfmt, 0)) return SSF_general(v4, o9); + if (v4 instanceof Date) v4 = datenum(v4, o9.date1904); + var f4 = choose_fmt(sfmt, v4); + if (SSF_isgeneral(f4[1])) return SSF_general(v4, o9); + if (v4 === true) v4 = "TRUE"; + else if (v4 === false) v4 = "FALSE"; + else if (v4 === "" || v4 == null) return ""; + else if (isNaN(v4) && f4[1].indexOf("0") > -1) return "#NUM!"; + else if (!isFinite(v4) && f4[1].indexOf("0") > -1) return "#DIV/0!"; + return eval_fmt(f4[1], v4, o9, f4[0]); +} +function SSF_load(fmt, idx) { + if (typeof idx != "number") { + idx = +idx || -1; + for (var i7 = 0; i7 < 392; ++i7) { + if (table_fmt[i7] == void 0) { + if (idx < 0) idx = i7; + continue; + } + if (table_fmt[i7] == fmt) { + idx = i7; + break; + } + } + if (idx < 0) idx = 391; + } + table_fmt[idx] = fmt; + return idx; +} +function make_ssf() { + table_fmt = SSF_init_table(); +} +function dateNF_regex(dateNF) { + var fmt = typeof dateNF == "number" ? table_fmt[dateNF] : dateNF; + fmt = fmt.replace(dateNFregex, "(\\d+)"); + dateNFregex.lastIndex = 0; + return new RegExp("^" + fmt + "$"); +} +function dateNF_fix(str2, dateNF, match2) { + var Y = -1, m4 = -1, d4 = -1, H2 = -1, M4 = -1, S5 = -1; + (dateNF.match(dateNFregex) || []).forEach(function(n7, i7) { + var v4 = parseInt(match2[i7 + 1], 10); + switch (n7.toLowerCase().charAt(0)) { + case "y": + Y = v4; + break; + case "d": + d4 = v4; + break; + case "h": + H2 = v4; + break; + case "s": + S5 = v4; + break; + case "m": + if (H2 >= 0) M4 = v4; + else m4 = v4; + break; + } + }); + dateNFregex.lastIndex = 0; + if (S5 >= 0 && M4 == -1 && m4 >= 0) { + M4 = m4; + m4 = -1; + } + var datestr = ("" + (Y >= 0 ? Y : (/* @__PURE__ */ new Date()).getFullYear())).slice(-4) + "-" + ("00" + (m4 >= 1 ? m4 : 1)).slice(-2) + "-" + ("00" + (d4 >= 1 ? d4 : 1)).slice(-2); + if (datestr.length == 7) datestr = "0" + datestr; + if (datestr.length == 8) datestr = "20" + datestr; + var timestr = ("00" + (H2 >= 0 ? H2 : 0)).slice(-2) + ":" + ("00" + (M4 >= 0 ? M4 : 0)).slice(-2) + ":" + ("00" + (S5 >= 0 ? S5 : 0)).slice(-2); + if (H2 == -1 && M4 == -1 && S5 == -1) return datestr; + if (Y == -1 && m4 == -1 && d4 == -1) return timestr; + return datestr + "T" + timestr; +} +function SSF__load(fmt, idx) { + return SSF_load(bad_formats[fmt] || fmt, idx); +} +function read_binary(path6) { + if (typeof _fs !== "undefined") return _fs.readFileSync(path6); + if (typeof Deno !== "undefined") return Deno.readFileSync(path6); + if (typeof $ !== "undefined" && typeof File !== "undefined" && typeof Folder !== "undefined") try { + var infile = File(path6); + infile.open("r"); + infile.encoding = "binary"; + var data = infile.read(); + infile.close(); + return data; + } catch (e9) { + if (!e9.message || e9.message.indexOf("onstruct") == -1) throw e9; + } + throw new Error("Cannot access file " + path6); +} +function keys(o9) { + var ks = Object.keys(o9), o22 = []; + for (var i7 = 0; i7 < ks.length; ++i7) if (Object.prototype.hasOwnProperty.call(o9, ks[i7])) o22.push(ks[i7]); + return o22; +} +function evert(obj) { + var o9 = [], K2 = keys(obj); + for (var i7 = 0; i7 !== K2.length; ++i7) o9[obj[K2[i7]]] = K2[i7]; + return o9; +} +function datenum(v4, date1904) { + var epoch = /* @__PURE__ */ v4.getTime(); + var res = (epoch - dnthresh) / (24 * 60 * 60 * 1e3); + if (date1904) { + res -= 1462; + return res < -1402 ? res - 1 : res; + } + return res < 60 ? res - 1 : res; +} +function numdate(v4) { + if (v4 >= 60 && v4 < 61) return v4; + var out = /* @__PURE__ */ new Date(); + out.setTime((v4 > 60 ? v4 : v4 + 1) * 24 * 60 * 60 * 1e3 + dnthresh); + return out; +} +function parse_isodur(s6) { + var sec = 0, mt = 0, time = false; + var m4 = s6.match(/P([0-9\.]+Y)?([0-9\.]+M)?([0-9\.]+D)?T([0-9\.]+H)?([0-9\.]+M)?([0-9\.]+S)?/); + if (!m4) throw new Error("|" + s6 + "| is not an ISO8601 Duration"); + for (var i7 = 1; i7 != m4.length; ++i7) { + if (!m4[i7]) continue; + mt = 1; + if (i7 > 3) time = true; + switch (m4[i7].slice(m4[i7].length - 1)) { + case "Y": + throw new Error("Unsupported ISO Duration Field: " + m4[i7].slice(m4[i7].length - 1)); + case "D": + mt *= 24; + /* falls through */ + case "H": + mt *= 60; + /* falls through */ + case "M": + if (!time) throw new Error("Unsupported ISO Duration Field: M"); + else mt *= 60; + /* falls through */ + case "S": + break; + } + sec += mt * parseInt(m4[i7], 10); + } + return sec; +} +function parseDate(str2, date1904) { + if (str2 instanceof Date) return str2; + var m4 = str2.match(pdre1); + if (m4) return new Date((date1904 ? dnthresh2 : dnthresh1) + ((parseInt(m4[1], 10) * 60 + parseInt(m4[2], 10)) * 60 + (m4[3] ? parseInt(m4[3].slice(1), 10) : 0)) * 1e3 + (m4[4] ? parseInt((m4[4] + "000").slice(1, 4), 10) : 0)); + m4 = str2.match(pdre2); + if (m4) return new Date(Date.UTC(+m4[1], +m4[2] - 1, +m4[3], 0, 0, 0, 0)); + m4 = str2.match(pdre3); + if (m4) return new Date(Date.UTC(+m4[1], +m4[2] - 1, +m4[3], +m4[4], +m4[5], m4[6] && parseInt(m4[6].slice(1), 10) || 0, m4[7] && parseInt((m4[7] + "0000").slice(1, 4), 10) || 0)); + var d4 = new Date(str2); + return d4; +} +function cc2str(arr, debomit) { + if (has_buf && Buffer.isBuffer(arr)) { + if (debomit && buf_utf16le) { + if (arr[0] == 255 && arr[1] == 254) return utf8write(arr.slice(2).toString("utf16le")); + if (arr[1] == 254 && arr[2] == 255) return utf8write(utf16beread(arr.slice(2).toString("binary"))); + } + return arr.toString("binary"); + } + if (typeof TextDecoder !== "undefined") try { + if (debomit) { + if (arr[0] == 255 && arr[1] == 254) return utf8write(new TextDecoder("utf-16le").decode(arr.slice(2))); + if (arr[0] == 254 && arr[1] == 255) return utf8write(new TextDecoder("utf-16be").decode(arr.slice(2))); + } + var rev = { + "\u20AC": "\x80", + "\u201A": "\x82", + "\u0192": "\x83", + "\u201E": "\x84", + "\u2026": "\x85", + "\u2020": "\x86", + "\u2021": "\x87", + "\u02C6": "\x88", + "\u2030": "\x89", + "\u0160": "\x8A", + "\u2039": "\x8B", + "\u0152": "\x8C", + "\u017D": "\x8E", + "\u2018": "\x91", + "\u2019": "\x92", + "\u201C": "\x93", + "\u201D": "\x94", + "\u2022": "\x95", + "\u2013": "\x96", + "\u2014": "\x97", + "\u02DC": "\x98", + "\u2122": "\x99", + "\u0161": "\x9A", + "\u203A": "\x9B", + "\u0153": "\x9C", + "\u017E": "\x9E", + "\u0178": "\x9F" + }; + if (Array.isArray(arr)) arr = new Uint8Array(arr); + return new TextDecoder("latin1").decode(arr).replace(/[€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ]/g, function(c6) { + return rev[c6] || c6; + }); + } catch (e9) { + } + var o9 = [], i7 = 0; + try { + for (i7 = 0; i7 < arr.length - 65536; i7 += 65536) o9.push(String.fromCharCode.apply(0, arr.slice(i7, i7 + 65536))); + o9.push(String.fromCharCode.apply(0, arr.slice(i7))); + } catch (e9) { + try { + for (; i7 < arr.length - 16384; i7 += 16384) o9.push(String.fromCharCode.apply(0, arr.slice(i7, i7 + 16384))); + o9.push(String.fromCharCode.apply(0, arr.slice(i7))); + } catch (e10) { + for (; i7 != arr.length; ++i7) o9.push(String.fromCharCode(arr[i7])); + } + } + return o9.join(""); +} +function dup(o9) { + if (typeof JSON != "undefined" && !Array.isArray(o9)) return JSON.parse(JSON.stringify(o9)); + if (typeof o9 != "object" || o9 == null) return o9; + if (o9 instanceof Date) return new Date(o9.getTime()); + var out = {}; + for (var k2 in o9) if (Object.prototype.hasOwnProperty.call(o9, k2)) out[k2] = dup(o9[k2]); + return out; +} +function fill(c6, l5) { + var o9 = ""; + while (o9.length < l5) o9 += c6; + return o9; +} +function fuzzynum(s6) { + var v4 = Number(s6); + if (!isNaN(v4)) return isFinite(v4) ? v4 : NaN; + if (!/\d/.test(s6)) return v4; + var wt = 1; + var ss = s6.replace(/([\d]),([\d])/g, "$1$2").replace(/[$]/g, "").replace(/[%]/g, function() { + wt *= 100; + return ""; + }); + if (!isNaN(v4 = Number(ss))) return v4 / wt; + ss = ss.replace(/[(]([^()]*)[)]/, function($$, $1) { + wt = -wt; + return $1; + }); + if (!isNaN(v4 = Number(ss))) return v4 / wt; + return v4; +} +function fuzzytime1(M4) { + if (!M4[2]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), 0, 0, 0)); + if (M4[3]) { + if (M4[4]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], +M4[4], parseFloat(M4[3]) * 1e3)); + else return new Date(Date.UTC(1899, 11, 31, M4[7] == "p" ? 12 : 0, +M4[1], +M4[2], parseFloat(M4[3]) * 1e3)); + } else if (M4[5]) return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], +M4[5], M4[6] ? parseFloat(M4[6]) * 1e3 : 0)); + else return new Date(Date.UTC(1899, 11, 31, +M4[1] % 12 + (M4[7] == "p" ? 12 : 0), +M4[2], 0, 0)); +} +function fuzzytime2(M4) { + if (!M4[2]) return new Date(Date.UTC(1899, 11, 31, +M4[1], 0, 0, 0)); + if (M4[3]) { + if (M4[4]) return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], +M4[4], parseFloat(M4[3]) * 1e3)); + else return new Date(Date.UTC(1899, 11, 31, 0, +M4[1], +M4[2], parseFloat(M4[3]) * 1e3)); + } else if (M4[5]) return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], +M4[5], M4[6] ? parseFloat(M4[6]) * 1e3 : 0)); + else return new Date(Date.UTC(1899, 11, 31, +M4[1], +M4[2], 0, 0)); +} +function fuzzydate(s6) { + if (FDISO.test(s6)) return s6.indexOf("Z") == -1 ? local_to_utc(new Date(s6)) : new Date(s6); + var lower = s6.toLowerCase(); + var lnos = lower.replace(/\s+/g, " ").trim(); + var M4 = lnos.match(FDRE1); + if (M4) return fuzzytime1(M4); + M4 = lnos.match(FDRE2); + if (M4) return fuzzytime2(M4); + M4 = lnos.match(pdre3); + if (M4) return new Date(Date.UTC(+M4[1], +M4[2] - 1, +M4[3], +M4[4], +M4[5], M4[6] && parseInt(M4[6].slice(1), 10) || 0, M4[7] && parseInt((M4[7] + "0000").slice(1, 4), 10) || 0)); + var o9 = new Date(utc_append_works && s6.indexOf("UTC") == -1 ? s6 + " UTC" : s6), n7 = /* @__PURE__ */ new Date(NaN); + var y4 = o9.getYear(), m4 = o9.getMonth(), d4 = o9.getDate(); + if (isNaN(d4)) return n7; + if (lower.match(/jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/)) { + lower = lower.replace(/[^a-z]/g, "").replace(/([^a-z]|^)[ap]m?([^a-z]|$)/, ""); + if (lower.length > 3 && lower_months.indexOf(lower) == -1) return n7; + } else if (lower.replace(/[ap]m?/, "").match(/[a-z]/)) return n7; + if (y4 < 0 || y4 > 8099 || s6.match(/[^-0-9:,\/\\\ ]/)) return n7; + return o9; +} +function utc_to_local(utc) { + return new Date(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate(), utc.getUTCHours(), utc.getUTCMinutes(), utc.getUTCSeconds(), utc.getUTCMilliseconds()); +} +function local_to_utc(local) { + return new Date(Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds())); +} +function remove_doctype(str2) { + var preamble = str2.slice(0, 1024); + var si = preamble.indexOf(" -1) { + var ei = str2.indexOf(e9, si + s6.length); + if (ei == -1) break; + out.push(str2.slice(si, ei + e9.length)); + si = str2.indexOf(s6, ei + e9.length); + } + return out.length > 0 ? out : null; +} +function str_remove_ng(str2, s6, e9) { + var out = [], last = 0; + var si = str2.indexOf(s6); + if (si == -1) return str2; + while (si > -1) { + out.push(str2.slice(last, si)); + var ei = str2.indexOf(e9, si + s6.length); + if (ei == -1) break; + if ((si = str2.indexOf(s6, last = ei + e9.length)) == -1) out.push(str2.slice(last)); + } + return out.join(""); +} +function str_match_xml(str2, tag) { + var si = str2.indexOf("<" + tag), w3 = tag.length + 1, L3 = str2.length; + while (si >= 0 && si <= L3 - w3 && !xml_boundary[str2.charAt(si + w3)]) si = str2.indexOf("<" + tag, si + 1); + if (si === -1) return null; + var sf = str2.indexOf(">", si + tag.length); + if (sf === -1) return null; + var et = ""; + var ei = str2.indexOf(et, sf); + if (ei == -1) return null; + return [str2.slice(si, ei + et.length), str2.slice(sf + 1, ei)]; +} +function getdatastr(data) { + if (!data) return null; + if (data.content && data.type) return cc2str(data.content, true); + if (data.data) return debom(data.data); + if (data.asNodeBuffer && has_buf) return debom(data.asNodeBuffer().toString("binary")); + if (data.asBinary) return debom(data.asBinary()); + if (data._data && data._data.getContent) return debom(cc2str(Array.prototype.slice.call(data._data.getContent(), 0))); + return null; +} +function getdatabin(data) { + if (!data) return null; + if (data.data) return char_codes(data.data); + if (data.asNodeBuffer && has_buf) return data.asNodeBuffer(); + if (data._data && data._data.getContent) { + var o9 = data._data.getContent(); + if (typeof o9 == "string") return char_codes(o9); + return Array.prototype.slice.call(o9); + } + if (data.content && data.type) return data.content; + return null; +} +function getdata(data) { + return data && data.name.slice(-4) === ".bin" ? getdatabin(data) : getdatastr(data); +} +function safegetzipfile(zip, file) { + var k2 = zip.FullPaths || keys(zip.files); + var f4 = file.toLowerCase().replace(/[\/]/g, "\\"), g3 = f4.replace(/\\/g, "/"); + for (var i7 = 0; i7 < k2.length; ++i7) { + var n7 = k2[i7].replace(/^Root Entry[\/]/, "").toLowerCase(); + if (f4 == n7 || g3 == n7) return zip.files ? zip.files[k2[i7]] : zip.FileIndex[i7]; + } + return null; +} +function getzipfile(zip, file) { + var o9 = safegetzipfile(zip, file); + if (o9 == null) throw new Error("Cannot find file " + file + " in zip"); + return o9; +} +function getzipdata(zip, file, safe) { + if (!safe) return getdata(getzipfile(zip, file)); + if (!file) return null; + try { + return getzipdata(zip, file); + } catch (e9) { + return null; + } +} +function getzipstr(zip, file, safe) { + if (!safe) return getdatastr(getzipfile(zip, file)); + if (!file) return null; + try { + return getzipstr(zip, file); + } catch (e9) { + return null; + } +} +function getzipbin(zip, file, safe) { + if (!safe) return getdatabin(getzipfile(zip, file)); + if (!file) return null; + try { + return getzipbin(zip, file); + } catch (e9) { + return null; + } +} +function zipentries(zip) { + var k2 = zip.FullPaths || keys(zip.files), o9 = []; + for (var i7 = 0; i7 < k2.length; ++i7) if (k2[i7].slice(-1) != "/") o9.push(k2[i7].replace(/^Root Entry[\/]/, "")); + return o9.sort(); +} +function zip_add_file(zip, path6, content) { + if (zip.FullPaths) { + if (Array.isArray(content) && typeof content[0] == "string") { + content = content.join(""); + } + if (typeof content == "string") { + var res; + if (has_buf) res = Buffer_from(content); + else res = utf8decode(content); + return CFB.utils.cfb_add(zip, path6, res); + } + CFB.utils.cfb_add(zip, path6, content); + } else zip.file(path6, content); +} +function zip_read(d4, o9) { + switch (o9.type) { + case "base64": + return CFB.read(d4, { type: "base64" }); + case "binary": + return CFB.read(d4, { type: "binary" }); + case "buffer": + case "array": + return CFB.read(d4, { type: "buffer" }); + } + throw new Error("Unrecognized type " + o9.type); +} +function resolve_path(path6, base) { + if (path6.charAt(0) == "/") return path6.slice(1); + var result = base.split("/"); + if (base.slice(-1) != "/") result.pop(); + var target = path6.split("/"); + while (target.length !== 0) { + var step = target.shift(); + if (step === "..") result.pop(); + else if (step !== ".") result.push(step); + } + return result.join("/"); +} +function parsexmltag(tag, skip_root, skip_LC) { + var z3 = {}; + var eq2 = 0, c6 = 0; + for (; eq2 !== tag.length; ++eq2) if ((c6 = tag.charCodeAt(eq2)) === 32 || c6 === 10 || c6 === 13) break; + if (!skip_root) z3[0] = tag.slice(0, eq2); + if (eq2 === tag.length) return z3; + var m4 = tag.match(attregexg), j3 = 0, v4 = "", i7 = 0, q2 = "", cc = "", quot = 1; + if (m4) for (i7 = 0; i7 != m4.length; ++i7) { + cc = m4[i7].slice(1); + for (c6 = 0; c6 != cc.length; ++c6) if (cc.charCodeAt(c6) === 61) break; + q2 = cc.slice(0, c6).trim(); + while (cc.charCodeAt(c6 + 1) == 32) ++c6; + quot = (eq2 = cc.charCodeAt(c6 + 1)) == 34 || eq2 == 39 ? 1 : 0; + v4 = cc.slice(c6 + 1 + quot, cc.length - quot); + for (j3 = 0; j3 != q2.length; ++j3) if (q2.charCodeAt(j3) === 58) break; + if (j3 === q2.length) { + if (q2.indexOf("_") > 0) q2 = q2.slice(0, q2.indexOf("_")); + z3[q2] = v4; + if (!skip_LC) z3[q2.toLowerCase()] = v4; + } else { + var k2 = (j3 === 5 && q2.slice(0, 5) === "xmlns" ? "xmlns" : "") + q2.slice(j3 + 1); + if (z3[k2] && q2.slice(j3 - 3, j3) == "ext") continue; + z3[k2] = v4; + if (!skip_LC) z3[k2.toLowerCase()] = v4; + } + } + return z3; +} +function parsexmltagraw(tag, skip_root, skip_LC) { + var z3 = {}; + var eq2 = 0, c6 = 0; + for (; eq2 !== tag.length; ++eq2) if ((c6 = tag.charCodeAt(eq2)) === 32 || c6 === 10 || c6 === 13) break; + if (!skip_root) z3[0] = tag.slice(0, eq2); + if (eq2 === tag.length) return z3; + var m4 = tag.match(attregexg), j3 = 0, v4 = "", i7 = 0, q2 = "", cc = "", quot = 1; + if (m4) for (i7 = 0; i7 != m4.length; ++i7) { + cc = m4[i7].slice(1); + for (c6 = 0; c6 != cc.length; ++c6) if (cc.charCodeAt(c6) === 61) break; + q2 = cc.slice(0, c6).trim(); + while (cc.charCodeAt(c6 + 1) == 32) ++c6; + quot = (eq2 = cc.charCodeAt(c6 + 1)) == 34 || eq2 == 39 ? 1 : 0; + v4 = cc.slice(c6 + 1 + quot, cc.length - quot); + if (q2.indexOf("_") > 0) q2 = q2.slice(0, q2.indexOf("_")); + z3[q2] = v4; + if (!skip_LC) z3[q2.toLowerCase()] = v4; + } + return z3; +} +function strip_ns(x2) { + return x2.replace(nsregex2, "<$1"); +} +function escapehtml(text3) { + var s6 = text3 + ""; + return s6.replace(decregex, function(y4) { + return rencoding[y4]; + }).replace(/\n/g, "
").replace(htmlcharegex, function(s7) { + return "&#x" + ("000" + s7.charCodeAt(0).toString(16)).slice(-4) + ";"; + }); +} +function parsexmlbool(value) { + switch (value) { + case 1: + case true: + case "1": + case "true": + return true; + case 0: + case false: + case "0": + case "false": + return false; + } + return false; +} +function utf8reada(orig) { + var out = "", i7 = 0, c6 = 0, d4 = 0, e9 = 0, f4 = 0, w3 = 0; + while (i7 < orig.length) { + c6 = orig.charCodeAt(i7++); + if (c6 < 128) { + out += String.fromCharCode(c6); + continue; + } + d4 = orig.charCodeAt(i7++); + if (c6 > 191 && c6 < 224) { + f4 = (c6 & 31) << 6; + f4 |= d4 & 63; + out += String.fromCharCode(f4); + continue; + } + e9 = orig.charCodeAt(i7++); + if (c6 < 240) { + out += String.fromCharCode((c6 & 15) << 12 | (d4 & 63) << 6 | e9 & 63); + continue; + } + f4 = orig.charCodeAt(i7++); + w3 = ((c6 & 7) << 18 | (d4 & 63) << 12 | (e9 & 63) << 6 | f4 & 63) - 65536; + out += String.fromCharCode(55296 + (w3 >>> 10 & 1023)); + out += String.fromCharCode(56320 + (w3 & 1023)); + } + return out; +} +function utf8readb(data) { + var out = new_raw_buf(2 * data.length), w3, i7, j3 = 1, k2 = 0, ww = 0, c6; + for (i7 = 0; i7 < data.length; i7 += j3) { + j3 = 1; + if ((c6 = data.charCodeAt(i7)) < 128) w3 = c6; + else if (c6 < 224) { + w3 = (c6 & 31) * 64 + (data.charCodeAt(i7 + 1) & 63); + j3 = 2; + } else if (c6 < 240) { + w3 = (c6 & 15) * 4096 + (data.charCodeAt(i7 + 1) & 63) * 64 + (data.charCodeAt(i7 + 2) & 63); + j3 = 3; + } else { + j3 = 4; + w3 = (c6 & 7) * 262144 + (data.charCodeAt(i7 + 1) & 63) * 4096 + (data.charCodeAt(i7 + 2) & 63) * 64 + (data.charCodeAt(i7 + 3) & 63); + w3 -= 65536; + ww = 55296 + (w3 >>> 10 & 1023); + w3 = 56320 + (w3 & 1023); + } + if (ww !== 0) { + out[k2++] = ww & 255; + out[k2++] = ww >>> 8; + ww = 0; + } + out[k2++] = w3 % 256; + out[k2++] = w3 >>> 8; + } + return out.slice(0, k2).toString("ucs2"); +} +function utf8readc(data) { + return Buffer_from(data, "binary").toString("utf8"); +} +function parseVector(data, opts) { + var h7 = parsexmltag(data); + var matches = str_match_xml_ns_g(data, h7.baseType) || []; + var res = []; + if (matches.length != h7.size) { + if (opts.WTF) throw new Error("unexpected vector length " + matches.length + " != " + h7.size); + return res; + } + matches.forEach(function(x2) { + var v4 = x2.replace(vtvregex, "").match(vtmregex); + if (v4) res.push({ v: utf8read(v4[2]), t: v4[1] }); + }); + return res; +} +function wxt_helper(h7) { + return keys(h7).map(function(k2) { + return " " + k2 + '="' + h7[k2] + '"'; + }).join(""); +} +function writextag(f4, g3, h7) { + return "<" + f4 + (h7 != null ? wxt_helper(h7) : "") + (g3 != null ? (g3.match(wtregex) ? ' xml:space="preserve"' : "") + ">" + g3 + ""; +} +function xlml_normalize(d4) { + if (has_buf && /*::typeof Buffer !== "undefined" && d != null && d instanceof Buffer &&*/ + Buffer.isBuffer(d4)) return d4.toString("utf8"); + if (typeof d4 === "string") return d4; + if (typeof Uint8Array !== "undefined" && d4 instanceof Uint8Array) return utf8read(a2s(ab2a(d4))); + throw new Error("Bad input format: expected Buffer or string"); +} +function read_double_le(b4, idx) { + var s6 = 1 - 2 * (b4[idx + 7] >>> 7); + var e9 = ((b4[idx + 7] & 127) << 4) + (b4[idx + 6] >>> 4 & 15); + var m4 = b4[idx + 6] & 15; + for (var i7 = 5; i7 >= 0; --i7) m4 = m4 * 256 + b4[idx + i7]; + if (e9 == 2047) return m4 == 0 ? s6 * Infinity : NaN; + if (e9 == 0) e9 = -1022; + else { + e9 -= 1023; + m4 += Math.pow(2, 52); + } + return s6 * Math.pow(2, e9 - 52) * m4; +} +function write_double_le(b4, v4, idx) { + var bs = (v4 < 0 || 1 / v4 == -Infinity ? 1 : 0) << 7, e9 = 0, m4 = 0; + var av = bs ? -v4 : v4; + if (!isFinite(av)) { + e9 = 2047; + m4 = isNaN(v4) ? 26985 : 0; + } else if (av == 0) e9 = m4 = 0; + else { + e9 = Math.floor(Math.log(av) / Math.LN2); + m4 = av * Math.pow(2, 52 - e9); + if (e9 <= -1023 && (!isFinite(m4) || m4 < Math.pow(2, 52))) { + e9 = -1022; + } else { + m4 -= Math.pow(2, 52); + e9 += 1023; + } + } + for (var i7 = 0; i7 <= 5; ++i7, m4 /= 256) b4[idx + i7] = m4 & 255; + b4[idx + 6] = (e9 & 15) << 4 | m4 & 15; + b4[idx + 7] = e9 >> 4 | bs; +} +function cpdoit() { + __utf16le = function(b4, s6, e9) { + return $cptable.utils.decode(1200, b4.slice(s6, e9)).replace(chr0, ""); + }; + __utf8 = function(b4, s6, e9) { + return $cptable.utils.decode(65001, b4.slice(s6, e9)); + }; + __lpstr = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? $cptable.utils.decode(current_ansi, b4.slice(i7 + 4, i7 + 4 + len - 1)) : ""; + }; + __cpstr = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? $cptable.utils.decode(current_codepage, b4.slice(i7 + 4, i7 + 4 + len - 1)) : ""; + }; + __lpwstr = function(b4, i7) { + var len = 2 * __readUInt32LE(b4, i7); + return len > 0 ? $cptable.utils.decode(1200, b4.slice(i7 + 4, i7 + 4 + len - 1)) : ""; + }; + __lpp4 = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? $cptable.utils.decode(1200, b4.slice(i7 + 4, i7 + 4 + len)) : ""; + }; + __8lpp4 = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? $cptable.utils.decode(65001, b4.slice(i7 + 4, i7 + 4 + len)) : ""; + }; +} +function ReadShift(size, t6) { + var o9 = "", oI, oR, oo = [], w3, vv, i7, loc; + switch (t6) { + case "dbcs": + loc = this.l; + if (has_buf && Buffer.isBuffer(this) && buf_utf16le) o9 = this.slice(this.l, this.l + 2 * size).toString("utf16le"); + else for (i7 = 0; i7 < size; ++i7) { + o9 += String.fromCharCode(__readUInt16LE(this, loc)); + loc += 2; + } + size *= 2; + break; + case "utf8": + o9 = __utf8(this, this.l, this.l + size); + break; + case "utf16le": + size *= 2; + o9 = __utf16le(this, this.l, this.l + size); + break; + case "wstr": + if (typeof $cptable !== "undefined") o9 = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + 2 * size)); + else return ReadShift.call(this, size, "dbcs"); + size = 2 * size; + break; + /* [MS-OLEDS] 2.1.4 LengthPrefixedAnsiString */ + case "lpstr-ansi": + o9 = __lpstr(this, this.l); + size = 4 + __readUInt32LE(this, this.l); + break; + case "lpstr-cp": + o9 = __cpstr(this, this.l); + size = 4 + __readUInt32LE(this, this.l); + break; + /* [MS-OLEDS] 2.1.5 LengthPrefixedUnicodeString */ + case "lpwstr": + o9 = __lpwstr(this, this.l); + size = 4 + 2 * __readUInt32LE(this, this.l); + break; + /* [MS-OFFCRYPTO] 2.1.2 Length-Prefixed Padded Unicode String (UNICODE-LP-P4) */ + case "lpp4": + size = 4 + __readUInt32LE(this, this.l); + o9 = __lpp4(this, this.l); + if (size & 2) size += 2; + break; + /* [MS-OFFCRYPTO] 2.1.3 Length-Prefixed UTF-8 String (UTF-8-LP-P4) */ + case "8lpp4": + size = 4 + __readUInt32LE(this, this.l); + o9 = __8lpp4(this, this.l); + if (size & 3) size += 4 - (size & 3); + break; + case "cstr": + size = 0; + o9 = ""; + while ((w3 = __readUInt8(this, this.l + size++)) !== 0) oo.push(_getchar(w3)); + o9 = oo.join(""); + break; + case "_wstr": + size = 0; + o9 = ""; + while ((w3 = __readUInt16LE(this, this.l + size)) !== 0) { + oo.push(_getchar(w3)); + size += 2; + } + size += 2; + o9 = oo.join(""); + break; + /* sbcs and dbcs support continue records in the SST way TODO codepages */ + case "dbcs-cont": + o9 = ""; + loc = this.l; + for (i7 = 0; i7 < size; ++i7) { + if (this.lens && this.lens.indexOf(loc) !== -1) { + w3 = __readUInt8(this, loc); + this.l = loc + 1; + vv = ReadShift.call(this, size - i7, w3 ? "dbcs-cont" : "sbcs-cont"); + return oo.join("") + vv; + } + oo.push(_getchar(__readUInt16LE(this, loc))); + loc += 2; + } + o9 = oo.join(""); + size *= 2; + break; + case "cpstr": + if (typeof $cptable !== "undefined") { + o9 = $cptable.utils.decode(current_codepage, this.slice(this.l, this.l + size)); + break; + } + /* falls through */ + case "sbcs-cont": + o9 = ""; + loc = this.l; + for (i7 = 0; i7 != size; ++i7) { + if (this.lens && this.lens.indexOf(loc) !== -1) { + w3 = __readUInt8(this, loc); + this.l = loc + 1; + vv = ReadShift.call(this, size - i7, w3 ? "dbcs-cont" : "sbcs-cont"); + return oo.join("") + vv; + } + oo.push(_getchar(__readUInt8(this, loc))); + loc += 1; + } + o9 = oo.join(""); + break; + default: + switch (size) { + case 1: + oI = __readUInt8(this, this.l); + this.l++; + return oI; + case 2: + oI = (t6 === "i" ? __readInt16LE : __readUInt16LE)(this, this.l); + this.l += 2; + return oI; + case 4: + case -4: + if (t6 === "i" || (this[this.l + 3] & 128) === 0) { + oI = (size > 0 ? __readInt32LE : __readInt32BE)(this, this.l); + this.l += 4; + return oI; + } else { + oR = __readUInt32LE(this, this.l); + this.l += 4; + } + return oR; + case 8: + case -8: + if (t6 === "f") { + if (size == 8) oR = __double(this, this.l); + else oR = __double([this[this.l + 7], this[this.l + 6], this[this.l + 5], this[this.l + 4], this[this.l + 3], this[this.l + 2], this[this.l + 1], this[this.l + 0]], 0); + this.l += 8; + return oR; + } else size = 8; + /* falls through */ + case 16: + o9 = __hexlify(this, this.l, size); + break; + } + } + this.l += size; + return o9; +} +function WriteShift(t6, val2, f4) { + var size = 0, i7 = 0; + if (f4 === "dbcs") { + for (i7 = 0; i7 != val2.length; ++i7) __writeUInt16LE(this, val2.charCodeAt(i7), this.l + 2 * i7); + size = 2 * val2.length; + } else if (f4 === "sbcs" || f4 == "cpstr") { + if (typeof $cptable !== "undefined" && current_ansi == 874) { + for (i7 = 0; i7 != val2.length; ++i7) { + var cpp = $cptable.utils.encode(current_ansi, val2.charAt(i7)); + this[this.l + i7] = cpp[0]; + } + size = val2.length; + } else if (typeof $cptable !== "undefined" && f4 == "cpstr") { + cpp = $cptable.utils.encode(current_codepage, val2); + if (cpp.length == val2.length) { + for (i7 = 0; i7 < val2.length; ++i7) if (cpp[i7] == 0 && val2.charCodeAt(i7) != 0) cpp[i7] = 95; + } + if (cpp.length == 2 * val2.length) { + for (i7 = 0; i7 < val2.length; ++i7) if (cpp[2 * i7] == 0 && cpp[2 * i7 + 1] == 0 && val2.charCodeAt(i7) != 0) cpp[2 * i7] = 95; + } + for (i7 = 0; i7 < cpp.length; ++i7) this[this.l + i7] = cpp[i7]; + size = cpp.length; + } else { + val2 = val2.replace(/[^\x00-\x7F]/g, "_"); + for (i7 = 0; i7 != val2.length; ++i7) this[this.l + i7] = val2.charCodeAt(i7) & 255; + size = val2.length; + } + } else if (f4 === "hex") { + for (; i7 < t6; ++i7) { + this[this.l++] = parseInt(val2.slice(2 * i7, 2 * i7 + 2), 16) || 0; + } + return this; + } else if (f4 === "utf16le") { + var end = Math.min(this.l + t6, this.length); + for (i7 = 0; i7 < Math.min(val2.length, t6); ++i7) { + var cc = val2.charCodeAt(i7); + this[this.l++] = cc & 255; + this[this.l++] = cc >> 8; + } + while (this.l < end) this[this.l++] = 0; + return this; + } else switch (t6) { + case 1: + size = 1; + this[this.l] = val2 & 255; + break; + case 2: + size = 2; + this[this.l] = val2 & 255; + val2 >>>= 8; + this[this.l + 1] = val2 & 255; + break; + case 3: + size = 3; + this[this.l] = val2 & 255; + val2 >>>= 8; + this[this.l + 1] = val2 & 255; + val2 >>>= 8; + this[this.l + 2] = val2 & 255; + break; + case 4: + size = 4; + __writeUInt32LE(this, val2, this.l); + break; + case 8: + size = 8; + if (f4 === "f") { + write_double_le(this, val2, this.l); + break; + } + /* falls through */ + case 16: + break; + case -4: + size = 4; + __writeInt32LE(this, val2, this.l); + break; + } + this.l += size; + return this; +} +function CheckField(hexstr, fld) { + var m4 = __hexlify(this, this.l, hexstr.length >> 1); + if (m4 !== hexstr) throw new Error(fld + "Expected " + hexstr + " saw " + m4); + this.l += hexstr.length >> 1; +} +function prep_blob(blob, pos) { + blob.l = pos; + blob.read_shift = /*::(*/ + ReadShift; + blob.chk = CheckField; + blob.write_shift = WriteShift; +} +function parsenoop(blob, length) { + blob.l += length; +} +function new_buf(sz) { + var o9 = new_raw_buf(sz); + prep_blob(o9, 0); + return o9; +} +function recordhopper(data, cb, opts) { + if (!data) return; + var tmpbyte, cntbyte, length; + prep_blob(data, data.l || 0); + var L3 = data.length, RT = 0, tgt = 0; + while (data.l < L3) { + RT = data.read_shift(1); + if (RT & 128) RT = (RT & 127) + ((data.read_shift(1) & 127) << 7); + var R3 = XLSBRecordEnum[RT] || XLSBRecordEnum[65535]; + tmpbyte = data.read_shift(1); + length = tmpbyte & 127; + for (cntbyte = 1; cntbyte < 4 && tmpbyte & 128; ++cntbyte) length += ((tmpbyte = data.read_shift(1)) & 127) << 7 * cntbyte; + tgt = data.l + length; + var d4 = R3.f && R3.f(data, length, opts); + data.l = tgt; + if (cb(d4, R3, RT)) return; + } +} +function buf_array() { + var bufs = [], blksz = has_buf ? 16384 : 2048; + var has_buf_copy = has_buf && typeof new_buf(blksz).copy == "function"; + var newblk = function ba_newblk(sz) { + var o9 = new_buf(sz); + prep_blob(o9, 0); + return o9; + }; + var curbuf = newblk(blksz); + var endbuf = function ba_endbuf() { + if (!curbuf) return; + if (curbuf.l) { + if (curbuf.length > curbuf.l) { + curbuf = curbuf.slice(0, curbuf.l); + curbuf.l = curbuf.length; + } + if (curbuf.length > 0) bufs.push(curbuf); + } + curbuf = null; + }; + var next = function ba_next(sz) { + if (curbuf && sz < curbuf.length - curbuf.l) return curbuf; + endbuf(); + return curbuf = newblk(Math.max(sz + 1, blksz)); + }; + var end = function ba_end() { + endbuf(); + return bconcat(bufs); + }; + var end2 = function() { + endbuf(); + return bufs; + }; + var push = function ba_push(buf) { + endbuf(); + curbuf = buf; + if (curbuf.l == null) curbuf.l = curbuf.length; + next(blksz); + }; + return { next, push, end, _bufs: bufs, end2 }; +} +function shift_cell_xls(cell, tgt, opts) { + var out = dup(cell); + if (tgt.s) { + if (out.cRel) out.c += tgt.s.c; + if (out.rRel) out.r += tgt.s.r; + } else { + if (out.cRel) out.c += tgt.c; + if (out.rRel) out.r += tgt.r; + } + if (!opts || opts.biff < 12) { + while (out.c >= 256) out.c -= 256; + while (out.r >= 65536) out.r -= 65536; + } + return out; +} +function shift_range_xls(cell, range2, opts) { + var out = dup(cell); + out.s = shift_cell_xls(out.s, range2.s, opts); + out.e = shift_cell_xls(out.e, range2.s, opts); + return out; +} +function encode_cell_xls(c6, biff) { + if (c6.cRel && c6.c < 0) { + c6 = dup(c6); + while (c6.c < 0) c6.c += biff > 8 ? 16384 : 256; + } + if (c6.rRel && c6.r < 0) { + c6 = dup(c6); + while (c6.r < 0) c6.r += biff > 8 ? 1048576 : biff > 5 ? 65536 : 16384; + } + var s6 = encode_cell(c6); + if (!c6.cRel && c6.cRel != null) s6 = fix_col(s6); + if (!c6.rRel && c6.rRel != null) s6 = fix_row(s6); + return s6; +} +function encode_range_xls(r8, opts) { + if (r8.s.r == 0 && !r8.s.rRel) { + if (r8.e.r == (opts.biff >= 12 ? 1048575 : opts.biff >= 8 ? 65536 : 16384) && !r8.e.rRel) { + return (r8.s.cRel ? "" : "$") + encode_col(r8.s.c) + ":" + (r8.e.cRel ? "" : "$") + encode_col(r8.e.c); + } + } + if (r8.s.c == 0 && !r8.s.cRel) { + if (r8.e.c == (opts.biff >= 12 ? 16383 : 255) && !r8.e.cRel) { + return (r8.s.rRel ? "" : "$") + encode_row(r8.s.r) + ":" + (r8.e.rRel ? "" : "$") + encode_row(r8.e.r); + } + } + return encode_cell_xls(r8.s, opts.biff) + ":" + encode_cell_xls(r8.e, opts.biff); +} +function decode_row(rowstr) { + return parseInt(unfix_row(rowstr), 10) - 1; +} +function encode_row(row) { + return "" + (row + 1); +} +function fix_row(cstr) { + return cstr.replace(/([A-Z]|^)(\d+)$/, "$1$$$2"); +} +function unfix_row(cstr) { + return cstr.replace(/\$(\d+)$/, "$1"); +} +function decode_col(colstr) { + var c6 = unfix_col(colstr), d4 = 0, i7 = 0; + for (; i7 !== c6.length; ++i7) d4 = 26 * d4 + c6.charCodeAt(i7) - 64; + return d4 - 1; +} +function encode_col(col) { + if (col < 0) throw new Error("invalid column " + col); + var s6 = ""; + for (++col; col; col = Math.floor((col - 1) / 26)) s6 = String.fromCharCode((col - 1) % 26 + 65) + s6; + return s6; +} +function fix_col(cstr) { + return cstr.replace(/^([A-Z])/, "$$$1"); +} +function unfix_col(cstr) { + return cstr.replace(/^\$([A-Z])/, "$1"); +} +function split_cell(cstr) { + return cstr.replace(/(\$?[A-Z]*)(\$?\d*)/, "$1,$2").split(","); +} +function decode_cell(cstr) { + var R3 = 0, C3 = 0; + for (var i7 = 0; i7 < cstr.length; ++i7) { + var cc = cstr.charCodeAt(i7); + if (cc >= 48 && cc <= 57) R3 = 10 * R3 + (cc - 48); + else if (cc >= 65 && cc <= 90) C3 = 26 * C3 + (cc - 64); + } + return { c: C3 - 1, r: R3 - 1 }; +} +function encode_cell(cell) { + var col = cell.c + 1; + var s6 = ""; + for (; col; col = (col - 1) / 26 | 0) s6 = String.fromCharCode((col - 1) % 26 + 65) + s6; + return s6 + (cell.r + 1); +} +function decode_range(range2) { + var idx = range2.indexOf(":"); + if (idx == -1) return { s: decode_cell(range2), e: decode_cell(range2) }; + return { s: decode_cell(range2.slice(0, idx)), e: decode_cell(range2.slice(idx + 1)) }; +} +function encode_range(cs, ce2) { + if (typeof ce2 === "undefined" || typeof ce2 === "number") { + return encode_range(cs.s, cs.e); + } + if (typeof cs !== "string") cs = encode_cell(cs); + if (typeof ce2 !== "string") ce2 = encode_cell(ce2); + return cs == ce2 ? cs : cs + ":" + ce2; +} +function formula_quote_sheet_name(sname, opts) { + if (!sname && !(opts && opts.biff <= 5 && opts.biff >= 2)) throw new Error("empty sheet name"); + if (/[^\w\u4E00-\u9FFF\u3040-\u30FF]/.test(sname)) return "'" + sname.replace(/'/g, "''") + "'"; + return sname; +} +function safe_decode_range(range2) { + var o9 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } }; + var idx = 0, i7 = 0, cc = 0; + var len = range2.length; + for (idx = 0; i7 < len; ++i7) { + if ((cc = range2.charCodeAt(i7) - 64) < 1 || cc > 26) break; + idx = 26 * idx + cc; + } + o9.s.c = --idx; + for (idx = 0; i7 < len; ++i7) { + if ((cc = range2.charCodeAt(i7) - 48) < 0 || cc > 9) break; + idx = 10 * idx + cc; + } + o9.s.r = --idx; + if (i7 === len || cc != 10) { + o9.e.c = o9.s.c; + o9.e.r = o9.s.r; + return o9; + } + ++i7; + for (idx = 0; i7 != len; ++i7) { + if ((cc = range2.charCodeAt(i7) - 64) < 1 || cc > 26) break; + idx = 26 * idx + cc; + } + o9.e.c = --idx; + for (idx = 0; i7 != len; ++i7) { + if ((cc = range2.charCodeAt(i7) - 48) < 0 || cc > 9) break; + idx = 10 * idx + cc; + } + o9.e.r = --idx; + return o9; +} +function safe_format_cell(cell, v4) { + var q2 = cell.t == "d" && v4 instanceof Date; + if (cell.z != null) try { + return cell.w = SSF_format(cell.z, q2 ? datenum(v4) : v4); + } catch (e9) { + } + try { + return cell.w = SSF_format((cell.XF || {}).numFmtId || (q2 ? 14 : 0), q2 ? datenum(v4) : v4); + } catch (e9) { + return "" + v4; + } +} +function format_cell(cell, v4, o9) { + if (cell == null || cell.t == null || cell.t == "z") return ""; + if (cell.w !== void 0) return cell.w; + if (cell.t == "d" && !cell.z && o9 && o9.dateNF) cell.z = o9.dateNF; + if (cell.t == "e") return BErr[cell.v] || cell.v; + if (v4 == void 0) return safe_format_cell(cell, cell.v); + return safe_format_cell(cell, v4); +} +function sheet_to_workbook(sheet, opts) { + var n7 = opts && opts.sheet ? opts.sheet : "Sheet1"; + var sheets = {}; + sheets[n7] = sheet; + return { SheetNames: [n7], Sheets: sheets }; +} +function sheet_new(opts) { + var out = {}; + var o9 = opts || {}; + if (o9.dense) out["!data"] = []; + return out; +} +function sheet_add_aoa(_ws, data, opts) { + var o9 = opts || {}; + var dense = _ws ? _ws["!data"] != null : o9.dense; + if (DENSE != null && dense == null) dense = DENSE; + var ws = _ws || (dense ? { "!data": [] } : {}); + if (dense && !ws["!data"]) ws["!data"] = []; + var _R = 0, _C = 0; + if (ws && o9.origin != null) { + if (typeof o9.origin == "number") _R = o9.origin; + else { + var _origin2 = typeof o9.origin == "string" ? decode_cell(o9.origin) : o9.origin; + _R = _origin2.r; + _C = _origin2.c; + } + } + var range2 = { s: { c: 1e7, r: 1e7 }, e: { c: 0, r: 0 } }; + if (ws["!ref"]) { + var _range = safe_decode_range(ws["!ref"]); + range2.s.c = _range.s.c; + range2.s.r = _range.s.r; + range2.e.c = Math.max(range2.e.c, _range.e.c); + range2.e.r = Math.max(range2.e.r, _range.e.r); + if (_R == -1) range2.e.r = _R = ws["!ref"] ? _range.e.r + 1 : 0; + } else { + range2.s.c = range2.e.c = range2.s.r = range2.e.r = 0; + } + var row = [], seen = false; + for (var R3 = 0; R3 != data.length; ++R3) { + if (!data[R3]) continue; + if (!Array.isArray(data[R3])) throw new Error("aoa_to_sheet expects an array of arrays"); + var __R = _R + R3; + if (dense) { + if (!ws["!data"][__R]) ws["!data"][__R] = []; + row = ws["!data"][__R]; + } + var data_R = data[R3]; + for (var C3 = 0; C3 != data_R.length; ++C3) { + if (typeof data_R[C3] === "undefined") continue; + var cell = { v: data_R[C3], t: "" }; + var __C = _C + C3; + if (range2.s.r > __R) range2.s.r = __R; + if (range2.s.c > __C) range2.s.c = __C; + if (range2.e.r < __R) range2.e.r = __R; + if (range2.e.c < __C) range2.e.c = __C; + seen = true; + if (data_R[C3] && typeof data_R[C3] === "object" && !Array.isArray(data_R[C3]) && !(data_R[C3] instanceof Date)) cell = data_R[C3]; + else { + if (Array.isArray(cell.v)) { + cell.f = data_R[C3][1]; + cell.v = cell.v[0]; + } + if (cell.v === null) { + if (cell.f) cell.t = "n"; + else if (o9.nullError) { + cell.t = "e"; + cell.v = 0; + } else if (!o9.sheetStubs) continue; + else cell.t = "z"; + } else if (typeof cell.v === "number") { + if (isFinite(cell.v)) cell.t = "n"; + else if (isNaN(cell.v)) { + cell.t = "e"; + cell.v = 15; + } else { + cell.t = "e"; + cell.v = 7; + } + } else if (typeof cell.v === "boolean") cell.t = "b"; + else if (cell.v instanceof Date) { + cell.z = o9.dateNF || table_fmt[14]; + if (!o9.UTC) cell.v = local_to_utc(cell.v); + if (o9.cellDates) { + cell.t = "d"; + cell.w = SSF_format(cell.z, datenum(cell.v, o9.date1904)); + } else { + cell.t = "n"; + cell.v = datenum(cell.v, o9.date1904); + cell.w = SSF_format(cell.z, cell.v); + } + } else cell.t = "s"; + } + if (dense) { + if (row[__C] && row[__C].z) cell.z = row[__C].z; + row[__C] = cell; + } else { + var cell_ref = encode_col(__C) + (__R + 1); + if (ws[cell_ref] && ws[cell_ref].z) cell.z = ws[cell_ref].z; + ws[cell_ref] = cell; + } + } + } + if (seen && range2.s.c < 104e5) ws["!ref"] = encode_range(range2); + return ws; +} +function aoa_to_sheet(data, opts) { + return sheet_add_aoa(null, data, opts); +} +function parse_Int32LE(data) { + return data.read_shift(4, "i"); +} +function parse_XLWideString(data) { + var cchCharacters = data.read_shift(4); + return cchCharacters === 0 ? "" : data.read_shift(cchCharacters, "dbcs"); +} +function parse_StrRun(data) { + return { ich: data.read_shift(2), ifnt: data.read_shift(2) }; +} +function parse_RichStr(data, length) { + var start = data.l; + var flags = data.read_shift(1); + var str2 = parse_XLWideString(data); + var rgsStrRun = []; + var z3 = { t: str2, h: str2 }; + if ((flags & 1) !== 0) { + var dwSizeStrRun = data.read_shift(4); + for (var i7 = 0; i7 != dwSizeStrRun; ++i7) rgsStrRun.push(parse_StrRun(data)); + z3.r = rgsStrRun; + } else z3.r = [{ ich: 0, ifnt: 0 }]; + data.l = start + length; + return z3; +} +function parse_XLSBCell(data) { + var col = data.read_shift(4); + var iStyleRef = data.read_shift(2); + iStyleRef += data.read_shift(1) << 16; + data.l++; + return { c: col, iStyleRef }; +} +function parse_XLSBShortCell(data) { + var iStyleRef = data.read_shift(2); + iStyleRef += data.read_shift(1) << 16; + data.l++; + return { c: -1, iStyleRef }; +} +function parse_XLNullableWideString(data) { + var cchCharacters = data.read_shift(4); + return cchCharacters === 0 || cchCharacters === 4294967295 ? "" : data.read_shift(cchCharacters, "dbcs"); +} +function parse_RkNumber(data) { + var b4 = data.slice(data.l, data.l + 4); + var fX100 = b4[0] & 1, fInt = b4[0] & 2; + data.l += 4; + var RK = fInt === 0 ? __double([0, 0, 0, 0, b4[0] & 252, b4[1], b4[2], b4[3]], 0) : __readInt32LE(b4, 0) >> 2; + return fX100 ? RK / 100 : RK; +} +function parse_RfX(data) { + var cell = { s: {}, e: {} }; + cell.s.r = data.read_shift(4); + cell.e.r = data.read_shift(4); + cell.s.c = data.read_shift(4); + cell.e.c = data.read_shift(4); + return cell; +} +function parse_Xnum(data) { + if (data.length - data.l < 8) throw "XLS Xnum Buffer underflow"; + return data.read_shift(8, "f"); +} +function parse_BrtColor(data) { + var out = {}; + var d4 = data.read_shift(1); + var xColorType = d4 >>> 1; + var index2 = data.read_shift(1); + var nTS = data.read_shift(2, "i"); + var bR = data.read_shift(1); + var bG = data.read_shift(1); + var bB = data.read_shift(1); + data.l++; + switch (xColorType) { + case 0: + out.auto = 1; + break; + case 1: + out.index = index2; + var icv = XLSIcv[index2]; + if (icv) out.rgb = rgb2Hex(icv); + break; + case 2: + out.rgb = rgb2Hex([bR, bG, bB]); + break; + case 3: + out.theme = index2; + break; + } + if (nTS != 0) out.tint = nTS > 0 ? nTS / 32767 : nTS / 32768; + return out; +} +function parse_FontFlags(data) { + var d4 = data.read_shift(1); + data.l++; + var out = { + fBold: d4 & 1, + fItalic: d4 & 2, + fUnderline: d4 & 4, + fStrikeout: d4 & 8, + fOutline: d4 & 16, + fShadow: d4 & 32, + fCondense: d4 & 64, + fExtend: d4 & 128 + }; + return out; +} +function parse_ClipboardFormatOrString(o9, w3) { + var ClipFmt = { 2: "BITMAP", 3: "METAFILEPICT", 8: "DIB", 14: "ENHMETAFILE" }; + var m4 = o9.read_shift(4); + switch (m4) { + case 0: + return ""; + case 4294967295: + case 4294967294: + return ClipFmt[o9.read_shift(4)] || ""; + } + if (m4 > 400) throw new Error("Unsupported Clipboard: " + m4.toString(16)); + o9.l -= 4; + return o9.read_shift(0, w3 == 1 ? "lpstr" : "lpwstr"); +} +function parse_ClipboardFormatOrAnsiString(o9) { + return parse_ClipboardFormatOrString(o9, 1); +} +function parse_ClipboardFormatOrUnicodeString(o9) { + return parse_ClipboardFormatOrString(o9, 2); +} +function rgbify(arr) { + return arr.map(function(x2) { + return [x2 >> 16 & 255, x2 >> 8 & 255, x2 & 255]; + }); +} +function new_ct() { + return { + workbooks: [], + sheets: [], + charts: [], + dialogs: [], + macros: [], + rels: [], + strs: [], + comments: [], + threadedcomments: [], + links: [], + coreprops: [], + extprops: [], + custprops: [], + themes: [], + styles: [], + calcchains: [], + vba: [], + drawings: [], + metadata: [], + people: [], + TODO: [], + xmlns: "" + }; +} +function parse_ct(data) { + var ct = new_ct(); + if (!data || !data.match) return ct; + var ctext = {}; + (data.match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2); + switch (y4[0].replace(nsregex, "<")) { + case " 0 ? ct.calcchains[0] : ""; + ct.sst = ct.strs.length > 0 ? ct.strs[0] : ""; + ct.style = ct.styles.length > 0 ? ct.styles[0] : ""; + ct.defaults = ctext; + delete ct.calcchains; + return ct; +} +function get_rels_path(file) { + var n7 = file.lastIndexOf("/"); + return file.slice(0, n7 + 1) + "_rels/" + file.slice(n7 + 1) + ".rels"; +} +function parse_rels(data, currentFilePath) { + var rels = { "!id": {} }; + if (!data) return rels; + if (currentFilePath.charAt(0) !== "/") { + currentFilePath = "/" + currentFilePath; + } + var hash = {}; + (data.match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2); + if (y4[0] === " 0) p4[f4[1]] = unescapexml(cur[1]); + if (f4[2] === "date" && p4[f4[1]]) p4[f4[1]] = parseDate(p4[f4[1]]); + } + return p4; +} +function load_props_pairs(HP, TOP, props, opts) { + var v4 = []; + if (typeof HP == "string") v4 = parseVector(HP, opts); + else for (var j3 = 0; j3 < HP.length; ++j3) v4 = v4.concat(HP[j3].map(function(hp) { + return { v: hp }; + })); + var parts = typeof TOP == "string" ? parseVector(TOP, opts).map(function(x2) { + return x2.v; + }) : TOP; + var idx = 0, len = 0; + if (parts.length > 0) for (var i7 = 0; i7 !== v4.length; i7 += 2) { + len = +v4[i7 + 1].v; + switch (v4[i7].v) { + case "Worksheets": + case "\u5DE5\u4F5C\u8868": + case "\u041B\u0438\u0441\u0442\u044B": + case "\u0623\u0648\u0631\u0627\u0642 \u0627\u0644\u0639\u0645\u0644": + case "\u30EF\u30FC\u30AF\u30B7\u30FC\u30C8": + case "\u05D2\u05DC\u05D9\u05D5\u05E0\u05D5\u05EA \u05E2\u05D1\u05D5\u05D3\u05D4": + case "Arbeitsbl\xE4tter": + case "\xC7al\u0131\u015Fma Sayfalar\u0131": + case "Feuilles de calcul": + case "Fogli di lavoro": + case "Folhas de c\xE1lculo": + case "Planilhas": + case "Regneark": + case "Hojas de c\xE1lculo": + case "Werkbladen": + props.Worksheets = len; + props.SheetNames = parts.slice(idx, idx + len); + break; + case "Named Ranges": + case "Rangos con nombre": + case "\u540D\u524D\u4ED8\u304D\u4E00\u89A7": + case "Benannte Bereiche": + case "Navngivne omr\xE5der": + props.NamedRanges = len; + props.DefinedNames = parts.slice(idx, idx + len); + break; + case "Charts": + case "Diagramme": + props.Chartsheets = len; + props.ChartNames = parts.slice(idx, idx + len); + break; + } + idx += len; + } +} +function parse_ext_props(data, p4, opts) { + var q2 = {}; + if (!p4) p4 = {}; + data = utf8read(data); + EXT_PROPS.forEach(function(f4) { + var xml2 = (str_match_xml_ns(data, f4[0]) || [])[1]; + switch (f4[2]) { + case "string": + if (xml2) p4[f4[1]] = unescapexml(xml2); + break; + case "bool": + p4[f4[1]] = xml2 === "true"; + break; + case "raw": + var cur = str_match_xml(data, f4[0]); + if (cur && cur.length > 0) q2[f4[1]] = cur[1]; + break; + } + }); + if (q2.HeadingPairs && q2.TitlesOfParts) load_props_pairs(q2.HeadingPairs, q2.TitlesOfParts, p4, opts); + return p4; +} +function parse_cust_props(data, opts) { + var p4 = {}, name = ""; + var m4 = data.match(custregex); + if (m4) for (var i7 = 0; i7 != m4.length; ++i7) { + var x2 = m4[i7], y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + name = null; + break; + default: + if (x2.indexOf(""); + var type = toks[0].slice(4), text3 = toks[1]; + switch (type) { + case "lpstr": + case "bstr": + case "lpwstr": + p4[name] = unescapexml(text3); + break; + case "bool": + p4[name] = parsexmlbool(text3); + break; + case "i1": + case "i2": + case "i4": + case "i8": + case "int": + case "uint": + p4[name] = parseInt(text3, 10); + break; + case "r4": + case "r8": + case "decimal": + p4[name] = parseFloat(text3); + break; + case "filetime": + case "date": + p4[name] = parseDate(text3); + break; + case "cy": + case "error": + p4[name] = unescapexml(text3); + break; + default: + if (type.slice(-1) == "/") break; + if (opts.WTF && typeof console !== "undefined") console.warn("Unexpected", x2, type, toks); + } + } else if (x2.slice(0, 2) === "> 2 + 1 << 2; + return dict; +} +function parse_BLOB(blob) { + var size = blob.read_shift(4); + var bytes = blob.slice(blob.l, blob.l + size); + blob.l += size; + if ((size & 3) > 0) blob.l += 4 - (size & 3) & 3; + return bytes; +} +function parse_ClipboardData(blob) { + var o9 = {}; + o9.Size = blob.read_shift(4); + blob.l += o9.Size + 3 - (o9.Size - 1) % 4; + return o9; +} +function parse_TypedPropertyValue(blob, type, _opts) { + var t6 = blob.read_shift(2), ret, opts = _opts || {}; + blob.l += 2; + if (type !== VT_VARIANT) { + if (t6 !== type && VT_CUSTOM.indexOf(type) === -1 && !((type & 65534) == 4126 && (t6 & 65534) == 4126)) throw new Error("Expected type " + type + " saw " + t6); + } + switch (type === VT_VARIANT ? t6 : type) { + case 2: + ret = blob.read_shift(2, "i"); + if (!opts.raw) blob.l += 2; + return ret; + case 3: + ret = blob.read_shift(4, "i"); + return ret; + case 11: + return blob.read_shift(4) !== 0; + case 19: + ret = blob.read_shift(4); + return ret; + case 30: + blob.l += 4; + val = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1"); + break; + case 31: + blob.l += 4; + val = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1"); + break; + case 64: + return parse_FILETIME(blob); + case 65: + return parse_BLOB(blob); + case 71: + return parse_ClipboardData(blob); + case 80: + return parse_VtString(blob, t6, !opts.raw).replace(chr0, ""); + case 81: + return parse_VtUnalignedString( + blob, + t6 + /*, 4*/ + ).replace(chr0, ""); + case 4108: + return parse_VtVecHeadingPairValue(blob); + case 4126: + case 4127: + return t6 == 4127 ? parse_VtVecLpwstrValue(blob) : parse_VtVecUnalignedLpstrValue(blob); + default: + throw new Error("TypedPropertyValue unrecognized type " + type + " " + t6); + } +} +function parse_PropertySet(blob, PIDSI) { + var start_addr = blob.l; + var size = blob.read_shift(4); + var NumProps = blob.read_shift(4); + var Props = [], i7 = 0; + var CodePage = 0; + var Dictionary = -1, DictObj = {}; + for (i7 = 0; i7 != NumProps; ++i7) { + var PropID = blob.read_shift(4); + var Offset = blob.read_shift(4); + Props[i7] = [PropID, Offset + start_addr]; + } + Props.sort(function(x2, y4) { + return x2[1] - y4[1]; + }); + var PropH = {}; + for (i7 = 0; i7 != NumProps; ++i7) { + if (blob.l !== Props[i7][1]) { + var fail = true; + if (i7 > 0 && PIDSI) switch (PIDSI[Props[i7 - 1][0]].t) { + case 2: + if (blob.l + 2 === Props[i7][1]) { + blob.l += 2; + fail = false; + } + break; + case 80: + if (blob.l <= Props[i7][1]) { + blob.l = Props[i7][1]; + fail = false; + } + break; + case 4108: + if (blob.l <= Props[i7][1]) { + blob.l = Props[i7][1]; + fail = false; + } + break; + } + if ((!PIDSI || i7 == 0) && blob.l <= Props[i7][1]) { + fail = false; + blob.l = Props[i7][1]; + } + if (fail) throw new Error("Read Error: Expected address " + Props[i7][1] + " at " + blob.l + " :" + i7); + } + if (PIDSI) { + if (Props[i7][0] == 0 && Props.length > i7 + 1 && Props[i7][1] == Props[i7 + 1][1]) continue; + var piddsi = PIDSI[Props[i7][0]]; + PropH[piddsi.n] = parse_TypedPropertyValue(blob, piddsi.t, { raw: true }); + if (piddsi.p === "version") PropH[piddsi.n] = String(PropH[piddsi.n] >> 16) + "." + ("0000" + String(PropH[piddsi.n] & 65535)).slice(-4); + if (piddsi.n == "CodePage") switch (PropH[piddsi.n]) { + case 0: + PropH[piddsi.n] = 1252; + /* falls through */ + case 874: + case 932: + case 936: + case 949: + case 950: + case 1250: + case 1251: + case 1253: + case 1254: + case 1255: + case 1256: + case 1257: + case 1258: + case 1e4: + case 1200: + case 1201: + case 1252: + case 65e3: + case -536: + case 65001: + case -535: + set_cp(CodePage = PropH[piddsi.n] >>> 0 & 65535); + break; + default: + throw new Error("Unsupported CodePage: " + PropH[piddsi.n]); + } + } else { + if (Props[i7][0] === 1) { + CodePage = PropH.CodePage = parse_TypedPropertyValue(blob, VT_I2); + set_cp(CodePage); + if (Dictionary !== -1) { + var oldpos = blob.l; + blob.l = Props[Dictionary][1]; + DictObj = parse_dictionary(blob, CodePage); + blob.l = oldpos; + } + } else if (Props[i7][0] === 0) { + if (CodePage === 0) { + Dictionary = i7; + blob.l = Props[i7 + 1][1]; + continue; + } + DictObj = parse_dictionary(blob, CodePage); + } else { + var name = DictObj[Props[i7][0]]; + var val2; + switch (blob[blob.l]) { + case 65: + blob.l += 4; + val2 = parse_BLOB(blob); + break; + case 30: + blob.l += 4; + val2 = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1"); + break; + case 31: + blob.l += 4; + val2 = parse_VtString(blob, blob[blob.l - 4]).replace(/(^|[^\u0000])\u0000+$/, "$1"); + break; + case 3: + blob.l += 4; + val2 = blob.read_shift(4, "i"); + break; + case 19: + blob.l += 4; + val2 = blob.read_shift(4); + break; + case 5: + blob.l += 4; + val2 = blob.read_shift(8, "f"); + break; + case 11: + blob.l += 4; + val2 = parsebool(blob, 4); + break; + case 64: + blob.l += 4; + val2 = parseDate(parse_FILETIME(blob)); + break; + default: + throw new Error("unparsed value: " + blob[blob.l]); + } + PropH[name] = val2; + } + } + } + blob.l = start_addr + size; + return PropH; +} +function parse_PropertySetStream(file, PIDSI, clsid) { + var blob = file.content; + if (!blob) return {}; + prep_blob(blob, 0); + var NumSets, FMTID0, FMTID1, Offset0, Offset1 = 0; + blob.chk("feff", "Byte Order: "); + blob.read_shift(2); + var SystemIdentifier = blob.read_shift(4); + var CLSID = blob.read_shift(16); + if (CLSID !== CFB.utils.consts.HEADER_CLSID && CLSID !== clsid) throw new Error("Bad PropertySet CLSID " + CLSID); + NumSets = blob.read_shift(4); + if (NumSets !== 1 && NumSets !== 2) throw new Error("Unrecognized #Sets: " + NumSets); + FMTID0 = blob.read_shift(16); + Offset0 = blob.read_shift(4); + if (NumSets === 1 && Offset0 !== blob.l) throw new Error("Length mismatch: " + Offset0 + " !== " + blob.l); + else if (NumSets === 2) { + FMTID1 = blob.read_shift(16); + Offset1 = blob.read_shift(4); + } + var PSet0 = parse_PropertySet(blob, PIDSI); + var rval = { SystemIdentifier }; + for (var y4 in PSet0) rval[y4] = PSet0[y4]; + rval.FMTID = FMTID0; + if (NumSets === 1) return rval; + if (Offset1 - blob.l == 2) blob.l += 2; + if (blob.l !== Offset1) throw new Error("Length mismatch 2: " + blob.l + " !== " + Offset1); + var PSet1; + try { + PSet1 = parse_PropertySet(blob, null); + } catch (e9) { + } + for (y4 in PSet1) rval[y4] = PSet1[y4]; + rval.FMTID = [FMTID0, FMTID1]; + return rval; +} +function parsenoop2(blob, length) { + blob.read_shift(length); + return null; +} +function parslurp(blob, length, cb) { + var arr = [], target = blob.l + length; + while (blob.l < target) arr.push(cb(blob, target - blob.l)); + if (target !== blob.l) throw new Error("Slurp error"); + return arr; +} +function parsebool(blob, length) { + return blob.read_shift(length) === 1; +} +function parseuint16(blob) { + return blob.read_shift(2, "u"); +} +function parseuint16a(blob, length) { + return parslurp(blob, length, parseuint16); +} +function parse_Bes(blob) { + var v4 = blob.read_shift(1), t6 = blob.read_shift(1); + return t6 === 1 ? v4 : v4 === 1; +} +function parse_ShortXLUnicodeString(blob, length, opts) { + var cch = blob.read_shift(opts && opts.biff >= 12 ? 2 : 1); + var encoding = "sbcs-cont"; + var cp = current_codepage; + if (opts && opts.biff >= 8) current_codepage = 1200; + if (!opts || opts.biff == 8) { + var fHighByte = blob.read_shift(1); + if (fHighByte) { + encoding = "dbcs-cont"; + } + } else if (opts.biff == 12) { + encoding = "wstr"; + } + if (opts.biff >= 2 && opts.biff <= 5) encoding = "cpstr"; + var o9 = cch ? blob.read_shift(cch, encoding) : ""; + current_codepage = cp; + return o9; +} +function parse_XLUnicodeRichExtendedString(blob) { + var cp = current_codepage; + current_codepage = 1200; + var cch = blob.read_shift(2), flags = blob.read_shift(1); + var fExtSt = flags & 4, fRichSt = flags & 8; + var width = 1 + (flags & 1); + var cRun = 0, cbExtRst; + var z3 = {}; + if (fRichSt) cRun = blob.read_shift(2); + if (fExtSt) cbExtRst = blob.read_shift(4); + var encoding = width == 2 ? "dbcs-cont" : "sbcs-cont"; + var msg = cch === 0 ? "" : blob.read_shift(cch, encoding); + if (fRichSt) blob.l += 4 * cRun; + if (fExtSt) blob.l += cbExtRst; + z3.t = msg; + if (!fRichSt) { + z3.raw = "" + z3.t + ""; + z3.r = z3.t; + } + current_codepage = cp; + return z3; +} +function parse_XLUnicodeStringNoCch(blob, cch, opts) { + var retval; + if (opts) { + if (opts.biff >= 2 && opts.biff <= 5) return blob.read_shift(cch, "cpstr"); + if (opts.biff >= 12) return blob.read_shift(cch, "dbcs-cont"); + } + var fHighByte = blob.read_shift(1); + if (fHighByte === 0) { + retval = blob.read_shift(cch, "sbcs-cont"); + } else { + retval = blob.read_shift(cch, "dbcs-cont"); + } + return retval; +} +function parse_XLUnicodeString(blob, length, opts) { + var cch = blob.read_shift(opts && opts.biff == 2 ? 1 : 2); + if (cch === 0) { + blob.l++; + return ""; + } + return parse_XLUnicodeStringNoCch(blob, cch, opts); +} +function parse_XLUnicodeString2(blob, length, opts) { + if (opts.biff > 5) return parse_XLUnicodeString(blob, length, opts); + var cch = blob.read_shift(1); + if (cch === 0) { + blob.l++; + return ""; + } + return blob.read_shift(cch, opts.biff <= 4 || !blob.lens ? "cpstr" : "sbcs-cont"); +} +function parse_ControlInfo(blob) { + var flags = blob.read_shift(1); + blob.l++; + var accel = blob.read_shift(2); + blob.l += 2; + return [flags, accel]; +} +function parse_URLMoniker(blob) { + var len = blob.read_shift(4), start = blob.l; + var extra = false; + if (len > 24) { + blob.l += len - 24; + if (blob.read_shift(16) === "795881f43b1d7f48af2c825dc4852763") extra = true; + blob.l = start; + } + var url = blob.read_shift((extra ? len - 24 : len) >> 1, "utf16le").replace(chr0, ""); + if (extra) blob.l += 24; + return url; +} +function parse_FileMoniker(blob) { + var cAnti = blob.read_shift(2); + var preamble = ""; + while (cAnti-- > 0) preamble += "../"; + var ansiPath = blob.read_shift(0, "lpstr-ansi"); + blob.l += 2; + if (blob.read_shift(2) != 57005) throw new Error("Bad FileMoniker"); + var sz = blob.read_shift(4); + if (sz === 0) return preamble + ansiPath.replace(/\\/g, "/"); + var bytes = blob.read_shift(4); + if (blob.read_shift(2) != 3) throw new Error("Bad FileMoniker"); + var unicodePath = blob.read_shift(bytes >> 1, "utf16le").replace(chr0, ""); + return preamble + unicodePath; +} +function parse_HyperlinkMoniker(blob, length) { + var clsid = blob.read_shift(16); + length -= 16; + switch (clsid) { + case "e0c9ea79f9bace118c8200aa004ba90b": + return parse_URLMoniker(blob, length); + case "0303000000000000c000000000000046": + return parse_FileMoniker(blob, length); + default: + throw new Error("Unsupported Moniker " + clsid); + } +} +function parse_HyperlinkString(blob) { + var len = blob.read_shift(4); + var o9 = len > 0 ? blob.read_shift(len, "utf16le").replace(chr0, "") : ""; + return o9; +} +function parse_Hyperlink(blob, length) { + var end = blob.l + length; + var sVer = blob.read_shift(4); + if (sVer !== 2) throw new Error("Unrecognized streamVersion: " + sVer); + var flags = blob.read_shift(2); + blob.l += 2; + var displayName, targetFrameName, moniker, oleMoniker, Loc = "", guid, fileTime; + if (flags & 16) displayName = parse_HyperlinkString(blob, end - blob.l); + if (flags & 128) targetFrameName = parse_HyperlinkString(blob, end - blob.l); + if ((flags & 257) === 257) moniker = parse_HyperlinkString(blob, end - blob.l); + if ((flags & 257) === 1) oleMoniker = parse_HyperlinkMoniker(blob, end - blob.l); + if (flags & 8) Loc = parse_HyperlinkString(blob, end - blob.l); + if (flags & 32) guid = blob.read_shift(16); + if (flags & 64) fileTime = parse_FILETIME( + blob + /*, 8*/ + ); + blob.l = end; + var target = targetFrameName || moniker || oleMoniker || ""; + if (target && Loc) target += "#" + Loc; + if (!target) target = "#" + Loc; + if (flags & 2 && target.charAt(0) == "/" && target.charAt(1) != "/") target = "file://" + target; + var out = { Target: target }; + if (guid) out.guid = guid; + if (fileTime) out.time = fileTime; + if (displayName) out.Tooltip = displayName; + return out; +} +function parse_LongRGBA(blob) { + var r8 = blob.read_shift(1), g3 = blob.read_shift(1), b4 = blob.read_shift(1), a3 = blob.read_shift(1); + return [r8, g3, b4, a3]; +} +function parse_LongRGB(blob, length) { + var x2 = parse_LongRGBA(blob, length); + x2[3] = 0; + return x2; +} +function parse_XLSCell(blob, length, opts) { + var rw = blob.read_shift(2); + var col = blob.read_shift(2); + var ret = { r: rw, c: col, ixfe: 0 }; + if (opts && opts.biff == 2 || length == 7) { + var flags = blob.read_shift(1); + ret.ixfe = flags & 63; + blob.l += 2; + } else ret.ixfe = blob.read_shift(2); + return ret; +} +function parse_frtHeader(blob) { + var rt = blob.read_shift(2); + var flags = blob.read_shift(2); + blob.l += 8; + return { type: rt, flags }; +} +function parse_OptXLUnicodeString(blob, length, opts) { + return length === 0 ? "" : parse_XLUnicodeString2(blob, length, opts); +} +function parse_XTI(blob, length, opts) { + var w3 = opts.biff > 8 ? 4 : 2; + var iSupBook = blob.read_shift(w3), itabFirst = blob.read_shift(w3, "i"), itabLast = blob.read_shift(w3, "i"); + return [iSupBook, itabFirst, itabLast]; +} +function parse_RkRec(blob) { + var ixfe = blob.read_shift(2); + var RK = parse_RkNumber(blob); + return [ixfe, RK]; +} +function parse_AddinUdf(blob, length, opts) { + blob.l += 4; + length -= 4; + var l5 = blob.l + length; + var udfName = parse_ShortXLUnicodeString(blob, length, opts); + var cb = blob.read_shift(2); + l5 -= blob.l; + if (cb !== l5) throw new Error("Malformed AddinUdf: padding = " + l5 + " != " + cb); + blob.l += cb; + return udfName; +} +function parse_Ref8U(blob) { + var rwFirst = blob.read_shift(2); + var rwLast = blob.read_shift(2); + var colFirst = blob.read_shift(2); + var colLast = blob.read_shift(2); + return { s: { c: colFirst, r: rwFirst }, e: { c: colLast, r: rwLast } }; +} +function parse_RefU(blob) { + var rwFirst = blob.read_shift(2); + var rwLast = blob.read_shift(2); + var colFirst = blob.read_shift(1); + var colLast = blob.read_shift(1); + return { s: { c: colFirst, r: rwFirst }, e: { c: colLast, r: rwLast } }; +} +function parse_FtCmo(blob) { + blob.l += 4; + var ot = blob.read_shift(2); + var id = blob.read_shift(2); + var flags = blob.read_shift(2); + blob.l += 12; + return [id, ot, flags]; +} +function parse_FtNts(blob) { + var out = {}; + blob.l += 4; + blob.l += 16; + out.fSharedNote = blob.read_shift(2); + blob.l += 4; + return out; +} +function parse_FtCf(blob) { + var out = {}; + blob.l += 4; + blob.cf = blob.read_shift(2); + return out; +} +function parse_FtSkip(blob) { + blob.l += 2; + blob.l += blob.read_shift(2); +} +function parse_FtArray(blob, length) { + var tgt = blob.l + length; + var fts = []; + while (blob.l < tgt) { + var ft = blob.read_shift(2); + blob.l -= 2; + try { + fts[ft] = FtTab[ft](blob, tgt - blob.l); + } catch (e9) { + blob.l = tgt; + return fts; + } + } + if (blob.l != tgt) blob.l = tgt; + return fts; +} +function parse_BOF(blob, length) { + var o9 = { BIFFVer: 0, dt: 0 }; + o9.BIFFVer = blob.read_shift(2); + length -= 2; + if (length >= 2) { + o9.dt = blob.read_shift(2); + blob.l -= 2; + } + switch (o9.BIFFVer) { + case 1536: + /* BIFF8 */ + case 1280: + /* BIFF5 */ + case 1024: + /* BIFF4 */ + case 768: + /* BIFF3 */ + case 512: + /* BIFF2 */ + case 2: + case 7: + break; + default: + if (length > 6) throw new Error("Unexpected BIFF Ver " + o9.BIFFVer); + } + blob.read_shift(length); + return o9; +} +function parse_InterfaceHdr(blob, length) { + if (length === 0) return 1200; + if (blob.read_shift(2) !== 1200) { + } + return 1200; +} +function parse_WriteAccess(blob, length, opts) { + if (opts.enc) { + blob.l += length; + return ""; + } + var l5 = blob.l; + var UserName = parse_XLUnicodeString2(blob, 0, opts); + blob.read_shift(length + l5 - blob.l); + return UserName; +} +function parse_WsBool(blob, length, opts) { + var flags = opts && opts.biff == 8 || length == 2 ? blob.read_shift(2) : (blob.l += length, 0); + return { fDialog: flags & 16, fBelow: flags & 64, fRight: flags & 128 }; +} +function parse_BoundSheet8(blob, length, opts) { + var name = ""; + if (opts.biff == 4) { + name = parse_ShortXLUnicodeString(blob, 0, opts); + if (name.length === 0) name = "Sheet1"; + return { name }; + } + var pos = blob.read_shift(4); + var hidden = blob.read_shift(1) & 3; + var dt = blob.read_shift(1); + switch (dt) { + case 0: + dt = "Worksheet"; + break; + case 1: + dt = "Macrosheet"; + break; + case 2: + dt = "Chartsheet"; + break; + case 6: + dt = "VBAModule"; + break; + } + name = parse_ShortXLUnicodeString(blob, 0, opts); + if (name.length === 0) name = "Sheet1"; + return { pos, hs: hidden, dt, name }; +} +function parse_SST(blob, length) { + var end = blob.l + length; + var cnt = blob.read_shift(4); + var ucnt = blob.read_shift(4); + var strs2 = []; + for (var i7 = 0; i7 != ucnt && blob.l < end; ++i7) { + strs2.push(parse_XLUnicodeRichExtendedString(blob)); + } + strs2.Count = cnt; + strs2.Unique = ucnt; + return strs2; +} +function parse_ExtSST(blob, length) { + var extsst = {}; + extsst.dsst = blob.read_shift(2); + blob.l += length - 2; + return extsst; +} +function parse_Row(blob) { + var z3 = {}; + z3.r = blob.read_shift(2); + z3.c = blob.read_shift(2); + z3.cnt = blob.read_shift(2) - z3.c; + var miyRw = blob.read_shift(2); + blob.l += 4; + var flags = blob.read_shift(1); + blob.l += 3; + if (flags & 7) z3.level = flags & 7; + if (flags & 32) z3.hidden = true; + if (flags & 64) z3.hpt = miyRw / 20; + return z3; +} +function parse_ForceFullCalculation(blob) { + var header = parse_frtHeader(blob); + if (header.type != 2211) throw new Error("Invalid Future Record " + header.type); + var fullcalc = blob.read_shift(4); + return fullcalc !== 0; +} +function parse_RecalcId(blob) { + blob.read_shift(2); + return blob.read_shift(4); +} +function parse_DefaultRowHeight(blob, length, opts) { + var f4 = 0; + if (!(opts && opts.biff == 2)) { + f4 = blob.read_shift(2); + } + var miyRw = blob.read_shift(2); + if (opts && opts.biff == 2) { + f4 = 1 - (miyRw >> 15); + miyRw &= 32767; + } + var fl = { Unsynced: f4 & 1, DyZero: (f4 & 2) >> 1, ExAsc: (f4 & 4) >> 2, ExDsc: (f4 & 8) >> 3 }; + return [fl, miyRw]; +} +function parse_Window1(blob) { + var xWn = blob.read_shift(2), yWn = blob.read_shift(2), dxWn = blob.read_shift(2), dyWn = blob.read_shift(2); + var flags = blob.read_shift(2), iTabCur = blob.read_shift(2), iTabFirst = blob.read_shift(2); + var ctabSel = blob.read_shift(2), wTabRatio = blob.read_shift(2); + return { + Pos: [xWn, yWn], + Dim: [dxWn, dyWn], + Flags: flags, + CurTab: iTabCur, + FirstTab: iTabFirst, + Selected: ctabSel, + TabRatio: wTabRatio + }; +} +function parse_Window2(blob, length, opts) { + if (opts && opts.biff >= 2 && opts.biff < 5) return {}; + var f4 = blob.read_shift(2); + return { RTL: f4 & 64 }; +} +function parse_Pane() { +} +function parse_Font(blob, length, opts) { + var o9 = { + dyHeight: blob.read_shift(2), + fl: blob.read_shift(2) + }; + switch (opts && opts.biff || 8) { + case 2: + break; + case 3: + case 4: + blob.l += 2; + break; + default: + blob.l += 10; + break; + } + o9.name = parse_ShortXLUnicodeString(blob, 0, opts); + return o9; +} +function parse_LabelSst(blob, length, opts) { + var cell = parse_XLSCell(blob, length, opts); + cell.isst = blob.read_shift(4); + return cell; +} +function parse_Label(blob, length, opts) { + if (opts.biffguess && opts.biff == 2) opts.biff = 5; + var target = blob.l + length; + var cell = parse_XLSCell(blob, length, opts); + var str2 = parse_XLUnicodeString(blob, target - blob.l, opts); + cell.val = str2; + return cell; +} +function parse_Format(blob, length, opts) { + var numFmtId = blob.read_shift(2); + var fmtstr = parse_XLUnicodeString2(blob, 0, opts); + return [numFmtId, fmtstr]; +} +function parse_Dimensions(blob, length, opts) { + var end = blob.l + length; + var w3 = opts.biff == 8 || !opts.biff ? 4 : 2; + var r8 = blob.read_shift(w3), R3 = blob.read_shift(w3); + var c6 = blob.read_shift(2), C3 = blob.read_shift(2); + blob.l = end; + return { s: { r: r8, c: c6 }, e: { r: R3, c: C3 } }; +} +function parse_RK(blob) { + var rw = blob.read_shift(2), col = blob.read_shift(2); + var rkrec = parse_RkRec(blob); + return { r: rw, c: col, ixfe: rkrec[0], rknum: rkrec[1] }; +} +function parse_MulRk(blob, length) { + var target = blob.l + length - 2; + var rw = blob.read_shift(2), col = blob.read_shift(2); + var rkrecs = []; + while (blob.l < target) rkrecs.push(parse_RkRec(blob)); + if (blob.l !== target) throw new Error("MulRK read error"); + var lastcol = blob.read_shift(2); + if (rkrecs.length != lastcol - col + 1) throw new Error("MulRK length mismatch"); + return { r: rw, c: col, C: lastcol, rkrec: rkrecs }; +} +function parse_MulBlank(blob, length) { + var target = blob.l + length - 2; + var rw = blob.read_shift(2), col = blob.read_shift(2); + var ixfes = []; + while (blob.l < target) ixfes.push(blob.read_shift(2)); + if (blob.l !== target) throw new Error("MulBlank read error"); + var lastcol = blob.read_shift(2); + if (ixfes.length != lastcol - col + 1) throw new Error("MulBlank length mismatch"); + return { r: rw, c: col, C: lastcol, ixfe: ixfes }; +} +function parse_CellStyleXF(blob, length, style, opts) { + var o9 = {}; + var a3 = blob.read_shift(4), b4 = blob.read_shift(4); + var c6 = blob.read_shift(4), d4 = blob.read_shift(2); + o9.patternType = XLSFillPattern[c6 >> 26]; + if (!opts.cellStyles) return o9; + o9.alc = a3 & 7; + o9.fWrap = a3 >> 3 & 1; + o9.alcV = a3 >> 4 & 7; + o9.fJustLast = a3 >> 7 & 1; + o9.trot = a3 >> 8 & 255; + o9.cIndent = a3 >> 16 & 15; + o9.fShrinkToFit = a3 >> 20 & 1; + o9.iReadOrder = a3 >> 22 & 2; + o9.fAtrNum = a3 >> 26 & 1; + o9.fAtrFnt = a3 >> 27 & 1; + o9.fAtrAlc = a3 >> 28 & 1; + o9.fAtrBdr = a3 >> 29 & 1; + o9.fAtrPat = a3 >> 30 & 1; + o9.fAtrProt = a3 >> 31 & 1; + o9.dgLeft = b4 & 15; + o9.dgRight = b4 >> 4 & 15; + o9.dgTop = b4 >> 8 & 15; + o9.dgBottom = b4 >> 12 & 15; + o9.icvLeft = b4 >> 16 & 127; + o9.icvRight = b4 >> 23 & 127; + o9.grbitDiag = b4 >> 30 & 3; + o9.icvTop = c6 & 127; + o9.icvBottom = c6 >> 7 & 127; + o9.icvDiag = c6 >> 14 & 127; + o9.dgDiag = c6 >> 21 & 15; + o9.icvFore = d4 & 127; + o9.icvBack = d4 >> 7 & 127; + o9.fsxButton = d4 >> 14 & 1; + return o9; +} +function parse_XF(blob, length, opts) { + var o9 = {}; + o9.ifnt = blob.read_shift(2); + o9.numFmtId = blob.read_shift(2); + o9.flags = blob.read_shift(2); + o9.fStyle = o9.flags >> 2 & 1; + length -= 6; + o9.data = parse_CellStyleXF(blob, length, o9.fStyle, opts); + return o9; +} +function parse_BIFF2XF(blob) { + var o9 = {}; + o9.ifnt = blob.read_shift(1); + blob.l++; + o9.flags = blob.read_shift(1); + o9.numFmtId = o9.flags & 63; + o9.flags >>= 6; + o9.fStyle = 0; + o9.data = {}; + return o9; +} +function parse_BIFF3XF(blob) { + var o9 = {}; + o9.ifnt = blob.read_shift(1); + o9.numFmtId = blob.read_shift(1); + o9.flags = blob.read_shift(2); + o9.fStyle = o9.flags >> 2 & 1; + o9.data = {}; + return o9; +} +function parse_BIFF4XF(blob) { + var o9 = {}; + o9.ifnt = blob.read_shift(1); + o9.numFmtId = blob.read_shift(1); + o9.flags = blob.read_shift(2); + o9.fStyle = o9.flags >> 2 & 1; + o9.data = {}; + return o9; +} +function parse_Guts(blob) { + blob.l += 4; + var out = [blob.read_shift(2), blob.read_shift(2)]; + if (out[0] !== 0) out[0]--; + if (out[1] !== 0) out[1]--; + if (out[0] > 7 || out[1] > 7) throw new Error("Bad Gutters: " + out.join("|")); + return out; +} +function parse_BoolErr(blob, length, opts) { + var cell = parse_XLSCell(blob, 6, opts); + var val2 = parse_Bes(blob, 2); + cell.val = val2; + cell.t = val2 === true || val2 === false ? "b" : "e"; + return cell; +} +function parse_Number(blob, length, opts) { + if (opts.biffguess && opts.biff == 2) opts.biff = 5; + var cell = parse_XLSCell(blob, 6, opts); + var xnum = parse_Xnum(blob, 8); + cell.val = xnum; + return cell; +} +function parse_SupBook(blob, length, opts) { + var end = blob.l + length; + var ctab = blob.read_shift(2); + var cch = blob.read_shift(2); + opts.sbcch = cch; + if (cch == 1025 || cch == 14849) return [cch, ctab]; + if (cch < 1 || cch > 255) throw new Error("Unexpected SupBook type: " + cch); + var virtPath = parse_XLUnicodeStringNoCch(blob, cch); + var rgst = []; + while (end > blob.l) rgst.push(parse_XLUnicodeString(blob)); + return [cch, ctab, virtPath, rgst]; +} +function parse_ExternName(blob, length, opts) { + var flags = blob.read_shift(2); + var body; + var o9 = { + fBuiltIn: flags & 1, + fWantAdvise: flags >>> 1 & 1, + fWantPict: flags >>> 2 & 1, + fOle: flags >>> 3 & 1, + fOleLink: flags >>> 4 & 1, + cf: flags >>> 5 & 1023, + fIcon: flags >>> 15 & 1 + }; + if (opts.sbcch === 14849) body = parse_AddinUdf(blob, length - 2, opts); + o9.body = body || blob.read_shift(length - 2); + if (typeof body === "string") o9.Name = body; + return o9; +} +function parse_Lbl(blob, length, opts) { + var target = blob.l + length; + var flags = blob.read_shift(2); + var chKey = blob.read_shift(1); + var cch = blob.read_shift(1); + var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2); + var itab = 0; + if (!opts || opts.biff >= 5) { + if (opts.biff != 5) blob.l += 2; + itab = blob.read_shift(2); + if (opts.biff == 5) blob.l += 2; + blob.l += 4; + } + var name = parse_XLUnicodeStringNoCch(blob, cch, opts); + if (flags & 32) name = XLSLblBuiltIn[name.charCodeAt(0)]; + var npflen = target - blob.l; + if (opts && opts.biff == 2) --npflen; + var rgce = target == blob.l || cce === 0 || !(npflen > 0) ? [] : parse_NameParsedFormula(blob, npflen, opts, cce); + return { + chKey, + Name: name, + itab, + rgce + }; +} +function parse_ExternSheet(blob, length, opts) { + if (opts.biff < 8) return parse_BIFF5ExternSheet(blob, length, opts); + if (!(opts.biff > 8) && length == blob[blob.l] + (blob[blob.l + 1] == 3 ? 1 : 0) + 1) return parse_BIFF5ExternSheet(blob, length, opts); + var o9 = [], target = blob.l + length, len = blob.read_shift(opts.biff > 8 ? 4 : 2); + while (len-- !== 0) o9.push(parse_XTI(blob, opts.biff > 8 ? 12 : 6, opts)); + if (blob.l != target) throw new Error("Bad ExternSheet: " + blob.l + " != " + target); + return o9; +} +function parse_BIFF5ExternSheet(blob, length, opts) { + if (blob[blob.l + 1] == 3) blob[blob.l]++; + var o9 = parse_ShortXLUnicodeString(blob, length, opts); + return o9.charCodeAt(0) == 3 ? o9.slice(1) : o9; +} +function parse_NameCmt(blob, length, opts) { + if (opts.biff < 8) { + blob.l += length; + return; + } + var cchName = blob.read_shift(2); + var cchComment = blob.read_shift(2); + var name = parse_XLUnicodeStringNoCch(blob, cchName, opts); + var comment = parse_XLUnicodeStringNoCch(blob, cchComment, opts); + return [name, comment]; +} +function parse_ShrFmla(blob, length, opts) { + var ref = parse_RefU(blob, 6); + blob.l++; + var cUse = blob.read_shift(1); + length -= 8; + return [parse_SharedParsedFormula(blob, length, opts), cUse, ref]; +} +function parse_Array(blob, length, opts) { + var ref = parse_Ref(blob, 6); + switch (opts.biff) { + case 2: + blob.l++; + length -= 7; + break; + case 3: + case 4: + blob.l += 2; + length -= 8; + break; + default: + blob.l += 6; + length -= 12; + } + return [ref, parse_ArrayParsedFormula(blob, length, opts, ref)]; +} +function parse_MTRSettings(blob) { + var fMTREnabled = blob.read_shift(4) !== 0; + var fUserSetThreadCount = blob.read_shift(4) !== 0; + var cUserThreadCount = blob.read_shift(4); + return [fMTREnabled, fUserSetThreadCount, cUserThreadCount]; +} +function parse_NoteSh(blob, length, opts) { + var row = blob.read_shift(2), col = blob.read_shift(2); + var flags = blob.read_shift(2), idObj = blob.read_shift(2); + var stAuthor = parse_XLUnicodeString2(blob, 0, opts); + return [{ r: row, c: col }, stAuthor, idObj, flags]; +} +function parse_Note(blob, length, opts) { + if (opts && opts.biff < 8) { + var row = blob.read_shift(2), col = blob.read_shift(2); + if (row == 65535 || row == -1) return; + var cch = blob.read_shift(2); + var cmnt = blob.read_shift(Math.min(cch, 2048), "cpstr"); + return [{ r: row, c: col }, cmnt]; + } + return parse_NoteSh(blob, length, opts); +} +function parse_MergeCells(blob, length) { + var merges = []; + var cmcs = blob.read_shift(2); + while (cmcs--) merges.push(parse_Ref8U(blob, length)); + return merges; +} +function parse_Obj(blob, length, opts) { + if (opts && opts.biff < 8) return parse_BIFF5Obj(blob, length, opts); + var cmo = parse_FtCmo(blob, 22); + var fts = parse_FtArray(blob, length - 22, cmo[1]); + return { cmo, ft: fts }; +} +function parse_BIFF5Obj(blob, length, opts) { + blob.l += 4; + var ot = blob.read_shift(2); + var id = blob.read_shift(2); + var grbit = blob.read_shift(2); + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 6; + length -= 36; + var fts = []; + fts.push((parse_BIFF5OT[ot] || parsenoop)(blob, length, opts)); + return { cmo: [id, ot, grbit], ft: fts }; +} +function parse_TxO(blob, length, opts) { + var s6 = blob.l; + var texts = ""; + try { + blob.l += 4; + var ot = (opts.lastobj || { cmo: [0, 0] }).cmo[1]; + var controlInfo; + if ([0, 5, 7, 11, 12, 14].indexOf(ot) == -1) blob.l += 6; + else controlInfo = parse_ControlInfo(blob, 6, opts); + var cchText = blob.read_shift(2); + blob.read_shift(2); + parseuint16(blob, 2); + var len = blob.read_shift(2); + blob.l += len; + for (var i7 = 1; i7 < blob.lens.length - 1; ++i7) { + if (blob.l - s6 != blob.lens[i7]) throw new Error("TxO: bad continue record"); + var hdr = blob[blob.l]; + var t6 = parse_XLUnicodeStringNoCch(blob, blob.lens[i7 + 1] - blob.lens[i7] - 1); + texts += t6; + if (texts.length >= (hdr ? cchText : 2 * cchText)) break; + } + if (texts.length !== cchText && texts.length !== cchText * 2) { + throw new Error("cchText: " + cchText + " != " + texts.length); + } + blob.l = s6 + length; + return { t: texts }; + } catch (e9) { + blob.l = s6 + length; + return { t: texts }; + } +} +function parse_HLink(blob, length) { + var ref = parse_Ref8U(blob, 8); + blob.l += 16; + var hlink = parse_Hyperlink(blob, length - 24); + return [ref, hlink]; +} +function parse_HLinkTooltip(blob, length) { + blob.read_shift(2); + var ref = parse_Ref8U(blob, 8); + var wzTooltip = blob.read_shift((length - 10) / 2, "dbcs-cont"); + wzTooltip = wzTooltip.replace(chr0, ""); + return [ref, wzTooltip]; +} +function parse_Country(blob) { + var o9 = [0, 0], d4; + d4 = blob.read_shift(2); + o9[0] = CountryEnum[d4] || d4; + d4 = blob.read_shift(2); + o9[1] = CountryEnum[d4] || d4; + return o9; +} +function parse_ClrtClient(blob) { + var ccv = blob.read_shift(2); + var o9 = []; + while (ccv-- > 0) o9.push(parse_LongRGB(blob, 8)); + return o9; +} +function parse_Palette(blob) { + var ccv = blob.read_shift(2); + var o9 = []; + while (ccv-- > 0) o9.push(parse_LongRGB(blob, 8)); + return o9; +} +function parse_XFCRC(blob) { + blob.l += 2; + var o9 = { cxfs: 0, crc: 0 }; + o9.cxfs = blob.read_shift(2); + o9.crc = blob.read_shift(4); + return o9; +} +function parse_ColInfo(blob, length, opts) { + if (!opts.cellStyles) return parsenoop(blob, length); + var w3 = opts && opts.biff >= 12 ? 4 : 2; + var colFirst = blob.read_shift(w3); + var colLast = blob.read_shift(w3); + var coldx = blob.read_shift(w3); + var ixfe = blob.read_shift(w3); + var flags = blob.read_shift(2); + if (w3 == 2) blob.l += 2; + var o9 = { s: colFirst, e: colLast, w: coldx, ixfe, flags }; + if (opts.biff >= 5 || !opts.biff) o9.level = flags >> 8 & 7; + return o9; +} +function parse_Setup(blob, length) { + var o9 = {}; + if (length < 32) return o9; + blob.l += 16; + o9.header = parse_Xnum(blob, 8); + o9.footer = parse_Xnum(blob, 8); + blob.l += 2; + return o9; +} +function parse_ShtProps(blob, length, opts) { + var def = { area: false }; + if (opts.biff != 5) { + blob.l += length; + return def; + } + var d4 = blob.read_shift(1); + blob.l += 3; + if (d4 & 16) def.area = true; + return def; +} +function parse_ImData(blob) { + var cf = blob.read_shift(2); + var env = blob.read_shift(2); + var lcb = blob.read_shift(4); + var o9 = { fmt: cf, env, len: lcb, data: blob.slice(blob.l, blob.l + lcb) }; + blob.l += lcb; + return o9; +} +function parse_BIFF2STR(blob, length, opts) { + if (opts.biffguess && opts.biff == 5) opts.biff = 2; + var cell = parse_XLSCell(blob, 7, opts); + var str2 = parse_XLUnicodeString2(blob, length - 7, opts); + cell.t = "str"; + cell.val = str2; + return cell; +} +function parse_BIFF2NUM(blob, length, opts) { + var cell = parse_XLSCell(blob, 7, opts); + var num = parse_Xnum(blob, 8); + cell.t = "n"; + cell.val = num; + return cell; +} +function parse_BIFF2INT(blob, length, opts) { + var cell = parse_XLSCell(blob, 7, opts); + var num = blob.read_shift(2); + cell.t = "n"; + cell.val = num; + return cell; +} +function parse_BIFF2STRING(blob) { + var cch = blob.read_shift(1); + if (cch === 0) { + blob.l++; + return ""; + } + return blob.read_shift(cch, "sbcs-cont"); +} +function parse_BIFF2BOOLERR(blob, length, opts) { + var bestart = blob.l + 7; + var cell = parse_XLSCell(blob, 6, opts); + blob.l = bestart; + var val2 = parse_Bes(blob, 2); + cell.val = val2; + cell.t = val2 === true || val2 === false ? "b" : "e"; + return cell; +} +function parse_BIFF2FONTXTRA(blob, length) { + blob.l += 6; + blob.l += 2; + blob.l += 1; + blob.l += 3; + blob.l += 1; + blob.l += length - 13; +} +function parse_RString(blob, length, opts) { + var end = blob.l + length; + var cell = parse_XLSCell(blob, 6, opts); + var cch = blob.read_shift(2); + var str2 = parse_XLUnicodeStringNoCch(blob, cch, opts); + blob.l = end; + cell.t = "str"; + cell.val = str2; + return cell; +} +function parse_BIFF4SheetInfo(blob) { + var flags = blob.read_shift(4); + var cch = blob.read_shift(1), name = blob.read_shift(cch, "sbcs"); + if (name.length === 0) name = "Sheet1"; + return { flags, name }; +} +function read_wb_ID(d4, opts) { + var o9 = opts || {}, OLD_WTF = !!o9.WTF; + o9.WTF = true; + try { + var out = SYLK.to_workbook(d4, o9); + o9.WTF = OLD_WTF; + return out; + } catch (e9) { + o9.WTF = OLD_WTF; + if (e9.message.indexOf("SYLK bad record ID") == -1 && OLD_WTF) throw e9; + return PRN.to_workbook(d4, opts); + } +} +function parse_rpr(rpr) { + var font = {}, m4 = rpr.match(tagregex), i7 = 0; + var pass = false; + if (m4) for (; i7 != m4.length; ++i7) { + var y4 = parsexmltag(m4[i7]); + switch (y4[0].replace(/<\w*:/g, "<")) { + /* 18.8.12 condense CT_BooleanProperty */ + /* ** not required . */ + case "": + case "": + font.shadow = 1; + break; + case "": + break; + /* 18.4.1 charset CT_IntProperty TODO */ + case "": + case "": + font.outline = 1; + break; + case "": + break; + /* 18.4.5 rFont CT_FontName */ + case "": + case "": + font.strike = 1; + break; + case "": + break; + /* 18.4.13 u CT_UnderlineProperty */ + case "": + case "": + font.u = 1; + break; + case "": + break; + /* 18.8.2 b */ + case "": + case "": + font.b = 1; + break; + case "": + break; + /* 18.8.26 i */ + case "": + case "": + font.i = 1; + break; + case "": + break; + /* 18.3.1.15 color CT_Color TODO: tint, theme, auto, indexed */ + case "": + case "": + case "": + break; + /* 18.8.18 family ST_FontFamily */ + case "": + case "": + case "": + break; + /* 18.4.14 vertAlign CT_VerticalAlignFontProperty TODO */ + case "": + case "": + case "": + break; + /* 18.8.35 scheme CT_FontScheme TODO */ + case "": + case "": + case "": + break; + /* 18.2.10 extLst CT_ExtensionList ? */ + case "": + case "": + break; + case "": + pass = false; + break; + default: + if (y4[0].charCodeAt(1) !== 47 && !pass) throw new Error("Unrecognized rich format " + y4[0]); + } + } + return font; +} +function parse_si(x2, opts) { + var html = opts ? opts.cellHTML : true; + var z3 = {}; + if (!x2) return { t: "" }; + if (x2.match(/^\s*<(?:\w+:)?t[^>]*>/)) { + z3.t = unescapexml(utf8read(x2.slice(x2.indexOf(">") + 1).split(/<\/(?:\w+:)?t>/)[0] || ""), true); + z3.r = utf8read(x2); + if (html) z3.h = escapehtml(z3.t); + } else if ( + /*y = */ + x2.match(sirregex) + ) { + z3.r = utf8read(x2); + z3.t = unescapexml(utf8read((str_remove_xml_ns_g(x2, "rPh").match(sitregex) || []).join("").replace(tagregex, "")), true); + if (html) z3.h = rs_to_html(parse_rs(z3.r)); + } + return z3; +} +function parse_sst_xml(data, opts) { + var s6 = [], ss = ""; + if (!data) return s6; + var sst = str_match_xml_ns(data, "sst"); + if (sst) { + ss = sst[1].replace(sstr1, "").split(sstr2); + for (var i7 = 0; i7 != ss.length; ++i7) { + var o9 = parse_si(ss[i7].trim(), opts); + if (o9 != null) s6[s6.length] = o9; + } + sst = parsexmltag(sst[0].slice(0, sst[0].indexOf(">"))); + s6.Count = sst.count; + s6.Unique = sst.uniqueCount; + } + return s6; +} +function parse_BrtBeginSst(data) { + return [data.read_shift(4), data.read_shift(4)]; +} +function parse_sst_bin(data, opts) { + var s6 = []; + var pass = false; + recordhopper(data, function hopper_sst(val2, R3, RT) { + switch (RT) { + case 159: + s6.Count = val2[0]; + s6.Unique = val2[1]; + break; + case 19: + s6.push(val2); + break; + case 160: + return true; + case 35: + pass = true; + break; + case 36: + pass = false; + break; + default: + if (R3.T) { + } + if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }); + return s6; +} +function _JS2ANSI(str2) { + if (typeof $cptable !== "undefined") return $cptable.utils.encode(current_ansi, str2); + var o9 = [], oo = str2.split(""); + for (var i7 = 0; i7 < oo.length; ++i7) o9[i7] = oo[i7].charCodeAt(0); + return o9; +} +function parse_CRYPTOVersion(blob, length) { + var o9 = {}; + o9.Major = blob.read_shift(2); + o9.Minor = blob.read_shift(2); + if (length >= 4) blob.l += length - 4; + return o9; +} +function parse_DataSpaceVersionInfo(blob) { + var o9 = {}; + o9.id = blob.read_shift(0, "lpp4"); + o9.R = parse_CRYPTOVersion(blob, 4); + o9.U = parse_CRYPTOVersion(blob, 4); + o9.W = parse_CRYPTOVersion(blob, 4); + return o9; +} +function parse_DataSpaceMapEntry(blob) { + var len = blob.read_shift(4); + var end = blob.l + len - 4; + var o9 = {}; + var cnt = blob.read_shift(4); + var comps = []; + while (cnt-- > 0) comps.push({ t: blob.read_shift(4), v: blob.read_shift(0, "lpp4") }); + o9.name = blob.read_shift(0, "lpp4"); + o9.comps = comps; + if (blob.l != end) throw new Error("Bad DataSpaceMapEntry: " + blob.l + " != " + end); + return o9; +} +function parse_DataSpaceMap(blob) { + var o9 = []; + blob.l += 4; + var cnt = blob.read_shift(4); + while (cnt-- > 0) o9.push(parse_DataSpaceMapEntry(blob)); + return o9; +} +function parse_DataSpaceDefinition(blob) { + var o9 = []; + blob.l += 4; + var cnt = blob.read_shift(4); + while (cnt-- > 0) o9.push(blob.read_shift(0, "lpp4")); + return o9; +} +function parse_TransformInfoHeader(blob) { + var o9 = {}; + blob.read_shift(4); + blob.l += 4; + o9.id = blob.read_shift(0, "lpp4"); + o9.name = blob.read_shift(0, "lpp4"); + o9.R = parse_CRYPTOVersion(blob, 4); + o9.U = parse_CRYPTOVersion(blob, 4); + o9.W = parse_CRYPTOVersion(blob, 4); + return o9; +} +function parse_Primary(blob) { + var hdr = parse_TransformInfoHeader(blob); + hdr.ename = blob.read_shift(0, "8lpp4"); + hdr.blksz = blob.read_shift(4); + hdr.cmode = blob.read_shift(4); + if (blob.read_shift(4) != 4) throw new Error("Bad !Primary record"); + return hdr; +} +function parse_EncryptionHeader(blob, length) { + var tgt = blob.l + length; + var o9 = {}; + o9.Flags = blob.read_shift(4) & 63; + blob.l += 4; + o9.AlgID = blob.read_shift(4); + var valid = false; + switch (o9.AlgID) { + case 26126: + case 26127: + case 26128: + valid = o9.Flags == 36; + break; + case 26625: + valid = o9.Flags == 4; + break; + case 0: + valid = o9.Flags == 16 || o9.Flags == 4 || o9.Flags == 36; + break; + default: + throw "Unrecognized encryption algorithm: " + o9.AlgID; + } + if (!valid) throw new Error("Encryption Flags/AlgID mismatch"); + o9.AlgIDHash = blob.read_shift(4); + o9.KeySize = blob.read_shift(4); + o9.ProviderType = blob.read_shift(4); + blob.l += 8; + o9.CSPName = blob.read_shift(tgt - blob.l >> 1, "utf16le"); + blob.l = tgt; + return o9; +} +function parse_EncryptionVerifier(blob, length) { + var o9 = {}, tgt = blob.l + length; + blob.l += 4; + o9.Salt = blob.slice(blob.l, blob.l + 16); + blob.l += 16; + o9.Verifier = blob.slice(blob.l, blob.l + 16); + blob.l += 16; + blob.read_shift(4); + o9.VerifierHash = blob.slice(blob.l, tgt); + blob.l = tgt; + return o9; +} +function parse_EncryptionInfo(blob) { + var vers = parse_CRYPTOVersion(blob); + switch (vers.Minor) { + case 2: + return [vers.Minor, parse_EncInfoStd(blob, vers)]; + case 3: + return [vers.Minor, parse_EncInfoExt(blob, vers)]; + case 4: + return [vers.Minor, parse_EncInfoAgl(blob, vers)]; + } + throw new Error("ECMA-376 Encrypted file unrecognized Version: " + vers.Minor); +} +function parse_EncInfoStd(blob) { + var flags = blob.read_shift(4); + if ((flags & 63) != 36) throw new Error("EncryptionInfo mismatch"); + var sz = blob.read_shift(4); + var hdr = parse_EncryptionHeader(blob, sz); + var verifier = parse_EncryptionVerifier(blob, blob.length - blob.l); + return { t: "Std", h: hdr, v: verifier }; +} +function parse_EncInfoExt() { + throw new Error("File is password-protected: ECMA-376 Extensible"); +} +function parse_EncInfoAgl(blob) { + var KeyData = ["saltSize", "blockSize", "keyBits", "hashSize", "cipherAlgorithm", "cipherChaining", "hashAlgorithm", "saltValue"]; + blob.l += 4; + var xml2 = blob.read_shift(blob.length - blob.l, "utf8"); + var o9 = {}; + xml2.replace(tagregex, function xml_agile(x2) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + break; + case "": + case "": + break; + case "": + break; + case " 4 || vers.Major < 2) throw new Error("unrecognized major version code: " + vers.Major); + o9.Flags = blob.read_shift(4); + length -= 4; + var sz = blob.read_shift(4); + length -= 4; + o9.EncryptionHeader = parse_EncryptionHeader(blob, sz); + length -= sz; + o9.EncryptionVerifier = parse_EncryptionVerifier(blob, length); + return o9; +} +function parse_RC4Header(blob) { + var o9 = {}; + var vers = o9.EncryptionVersionInfo = parse_CRYPTOVersion(blob, 4); + if (vers.Major != 1 || vers.Minor != 1) throw "unrecognized version code " + vers.Major + " : " + vers.Minor; + o9.Salt = blob.read_shift(16); + o9.EncryptedVerifier = blob.read_shift(16); + o9.EncryptedVerifierHash = blob.read_shift(16); + return o9; +} +function crypto_CreatePasswordVerifier_Method1(Password) { + var Verifier = 0, PasswordArray; + var PasswordDecoded = _JS2ANSI(Password); + var len = PasswordDecoded.length + 1, i7, PasswordByte; + var Intermediate1, Intermediate2, Intermediate3; + PasswordArray = new_raw_buf(len); + PasswordArray[0] = PasswordDecoded.length; + for (i7 = 1; i7 != len; ++i7) PasswordArray[i7] = PasswordDecoded[i7 - 1]; + for (i7 = len - 1; i7 >= 0; --i7) { + PasswordByte = PasswordArray[i7]; + Intermediate1 = (Verifier & 16384) === 0 ? 0 : 1; + Intermediate2 = Verifier << 1 & 32767; + Intermediate3 = Intermediate1 | Intermediate2; + Verifier = Intermediate3 ^ PasswordByte; + } + return Verifier ^ 52811; +} +function parse_XORObfuscation(blob, length, opts, out) { + var o9 = { key: parseuint16(blob), verificationBytes: parseuint16(blob) }; + if (opts.password) o9.verifier = crypto_CreatePasswordVerifier_Method1(opts.password); + out.valid = o9.verificationBytes === o9.verifier; + if (out.valid) out.insitu = crypto_MakeXorDecryptor(opts.password); + return o9; +} +function parse_FilePassHeader(blob, length, oo) { + var o9 = oo || {}; + o9.Info = blob.read_shift(2); + blob.l -= 2; + if (o9.Info === 1) o9.Data = parse_RC4Header(blob, length); + else o9.Data = parse_RC4CryptoHeader(blob, length); + return o9; +} +function parse_FilePass(blob, length, opts) { + var o9 = { Type: opts.biff >= 8 ? blob.read_shift(2) : 0 }; + if (o9.Type) parse_FilePassHeader(blob, length - 2, o9); + else parse_XORObfuscation(blob, opts.biff >= 8 ? length : length - 2, opts, o9); + return o9; +} +function rtf_to_sheet(d4, opts) { + switch (opts.type) { + case "base64": + return rtf_to_sheet_str(Base64_decode(d4), opts); + case "binary": + return rtf_to_sheet_str(d4, opts); + case "buffer": + return rtf_to_sheet_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts); + case "array": + return rtf_to_sheet_str(cc2str(d4), opts); + } + throw new Error("Unrecognized type " + opts.type); +} +function rtf_to_sheet_str(str2, opts) { + var o9 = opts || {}; + var ws = {}; + var dense = o9.dense; + if (dense) + ws["!data"] = []; + var rows = str_match_ng(str2, "\\trowd", "\\row"); + if (!rows) + throw new Error("RTF missing table"); + var range2 = { s: { c: 0, r: 0 }, e: { c: 0, r: rows.length - 1 } }; + var row = []; + rows.forEach(function(rowtf, R3) { + if (dense) + row = ws["!data"][R3] = []; + var rtfre = /\\[\w\-]+\b/g; + var last_index = 0; + var res; + var C3 = -1; + var payload = []; + while ((res = rtfre.exec(rowtf)) != null) { + var data = rowtf.slice(last_index, rtfre.lastIndex - res[0].length); + if (data.charCodeAt(0) == 32) + data = data.slice(1); + if (data.length) + payload.push(data); + switch (res[0]) { + case "\\cell": + ++C3; + if (payload.length) { + var cell = { v: payload.join(""), t: "s" }; + if (cell.v == "TRUE" || cell.v == "FALSE") { + cell.v = cell.v == "TRUE"; + cell.t = "b"; + } else if (!isNaN(fuzzynum(cell.v))) { + cell.t = "n"; + if (o9.cellText !== false) + cell.w = cell.v; + cell.v = fuzzynum(cell.v); + } else if (RBErr[cell.v] != null) { + cell.t = "e"; + cell.w = cell.v; + cell.v = RBErr[cell.v]; + } + if (dense) + row[C3] = cell; + else + ws[encode_cell({ r: R3, c: C3 })] = cell; + } + payload = []; + break; + case "\\par": + payload.push("\n"); + break; + } + last_index = rtfre.lastIndex; + } + if (C3 > range2.e.c) + range2.e.c = C3; + }); + ws["!ref"] = encode_range(range2); + return ws; +} +function rtf_to_workbook(d4, opts) { + var wb = sheet_to_workbook(rtf_to_sheet(d4, opts), opts); + wb.bookType = "rtf"; + return wb; +} +function hex2RGB(h7) { + var o9 = h7.slice(h7[0] === "#" ? 1 : 0).slice(0, 6); + return [parseInt(o9.slice(0, 2), 16), parseInt(o9.slice(2, 4), 16), parseInt(o9.slice(4, 6), 16)]; +} +function rgb2Hex(rgb) { + for (var i7 = 0, o9 = 1; i7 != 3; ++i7) o9 = o9 * 256 + (rgb[i7] > 255 ? 255 : rgb[i7] < 0 ? 0 : rgb[i7]); + return o9.toString(16).toUpperCase().slice(1); +} +function rgb2HSL(rgb) { + var R3 = rgb[0] / 255, G2 = rgb[1] / 255, B3 = rgb[2] / 255; + var M4 = Math.max(R3, G2, B3), m4 = Math.min(R3, G2, B3), C3 = M4 - m4; + if (C3 === 0) return [0, 0, R3]; + var H6 = 0, S5 = 0, L22 = M4 + m4; + S5 = C3 / (L22 > 1 ? 2 - L22 : L22); + switch (M4) { + case R3: + H6 = ((G2 - B3) / C3 + 6) % 6; + break; + case G2: + H6 = (B3 - R3) / C3 + 2; + break; + case B3: + H6 = (R3 - G2) / C3 + 4; + break; + } + return [H6 / 6, S5, L22 / 2]; +} +function hsl2RGB(hsl) { + var H2 = hsl[0], S5 = hsl[1], L3 = hsl[2]; + var C3 = S5 * 2 * (L3 < 0.5 ? L3 : 1 - L3), m4 = L3 - C3 / 2; + var rgb = [m4, m4, m4], h62 = 6 * H2; + var X4; + if (S5 !== 0) switch (h62 | 0) { + case 0: + case 6: + X4 = C3 * h62; + rgb[0] += C3; + rgb[1] += X4; + break; + case 1: + X4 = C3 * (2 - h62); + rgb[0] += X4; + rgb[1] += C3; + break; + case 2: + X4 = C3 * (h62 - 2); + rgb[1] += C3; + rgb[2] += X4; + break; + case 3: + X4 = C3 * (4 - h62); + rgb[1] += X4; + rgb[2] += C3; + break; + case 4: + X4 = C3 * (h62 - 4); + rgb[2] += C3; + rgb[0] += X4; + break; + case 5: + X4 = C3 * (6 - h62); + rgb[2] += X4; + rgb[0] += C3; + break; + } + for (var i7 = 0; i7 != 3; ++i7) rgb[i7] = Math.round(rgb[i7] * 255); + return rgb; +} +function rgb_tint(hex2, tint) { + if (tint === 0) return hex2; + var hsl = rgb2HSL(hex2RGB(hex2)); + if (tint < 0) hsl[2] = hsl[2] * (1 + tint); + else hsl[2] = 1 - (1 - hsl[2]) * (1 - tint); + return rgb2Hex(hsl2RGB(hsl)); +} +function width2px(width) { + return Math.floor((width + Math.round(128 / MDW) / 256) * MDW); +} +function px2char(px) { + return Math.floor((px - 5) / MDW * 100 + 0.5) / 100; +} +function char2width(chr) { + return Math.round((chr * MDW + 5) / MDW * 256) / 256; +} +function cycle_width(collw) { + return char2width(px2char(width2px(collw))); +} +function find_mdw_colw(collw) { + var delta = Math.abs(collw - cycle_width(collw)), _MDW = MDW; + if (delta > 5e-3) { + for (MDW = MIN_MDW; MDW < MAX_MDW; ++MDW) if (Math.abs(collw - cycle_width(collw)) <= delta) { + delta = Math.abs(collw - cycle_width(collw)); + _MDW = MDW; + } + } + MDW = _MDW; +} +function process_col(coll) { + if (coll.width) { + coll.wpx = width2px(coll.width); + coll.wch = px2char(coll.wpx); + coll.MDW = MDW; + } else if (coll.wpx) { + coll.wch = px2char(coll.wpx); + coll.width = char2width(coll.wch); + coll.MDW = MDW; + } else if (typeof coll.wch == "number") { + coll.width = char2width(coll.wch); + coll.wpx = width2px(coll.width); + coll.MDW = MDW; + } + if (coll.customWidth) delete coll.customWidth; +} +function px2pt(px) { + return px * 96 / PPI; +} +function pt2px(pt) { + return pt * PPI / 96; +} +function parse_borders(t6, styles2, themes, opts) { + styles2.Borders = []; + var border = {}; + var pass = false; + (t6.match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + case "": + break; + /* 18.8.4 border CT_Border */ + case "": + case "": + border = /*::(*/ + {}; + if (y4.diagonalUp) border.diagonalUp = parsexmlbool(y4.diagonalUp); + if (y4.diagonalDown) border.diagonalDown = parsexmlbool(y4.diagonalDown); + styles2.Borders.push(border); + break; + case "": + break; + /* note: not in spec, appears to be CT_BorderPr */ + case "": + break; + case "": + break; + case "": + break; + /* note: not in spec, appears to be CT_BorderPr */ + case "": + break; + case "": + break; + case "": + break; + /* 18.8.43 top CT_BorderPr */ + case "": + break; + case "": + break; + case "": + break; + /* 18.8.6 bottom CT_BorderPr */ + case "": + break; + case "": + break; + case "": + break; + /* 18.8.13 diagonal CT_BorderPr */ + case "": + case "": + break; + case "": + break; + /* 18.8.25 horizontal CT_BorderPr */ + case "": + case "": + break; + case "": + break; + /* 18.8.44 vertical CT_BorderPr */ + case "": + case "": + break; + case "": + break; + /* 18.8.37 start CT_BorderPr */ + case "": + case "": + break; + case "": + break; + /* 18.8.16 end CT_BorderPr */ + case "": + case "": + break; + case "": + break; + /* 18.8.? color CT_Color */ + case "": + break; + case "": + case "": + break; + /* 18.2.10 extLst CT_ExtensionList ? */ + case "": + case "": + break; + case "": + pass = false; + break; + default: + if (opts && opts.WTF) { + if (!pass) throw new Error("unrecognized " + y4[0] + " in borders"); + } + } + }); +} +function parse_fills(t6, styles2, themes, opts) { + styles2.Fills = []; + var fill3 = {}; + var pass = false; + (t6.match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + case "": + break; + /* 18.8.20 fill CT_Fill */ + case "": + case "": + fill3 = {}; + styles2.Fills.push(fill3); + break; + case "": + break; + /* 18.8.24 gradientFill CT_GradientFill */ + case "": + break; + case "": + styles2.Fills.push(fill3); + fill3 = {}; + break; + /* 18.8.32 patternFill CT_PatternFill */ + case "": + if (y4.patternType) fill3.patternType = y4.patternType; + break; + case "": + case "": + break; + /* 18.8.3 bgColor CT_Color */ + case "": + case "": + break; + /* 18.8.19 fgColor CT_Color */ + case "": + case "": + break; + /* 18.8.38 stop CT_GradientStop */ + case "": + break; + case "": + break; + /* 18.8.? color CT_Color */ + case "": + break; + case "": + break; + /* 18.2.10 extLst CT_ExtensionList ? */ + case "": + case "": + break; + case "": + pass = false; + break; + default: + if (opts && opts.WTF) { + if (!pass) throw new Error("unrecognized " + y4[0] + " in fills"); + } + } + }); +} +function parse_fonts(t6, styles2, themes, opts) { + styles2.Fonts = []; + var font = {}; + var pass = false; + (t6.match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + case "": + break; + /* 18.8.22 font CT_Font */ + case "": + break; + case "": + case "": + styles2.Fonts.push(font); + font = {}; + break; + /* 18.8.29 name CT_FontName */ + case "": + case "": + break; + /* 18.8.2 b CT_BooleanProperty */ + case "": + font.bold = 1; + break; + case "": + case "": + font.italic = 1; + break; + case "": + case "": + font.underline = 1; + break; + case "": + case "": + font.strike = 1; + break; + case "": + case "": + font.outline = 1; + break; + case "": + case "": + font.shadow = 1; + break; + case "": + case "": + font.condense = 1; + break; + case "": + case "": + font.extend = 1; + break; + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + break; + case "": + pass = false; + break; + default: + if (opts && opts.WTF) { + if (!pass) throw new Error("unrecognized " + y4[0] + " in fonts"); + } + } + }); +} +function parse_numFmts(t6, styles2, opts) { + styles2.NumberFmt = []; + var k2 = keys(table_fmt); + for (var i7 = 0; i7 < k2.length; ++i7) styles2.NumberFmt[k2[i7]] = table_fmt[k2[i7]]; + var m4 = t6.match(tagregex); + if (!m4) return; + for (i7 = 0; i7 < m4.length; ++i7) { + var y4 = parsexmltag(m4[i7]); + switch (strip_ns(y4[0])) { + case "": + case "": + case "": + break; + case " 0) { + if (j3 > 392) { + for (j3 = 392; j3 > 60; --j3) if (styles2.NumberFmt[j3] == null) break; + styles2.NumberFmt[j3] = f4; + } + SSF__load(f4, j3); + } + } + break; + case "": + break; + default: + if (opts.WTF) throw new Error("unrecognized " + y4[0] + " in numFmts"); + } + } +} +function parse_cellXfs(t6, styles2, opts) { + styles2.CellXf = []; + var xf; + var pass = false; + (t6.match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2), i7 = 0; + switch (strip_ns(y4[0])) { + case "": + case "": + case "": + break; + /* 18.8.45 xf CT_Xf */ + case "": + case "": + xf = y4; + delete xf[0]; + for (i7 = 0; i7 < cellXF_uint.length; ++i7) if (xf[cellXF_uint[i7]]) + xf[cellXF_uint[i7]] = parseInt(xf[cellXF_uint[i7]], 10); + for (i7 = 0; i7 < cellXF_bool.length; ++i7) if (xf[cellXF_bool[i7]]) + xf[cellXF_bool[i7]] = parsexmlbool(xf[cellXF_bool[i7]]); + if (styles2.NumberFmt && xf.numFmtId > 392) { + for (i7 = 392; i7 > 60; --i7) if (styles2.NumberFmt[xf.numFmtId] == styles2.NumberFmt[i7]) { + xf.numFmtId = i7; + break; + } + } + styles2.CellXf.push(xf); + break; + case "": + break; + /* 18.8.1 alignment CT_CellAlignment */ + case "": + case "": + var alignment = {}; + if (y4.vertical) alignment.vertical = y4.vertical; + if (y4.horizontal) alignment.horizontal = y4.horizontal; + if (y4.textRotation != null) alignment.textRotation = y4.textRotation; + if (y4.indent) alignment.indent = y4.indent; + if (y4.wrapText) alignment.wrapText = parsexmlbool(y4.wrapText); + xf.alignment = alignment; + break; + case "": + break; + /* 18.8.33 protection CT_CellProtection */ + case "": + break; + case "": + case "": + break; + /* note: sometimes mc:AlternateContent appears bare */ + case "": + pass = true; + break; + case "": + pass = false; + break; + /* 18.2.10 extLst CT_ExtensionList ? */ + case "": + case "": + break; + case "": + pass = false; + break; + default: + if (opts && opts.WTF) { + if (!pass) throw new Error("unrecognized " + y4[0] + " in cellXfs"); + } + } + }); +} +function parse_BrtFmt(data, length) { + var numFmtId = data.read_shift(2); + var stFmtCode = parse_XLWideString(data, length - 2); + return [numFmtId, stFmtCode]; +} +function parse_BrtFont(data, length, opts) { + var out = {}; + out.sz = data.read_shift(2) / 20; + var grbit = parse_FontFlags(data, 2, opts); + if (grbit.fItalic) out.italic = 1; + if (grbit.fCondense) out.condense = 1; + if (grbit.fExtend) out.extend = 1; + if (grbit.fShadow) out.shadow = 1; + if (grbit.fOutline) out.outline = 1; + if (grbit.fStrikeout) out.strike = 1; + var bls = data.read_shift(2); + if (bls === 700) out.bold = 1; + switch (data.read_shift(2)) { + /* case 0: out.vertAlign = "baseline"; break; */ + case 1: + out.vertAlign = "superscript"; + break; + case 2: + out.vertAlign = "subscript"; + break; + } + var underline = data.read_shift(1); + if (underline != 0) out.underline = underline; + var family = data.read_shift(1); + if (family > 0) out.family = family; + var bCharSet = data.read_shift(1); + if (bCharSet > 0) out.charset = bCharSet; + data.l++; + out.color = parse_BrtColor(data, 8); + switch (data.read_shift(1)) { + /* case 0: out.scheme = "none": break; */ + case 1: + out.scheme = "major"; + break; + case 2: + out.scheme = "minor"; + break; + } + out.name = parse_XLWideString(data, length - 21); + return out; +} +function parse_BrtXF(data, length) { + var tgt = data.l + length; + var ixfeParent = data.read_shift(2); + var ifmt = data.read_shift(2); + data.l = tgt; + return { ixfe: ixfeParent, numFmtId: ifmt }; +} +function parse_sty_bin(data, themes, opts) { + var styles2 = {}; + styles2.NumberFmt = []; + for (var y4 in table_fmt) styles2.NumberFmt[y4] = table_fmt[y4]; + styles2.CellXf = []; + styles2.Fonts = []; + var state = []; + var pass = false; + recordhopper(data, function hopper_sty(val2, R3, RT) { + switch (RT) { + case 44: + styles2.NumberFmt[val2[0]] = val2[1]; + SSF__load(val2[1], val2[0]); + break; + case 43: + styles2.Fonts.push(val2); + if (val2.color.theme != null && themes && themes.themeElements && themes.themeElements.clrScheme) { + val2.color.rgb = rgb_tint(themes.themeElements.clrScheme[val2.color.theme].rgb, val2.color.tint || 0); + } + break; + case 1025: + break; + case 45: + break; + case 46: + break; + case 47: + if (state[state.length - 1] == 617) { + styles2.CellXf.push(val2); + } + break; + case 48: + /* BrtStyle */ + case 507: + /* BrtDXF */ + case 572: + /* BrtMRUColor */ + case 475: + break; + case 1171: + /* BrtDXF14 */ + case 2102: + /* BrtDXF15 */ + case 1130: + /* BrtSlicerStyleElement */ + case 512: + /* BrtTableStyleElement */ + case 2095: + /* BrtTimelineStyleElement */ + case 3072: + break; + case 35: + pass = true; + break; + case 36: + pass = false; + break; + case 37: + state.push(RT); + pass = true; + break; + case 38: + state.pop(); + pass = false; + break; + default: + if (R3.T > 0) state.push(RT); + else if (R3.T < 0) state.pop(); + else if (!pass || opts.WTF && state[state.length - 1] != 37) throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }); + return styles2; +} +function parse_clrScheme(t6, themes, opts) { + themes.themeElements.clrScheme = []; + var color2 = {}; + (t6[0].match(tagregex) || []).forEach(function(x2) { + var y4 = parsexmltag(x2); + switch (y4[0]) { + /* 20.1.6.2 clrScheme (Color Scheme) CT_ColorScheme */ + case "": + break; + /* 20.1.2.3.32 srgbClr CT_SRgbColor */ + case "": + break; + /* 20.1.2.3.33 sysClr CT_SystemColor */ + case "": + break; + /* 20.1.4.1.1 accent1 (Accent 1) */ + /* 20.1.4.1.2 accent2 (Accent 2) */ + /* 20.1.4.1.3 accent3 (Accent 3) */ + /* 20.1.4.1.4 accent4 (Accent 4) */ + /* 20.1.4.1.5 accent5 (Accent 5) */ + /* 20.1.4.1.6 accent6 (Accent 6) */ + /* 20.1.4.1.9 dk1 (Dark 1) */ + /* 20.1.4.1.10 dk2 (Dark 2) */ + /* 20.1.4.1.15 folHlink (Followed Hyperlink) */ + /* 20.1.4.1.19 hlink (Hyperlink) */ + /* 20.1.4.1.22 lt1 (Light 1) */ + /* 20.1.4.1.23 lt2 (Light 2) */ + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + case "": + if (y4[0].charAt(1) === "/") { + themes.themeElements.clrScheme[XLSXThemeClrScheme.indexOf(y4[0])] = color2; + color2 = {}; + } else { + color2.name = y4[0].slice(3, y4[0].length - 1); + } + break; + default: + if (opts && opts.WTF) throw new Error("Unrecognized " + y4[0] + " in clrScheme"); + } + }); +} +function parse_fontScheme() { +} +function parse_fmtScheme() { +} +function parse_themeElements(data, themes, opts) { + themes.themeElements = {}; + var t6; + if (!(t6 = str_match_xml(data, "a:clrScheme"))) throw new Error("clrScheme not found in themeElements"); + parse_clrScheme(t6, themes, opts); + if (!(t6 = str_match_xml(data, "a:fontScheme"))) throw new Error("fontScheme not found in themeElements"); + parse_fontScheme(t6, themes, opts); + if (!(t6 = str_match_xml(data, "a:fmtScheme"))) throw new Error("fmtScheme not found in themeElements"); + parse_fmtScheme(t6, themes, opts); +} +function parse_theme_xml(data, opts) { + if (!data || data.length === 0) data = write_theme(); + var t6; + var themes = {}; + if (!(t6 = str_match_xml(data, "a:themeElements"))) throw new Error("themeElements not found in theme"); + parse_themeElements(t6[0], themes, opts); + themes.raw = data; + return themes; +} +function write_theme(Themes, opts) { + if (opts && opts.themeXLSX) return opts.themeXLSX; + if (Themes && typeof Themes.raw == "string") return Themes.raw; + var o9 = [XML_HEADER]; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ''; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + o9[o9.length] = ""; + return o9.join(""); +} +function parse_Theme(blob, length, opts) { + var end = blob.l + length; + var dwThemeVersion = blob.read_shift(4); + if (dwThemeVersion === 124226) return; + if (!opts.cellStyles) { + blob.l = end; + return; + } + var data = blob.slice(blob.l); + blob.l = end; + var zip; + try { + zip = zip_read(data, { type: "array" }); + } catch (e9) { + return; + } + var themeXML = getzipstr(zip, "theme/theme/theme1.xml", true); + if (!themeXML) return; + return parse_theme_xml(themeXML, opts); +} +function parse_ColorTheme(blob) { + return blob.read_shift(4); +} +function parse_FullColorExt(blob) { + var o9 = {}; + o9.xclrType = blob.read_shift(2); + o9.nTintShade = blob.read_shift(2); + switch (o9.xclrType) { + case 0: + blob.l += 4; + break; + case 1: + o9.xclrValue = parse_IcvXF(blob, 4); + break; + case 2: + o9.xclrValue = parse_LongRGBA(blob, 4); + break; + case 3: + o9.xclrValue = parse_ColorTheme(blob, 4); + break; + case 4: + blob.l += 4; + break; + } + blob.l += 8; + return o9; +} +function parse_IcvXF(blob, length) { + return parsenoop(blob, length); +} +function parse_XFExtGradient(blob, length) { + return parsenoop(blob, length); +} +function parse_ExtProp(blob) { + var extType = blob.read_shift(2); + var cb = blob.read_shift(2) - 4; + var o9 = [extType]; + switch (extType) { + case 4: + case 5: + case 7: + case 8: + case 9: + case 10: + case 11: + case 13: + o9[1] = parse_FullColorExt(blob, cb); + break; + case 6: + o9[1] = parse_XFExtGradient(blob, cb); + break; + case 14: + case 15: + o9[1] = blob.read_shift(cb === 1 ? 1 : 2); + break; + default: + throw new Error("Unrecognized ExtProp type: " + extType + " " + cb); + } + return o9; +} +function parse_XFExt(blob, length) { + var end = blob.l + length; + blob.l += 2; + var ixfe = blob.read_shift(2); + blob.l += 2; + var cexts = blob.read_shift(2); + var ext2 = []; + while (cexts-- > 0) ext2.push(parse_ExtProp(blob, end - blob.l)); + return { ixfe, ext: ext2 }; +} +function update_xfext(xf, xfext) { + xfext.forEach(function(xfe) { + switch (xfe[0]) { + /* 2.5.108 extPropData */ + case 4: + break; + /* foreground color */ + case 5: + break; + /* background color */ + case 6: + break; + /* gradient fill */ + case 7: + break; + /* top cell border color */ + case 8: + break; + /* bottom cell border color */ + case 9: + break; + /* left cell border color */ + case 10: + break; + /* right cell border color */ + case 11: + break; + /* diagonal cell border color */ + case 13: + break; + case 14: + break; + /* font scheme */ + case 15: + break; + } + }); +} +function parse_BrtMdtinfo(data, length) { + return { + flags: data.read_shift(4), + version: data.read_shift(4), + name: parse_XLWideString(data, length - 8) + }; +} +function parse_BrtMdb(data) { + var out = []; + var cnt = data.read_shift(4); + while (cnt-- > 0) + out.push([data.read_shift(4), data.read_shift(4)]); + return out; +} +function parse_BrtBeginEsmdb(data) { + data.l += 4; + return data.read_shift(4) != 0; +} +function parse_xlmeta_bin(data, name, _opts) { + var out = { Types: [], Cell: [], Value: [] }; + var opts = _opts || {}; + var state = []; + var pass = false; + var metatype = 2; + recordhopper(data, function(val2, R3, RT) { + switch (RT) { + case 335: + out.Types.push({ name: val2.name }); + break; + case 51: + val2.forEach(function(r8) { + if (metatype == 1) + out.Cell.push({ type: out.Types[r8[0] - 1].name, index: r8[1] }); + else if (metatype == 0) + out.Value.push({ type: out.Types[r8[0] - 1].name, index: r8[1] }); + }); + break; + case 337: + metatype = val2 ? 1 : 0; + break; + case 338: + metatype = 2; + break; + case 35: + state.push(RT); + pass = true; + break; + case 36: + state.pop(); + pass = false; + break; + default: + if (R3.T) { + } else if (!pass || opts.WTF && state[state.length - 1] != 35) + throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }); + return out; +} +function parse_xlmeta_xml(data, name, opts) { + var out = { Types: [], Cell: [], Value: [] }; + if (!data) + return out; + var pass = false; + var metatype = 2; + var lastmeta; + data.replace(tagregex, function(x2) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + break; + case "": + break; + case "": + break; + case "": + break; + case "": + break; + case "": + break; + case "": + break; + case "": + metatype = 2; + break; + case "": + metatype = 2; + break; + case "": + case "": + case "": + break; + case "": + pass = false; + break; + case "": + case "": + break; + /* 18.6.1 c CT_CalcCell 1 */ + case "]*r:id="([^<>"]*)"/) || ["", ""])[1]; + return rels["!id"][id].Target; +} +function parse_vml(data, sheet, comments) { + var cidx = 0; + (str_match_xml_ns_g(data, "shape") || []).forEach(function(m4) { + var type = ""; + var hidden = true; + var aidx = -1; + var R3 = -1, C3 = -1; + m4.replace(tagregex, function(x2, idx) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + hidden = false; + break; + case "": + aidx = idx + x2.length; + break; + case "": + R3 = +m4.slice(aidx, idx).trim(); + break; + case "": + aidx = idx + x2.length; + break; + case "": + C3 = +m4.slice(aidx, idx).trim(); + break; + } + return ""; + }); + switch (type) { + case "Note": + var cell = ws_get_cell_stub(sheet, R3 >= 0 && C3 >= 0 ? encode_cell({ r: R3, c: C3 }) : comments[cidx].ref); + if (cell.c) { + cell.c.hidden = hidden; + } + ++cidx; + break; + } + }); +} +function sheet_insert_comments(sheet, comments, threaded, people) { + var dense = sheet["!data"] != null; + var cell; + comments.forEach(function(comment) { + var r8 = decode_cell(comment.ref); + if (r8.r < 0 || r8.c < 0) return; + if (dense) { + if (!sheet["!data"][r8.r]) sheet["!data"][r8.r] = []; + cell = sheet["!data"][r8.r][r8.c]; + } else cell = sheet[comment.ref]; + if (!cell) { + cell = { t: "z" }; + if (dense) sheet["!data"][r8.r][r8.c] = cell; + else sheet[comment.ref] = cell; + var range2 = safe_decode_range(sheet["!ref"] || "BDWGO1000001:A1"); + if (range2.s.r > r8.r) range2.s.r = r8.r; + if (range2.e.r < r8.r) range2.e.r = r8.r; + if (range2.s.c > r8.c) range2.s.c = r8.c; + if (range2.e.c < r8.c) range2.e.c = r8.c; + var encoded = encode_range(range2); + sheet["!ref"] = encoded; + } + if (!cell.c) cell.c = []; + var o9 = { a: comment.author, t: comment.t, r: comment.r, T: threaded }; + if (comment.h) o9.h = comment.h; + for (var i7 = cell.c.length - 1; i7 >= 0; --i7) { + if (!threaded && cell.c[i7].T) return; + if (threaded && !cell.c[i7].T) cell.c.splice(i7, 1); + } + if (threaded && people) for (i7 = 0; i7 < people.length; ++i7) { + if (o9.a == people[i7].id) { + o9.a = people[i7].name || o9.a; + break; + } + } + cell.c.push(o9); + }); +} +function parse_comments_xml(data, opts) { + if (data.match(/<(?:\w+:)?comments *\/>/)) return []; + var authors = []; + var commentList = []; + var authtag = str_match_xml_ns(data, "authors"); + if (authtag && authtag[1]) authtag[1].split(/<\/\w*:?author>/).forEach(function(x2) { + if (x2 === "" || x2.trim() === "") return; + var a3 = x2.match(/<(?:\w+:)?author[^<>]*>(.*)/); + if (a3) authors.push(a3[1]); + }); + var cmnttag = str_match_xml_ns(data, "commentList"); + if (cmnttag && cmnttag[1]) cmnttag[1].split(/<\/\w*:?comment>/).forEach(function(x2) { + if (x2 === "" || x2.trim() === "") return; + var cm = x2.match(/<(?:\w+:)?comment[^<>]*>/); + if (!cm) return; + var y4 = parsexmltag(cm[0]); + var comment = { author: y4.authorId && authors[y4.authorId] || "sheetjsghost", ref: y4.ref, guid: y4.guid }; + var cell = decode_cell(y4.ref); + if (opts.sheetRows && opts.sheetRows <= cell.r) return; + var textMatch = str_match_xml_ns(x2, "text"); + var rt = !!textMatch && !!textMatch[1] && parse_si(textMatch[1]) || { r: "", t: "", h: "" }; + comment.r = rt.r; + if (rt.r == "") rt.t = rt.h = ""; + comment.t = (rt.t || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + if (opts.cellHTML) comment.h = rt.h; + commentList.push(comment); + }); + return commentList; +} +function parse_tcmnt_xml(data, opts) { + var out = []; + var pass = false, comment = {}, tidx = 0; + data.replace(tagregex, function xml_tcmnt(x2, idx) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + break; + /* 2.6.205 threadedComment CT_ThreadedComment */ + case "": + if (comment.t != null) out.push(comment); + break; + case "": + case "": + comment.t = data.slice(tidx, idx).replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + break; + /* 2.6.206 mentions CT_ThreadedCommentMentions TODO */ + case "": + pass = true; + break; + case "": + pass = false; + break; + /* 2.6.202 mention CT_Mention TODO */ + /* 18.2.10 extLst CT_ExtensionList ? */ + case "": + case "": + case "": + break; + /* 18.2.7 ext CT_Extension + */ + case "": + pass = false; + break; + default: + if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in threaded comments"); + } + return x2; + }); + return out; +} +function parse_people_xml(data, opts) { + var out = []; + var pass = false; + data.replace(tagregex, function xml_tcmnt(x2) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + break; + /* 2.6.203 person CT_Person TODO: providers */ + case "": + break; + /* 18.2.10 extLst CT_ExtensionList ? */ + case "": + case "": + case "": + break; + /* 18.2.7 ext CT_Extension + */ + case "": + pass = false; + break; + default: + if (!pass && opts.WTF) throw new Error("unrecognized " + y4[0] + " in threaded comments"); + } + return x2; + }); + return out; +} +function parse_BrtBeginComment(data) { + var out = {}; + out.iauthor = data.read_shift(4); + var rfx = parse_UncheckedRfX(data, 16); + out.rfx = rfx.s; + out.ref = encode_cell(rfx.s); + data.l += 16; + return out; +} +function parse_comments_bin(data, opts) { + var out = []; + var authors = []; + var c6 = {}; + var pass = false; + recordhopper(data, function hopper_cmnt(val2, R3, RT) { + switch (RT) { + case 632: + authors.push(val2); + break; + case 635: + c6 = val2; + break; + case 637: + c6.t = val2.t; + c6.h = val2.h; + c6.r = val2.r; + break; + case 636: + c6.author = authors[c6.iauthor]; + delete c6.iauthor; + if (opts.sheetRows && c6.rfx && opts.sheetRows <= c6.rfx.r) break; + if (!c6.t) c6.t = ""; + delete c6.rfx; + out.push(c6); + break; + case 3072: + break; + case 35: + pass = true; + break; + case 36: + pass = false; + break; + case 37: + break; + case 38: + break; + default: + if (R3.T) { + } else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }); + return out; +} +function make_vba_xls(cfb) { + var newcfb = CFB.utils.cfb_new({ root: "R" }); + cfb.FullPaths.forEach(function(p4, i7) { + if (p4.slice(-1) === "/" || !p4.match(/_VBA_PROJECT_CUR/)) + return; + var newpath = p4.replace(/^[^\/]*/, "R").replace(/\/_VBA_PROJECT_CUR\u0000*/, ""); + CFB.utils.cfb_add(newcfb, newpath, cfb.FileIndex[i7].content); + }); + return CFB.write(newcfb); +} +function parse_ds_bin() { + return { "!type": "dialog" }; +} +function parse_ds_xml() { + return { "!type": "dialog" }; +} +function parse_ms_bin() { + return { "!type": "macro" }; +} +function parse_ms_xml() { + return { "!type": "macro" }; +} +function shift_formula_str(f4, delta) { + return f4.replace(crefregex, function($0, $1, $22, $32, $4, $5) { + return $1 + ($22 == "$" ? $22 + $32 : encode_col(decode_col($32) + delta.c)) + ($4 == "$" ? $4 + $5 : encode_row(decode_row($5) + delta.r)); + }); +} +function shift_formula_xlsx(f4, range2, cell) { + var r8 = decode_range(range2), s6 = r8.s, c6 = decode_cell(cell); + var delta = { r: c6.r - s6.r, c: c6.c - s6.c }; + return shift_formula_str(f4, delta); +} +function fuzzyfmla(f4) { + if (f4.length == 1) return false; + return true; +} +function _xlfn(f4) { + return f4.replace(/_xlfn\./g, ""); +} +function parseread1(blob) { + blob.l += 1; + return; +} +function parse_ColRelU(blob, length) { + var c6 = blob.read_shift(length == 1 ? 1 : 2); + return [c6 & 16383, c6 >> 14 & 1, c6 >> 15 & 1]; +} +function parse_RgceArea(blob, length, opts) { + var w3 = 2; + if (opts) { + if (opts.biff >= 2 && opts.biff <= 5) return parse_RgceArea_BIFF2(blob, length, opts); + else if (opts.biff == 12) w3 = 4; + } + var r8 = blob.read_shift(w3), R3 = blob.read_shift(w3); + var c6 = parse_ColRelU(blob, 2); + var C3 = parse_ColRelU(blob, 2); + return { s: { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }, e: { r: R3, c: C3[0], cRel: C3[1], rRel: C3[2] } }; +} +function parse_RgceArea_BIFF2(blob) { + var r8 = parse_ColRelU(blob, 2), R3 = parse_ColRelU(blob, 2); + var c6 = blob.read_shift(1); + var C3 = blob.read_shift(1); + return { s: { r: r8[0], c: c6, cRel: r8[1], rRel: r8[2] }, e: { r: R3[0], c: C3, cRel: R3[1], rRel: R3[2] } }; +} +function parse_RgceAreaRel(blob, length, opts) { + if (opts.biff < 8) return parse_RgceArea_BIFF2(blob, length, opts); + var r8 = blob.read_shift(opts.biff == 12 ? 4 : 2), R3 = blob.read_shift(opts.biff == 12 ? 4 : 2); + var c6 = parse_ColRelU(blob, 2); + var C3 = parse_ColRelU(blob, 2); + return { s: { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }, e: { r: R3, c: C3[0], cRel: C3[1], rRel: C3[2] } }; +} +function parse_RgceLoc(blob, length, opts) { + if (opts && opts.biff >= 2 && opts.biff <= 5) return parse_RgceLoc_BIFF2(blob, length, opts); + var r8 = blob.read_shift(opts && opts.biff == 12 ? 4 : 2); + var c6 = parse_ColRelU(blob, 2); + return { r: r8, c: c6[0], cRel: c6[1], rRel: c6[2] }; +} +function parse_RgceLoc_BIFF2(blob) { + var r8 = parse_ColRelU(blob, 2); + var c6 = blob.read_shift(1); + return { r: r8[0], c: c6, cRel: r8[1], rRel: r8[2] }; +} +function parse_RgceElfLoc(blob) { + var r8 = blob.read_shift(2); + var c6 = blob.read_shift(2); + return { r: r8, c: c6 & 255, fQuoted: !!(c6 & 16384), cRel: c6 >> 15, rRel: c6 >> 15 }; +} +function parse_RgceLocRel(blob, length, opts) { + var biff = opts && opts.biff ? opts.biff : 8; + if (biff >= 2 && biff <= 5) return parse_RgceLocRel_BIFF2(blob, length, opts); + var r8 = blob.read_shift(biff >= 12 ? 4 : 2); + var cl = blob.read_shift(2); + var cRel = (cl & 16384) >> 14, rRel = (cl & 32768) >> 15; + cl &= 16383; + if (rRel == 1) while (r8 > 524287) r8 -= 1048576; + if (cRel == 1) while (cl > 8191) cl = cl - 16384; + return { r: r8, c: cl, cRel, rRel }; +} +function parse_RgceLocRel_BIFF2(blob) { + var rl = blob.read_shift(2); + var c6 = blob.read_shift(1); + var rRel = (rl & 32768) >> 15, cRel = (rl & 16384) >> 14; + rl &= 16383; + if (rRel == 1 && rl >= 8192) rl = rl - 16384; + if (cRel == 1 && c6 >= 128) c6 = c6 - 256; + return { r: rl, c: c6, cRel, rRel }; +} +function parse_PtgArea(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + var area = parse_RgceArea(blob, opts.biff >= 2 && opts.biff <= 5 ? 6 : 8, opts); + return [type, area]; +} +function parse_PtgArea3d(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + var ixti = blob.read_shift(2, "i"); + var w3 = 8; + if (opts) switch (opts.biff) { + case 5: + blob.l += 12; + w3 = 6; + break; + case 12: + w3 = 12; + break; + } + var area = parse_RgceArea(blob, w3, opts); + return [type, ixti, area]; +} +function parse_PtgAreaErr(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + blob.l += opts && opts.biff > 8 ? 12 : opts.biff < 8 ? 6 : 8; + return [type]; +} +function parse_PtgAreaErr3d(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + var ixti = blob.read_shift(2); + var w3 = 8; + if (opts) switch (opts.biff) { + case 5: + blob.l += 12; + w3 = 6; + break; + case 12: + w3 = 12; + break; + } + blob.l += w3; + return [type, ixti]; +} +function parse_PtgAreaN(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + var area = parse_RgceAreaRel(blob, length - 1, opts); + return [type, area]; +} +function parse_PtgArray(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + blob.l += opts.biff == 2 ? 6 : opts.biff == 12 ? 14 : 7; + return [type]; +} +function parse_PtgAttrBaxcel(blob) { + var bitSemi = blob[blob.l + 1] & 1; + var bitBaxcel = 1; + blob.l += 4; + return [bitSemi, bitBaxcel]; +} +function parse_PtgAttrChoose(blob, length, opts) { + blob.l += 2; + var offset = blob.read_shift(opts && opts.biff == 2 ? 1 : 2); + var o9 = []; + for (var i7 = 0; i7 <= offset; ++i7) o9.push(blob.read_shift(opts && opts.biff == 2 ? 1 : 2)); + return o9; +} +function parse_PtgAttrGoto(blob, length, opts) { + var bitGoto = blob[blob.l + 1] & 255 ? 1 : 0; + blob.l += 2; + return [bitGoto, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)]; +} +function parse_PtgAttrIf(blob, length, opts) { + var bitIf = blob[blob.l + 1] & 255 ? 1 : 0; + blob.l += 2; + return [bitIf, blob.read_shift(opts && opts.biff == 2 ? 1 : 2)]; +} +function parse_PtgAttrIfError(blob) { + var bitIf = blob[blob.l + 1] & 255 ? 1 : 0; + blob.l += 2; + return [bitIf, blob.read_shift(2)]; +} +function parse_PtgAttrSemi(blob, length, opts) { + var bitSemi = blob[blob.l + 1] & 255 ? 1 : 0; + blob.l += opts && opts.biff == 2 ? 3 : 4; + return [bitSemi]; +} +function parse_PtgAttrSpaceType(blob) { + var type = blob.read_shift(1), cch = blob.read_shift(1); + return [type, cch]; +} +function parse_PtgAttrSpace(blob) { + blob.read_shift(2); + return parse_PtgAttrSpaceType(blob, 2); +} +function parse_PtgAttrSpaceSemi(blob) { + blob.read_shift(2); + return parse_PtgAttrSpaceType(blob, 2); +} +function parse_PtgRef(blob, length, opts) { + var type = (blob[blob.l] & 96) >> 5; + blob.l += 1; + var loc = parse_RgceLoc(blob, 0, opts); + return [type, loc]; +} +function parse_PtgRefN(blob, length, opts) { + var type = (blob[blob.l] & 96) >> 5; + blob.l += 1; + var loc = parse_RgceLocRel(blob, 0, opts); + return [type, loc]; +} +function parse_PtgRef3d(blob, length, opts) { + var type = (blob[blob.l] & 96) >> 5; + blob.l += 1; + var ixti = blob.read_shift(2); + if (opts && opts.biff == 5) blob.l += 12; + var loc = parse_RgceLoc(blob, 0, opts); + return [type, ixti, loc]; +} +function parse_PtgFunc(blob, length, opts) { + var type = (blob[blob.l] & 96) >> 5; + blob.l += 1; + var iftab = blob.read_shift(opts && opts.biff <= 3 ? 1 : 2); + return [FtabArgc[iftab], Ftab[iftab], type]; +} +function parse_PtgFuncVar(blob, length, opts) { + var type = blob[blob.l++]; + var cparams = blob.read_shift(1), tab = opts && opts.biff <= 3 ? [type == 88 ? -1 : 0, blob.read_shift(1)] : parsetab(blob); + return [cparams, (tab[0] === 0 ? Ftab : Cetab)[tab[1]]]; +} +function parsetab(blob) { + return [blob[blob.l + 1] >> 7, blob.read_shift(2) & 32767]; +} +function parse_PtgAttrSum(blob, length, opts) { + blob.l += opts && opts.biff == 2 ? 3 : 4; + return; +} +function parse_PtgExp(blob, length, opts) { + blob.l++; + if (opts && opts.biff == 12) return [blob.read_shift(4, "i"), 0]; + var row = blob.read_shift(2); + var col = blob.read_shift(opts && opts.biff == 2 ? 1 : 2); + return [row, col]; +} +function parse_PtgErr(blob) { + blob.l++; + return BErr[blob.read_shift(1)]; +} +function parse_PtgInt(blob) { + blob.l++; + return blob.read_shift(2); +} +function parse_PtgBool(blob) { + blob.l++; + return blob.read_shift(1) !== 0; +} +function parse_PtgNum(blob) { + blob.l++; + return parse_Xnum(blob, 8); +} +function parse_PtgStr(blob, length, opts) { + blob.l++; + return parse_ShortXLUnicodeString(blob, length - 1, opts); +} +function parse_SerAr(blob, biff) { + var val2 = [blob.read_shift(1)]; + if (biff == 12) switch (val2[0]) { + case 2: + val2[0] = 4; + break; + /* SerBool */ + case 4: + val2[0] = 16; + break; + /* SerErr */ + case 0: + val2[0] = 1; + break; + /* SerNum */ + case 1: + val2[0] = 2; + break; + } + switch (val2[0]) { + case 4: + val2[1] = parsebool(blob, 1) ? "TRUE" : "FALSE"; + if (biff != 12) blob.l += 7; + break; + case 37: + /* appears to be an alias */ + case 16: + val2[1] = BErr[blob[blob.l]]; + blob.l += biff == 12 ? 4 : 8; + break; + case 0: + blob.l += 8; + break; + case 1: + val2[1] = parse_Xnum(blob, 8); + break; + case 2: + val2[1] = parse_XLUnicodeString2(blob, 0, { biff: biff > 0 && biff < 8 ? 2 : biff }); + break; + default: + throw new Error("Bad SerAr: " + val2[0]); + } + return val2; +} +function parse_PtgExtraMem(blob, cce, opts) { + var count = blob.read_shift(opts.biff == 12 ? 4 : 2); + var out = []; + for (var i7 = 0; i7 != count; ++i7) out.push((opts.biff == 12 ? parse_UncheckedRfX : parse_Ref8U)(blob, 8)); + return out; +} +function parse_PtgExtraArray(blob, length, opts) { + var rows = 0, cols = 0; + if (opts.biff == 12) { + rows = blob.read_shift(4); + cols = blob.read_shift(4); + } else { + cols = 1 + blob.read_shift(1); + rows = 1 + blob.read_shift(2); + } + if (opts.biff >= 2 && opts.biff < 8) { + --rows; + if (--cols == 0) cols = 256; + } + for (var i7 = 0, o9 = []; i7 != rows && (o9[i7] = []); ++i7) + for (var j3 = 0; j3 != cols; ++j3) o9[i7][j3] = parse_SerAr(blob, opts.biff); + return o9; +} +function parse_PtgName(blob, length, opts) { + var type = blob.read_shift(1) >>> 5 & 3; + var w3 = !opts || opts.biff >= 8 ? 4 : 2; + var nameindex = blob.read_shift(w3); + switch (opts.biff) { + case 2: + blob.l += 5; + break; + case 3: + case 4: + blob.l += 8; + break; + case 5: + blob.l += 12; + break; + } + return [type, 0, nameindex]; +} +function parse_PtgNameX(blob, length, opts) { + if (opts.biff == 5) return parse_PtgNameX_BIFF5(blob, length, opts); + var type = blob.read_shift(1) >>> 5 & 3; + var ixti = blob.read_shift(2); + var nameindex = blob.read_shift(4); + return [type, ixti, nameindex]; +} +function parse_PtgNameX_BIFF5(blob) { + var type = blob.read_shift(1) >>> 5 & 3; + var ixti = blob.read_shift(2, "i"); + blob.l += 8; + var nameindex = blob.read_shift(2); + blob.l += 12; + return [type, ixti, nameindex]; +} +function parse_PtgMemArea(blob, length, opts) { + var type = blob.read_shift(1) >>> 5 & 3; + blob.l += opts && opts.biff == 2 ? 3 : 4; + var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2); + return [type, cce]; +} +function parse_PtgMemFunc(blob, length, opts) { + var type = blob.read_shift(1) >>> 5 & 3; + var cce = blob.read_shift(opts && opts.biff == 2 ? 1 : 2); + return [type, cce]; +} +function parse_PtgRefErr(blob, length, opts) { + var type = blob.read_shift(1) >>> 5 & 3; + blob.l += 4; + if (opts.biff < 8) blob.l--; + if (opts.biff == 12) blob.l += 2; + return [type]; +} +function parse_PtgRefErr3d(blob, length, opts) { + var type = (blob[blob.l++] & 96) >> 5; + var ixti = blob.read_shift(2); + var w3 = 4; + if (opts) switch (opts.biff) { + case 5: + w3 = 15; + break; + case 12: + w3 = 6; + break; + } + blob.l += w3; + return [type, ixti]; +} +function parse_PtgElfLoc(blob, length, opts) { + blob.l += 2; + return [parse_RgceElfLoc(blob, 4, opts)]; +} +function parse_PtgElfNoop(blob) { + blob.l += 6; + return []; +} +function parse_PtgElfLel(blob) { + blob.l += 2; + return [parseuint16(blob), blob.read_shift(2) & 1]; +} +function parse_PtgList(blob) { + blob.l += 2; + var ixti = blob.read_shift(2); + var flags = blob.read_shift(2); + var idx = blob.read_shift(4); + var c6 = blob.read_shift(2); + var C3 = blob.read_shift(2); + var rt = PtgListRT[flags >> 2 & 31]; + return { ixti, coltype: flags & 3, rt, idx, c: c6, C: C3 }; +} +function parse_PtgSxName(blob) { + blob.l += 2; + return [blob.read_shift(4)]; +} +function parse_PtgSheet(blob, length, opts) { + blob.l += 5; + blob.l += 2; + blob.l += opts.biff == 2 ? 1 : 4; + return ["PTGSHEET"]; +} +function parse_PtgEndSheet(blob, length, opts) { + blob.l += opts.biff == 2 ? 4 : 5; + return ["PTGENDSHEET"]; +} +function parse_PtgMemAreaN(blob) { + var type = blob.read_shift(1) >>> 5 & 3; + var cce = blob.read_shift(2); + return [type, cce]; +} +function parse_PtgMemNoMemN(blob) { + var type = blob.read_shift(1) >>> 5 & 3; + var cce = blob.read_shift(2); + return [type, cce]; +} +function parse_PtgAttrNoop(blob) { + blob.l += 4; + return [0, 0]; +} +function parse_RgbExtra(blob, length, rgce, opts) { + if (opts.biff < 8) return parsenoop(blob, length); + var target = blob.l + length; + var o9 = []; + for (var i7 = 0; i7 !== rgce.length; ++i7) { + switch (rgce[i7][0]) { + case "PtgArray": + rgce[i7][1] = parse_PtgExtraArray(blob, 0, opts); + o9.push(rgce[i7][1]); + break; + case "PtgMemArea": + rgce[i7][2] = parse_PtgExtraMem(blob, rgce[i7][1], opts); + o9.push(rgce[i7][2]); + break; + case "PtgExp": + if (opts && opts.biff == 12) { + rgce[i7][1][1] = blob.read_shift(4); + o9.push(rgce[i7][1]); + } + break; + case "PtgList": + /* TODO: PtgList -> PtgExtraList */ + case "PtgElfRadicalS": + /* TODO: PtgElfRadicalS -> PtgExtraElf */ + case "PtgElfColS": + /* TODO: PtgElfColS -> PtgExtraElf */ + case "PtgElfColSV": + throw "Unsupported " + rgce[i7][0]; + default: + break; + } + } + length = target - blob.l; + if (length !== 0) o9.push(parsenoop(blob, length)); + return o9; +} +function parse_Rgce(blob, length, opts) { + var target = blob.l + length; + var R3, id, ptgs = []; + while (target != blob.l) { + length = target - blob.l; + id = blob[blob.l]; + R3 = PtgTypes[id] || PtgTypes[PtgDupes[id]]; + if (id === 24 || id === 25) R3 = (id === 24 ? Ptg18 : Ptg19)[blob[blob.l + 1]]; + if (!R3 || !R3.f) { + parsenoop(blob, length); + } else { + ptgs.push([R3.n, R3.f(blob, length, opts)]); + } + } + return ptgs; +} +function stringify_array(f4) { + var o9 = []; + for (var i7 = 0; i7 < f4.length; ++i7) { + var x2 = f4[i7], r8 = []; + for (var j3 = 0; j3 < x2.length; ++j3) { + var y4 = x2[j3]; + if (y4) switch (y4[0]) { + // TODO: handle embedded quotes + case 2: + r8.push('"' + y4[1].replace(/"/g, '""') + '"'); + break; + default: + r8.push(y4[1]); + } + else r8.push(""); + } + o9.push(r8.join(",")); + } + return o9.join(";"); +} +function make_3d_range(start, end) { + var s6 = start.lastIndexOf("!"), e9 = end.lastIndexOf("!"); + if (s6 == -1 && e9 == -1) return start + ":" + end; + if (s6 > 0 && e9 > 0 && start.slice(0, s6).toLowerCase() == end.slice(0, e9).toLowerCase()) return start + ":" + end.slice(e9 + 1); + console.error("Cannot hydrate range", start, end); + return start + ":" + end; +} +function get_ixti_raw(supbooks, ixti, opts) { + if (!supbooks) return "SH33TJSERR0"; + if (opts.biff > 8 && (!supbooks.XTI || !supbooks.XTI[ixti])) return supbooks.SheetNames[ixti]; + if (!supbooks.XTI) return "SH33TJSERR6"; + var XTI = supbooks.XTI[ixti]; + if (opts.biff < 8) { + if (ixti > 1e4) ixti -= 65536; + if (ixti < 0) ixti = -ixti; + return ixti == 0 ? "" : supbooks.XTI[ixti - 1]; + } + if (!XTI) return "SH33TJSERR1"; + var o9 = ""; + if (opts.biff > 8) switch (supbooks[XTI[0]][0]) { + case 357: + o9 = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]]; + return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks.SheetNames[XTI[2]]; + case 358: + if (opts.SID != null) return supbooks.SheetNames[opts.SID]; + return "SH33TJSSAME" + supbooks[XTI[0]][0]; + case 355: + /* 'BrtSupBookSrc' */ + /* falls through */ + default: + return "SH33TJSSRC" + supbooks[XTI[0]][0]; + } + switch (supbooks[XTI[0]][0][0]) { + case 1025: + o9 = XTI[1] == -1 ? "#REF" : supbooks.SheetNames[XTI[1]] || "SH33TJSERR3"; + return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks.SheetNames[XTI[2]]; + case 14849: + return supbooks[XTI[0]].slice(1).map(function(name) { + return name.Name; + }).join(";;"); + //return "SH33TJSERR8"; + default: + if (!supbooks[XTI[0]][0][3]) return "SH33TJSERR2"; + o9 = XTI[1] == -1 ? "#REF" : supbooks[XTI[0]][0][3][XTI[1]] || "SH33TJSERR4"; + return XTI[1] == XTI[2] ? o9 : o9 + ":" + supbooks[XTI[0]][0][3][XTI[2]]; + } +} +function get_ixti(supbooks, ixti, opts) { + var ixtiraw = get_ixti_raw(supbooks, ixti, opts); + return ixtiraw == "#REF" ? ixtiraw : formula_quote_sheet_name(ixtiraw, opts); +} +function stringify_formula(formula, range2, cell, supbooks, opts) { + var biff = opts && opts.biff || 8; + var _range = ( + /*range != null ? range :*/ + { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } } + ); + var stack = [], e1, e22, c6, ixti = 0, nameidx = 0, r8, sname = ""; + if (!formula[0] || !formula[0][0]) return ""; + var last_sp = -1, sp = ""; + for (var ff = 0, fflen = formula[0].length; ff < fflen; ++ff) { + var f4 = formula[0][ff]; + switch (f4[0]) { + case "PtgUminus": + stack.push("-" + stack.pop()); + break; + case "PtgUplus": + stack.push("+" + stack.pop()); + break; + case "PtgPercent": + stack.push(stack.pop() + "%"); + break; + case "PtgAdd": + /* [MS-XLS] 2.5.198.26 */ + case "PtgConcat": + /* [MS-XLS] 2.5.198.43 */ + case "PtgDiv": + /* [MS-XLS] 2.5.198.45 */ + case "PtgEq": + /* [MS-XLS] 2.5.198.56 */ + case "PtgGe": + /* [MS-XLS] 2.5.198.64 */ + case "PtgGt": + /* [MS-XLS] 2.5.198.65 */ + case "PtgLe": + /* [MS-XLS] 2.5.198.68 */ + case "PtgLt": + /* [MS-XLS] 2.5.198.69 */ + case "PtgMul": + /* [MS-XLS] 2.5.198.75 */ + case "PtgNe": + /* [MS-XLS] 2.5.198.78 */ + case "PtgPower": + /* [MS-XLS] 2.5.198.82 */ + case "PtgSub": + e1 = stack.pop(); + e22 = stack.pop(); + if (last_sp >= 0) { + switch (formula[0][last_sp][1][0]) { + case 0: + sp = fill(" ", formula[0][last_sp][1][1]); + break; + case 1: + sp = fill("\r", formula[0][last_sp][1][1]); + break; + default: + sp = ""; + if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]); + } + e22 = e22 + sp; + last_sp = -1; + } + stack.push(e22 + PtgBinOp[f4[0]] + e1); + break; + case "PtgIsect": + e1 = stack.pop(); + e22 = stack.pop(); + stack.push(e22 + " " + e1); + break; + case "PtgUnion": + e1 = stack.pop(); + e22 = stack.pop(); + stack.push(e22 + "," + e1); + break; + case "PtgRange": + e1 = stack.pop(); + e22 = stack.pop(); + stack.push(make_3d_range(e22, e1)); + break; + case "PtgAttrChoose": + break; + case "PtgAttrGoto": + break; + case "PtgAttrIf": + break; + case "PtgAttrIfError": + break; + case "PtgRef": + c6 = shift_cell_xls(f4[1][1], _range, opts); + stack.push(encode_cell_xls(c6, biff)); + break; + case "PtgRefN": + c6 = cell ? shift_cell_xls(f4[1][1], cell, opts) : f4[1][1]; + stack.push(encode_cell_xls(c6, biff)); + break; + case "PtgRef3d": + ixti = /*::Number(*/ + f4[1][1]; + c6 = shift_cell_xls(f4[1][2], _range, opts); + sname = get_ixti(supbooks, ixti, opts); + var w3 = sname; + stack.push(sname + "!" + encode_cell_xls(c6, biff)); + break; + case "PtgFunc": + /* [MS-XLS] 2.5.198.62 */ + case "PtgFuncVar": + var argc = f4[1][0], func = f4[1][1]; + if (!argc) argc = 0; + argc &= 127; + var args = argc == 0 ? [] : stack.slice(-argc); + stack.length -= argc; + if (func === "User") func = args.shift(); + stack.push(func + "(" + args.join(",") + ")"); + break; + case "PtgBool": + stack.push(f4[1] ? "TRUE" : "FALSE"); + break; + case "PtgInt": + stack.push( + /*::String(*/ + f4[1] + /*::)*/ + ); + break; + case "PtgNum": + stack.push(String(f4[1])); + break; + case "PtgStr": + stack.push('"' + f4[1].replace(/"/g, '""') + '"'); + break; + case "PtgErr": + stack.push( + /*::String(*/ + f4[1] + /*::)*/ + ); + break; + case "PtgAreaN": + r8 = shift_range_xls(f4[1][1], cell ? { s: cell } : _range, opts); + stack.push(encode_range_xls(r8, opts)); + break; + case "PtgArea": + r8 = shift_range_xls(f4[1][1], _range, opts); + stack.push(encode_range_xls(r8, opts)); + break; + case "PtgArea3d": + ixti = /*::Number(*/ + f4[1][1]; + r8 = f4[1][2]; + sname = get_ixti(supbooks, ixti, opts); + stack.push(sname + "!" + encode_range_xls(r8, opts)); + break; + case "PtgAttrSum": + stack.push("SUM(" + stack.pop() + ")"); + break; + case "PtgAttrBaxcel": + /* [MS-XLS] 2.5.198.33 */ + case "PtgAttrSemi": + break; + case "PtgName": + nameidx = f4[1][2]; + var lbl = (supbooks.names || [])[nameidx - 1] || (supbooks[0] || [])[nameidx]; + var name = lbl ? lbl.Name : "SH33TJSNAME" + String(nameidx); + if (name && name.slice(0, 6) == "_xlfn." && !opts.xlfn) name = name.slice(6); + stack.push(name); + break; + case "PtgNameX": + var bookidx = f4[1][1]; + nameidx = f4[1][2]; + var externbook; + if (opts.biff <= 5) { + if (bookidx < 0) bookidx = -bookidx; + if (supbooks[bookidx]) externbook = supbooks[bookidx][nameidx]; + } else { + var o9 = ""; + if (((supbooks[bookidx] || [])[0] || [])[0] == 14849) { + } else if (((supbooks[bookidx] || [])[0] || [])[0] == 1025) { + if (supbooks[bookidx][nameidx] && supbooks[bookidx][nameidx].itab > 0) { + o9 = supbooks.SheetNames[supbooks[bookidx][nameidx].itab - 1] + "!"; + } + } else o9 = supbooks.SheetNames[nameidx - 1] + "!"; + if (supbooks[bookidx] && supbooks[bookidx][nameidx]) o9 += supbooks[bookidx][nameidx].Name; + else if (supbooks[0] && supbooks[0][nameidx]) o9 += supbooks[0][nameidx].Name; + else { + var ixtidata = (get_ixti_raw(supbooks, bookidx, opts) || "").split(";;"); + if (ixtidata[nameidx - 1]) o9 = ixtidata[nameidx - 1]; + else o9 += "SH33TJSERRX"; + } + stack.push(o9); + break; + } + if (!externbook) externbook = { Name: "SH33TJSERRY" }; + stack.push(externbook.Name); + break; + case "PtgParen": + var lp = "(", rp = ")"; + if (last_sp >= 0) { + sp = ""; + switch (formula[0][last_sp][1][0]) { + // $FlowIgnore + case 2: + lp = fill(" ", formula[0][last_sp][1][1]) + lp; + break; + // $FlowIgnore + case 3: + lp = fill("\r", formula[0][last_sp][1][1]) + lp; + break; + // $FlowIgnore + case 4: + rp = fill(" ", formula[0][last_sp][1][1]) + rp; + break; + // $FlowIgnore + case 5: + rp = fill("\r", formula[0][last_sp][1][1]) + rp; + break; + default: + if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + formula[0][last_sp][1][0]); + } + last_sp = -1; + } + stack.push(lp + stack.pop() + rp); + break; + case "PtgRefErr": + stack.push("#REF!"); + break; + case "PtgRefErr3d": + stack.push("#REF!"); + break; + case "PtgExp": + c6 = { c: f4[1][1], r: f4[1][0] }; + var q2 = { c: cell.c, r: cell.r }; + if (supbooks.sharedf[encode_cell(c6)]) { + var parsedf = supbooks.sharedf[encode_cell(c6)]; + stack.push(stringify_formula(parsedf, _range, q2, supbooks, opts)); + } else { + var fnd = false; + for (e1 = 0; e1 != supbooks.arrayf.length; ++e1) { + e22 = supbooks.arrayf[e1]; + if (c6.c < e22[0].s.c || c6.c > e22[0].e.c) continue; + if (c6.r < e22[0].s.r || c6.r > e22[0].e.r) continue; + stack.push(stringify_formula(e22[1], _range, q2, supbooks, opts)); + fnd = true; + break; + } + if (!fnd) stack.push( + /*::String(*/ + f4[1] + /*::)*/ + ); + } + break; + case "PtgArray": + stack.push("{" + stringify_array( + /*::(*/ + f4[1] + /*:: :any)*/ + ) + "}"); + break; + case "PtgMemArea": + break; + case "PtgAttrSpace": + /* [MS-XLS] 2.5.198.38 */ + case "PtgAttrSpaceSemi": + last_sp = ff; + break; + case "PtgTbl": + break; + case "PtgMemErr": + break; + case "PtgMissArg": + stack.push(""); + break; + case "PtgAreaErr": + stack.push("#REF!"); + break; + case "PtgAreaErr3d": + stack.push("#REF!"); + break; + case "PtgList": + stack.push("Table" + f4[1].idx + "[#" + f4[1].rt + "]"); + break; + case "PtgMemAreaN": + case "PtgMemNoMemN": + case "PtgAttrNoop": + case "PtgSheet": + case "PtgEndSheet": + break; + case "PtgMemFunc": + break; + case "PtgMemNoMem": + break; + case "PtgElfCol": + /* [MS-XLS] 2.5.198.46 */ + case "PtgElfColS": + /* [MS-XLS] 2.5.198.47 */ + case "PtgElfColSV": + /* [MS-XLS] 2.5.198.48 */ + case "PtgElfColV": + /* [MS-XLS] 2.5.198.49 */ + case "PtgElfLel": + /* [MS-XLS] 2.5.198.50 */ + case "PtgElfRadical": + /* [MS-XLS] 2.5.198.51 */ + case "PtgElfRadicalLel": + /* [MS-XLS] 2.5.198.52 */ + case "PtgElfRadicalS": + /* [MS-XLS] 2.5.198.53 */ + case "PtgElfRw": + /* [MS-XLS] 2.5.198.54 */ + case "PtgElfRwV": + throw new Error("Unsupported ELFs"); + case "PtgSxName": + throw new Error("Unrecognized Formula Token: " + String(f4)); + default: + throw new Error("Unrecognized Formula Token: " + String(f4)); + } + var PtgNonDisp = ["PtgAttrSpace", "PtgAttrSpaceSemi", "PtgAttrGoto"]; + if (opts.biff != 3) { + if (last_sp >= 0 && PtgNonDisp.indexOf(formula[0][ff][0]) == -1) { + f4 = formula[0][last_sp]; + var _left = true; + switch (f4[1][0]) { + /* note: some bad XLSB files omit the PtgParen */ + case 4: + _left = false; + /* falls through */ + case 0: + sp = fill(" ", f4[1][1]); + break; + case 5: + _left = false; + /* falls through */ + case 1: + sp = fill("\r", f4[1][1]); + break; + default: + sp = ""; + if (opts.WTF) throw new Error("Unexpected PtgAttrSpaceType " + f4[1][0]); + } + stack.push((_left ? sp : "") + stack.pop() + (_left ? "" : sp)); + last_sp = -1; + } + } + } + if (stack.length > 1 && opts.WTF) throw new Error("bad formula stack"); + if (stack[0] == "TRUE") return true; + if (stack[0] == "FALSE") return false; + return stack[0]; +} +function parse_ArrayParsedFormula(blob, length, opts) { + var target = blob.l + length, len = opts.biff == 2 ? 1 : 2; + var rgcb, cce = blob.read_shift(len); + if (cce == 65535) return [[], parsenoop(blob, length - 2)]; + var rgce = parse_Rgce(blob, cce, opts); + if (length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts); + blob.l = target; + return [rgce, rgcb]; +} +function parse_XLSCellParsedFormula(blob, length, opts) { + var target = blob.l + length, len = opts.biff == 2 ? 1 : 2; + var rgcb, cce = blob.read_shift(len); + if (cce == 65535) return [[], parsenoop(blob, length - 2)]; + var rgce = parse_Rgce(blob, cce, opts); + if (length !== cce + len) rgcb = parse_RgbExtra(blob, length - cce - len, rgce, opts); + blob.l = target; + return [rgce, rgcb]; +} +function parse_NameParsedFormula(blob, length, opts, cce) { + var target = blob.l + length; + var rgce = parse_Rgce(blob, cce, opts); + var rgcb; + if (target !== blob.l) rgcb = parse_RgbExtra(blob, target - blob.l, rgce, opts); + return [rgce, rgcb]; +} +function parse_SharedParsedFormula(blob, length, opts) { + var target = blob.l + length; + var rgcb, cce = blob.read_shift(2); + var rgce = parse_Rgce(blob, cce, opts); + if (cce == 65535) return [[], parsenoop(blob, length - 2)]; + if (length !== cce + 2) rgcb = parse_RgbExtra(blob, target - cce - 2, rgce, opts); + return [rgce, rgcb]; +} +function parse_FormulaValue(blob) { + var b4; + if (__readUInt16LE(blob, blob.l + 6) !== 65535) return [parse_Xnum(blob), "n"]; + switch (blob[blob.l]) { + case 0: + blob.l += 8; + return ["String", "s"]; + case 1: + b4 = blob[blob.l + 2] === 1; + blob.l += 8; + return [b4, "b"]; + case 2: + b4 = blob[blob.l + 2]; + blob.l += 8; + return [b4, "e"]; + case 3: + blob.l += 8; + return ["", "s"]; + } + return []; +} +function parse_Formula(blob, length, opts) { + var end = blob.l + length; + var cell = parse_XLSCell(blob, 6, opts); + var val2 = parse_FormulaValue(blob, 8); + var flags = blob.read_shift(1); + if (opts.biff != 2) { + blob.read_shift(1); + if (opts.biff >= 5) { + blob.read_shift(4); + } + } + var cbf = parse_XLSCellParsedFormula(blob, end - blob.l, opts); + return { cell, val: val2[0], formula: cbf, shared: flags >> 3 & 1, tt: val2[1] }; +} +function parse_XLSBParsedFormula(data, length, opts) { + var cce = data.read_shift(4); + var rgce = parse_Rgce(data, cce, opts); + var cb = data.read_shift(4); + var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null; + return [rgce, rgcb]; +} +function ods_to_csf_formula(f4) { + if (f4.slice(0, 3) == "of:") f4 = f4.slice(3); + if (f4.charCodeAt(0) == 61) { + f4 = f4.slice(1); + if (f4.charCodeAt(0) == 61) f4 = f4.slice(1); + } + f4 = f4.replace(/COM\.MICROSOFT\./g, ""); + f4 = f4.replace(/\[((?:\.[A-Z]+[0-9]+)(?::\.[A-Z]+[0-9]+)?)\]/g, function($$, $1) { + return $1.replace(/\./g, ""); + }); + f4 = f4.replace(/\$'([^']|'')+'/g, function($$) { + return $$.slice(1); + }); + f4 = f4.replace(/\$([^\]\. #$]+)/g, function($$, $1) { + return $1.match(/^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])?(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})?$/) ? $$ : $1; + }); + f4 = f4.replace(/\[.(#[A-Z]*[?!])\]/g, "$1"); + return f4.replace(/[;~]/g, ",").replace(/\|/g, ";"); +} +function ods_to_csf_3D(r8) { + r8 = r8.replace(/\$'([^']|'')+'/g, function($$) { + return $$.slice(1); + }); + r8 = r8.replace(/\$([^\]\. #$]+)/g, function($$, $1) { + return $1.match(/^([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])?(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})?$/) ? $$ : $1; + }); + var a3 = r8.split(":"); + var s6 = a3[0].split(".")[0]; + return [s6, a3[0].split(".")[1] + (a3.length > 1 ? ":" + (a3[1].split(".")[1] || a3[1].split(".")[0]) : "")]; +} +function default_margins(margins, mode) { + if (!margins) return; + var defs = [0.7, 0.7, 0.75, 0.75, 0.3, 0.3]; + if (mode == "xlml") defs = [1, 1, 1, 1, 0.5, 0.5]; + if (margins.left == null) margins.left = defs[0]; + if (margins.right == null) margins.right = defs[1]; + if (margins.top == null) margins.top = defs[2]; + if (margins.bottom == null) margins.bottom = defs[3]; + if (margins.header == null) margins.header = defs[4]; + if (margins.footer == null) margins.footer = defs[5]; +} +function safe_format(p4, fmtid, fillid, opts, themes, styles2, date1904) { + try { + if (opts.cellNF) p4.z = table_fmt[fmtid]; + } catch (e9) { + if (opts.WTF) throw e9; + } + if (p4.t === "z" && !opts.cellStyles) return; + if (p4.t === "d" && typeof p4.v === "string") p4.v = parseDate(p4.v); + if ((!opts || opts.cellText !== false) && p4.t !== "z") try { + if (table_fmt[fmtid] == null) SSF__load(SSFImplicit[fmtid] || "General", fmtid); + if (p4.t === "e") p4.w = p4.w || BErr[p4.v]; + else if (fmtid === 0) { + if (p4.t === "n") { + if ((p4.v | 0) === p4.v) p4.w = p4.v.toString(10); + else p4.w = SSF_general_num(p4.v); + } else if (p4.t === "d") { + var dd = datenum(p4.v, !!date1904); + if ((dd | 0) === dd) p4.w = dd.toString(10); + else p4.w = SSF_general_num(dd); + } else if (p4.v === void 0) return ""; + else p4.w = SSF_general(p4.v, _ssfopts); + } else if (p4.t === "d") p4.w = SSF_format(fmtid, datenum(p4.v, !!date1904), _ssfopts); + else p4.w = SSF_format(fmtid, p4.v, _ssfopts); + } catch (e9) { + if (opts.WTF) throw e9; + } + if (!opts.cellStyles) return; + if (fillid != null) try { + p4.s = styles2.Fills[fillid]; + if (p4.s.fgColor && p4.s.fgColor.theme && !p4.s.fgColor.rgb) { + p4.s.fgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p4.s.fgColor.theme].rgb, p4.s.fgColor.tint || 0); + if (opts.WTF) p4.s.fgColor.raw_rgb = themes.themeElements.clrScheme[p4.s.fgColor.theme].rgb; + } + if (p4.s.bgColor && p4.s.bgColor.theme) { + p4.s.bgColor.rgb = rgb_tint(themes.themeElements.clrScheme[p4.s.bgColor.theme].rgb, p4.s.bgColor.tint || 0); + if (opts.WTF) p4.s.bgColor.raw_rgb = themes.themeElements.clrScheme[p4.s.bgColor.theme].rgb; + } + } catch (e9) { + if (opts.WTF && styles2.Fills) throw e9; + } +} +function parse_ws_xml_dim(ws, s6) { + var d4 = safe_decode_range(s6); + if (d4.s.r <= d4.e.r && d4.s.c <= d4.e.c && d4.s.r >= 0 && d4.s.c >= 0) ws["!ref"] = encode_range(d4); +} +function parse_ws_xml(data, opts, idx, rels, wb, themes, styles2) { + if (!data) return data; + if (!rels) rels = { "!id": {} }; + if (DENSE != null && opts.dense == null) opts.dense = DENSE; + var s6 = {}; + if (opts.dense) s6["!data"] = []; + var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } }; + var data1 = "", data2 = ""; + var mtch = str_match_xml_ns(data, "sheetData"); + if (mtch) { + data1 = data.slice(0, mtch.index); + data2 = data.slice(mtch.index + mtch[0].length); + } else data1 = data2 = data; + var sheetPr = data1.match(sheetprregex); + if (sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s6, wb, idx); + else if (sheetPr = str_match_xml_ns(data1, "sheetPr")) parse_ws_xml_sheetpr2(sheetPr[0], sheetPr[1] || "", s6, wb, idx, styles2, themes); + var ridx = (data1.match(/<(?:\w*:)?dimension/) || { index: -1 }).index; + if (ridx > 0) { + var ref = data1.slice(ridx, ridx + 50).match(dimregex); + if (ref && !(opts && opts.nodim)) parse_ws_xml_dim(s6, ref[1]); + } + var svs = str_match_xml_ns(data1, "sheetViews"); + if (svs && svs[1]) parse_ws_xml_sheetviews(svs[1], wb); + var columns = []; + if (opts.cellStyles) { + var cols = data1.match(colregex); + if (cols) parse_ws_xml_cols(columns, cols); + } + if (mtch) parse_ws_xml_data(mtch[1], s6, opts, refguess, themes, styles2, wb); + var afilter = data2.match(afregex); + if (afilter) s6["!autofilter"] = parse_ws_xml_autofilter(afilter[0]); + var merges = []; + var _merge = data2.match(mergecregex); + if (_merge) for (ridx = 0; ridx != _merge.length; ++ridx) + merges[ridx] = safe_decode_range(_merge[ridx].slice(_merge[ridx].indexOf("=") + 2)); + var hlink = data2.match(hlinkregex); + if (hlink) parse_ws_xml_hlinks(s6, hlink, rels); + var margins = data2.match(marginregex); + if (margins) s6["!margins"] = parse_ws_xml_margins(parsexmltag(margins[0])); + var m4; + if (m4 = data2.match(/legacyDrawing r:id="(.*?)"/)) s6["!legrel"] = m4[1]; + if (opts && opts.nodim) refguess.s.c = refguess.s.r = 0; + if (!s6["!ref"] && refguess.e.c >= refguess.s.c && refguess.e.r >= refguess.s.r) s6["!ref"] = encode_range(refguess); + if (opts.sheetRows > 0 && s6["!ref"]) { + var tmpref = safe_decode_range(s6["!ref"]); + if (opts.sheetRows <= +tmpref.e.r) { + tmpref.e.r = opts.sheetRows - 1; + if (tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r; + if (tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r; + if (tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c; + if (tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c; + s6["!fullref"] = s6["!ref"]; + s6["!ref"] = encode_range(tmpref); + } + } + if (columns.length > 0) s6["!cols"] = columns; + if (merges.length > 0) s6["!merges"] = merges; + if (rels["!id"][s6["!legrel"]]) s6["!legdrawel"] = rels["!id"][s6["!legrel"]]; + return s6; +} +function parse_ws_xml_sheetpr(sheetPr, s6, wb, idx) { + var data = parsexmltag(sheetPr); + if (!wb.Sheets[idx]) wb.Sheets[idx] = {}; + if (data.codeName) wb.Sheets[idx].CodeName = unescapexml(utf8read(data.codeName)); +} +function parse_ws_xml_sheetpr2(sheetPr, body, s6, wb, idx) { + parse_ws_xml_sheetpr(sheetPr.slice(0, sheetPr.indexOf(">")), s6, wb, idx); +} +function parse_ws_xml_hlinks(s6, data, rels) { + var dense = s6["!data"] != null; + for (var i7 = 0; i7 != data.length; ++i7) { + var val2 = parsexmltag(utf8read(data[i7]), true); + if (!val2.ref) return; + var rel2 = ((rels || {})["!id"] || [])[val2.id]; + if (rel2) { + val2.Target = rel2.Target; + if (val2.location) val2.Target += "#" + unescapexml(val2.location); + } else { + val2.Target = "#" + unescapexml(val2.location); + rel2 = { Target: val2.Target, TargetMode: "Internal" }; + } + val2.Rel = rel2; + if (val2.tooltip) { + val2.Tooltip = val2.tooltip; + delete val2.tooltip; + } + var rng = safe_decode_range(val2.ref); + for (var R3 = rng.s.r; R3 <= rng.e.r; ++R3) for (var C3 = rng.s.c; C3 <= rng.e.c; ++C3) { + var addr = encode_col(C3) + encode_row(R3); + if (dense) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + if (!s6["!data"][R3][C3]) s6["!data"][R3][C3] = { t: "z", v: void 0 }; + s6["!data"][R3][C3].l = val2; + } else { + if (!s6[addr]) s6[addr] = { t: "z", v: void 0 }; + s6[addr].l = val2; + } + } + } +} +function parse_ws_xml_margins(margin) { + var o9 = {}; + ["left", "right", "top", "bottom", "header", "footer"].forEach(function(k2) { + if (margin[k2]) o9[k2] = parseFloat(margin[k2]); + }); + return o9; +} +function parse_ws_xml_cols(columns, cols) { + var seencol = false; + for (var coli = 0; coli != cols.length; ++coli) { + var coll = parsexmltag(cols[coli], true); + if (coll.hidden) coll.hidden = parsexmlbool(coll.hidden); + var colm = parseInt(coll.min, 10) - 1, colM = parseInt(coll.max, 10) - 1; + if (coll.outlineLevel) coll.level = +coll.outlineLevel || 0; + delete coll.min; + delete coll.max; + coll.width = +coll.width; + if (!seencol && coll.width) { + seencol = true; + find_mdw_colw(coll.width); + } + process_col(coll); + while (colm <= colM) columns[colm++] = dup(coll); + } +} +function parse_ws_xml_autofilter(data) { + var o9 = { ref: (data.match(/ref="([^"]*)"/) || [])[1] }; + return o9; +} +function parse_ws_xml_sheetviews(data, wb) { + if (!wb.Views) wb.Views = [{}]; + (data.match(sviewregex) || []).forEach(function(r8, i7) { + var tag = parsexmltag(r8); + if (!wb.Views[i7]) wb.Views[i7] = {}; + if (+tag.zoomScale) wb.Views[i7].zoom = +tag.zoomScale; + if (tag.rightToLeft && parsexmlbool(tag.rightToLeft)) wb.Views[i7].RTL = true; + }); +} +function parse_BrtRowHdr(data, length) { + var z3 = {}; + var tgt = data.l + length; + z3.r = data.read_shift(4); + data.l += 4; + var miyRw = data.read_shift(2); + data.l += 1; + var flags = data.read_shift(1); + data.l = tgt; + if (flags & 7) z3.level = flags & 7; + if (flags & 16) z3.hidden = true; + if (flags & 32) z3.hpt = miyRw / 20; + return z3; +} +function parse_BrtWsFmtInfo() { +} +function parse_BrtWsProp(data, length) { + var z3 = {}; + var f4 = data[data.l]; + ++data.l; + z3.above = !(f4 & 64); + z3.left = !(f4 & 128); + data.l += 18; + z3.name = parse_XLSBCodeName(data, length - 19); + return z3; +} +function parse_BrtCellBlank(data) { + var cell = parse_XLSBCell(data); + return [cell]; +} +function parse_BrtShortBlank(data) { + var cell = parse_XLSBShortCell(data); + return [cell]; +} +function parse_BrtCellBool(data) { + var cell = parse_XLSBCell(data); + var fBool = data.read_shift(1); + return [cell, fBool, "b"]; +} +function parse_BrtShortBool(data) { + var cell = parse_XLSBShortCell(data); + var fBool = data.read_shift(1); + return [cell, fBool, "b"]; +} +function parse_BrtCellError(data) { + var cell = parse_XLSBCell(data); + var bError = data.read_shift(1); + return [cell, bError, "e"]; +} +function parse_BrtShortError(data) { + var cell = parse_XLSBShortCell(data); + var bError = data.read_shift(1); + return [cell, bError, "e"]; +} +function parse_BrtCellIsst(data) { + var cell = parse_XLSBCell(data); + var isst = data.read_shift(4); + return [cell, isst, "s"]; +} +function parse_BrtShortIsst(data) { + var cell = parse_XLSBShortCell(data); + var isst = data.read_shift(4); + return [cell, isst, "s"]; +} +function parse_BrtCellReal(data) { + var cell = parse_XLSBCell(data); + var value = parse_Xnum(data); + return [cell, value, "n"]; +} +function parse_BrtShortReal(data) { + var cell = parse_XLSBShortCell(data); + var value = parse_Xnum(data); + return [cell, value, "n"]; +} +function parse_BrtCellRk(data) { + var cell = parse_XLSBCell(data); + var value = parse_RkNumber(data); + return [cell, value, "n"]; +} +function parse_BrtShortRk(data) { + var cell = parse_XLSBShortCell(data); + var value = parse_RkNumber(data); + return [cell, value, "n"]; +} +function parse_BrtCellRString(data) { + var cell = parse_XLSBCell(data); + var value = parse_RichStr(data); + return [cell, value, "is"]; +} +function parse_BrtCellSt(data) { + var cell = parse_XLSBCell(data); + var value = parse_XLWideString(data); + return [cell, value, "str"]; +} +function parse_BrtShortSt(data) { + var cell = parse_XLSBShortCell(data); + var value = parse_XLWideString(data); + return [cell, value, "str"]; +} +function parse_BrtFmlaBool(data, length, opts) { + var end = data.l + length; + var cell = parse_XLSBCell(data); + cell.r = opts["!row"]; + var value = data.read_shift(1); + var o9 = [cell, value, "b"]; + if (opts.cellFormula) { + data.l += 2; + var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts); + o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts); + } else data.l = end; + return o9; +} +function parse_BrtFmlaError(data, length, opts) { + var end = data.l + length; + var cell = parse_XLSBCell(data); + cell.r = opts["!row"]; + var value = data.read_shift(1); + var o9 = [cell, value, "e"]; + if (opts.cellFormula) { + data.l += 2; + var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts); + o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts); + } else data.l = end; + return o9; +} +function parse_BrtFmlaNum(data, length, opts) { + var end = data.l + length; + var cell = parse_XLSBCell(data); + cell.r = opts["!row"]; + var value = parse_Xnum(data); + var o9 = [cell, value, "n"]; + if (opts.cellFormula) { + data.l += 2; + var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts); + o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts); + } else data.l = end; + return o9; +} +function parse_BrtFmlaString(data, length, opts) { + var end = data.l + length; + var cell = parse_XLSBCell(data); + cell.r = opts["!row"]; + var value = parse_XLWideString(data); + var o9 = [cell, value, "str"]; + if (opts.cellFormula) { + data.l += 2; + var formula = parse_XLSBCellParsedFormula(data, end - data.l, opts); + o9[3] = stringify_formula(formula, null, cell, opts.supbooks, opts); + } else data.l = end; + return o9; +} +function parse_BrtHLink(data, length) { + var end = data.l + length; + var rfx = parse_UncheckedRfX(data, 16); + var relId = parse_XLNullableWideString(data); + var loc = parse_XLWideString(data); + var tooltip = parse_XLWideString(data); + var display = parse_XLWideString(data); + data.l = end; + var o9 = { rfx, relId, loc, display }; + if (tooltip) o9.Tooltip = tooltip; + return o9; +} +function parse_BrtPane() { +} +function parse_BrtArrFmla(data, length, opts) { + var end = data.l + length; + var rfx = parse_RfX(data, 16); + var fAlwaysCalc = data.read_shift(1); + var o9 = [rfx]; + o9[2] = fAlwaysCalc; + if (opts.cellFormula) { + var formula = parse_XLSBArrayParsedFormula(data, end - data.l, opts); + o9[1] = formula; + } else data.l = end; + return o9; +} +function parse_BrtShrFmla(data, length, opts) { + var end = data.l + length; + var rfx = parse_UncheckedRfX(data, 16); + var o9 = [rfx]; + if (opts.cellFormula) { + var formula = parse_XLSBSharedParsedFormula(data, end - data.l, opts); + o9[1] = formula; + data.l = end; + } else data.l = end; + return o9; +} +function parse_BrtMargins(data) { + var margins = {}; + BrtMarginKeys.forEach(function(k2) { + margins[k2] = parse_Xnum(data, 8); + }); + return margins; +} +function parse_BrtBeginWsView(data) { + var f4 = data.read_shift(2); + data.l += 28; + return { RTL: f4 & 32 }; +} +function parse_BrtDVal() { +} +function parse_BrtDVal14() { +} +function parse_ws_bin(data, _opts, idx, rels, wb, themes, styles2) { + if (!data) return data; + var opts = _opts || {}; + if (!rels) rels = { "!id": {} }; + if (DENSE != null && opts.dense == null) opts.dense = DENSE; + var s6 = {}; + if (opts.dense) s6["!data"] = []; + var ref; + var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } }; + var state = []; + var pass = false, end = false; + var row, p4, cf, R3, C3, addr, sstr, rr, cell; + var merges = []; + opts.biff = 12; + opts["!row"] = 0; + var ai = 0, af = false; + var arrayf = []; + var sharedf = {}; + var supbooks = opts.supbooks || /*::(*/ + wb.supbooks || [[]]; + supbooks.sharedf = sharedf; + supbooks.arrayf = arrayf; + supbooks.SheetNames = wb.SheetNames || wb.Sheets.map(function(x2) { + return x2.name; + }); + if (!opts.supbooks) { + opts.supbooks = supbooks; + if (wb.Names) for (var i7 = 0; i7 < wb.Names.length; ++i7) supbooks[0][i7 + 1] = wb.Names[i7]; + } + var colinfo = [], rowinfo = []; + var seencol = false; + XLSBRecordEnum[16] = { n: "BrtShortReal", f: parse_BrtShortReal }; + var cm, vm; + var date1904 = 1462 * +!!((wb || {}).WBProps || {}).date1904; + recordhopper(data, function ws_parse(val2, RR, RT) { + if (end) return; + switch (RT) { + case 148: + ref = val2; + break; + case 0: + row = val2; + if (opts.sheetRows && opts.sheetRows <= row.r) end = true; + rr = encode_row(R3 = row.r); + opts["!row"] = row.r; + if (val2.hidden || val2.hpt || val2.level != null) { + if (val2.hpt) val2.hpx = pt2px(val2.hpt); + rowinfo[val2.r] = val2; + } + break; + case 2: + /* 'BrtCellRk' */ + case 3: + /* 'BrtCellError' */ + case 4: + /* 'BrtCellBool' */ + case 5: + /* 'BrtCellReal' */ + case 6: + /* 'BrtCellSt' */ + case 7: + /* 'BrtCellIsst' */ + case 8: + /* 'BrtFmlaString' */ + case 9: + /* 'BrtFmlaNum' */ + case 10: + /* 'BrtFmlaBool' */ + case 11: + /* 'BrtFmlaError' */ + case 13: + /* 'BrtShortRk' */ + case 14: + /* 'BrtShortError' */ + case 15: + /* 'BrtShortBool' */ + case 16: + /* 'BrtShortReal' */ + case 17: + /* 'BrtShortSt' */ + case 18: + /* 'BrtShortIsst' */ + case 62: + p4 = { t: val2[2] }; + switch (val2[2]) { + case "n": + p4.v = val2[1]; + break; + case "s": + sstr = strs[val2[1]]; + p4.v = sstr.t; + p4.r = sstr.r; + break; + case "b": + p4.v = val2[1] ? true : false; + break; + case "e": + p4.v = val2[1]; + if (opts.cellText !== false) p4.w = BErr[p4.v]; + break; + case "str": + p4.t = "s"; + p4.v = val2[1]; + break; + case "is": + p4.t = "s"; + p4.v = val2[1].t; + break; + } + if (cf = styles2.CellXf[val2[0].iStyleRef]) safe_format(p4, cf.numFmtId, null, opts, themes, styles2, date1904 > 0); + C3 = val2[0].c == -1 ? C3 + 1 : val2[0].c; + if (opts.dense) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + s6["!data"][R3][C3] = p4; + } else s6[encode_col(C3) + rr] = p4; + if (opts.cellFormula) { + af = false; + for (ai = 0; ai < arrayf.length; ++ai) { + var aii = arrayf[ai]; + if (row.r >= aii[0].s.r && row.r <= aii[0].e.r) { + if (C3 >= aii[0].s.c && C3 <= aii[0].e.c) { + p4.F = encode_range(aii[0]); + af = true; + } + } + } + if (!af && val2.length > 3) p4.f = val2[3]; + } + if (refguess.s.r > row.r) refguess.s.r = row.r; + if (refguess.s.c > C3) refguess.s.c = C3; + if (refguess.e.r < row.r) refguess.e.r = row.r; + if (refguess.e.c < C3) refguess.e.c = C3; + if (opts.cellDates && cf && p4.t == "n" && fmt_is_date(table_fmt[cf.numFmtId])) { + var _d = SSF_parse_date_code(p4.v + date1904); + if (_d) { + p4.t = "d"; + p4.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u)); + } + } + if (cm) { + if (cm.type == "XLDAPR") p4.D = true; + cm = void 0; + } + if (vm) vm = void 0; + break; + case 1: + /* 'BrtCellBlank' */ + case 12: + if (!opts.sheetStubs || pass) break; + p4 = { t: "z", v: void 0 }; + C3 = val2[0].c == -1 ? C3 + 1 : val2[0].c; + if (opts.dense) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + s6["!data"][R3][C3] = p4; + } else s6[encode_col(C3) + rr] = p4; + if (refguess.s.r > row.r) refguess.s.r = row.r; + if (refguess.s.c > C3) refguess.s.c = C3; + if (refguess.e.r < row.r) refguess.e.r = row.r; + if (refguess.e.c < C3) refguess.e.c = C3; + if (cm) { + if (cm.type == "XLDAPR") p4.D = true; + cm = void 0; + } + if (vm) vm = void 0; + break; + case 176: + merges.push(val2); + break; + case 49: + { + cm = ((opts.xlmeta || {}).Cell || [])[val2 - 1]; + } + break; + case 494: + var rel2 = rels["!id"][val2.relId]; + if (rel2) { + val2.Target = rel2.Target; + if (val2.loc) val2.Target += "#" + val2.loc; + val2.Rel = rel2; + } else if (val2.relId == "") { + val2.Target = "#" + val2.loc; + } + for (R3 = val2.rfx.s.r; R3 <= val2.rfx.e.r; ++R3) for (C3 = val2.rfx.s.c; C3 <= val2.rfx.e.c; ++C3) { + if (opts.dense) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + if (!s6["!data"][R3][C3]) s6["!data"][R3][C3] = { t: "z", v: void 0 }; + s6["!data"][R3][C3].l = val2; + } else { + addr = encode_col(C3) + encode_row(R3); + if (!s6[addr]) s6[addr] = { t: "z", v: void 0 }; + s6[addr].l = val2; + } + } + break; + case 426: + if (!opts.cellFormula) break; + arrayf.push(val2); + cell = opts.dense ? s6["!data"][R3][C3] : s6[encode_col(C3) + rr]; + cell.f = stringify_formula(val2[1], refguess, { r: row.r, c: C3 }, supbooks, opts); + cell.F = encode_range(val2[0]); + break; + case 427: + if (!opts.cellFormula) break; + sharedf[encode_cell(val2[0].s)] = val2[1]; + cell = opts.dense ? s6["!data"][R3][C3] : s6[encode_col(C3) + rr]; + cell.f = stringify_formula(val2[1], refguess, { r: row.r, c: C3 }, supbooks, opts); + break; + /* identical to 'ColInfo' in XLS */ + case 60: + if (!opts.cellStyles) break; + while (val2.e >= val2.s) { + colinfo[val2.e--] = { width: val2.w / 256, hidden: !!(val2.flags & 1), level: val2.level }; + if (!seencol) { + seencol = true; + find_mdw_colw(val2.w / 256); + } + process_col(colinfo[val2.e + 1]); + } + break; + case 551: + if (val2) s6["!legrel"] = val2; + break; + case 161: + s6["!autofilter"] = { ref: encode_range(val2) }; + break; + case 476: + s6["!margins"] = val2; + break; + case 147: + if (!wb.Sheets[idx]) wb.Sheets[idx] = {}; + if (val2.name) wb.Sheets[idx].CodeName = val2.name; + if (val2.above || val2.left) s6["!outline"] = { above: val2.above, left: val2.left }; + break; + case 137: + if (!wb.Views) wb.Views = [{}]; + if (!wb.Views[0]) wb.Views[0] = {}; + if (val2.RTL) wb.Views[0].RTL = true; + break; + case 485: + break; + case 64: + /* 'BrtDVal' */ + case 1053: + break; + case 151: + break; + case 152: + /* 'BrtSel' */ + case 175: + /* 'BrtAFilterDateGroupItem' */ + case 644: + /* 'BrtActiveX' */ + case 625: + /* 'BrtBigName' */ + case 562: + /* 'BrtBkHim' */ + case 396: + /* 'BrtBrk' */ + case 1112: + /* 'BrtCFIcon' */ + case 1146: + /* 'BrtCFRuleExt' */ + case 471: + /* 'BrtCFVO' */ + case 1050: + /* 'BrtCFVO14' */ + case 649: + /* 'BrtCellIgnoreEC' */ + case 1105: + /* 'BrtCellIgnoreEC14' */ + case 589: + /* 'BrtCellSmartTagProperty' */ + case 607: + /* 'BrtCellWatch' */ + case 564: + /* 'BrtColor' */ + case 1055: + /* 'BrtColor14' */ + case 168: + /* 'BrtColorFilter' */ + case 174: + /* 'BrtCustomFilter' */ + case 1180: + /* 'BrtCustomFilter14' */ + case 499: + /* 'BrtDRef' */ + case 507: + /* 'BrtDXF' */ + case 550: + /* 'BrtDrawing' */ + case 171: + /* 'BrtDynamicFilter' */ + case 167: + /* 'BrtFilter' */ + case 1177: + /* 'BrtFilter14' */ + case 169: + /* 'BrtIconFilter' */ + case 1181: + /* 'BrtIconFilter14' */ + case 552: + /* 'BrtLegacyDrawingHF' */ + case 661: + /* 'BrtListPart' */ + case 639: + /* 'BrtOleObject' */ + case 478: + /* 'BrtPageSetup' */ + case 537: + /* 'BrtPhoneticInfo' */ + case 477: + /* 'BrtPrintOptions' */ + case 536: + /* 'BrtRangeProtection' */ + case 1103: + /* 'BrtRangeProtection14' */ + case 680: + /* 'BrtRangeProtectionIso' */ + case 1104: + /* 'BrtRangeProtectionIso14' */ + case 1024: + /* 'BrtRwDescent' */ + case 663: + /* 'BrtSheetCalcProp' */ + case 535: + /* 'BrtSheetProtection' */ + case 678: + /* 'BrtSheetProtectionIso' */ + case 504: + /* 'BrtSlc' */ + case 1043: + /* 'BrtSparkline' */ + case 428: + /* 'BrtTable' */ + case 170: + /* 'BrtTop10Filter' */ + case 3072: + /* 'BrtUid' */ + case 50: + /* 'BrtValueMeta' */ + case 2070: + /* 'BrtWebExtension' */ + case 1045: + break; + case 35: + pass = true; + break; + case 36: + pass = false; + break; + case 37: + state.push(RT); + pass = true; + break; + case 38: + state.pop(); + pass = false; + break; + default: + if (RR.T) { + } else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }, opts); + delete opts.supbooks; + delete opts["!row"]; + if (!s6["!ref"] && (refguess.s.r < 2e6 || ref && (ref.e.r > 0 || ref.e.c > 0 || ref.s.r > 0 || ref.s.c > 0))) s6["!ref"] = encode_range(ref || refguess); + if (opts.sheetRows && s6["!ref"]) { + var tmpref = safe_decode_range(s6["!ref"]); + if (opts.sheetRows <= +tmpref.e.r) { + tmpref.e.r = opts.sheetRows - 1; + if (tmpref.e.r > refguess.e.r) tmpref.e.r = refguess.e.r; + if (tmpref.e.r < tmpref.s.r) tmpref.s.r = tmpref.e.r; + if (tmpref.e.c > refguess.e.c) tmpref.e.c = refguess.e.c; + if (tmpref.e.c < tmpref.s.c) tmpref.s.c = tmpref.e.c; + s6["!fullref"] = s6["!ref"]; + s6["!ref"] = encode_range(tmpref); + } + } + if (merges.length > 0) s6["!merges"] = merges; + if (colinfo.length > 0) s6["!cols"] = colinfo; + if (rowinfo.length > 0) s6["!rows"] = rowinfo; + if (rels["!id"][s6["!legrel"]]) s6["!legdrawel"] = rels["!id"][s6["!legrel"]]; + return s6; +} +function parse_Cache(data) { + var col = []; + var num = data.match(/^/); + var f4; + (data.match(/\/]*>([^<])<\/c:v><\/c:pt>/mg) || []).forEach(function(pt) { + var q2 = pt.match(/\/]*>([^<]*)<\/c:v><\/c:pt>/); + if (!q2) return; + col[+q2[1]] = num ? +q2[2] : q2[2]; + }); + var nf = unescapexml((str_match_xml(data, "c:formatCode") || ["", "General"])[1]); + (str_match_ng(data, "", "") || []).forEach(function(F2) { + f4 = F2.replace(/<[^<>]*>/g, ""); + }); + return [col, nf, f4]; +} +function parse_chart(data, name, opts, rels, wb, csheet) { + var cs = csheet || { "!type": "chart" }; + if (!data) return csheet; + var C3 = 0, R3 = 0, col = "A"; + var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } }; + (str_match_ng(data, "", "") || []).forEach(function(nc) { + var cache = parse_Cache(nc); + refguess.s.r = refguess.s.c = 0; + refguess.e.c = C3; + col = encode_col(C3); + cache[0].forEach(function(n7, i7) { + if (cs["!data"]) { + if (!cs["!data"][i7]) cs["!data"][i7] = []; + cs["!data"][i7][C3] = { t: "n", v: n7, z: cache[1] }; + } else cs[col + encode_row(i7)] = { t: "n", v: n7, z: cache[1] }; + R3 = i7; + }); + if (refguess.e.r < R3) refguess.e.r = R3; + ++C3; + }); + if (C3 > 0) cs["!ref"] = encode_range(refguess); + return cs; +} +function parse_cs_xml(data, opts, idx, rels, wb) { + if (!data) return data; + if (!rels) rels = { "!id": {} }; + var s6 = { "!type": "chart", "!drawel": null, "!rel": "" }; + var m4; + var sheetPr = data.match(sheetprregex); + if (sheetPr) parse_ws_xml_sheetpr(sheetPr[0], s6, wb, idx); + if (m4 = data.match(/drawing r:id="(.*?)"/)) s6["!rel"] = m4[1]; + if (rels["!id"][s6["!rel"]]) s6["!drawel"] = rels["!id"][s6["!rel"]]; + return s6; +} +function parse_BrtCsProp(data, length) { + data.l += 10; + var name = parse_XLWideString(data, length - 10); + return { name }; +} +function parse_cs_bin(data, opts, idx, rels, wb) { + if (!data) return data; + if (!rels) rels = { "!id": {} }; + var s6 = { "!type": "chart", "!drawel": null, "!rel": "" }; + var state = []; + var pass = false; + recordhopper(data, function cs_parse(val2, R3, RT) { + switch (RT) { + case 550: + s6["!rel"] = val2; + break; + case 651: + if (!wb.Sheets[idx]) wb.Sheets[idx] = {}; + if (val2.name) wb.Sheets[idx].CodeName = val2.name; + break; + case 562: + /* 'BrtBkHim' */ + case 652: + /* 'BrtCsPageSetup' */ + case 669: + /* 'BrtCsProtection' */ + case 679: + /* 'BrtCsProtectionIso' */ + case 551: + /* 'BrtLegacyDrawing' */ + case 552: + /* 'BrtLegacyDrawingHF' */ + case 476: + /* 'BrtMargins' */ + case 3072: + break; + case 35: + pass = true; + break; + case 36: + pass = false; + break; + case 37: + state.push(RT); + break; + case 38: + state.pop(); + break; + default: + if (R3.T > 0) state.push(RT); + else if (R3.T < 0) state.pop(); + else if (!pass || opts.WTF) throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }, opts); + if (rels["!id"][s6["!rel"]]) s6["!drawel"] = rels["!id"][s6["!rel"]]; + return s6; +} +function push_defaults_array(target, defaults4) { + for (var j3 = 0; j3 != target.length; ++j3) { + var w3 = target[j3]; + for (var i7 = 0; i7 != defaults4.length; ++i7) { + var z3 = defaults4[i7]; + if (w3[z3[0]] == null) w3[z3[0]] = z3[1]; + else switch (z3[2]) { + case "bool": + if (typeof w3[z3[0]] == "string") w3[z3[0]] = parsexmlbool(w3[z3[0]]); + break; + case "int": + if (typeof w3[z3[0]] == "string") w3[z3[0]] = parseInt(w3[z3[0]], 10); + break; + } + } + } +} +function push_defaults(target, defaults4) { + for (var i7 = 0; i7 != defaults4.length; ++i7) { + var z3 = defaults4[i7]; + if (target[z3[0]] == null) target[z3[0]] = z3[1]; + else switch (z3[2]) { + case "bool": + if (typeof target[z3[0]] == "string") target[z3[0]] = parsexmlbool(target[z3[0]]); + break; + case "int": + if (typeof target[z3[0]] == "string") target[z3[0]] = parseInt(target[z3[0]], 10); + break; + } + } +} +function parse_wb_defaults(wb) { + push_defaults(wb.WBProps, WBPropsDef); + push_defaults(wb.CalcPr, CalcPrDef); + push_defaults_array(wb.WBView, WBViewDef); + push_defaults_array(wb.Sheets, SheetDef); + _ssfopts.date1904 = parsexmlbool(wb.WBProps.date1904); +} +function check_ws_name(n7, safe) { + try { + if (n7 == "") throw new Error("Sheet name cannot be blank"); + if (n7.length > 31) throw new Error("Sheet name cannot exceed 31 chars"); + if (n7.charCodeAt(0) == 39 || n7.charCodeAt(n7.length - 1) == 39) throw new Error("Sheet name cannot start or end with apostrophe (')"); + if (n7.toLowerCase() == "history") throw new Error("Sheet name cannot be 'History'"); + badchars.forEach(function(c6) { + if (n7.indexOf(c6) == -1) return; + throw new Error("Sheet name cannot contain : \\ / ? * [ ]"); + }); + } catch (e9) { + if (safe) return false; + throw e9; + } + return true; +} +function parse_wb_xml(data, opts) { + if (!data) throw new Error("Could not find file"); + var wb = ( + /*::(*/ + { AppVersion: {}, WBProps: {}, WBView: [], Sheets: [], CalcPr: {}, Names: [], xmlns: "" } + ); + var pass = false, xmlns = "xmlns"; + var dname = {}, dnstart = 0; + data.replace(tagregex, function xml_wb(x2, idx) { + var y4 = parsexmltag(x2); + switch (strip_ns(y4[0])) { + case "": + break; + /* 18.2.13 fileVersion CT_FileVersion ? */ + case "": + case "": + break; + /* 18.2.12 fileSharing CT_FileSharing ? */ + case "": + break; + /* 18.2.28 workbookPr CT_WorkbookPr ? */ + case "": + WBPropsDef.forEach(function(w3) { + if (y4[w3[0]] == null) return; + switch (w3[2]) { + case "bool": + wb.WBProps[w3[0]] = parsexmlbool(y4[w3[0]]); + break; + case "int": + wb.WBProps[w3[0]] = parseInt(y4[w3[0]], 10); + break; + default: + wb.WBProps[w3[0]] = y4[w3[0]]; + } + }); + if (y4.codeName) wb.WBProps.CodeName = utf8read(y4.codeName); + break; + case "": + break; + /* 18.2.29 workbookProtection CT_WorkbookProtection ? */ + case "": + break; + /* 18.2.1 bookViews CT_BookViews ? */ + case "": + case "": + break; + /* 18.2.30 workbookView CT_BookView + */ + case "": + delete y4[0]; + wb.WBView.push(y4); + break; + case "": + break; + /* 18.2.20 sheets CT_Sheets 1 */ + case "": + case "": + break; + // aggregate sheet + /* 18.2.19 sheet CT_Sheet + */ + case "": + break; + /* 18.2.15 functionGroups CT_FunctionGroups ? */ + case "": + break; + /* 18.2.14 functionGroup CT_FunctionGroup + */ + case "": + case "": + break; + /* 18.2.8 externalReference CT_ExternalReference + */ + case "": + break; + case "": + case "": + pass = false; + break; + /* 18.2.5 definedName CT_DefinedName + */ + case "": + { + dname.Ref = unescapexml(utf8read(data.slice(dnstart, idx))); + wb.Names.push(dname); + } + break; + case "": + break; + /* 18.2.2 calcPr CT_CalcPr ? */ + case "": + delete y4[0]; + wb.CalcPr = y4; + break; + case "": + break; + /* 18.2.16 oleSize CT_OleSize ? (ref required) */ + case "": + case "": + case "": + break; + /* 18.2.18 pivotCaches CT_PivotCaches ? */ + case "": + case "": + case "": + break; + /* 18.2.23 smartTagTypes CT_SmartTagTypes ? */ + case "": + case "": + break; + /* 18.2.22 smartTagType CT_SmartTagType ? */ + case "": + break; + /* 18.2.11 fileRecoveryPr CT_FileRecoveryPr ? */ + case "": + break; + /* 18.2.26 webPublishObjects CT_WebPublishObjects ? */ + case "": + case "": + break; + /* 18.2.25 webPublishObject CT_WebPublishObject ? */ + case "": + case "": + case "": + break; + /* 18.2.7 ext CT_Extension + */ + case "": + pass = false; + break; + /* Others */ + case "": + pass = true; + break; + case "": + pass = false; + break; + /* TODO */ + case " 8 ? parse_XLWideString(data) : ""; + if (strName.length > 0) o9.CodeName = strName; + o9.autoCompressPictures = !!(flags & 65536); + o9.backupFile = !!(flags & 64); + o9.checkCompatibility = !!(flags & 4096); + o9.date1904 = !!(flags & 1); + o9.filterPrivacy = !!(flags & 8); + o9.hidePivotFieldList = !!(flags & 1024); + o9.promptedSolutions = !!(flags & 16); + o9.publishItems = !!(flags & 2048); + o9.refreshAllConnections = !!(flags & 262144); + o9.saveExternalLinkValues = !!(flags & 128); + o9.showBorderUnselectedTables = !!(flags & 4); + o9.showInkAnnotation = !!(flags & 32); + o9.showObjects = ["all", "placeholders", "none"][flags >> 13 & 3]; + o9.showPivotChartFilter = !!(flags & 32768); + o9.updateLinks = ["userSet", "never", "always"][flags >> 8 & 3]; + return o9; +} +function parse_BrtFRTArchID$(data, length) { + var o9 = {}; + data.read_shift(4); + o9.ArchID = data.read_shift(4); + data.l += length - 8; + return o9; +} +function parse_BrtName(data, length, opts) { + var end = data.l + length; + var flags = data.read_shift(4); + data.l += 1; + var itab = data.read_shift(4); + var name = parse_XLNameWideString(data); + var formula; + var comment = ""; + try { + formula = parse_XLSBNameParsedFormula(data, 0, opts); + try { + comment = parse_XLNullableWideString(data); + } catch (e9) { + } + } catch (e9) { + console.error("Could not parse defined name " + name); + } + if (flags & 32) name = "_xlnm." + name; + data.l = end; + var out = { Name: name, Ptg: formula, Flags: flags }; + if (itab < 268435455) out.Sheet = itab; + if (comment) out.Comment = comment; + return out; +} +function parse_wb_bin(data, opts) { + var wb = { AppVersion: {}, WBProps: {}, WBView: [], Sheets: [], CalcPr: {}, xmlns: "" }; + var state = []; + var pass = false; + if (!opts) opts = {}; + opts.biff = 12; + var Names = []; + var supbooks = [[]]; + supbooks.SheetNames = []; + supbooks.XTI = []; + XLSBRecordEnum[16] = { n: "BrtFRTArchID$", f: parse_BrtFRTArchID$ }; + recordhopper(data, function hopper_wb(val2, R3, RT) { + switch (RT) { + case 156: + supbooks.SheetNames.push(val2.name); + wb.Sheets.push(val2); + break; + case 153: + wb.WBProps = val2; + break; + case 39: + if (val2.Sheet != null) opts.SID = val2.Sheet; + val2.Ref = val2.Ptg ? stringify_formula(val2.Ptg, null, null, supbooks, opts) : "#REF!"; + delete opts.SID; + delete val2.Ptg; + Names.push(val2); + break; + case 1036: + break; + case 357: + /* 'BrtSupSelf' */ + case 358: + /* 'BrtSupSame' */ + case 355: + /* 'BrtSupBookSrc' */ + case 667: + if (!supbooks[0].length) supbooks[0] = [RT, val2]; + else supbooks.push([RT, val2]); + supbooks[supbooks.length - 1].XTI = []; + break; + case 362: + if (supbooks.length === 0) { + supbooks[0] = []; + supbooks[0].XTI = []; + } + supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val2); + supbooks.XTI = supbooks.XTI.concat(val2); + break; + case 361: + break; + case 2071: + /* 'BrtAbsPath15' */ + case 158: + /* 'BrtBookView' */ + case 143: + /* 'BrtBeginBundleShs' */ + case 664: + /* 'BrtBeginFnGroup' */ + case 353: + break; + /* case 'BrtModelTimeGroupingCalcCol' */ + case 3072: + /* 'BrtUid' */ + case 3073: + /* 'BrtRevisionPtr' */ + case 534: + /* 'BrtBookProtection' */ + case 677: + /* 'BrtBookProtectionIso' */ + case 157: + /* 'BrtCalcProp' */ + case 610: + /* 'BrtCrashRecErr' */ + case 2050: + /* 'BrtDecoupledPivotCacheID' */ + case 155: + /* 'BrtFileRecover' */ + case 548: + /* 'BrtFileSharing' */ + case 676: + /* 'BrtFileSharingIso' */ + case 128: + /* 'BrtFileVersion' */ + case 665: + /* 'BrtFnGroup' */ + case 2128: + /* 'BrtModelRelationship' */ + case 2125: + /* 'BrtModelTable' */ + case 549: + /* 'BrtOleSize' */ + case 2053: + /* 'BrtPivotTableRef' */ + case 596: + /* 'BrtSmartTagType' */ + case 2076: + /* 'BrtTableSlicerCacheID' */ + case 2075: + /* 'BrtTableSlicerCacheIDs' */ + case 2082: + /* 'BrtTimelineCachePivotCacheID' */ + case 397: + /* 'BrtUserBookView' */ + case 154: + /* 'BrtWbFactoid' */ + case 1117: + /* 'BrtWbProp14' */ + case 553: + /* 'BrtWebOpt' */ + case 2091: + break; + case 35: + state.push(RT); + pass = true; + break; + case 36: + state.pop(); + pass = false; + break; + case 37: + state.push(RT); + pass = true; + break; + case 38: + state.pop(); + pass = false; + break; + case 16: + break; + default: + if (R3.T) { + } else if (!pass || opts.WTF && state[state.length - 1] != 37 && state[state.length - 1] != 35) throw new Error("Unexpected record 0x" + RT.toString(16)); + } + }, opts); + parse_wb_defaults(wb); + wb.Names = Names; + wb.supbooks = supbooks; + return wb; +} +function parse_wb(data, name, opts) { + if (name.slice(-4) === ".bin") return parse_wb_bin(data, opts); + return parse_wb_xml(data, opts); +} +function parse_ws(data, name, idx, opts, rels, wb, themes, styles2) { + if (name.slice(-4) === ".bin") return parse_ws_bin(data, opts, idx, rels, wb, themes, styles2); + return parse_ws_xml(data, opts, idx, rels, wb, themes, styles2); +} +function parse_cs(data, name, idx, opts, rels, wb, themes, styles2) { + if (name.slice(-4) === ".bin") return parse_cs_bin(data, opts, idx, rels, wb, themes, styles2); + return parse_cs_xml(data, opts, idx, rels, wb, themes, styles2); +} +function parse_ms(data, name, idx, opts, rels, wb, themes, styles2) { + if (name.slice(-4) === ".bin") return parse_ms_bin(data, opts, idx, rels, wb, themes, styles2); + return parse_ms_xml(data, opts, idx, rels, wb, themes, styles2); +} +function parse_ds(data, name, idx, opts, rels, wb, themes, styles2) { + if (name.slice(-4) === ".bin") return parse_ds_bin(data, opts, idx, rels, wb, themes, styles2); + return parse_ds_xml(data, opts, idx, rels, wb, themes, styles2); +} +function parse_sty(data, name, themes, opts) { + if (name.slice(-4) === ".bin") return parse_sty_bin(data, themes, opts); + return parse_sty_xml(data, themes, opts); +} +function parse_sst(data, name, opts) { + if (name.slice(-4) === ".bin") return parse_sst_bin(data, opts); + return parse_sst_xml(data, opts); +} +function parse_cmnt(data, name, opts) { + if (name.slice(-4) === ".bin") return parse_comments_bin(data, opts); + return parse_comments_xml(data, opts); +} +function parse_cc(data, name, opts) { + if (name.slice(-4) === ".bin") return parse_cc_bin(data, name, opts); + return parse_cc_xml(data, name, opts); +} +function parse_xlink(data, rel2, name, opts) { + if (name.slice(-4) === ".bin") return parse_xlink_bin(data, rel2, name, opts); + return parse_xlink_xml(data, rel2, name, opts); +} +function parse_xlmeta(data, name, opts) { + if (name.slice(-4) === ".bin") return parse_xlmeta_bin(data, name, opts); + return parse_xlmeta_xml(data, name, opts); +} +function xlml_parsexmltag(tag, skip_root) { + var words = tag.split(/\s+/); + var z3 = []; + if (!skip_root) z3[0] = words[0]; + if (words.length === 1) return z3; + var m4 = tag.match(attregexg2), y4, j3, w3, i7; + if (m4) for (i7 = 0; i7 != m4.length; ++i7) { + y4 = m4[i7].match(attregex2); + if ((j3 = y4[1].indexOf(":")) === -1) z3[y4[1]] = y4[2].slice(1, y4[2].length - 1); + else { + if (y4[1].slice(0, 6) === "xmlns:") w3 = "xmlns" + y4[1].slice(6); + else w3 = y4[1].slice(j3 + 1); + z3[w3] = y4[2].slice(1, y4[2].length - 1); + } + } + return z3; +} +function xlml_parsexmltagobj(tag) { + var words = tag.split(/\s+/); + var z3 = {}; + if (words.length === 1) return z3; + var m4 = tag.match(attregexg2), y4, j3, w3, i7; + if (m4) for (i7 = 0; i7 != m4.length; ++i7) { + y4 = m4[i7].match(attregex2); + if ((j3 = y4[1].indexOf(":")) === -1) z3[y4[1]] = y4[2].slice(1, y4[2].length - 1); + else { + if (y4[1].slice(0, 6) === "xmlns:") w3 = "xmlns" + y4[1].slice(6); + else w3 = y4[1].slice(j3 + 1); + z3[w3] = y4[2].slice(1, y4[2].length - 1); + } + } + return z3; +} +function xlml_format(format2, value, date1904) { + var fmt = XLMLFormatMap[format2] || unescapexml(format2); + if (fmt === "General") return SSF_general(value); + return SSF_format(fmt, value, { date1904: !!date1904 }); +} +function xlml_set_custprop(Custprops, key, cp, val2) { + var oval = val2; + switch ((cp[0].match(/dt:dt="([\w.]+)"/) || ["", ""])[1]) { + case "boolean": + oval = parsexmlbool(val2); + break; + case "i2": + case "int": + oval = parseInt(val2, 10); + break; + case "r4": + case "float": + oval = parseFloat(val2); + break; + case "date": + case "dateTime.tz": + oval = parseDate(val2); + break; + case "i8": + case "string": + case "fixed": + case "uuid": + case "bin.base64": + break; + default: + throw new Error("bad custprop:" + cp[0]); + } + Custprops[unescapexml(key)] = oval; +} +function safe_format_xlml(cell, nf, o9, date1904) { + if (cell.t === "z") return; + if (!o9 || o9.cellText !== false) try { + if (cell.t === "e") { + cell.w = cell.w || BErr[cell.v]; + } else if (nf === "General") { + if (cell.t === "n") { + if ((cell.v | 0) === cell.v) cell.w = cell.v.toString(10); + else cell.w = SSF_general_num(cell.v); + } else cell.w = SSF_general(cell.v); + } else cell.w = xlml_format(nf || "General", cell.v, date1904); + } catch (e9) { + if (o9.WTF) throw e9; + } + try { + var z3 = XLMLFormatMap[nf] || nf || "General"; + if (o9.cellNF) cell.z = z3; + if (o9.cellDates && cell.t == "n" && fmt_is_date(z3)) { + var _d = SSF_parse_date_code(cell.v + (date1904 ? 1462 : 0)); + if (_d) { + cell.t = "d"; + cell.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u)); + } + } + } catch (e9) { + if (o9.WTF) throw e9; + } +} +function process_style_xlml(styles2, stag, opts) { + if (opts.cellStyles) { + if (stag.Interior) { + var I3 = stag.Interior; + if (I3.Pattern) I3.patternType = XLMLPatternTypeMap[I3.Pattern] || I3.Pattern; + } + } + styles2[stag.ID] = stag; +} +function parse_xlml_data(xml2, ss, data, cell, base, styles2, csty, row, arrayf, o9, date1904) { + var nf = "General", sid = cell.StyleID, S5 = {}; + o9 = o9 || {}; + var interiors = []; + var i7 = 0; + if (sid === void 0 && row) sid = row.StyleID; + if (sid === void 0 && csty) sid = csty.StyleID; + while (styles2[sid] !== void 0) { + var ssid = styles2[sid]; + if (ssid.nf) nf = ssid.nf; + if (ssid.Interior) interiors.push(ssid.Interior); + if (!ssid.Parent) break; + sid = ssid.Parent; + } + switch (data.Type) { + case "Boolean": + cell.t = "b"; + cell.v = parsexmlbool(xml2); + break; + case "String": + cell.t = "s"; + cell.r = xlml_fixstr(unescapexml(xml2)); + cell.v = xml2.indexOf("<") > -1 ? unescapexml(ss || xml2).replace(/<[^<>]*>/g, "") : cell.r; + break; + case "DateTime": + if (xml2.slice(-1) != "Z") xml2 += "Z"; + cell.v = datenum(parseDate(xml2, date1904), date1904); + if (cell.v !== cell.v) cell.v = unescapexml(xml2); + if (!nf || nf == "General") nf = "yyyy-mm-dd"; + /* falls through */ + case "Number": + if (cell.v === void 0) cell.v = +xml2; + if (!cell.t) cell.t = "n"; + break; + case "Error": + cell.t = "e"; + cell.v = RBErr[xml2]; + if (o9.cellText !== false) cell.w = xml2; + break; + default: + if (xml2 == "" && ss == "") { + cell.t = "z"; + } else { + cell.t = "s"; + cell.v = xlml_fixstr(ss || xml2); + } + break; + } + safe_format_xlml(cell, nf, o9, date1904); + if (o9.cellFormula !== false) { + if (cell.Formula) { + var fstr = unescapexml(cell.Formula); + if (fstr.charCodeAt(0) == 61) fstr = fstr.slice(1); + cell.f = rc_to_a1(fstr, base); + delete cell.Formula; + if (cell.ArrayRange == "RC") cell.F = rc_to_a1("RC:RC", base); + else if (cell.ArrayRange) { + cell.F = rc_to_a1(cell.ArrayRange, base); + arrayf.push([safe_decode_range(cell.F), cell.F]); + } + } else { + for (i7 = 0; i7 < arrayf.length; ++i7) + if (base.r >= arrayf[i7][0].s.r && base.r <= arrayf[i7][0].e.r) { + if (base.c >= arrayf[i7][0].s.c && base.c <= arrayf[i7][0].e.c) + cell.F = arrayf[i7][1]; + } + } + } + if (o9.cellStyles) { + interiors.forEach(function(x2) { + if (!S5.patternType && x2.patternType) S5.patternType = x2.patternType; + }); + cell.s = S5; + } + if (cell.StyleID !== void 0) cell.ixfe = cell.StyleID; +} +function xlml_prefix_dname(dname) { + return XLSLblBuiltIn.indexOf("_xlnm." + dname) > -1 ? "_xlnm." + dname : dname; +} +function xlml_clean_comment(comment) { + comment.t = comment.v || ""; + comment.t = comment.t.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + comment.v = comment.w = comment.ixfe = void 0; +} +function parse_xlml_xml(d4, _opts) { + var opts = _opts || {}; + make_ssf(); + var str2 = debom(xlml_normalize(d4)); + if (opts.type == "binary" || opts.type == "array" || opts.type == "base64") { + if (typeof $cptable !== "undefined") str2 = $cptable.utils.decode(65001, char_codes(str2)); + else str2 = utf8read(str2); + } + var opening = str2.slice(0, 1024).toLowerCase(), ishtml = false; + opening = opening.replace(/".*?"/g, ""); + if ((opening.indexOf(">") & 1023) > Math.min(opening.indexOf(",") & 1023, opening.indexOf(";") & 1023)) { + var _o = dup(opts); + _o.type = "string"; + return PRN.to_workbook(str2, _o); + } + if (opening.indexOf("= 0) ishtml = true; + }); + if (ishtml) return html_to_workbook(str2, opts); + XLMLFormatMap = { + "General Number": "General", + "General Date": table_fmt[22], + "Long Date": "dddd, mmmm dd, yyyy", + "Medium Date": table_fmt[15], + "Short Date": table_fmt[14], + "Long Time": table_fmt[19], + "Medium Time": table_fmt[18], + "Short Time": table_fmt[20], + "Currency": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', + "Fixed": table_fmt[2], + "Standard": table_fmt[4], + "Percent": table_fmt[10], + "Scientific": table_fmt[11], + "Yes/No": '"Yes";"Yes";"No";@', + "True/False": '"True";"True";"False";@', + "On/Off": '"Yes";"Yes";"No";@' + }; + var Rn; + var state = [], tmp; + if (DENSE != null && opts.dense == null) opts.dense = DENSE; + var sheets = {}, sheetnames = [], cursheet = {}, sheetname = ""; + if (opts.dense) cursheet["!data"] = []; + var cell = {}, row = {}; + var dtag = xlml_parsexmltag(''), didx = 0; + var c6 = 0, r8 = 0; + var refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } }; + var styles2 = {}, stag = {}; + var ss = "", fidx = 0; + var merges = []; + var Props = {}, Custprops = {}, pidx = 0, cp = []; + var comments = [], comment = {}; + var cstys = [], csty, seencol = false; + var arrayf = []; + var rowinfo = [], rowobj = {}, cc = 0, rr = 0; + var Workbook = { Sheets: [], WBProps: { date1904: false } }, wsprops = {}; + xlmlregex.lastIndex = 0; + str2 = str_remove_ng(str2, ""); + var raw_Rn3 = ""; + while (Rn = xlmlregex.exec(str2)) switch (Rn[3] = (raw_Rn3 = Rn[3]).toLowerCase()) { + case "data": + if (raw_Rn3 == "data") { + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]); + break; + } + if (state[state.length - 1][1]) break; + if (Rn[1] === "/") parse_xlml_data(str2.slice(didx, Rn.index), ss, dtag, state[state.length - 1][0] == /*"Comment"*/ + "comment" ? comment : cell, { c: c6, r: r8 }, styles2, cstys[c6], row, arrayf, opts, Workbook.WBProps.date1904); + else { + ss = ""; + dtag = xlml_parsexmltag(Rn[0]); + didx = Rn.index + Rn[0].length; + } + break; + case "cell": + if (Rn[1] === "/") { + if (comments.length > 0) cell.c = comments; + if ((!opts.sheetRows || opts.sheetRows > r8) && cell.v !== void 0) { + if (opts.dense) { + if (!cursheet["!data"][r8]) cursheet["!data"][r8] = []; + cursheet["!data"][r8][c6] = cell; + } else cursheet[encode_col(c6) + encode_row(r8)] = cell; + } + if (cell.HRef) { + cell.l = { Target: unescapexml(cell.HRef) }; + if (cell.HRefScreenTip) cell.l.Tooltip = cell.HRefScreenTip; + delete cell.HRef; + delete cell.HRefScreenTip; + } + if (cell.MergeAcross || cell.MergeDown) { + cc = c6 + (parseInt(cell.MergeAcross, 10) | 0); + rr = r8 + (parseInt(cell.MergeDown, 10) | 0); + if (cc > c6 || rr > r8) merges.push({ s: { c: c6, r: r8 }, e: { c: cc, r: rr } }); + } + if (!opts.sheetStubs) { + if (cell.MergeAcross) c6 = cc + 1; + else ++c6; + } else if (cell.MergeAcross || cell.MergeDown) { + for (var cma = c6; cma <= cc; ++cma) { + for (var cmd = r8; cmd <= rr; ++cmd) { + if (cma > c6 || cmd > r8) { + if (opts.dense) { + if (!cursheet["!data"][cmd]) cursheet["!data"][cmd] = []; + cursheet["!data"][cmd][cma] = { t: "z" }; + } else cursheet[encode_col(cma) + encode_row(cmd)] = { t: "z" }; + } + } + } + c6 = cc + 1; + } else ++c6; + } else { + cell = xlml_parsexmltagobj(Rn[0]); + if (cell.Index) c6 = +cell.Index - 1; + if (c6 < refguess.s.c) refguess.s.c = c6; + if (c6 > refguess.e.c) refguess.e.c = c6; + if (Rn[0].slice(-2) === "/>") ++c6; + comments = []; + } + break; + case "row": + if (Rn[1] === "/" || Rn[0].slice(-2) === "/>") { + if (r8 < refguess.s.r) refguess.s.r = r8; + if (r8 > refguess.e.r) refguess.e.r = r8; + if (Rn[0].slice(-2) === "/>") { + row = xlml_parsexmltag(Rn[0]); + if (row.Index) r8 = +row.Index - 1; + } + c6 = 0; + ++r8; + } else { + row = xlml_parsexmltag(Rn[0]); + if (row.Index) r8 = +row.Index - 1; + rowobj = {}; + if (row.AutoFitHeight == "0" || row.Height) { + rowobj.hpx = parseInt(row.Height, 10); + rowobj.hpt = px2pt(rowobj.hpx); + rowinfo[r8] = rowobj; + } + if (row.Hidden == "1") { + rowobj.hidden = true; + rowinfo[r8] = rowobj; + } + } + break; + case "worksheet": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + sheetnames.push(sheetname); + if (refguess.s.r <= refguess.e.r && refguess.s.c <= refguess.e.c) { + cursheet["!ref"] = encode_range(refguess); + if (opts.sheetRows && opts.sheetRows <= refguess.e.r) { + cursheet["!fullref"] = cursheet["!ref"]; + refguess.e.r = opts.sheetRows - 1; + cursheet["!ref"] = encode_range(refguess); + } + } + if (merges.length) cursheet["!merges"] = merges; + if (cstys.length > 0) cursheet["!cols"] = cstys; + if (rowinfo.length > 0) cursheet["!rows"] = rowinfo; + sheets[sheetname] = cursheet; + } else { + refguess = { s: { r: 2e6, c: 2e6 }, e: { r: 0, c: 0 } }; + r8 = c6 = 0; + state.push([Rn[3], false]); + tmp = xlml_parsexmltag(Rn[0]); + sheetname = unescapexml(tmp.Name); + cursheet = {}; + if (opts.dense) cursheet["!data"] = []; + merges = []; + arrayf = []; + rowinfo = []; + wsprops = { name: sheetname, Hidden: 0 }; + Workbook.Sheets.push(wsprops); + } + break; + case "table": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + } else if (Rn[0].slice(-2) == "/>") break; + else { + state.push([Rn[3], false]); + cstys = []; + seencol = false; + } + break; + case "style": + if (Rn[1] === "/") process_style_xlml(styles2, stag, opts); + else stag = xlml_parsexmltag(Rn[0]); + break; + case "numberformat": + stag.nf = unescapexml(xlml_parsexmltag(Rn[0]).Format || "General"); + if (XLMLFormatMap[stag.nf]) stag.nf = XLMLFormatMap[stag.nf]; + for (var ssfidx = 0; ssfidx != 392; ++ssfidx) if (table_fmt[ssfidx] == stag.nf) break; + if (ssfidx == 392) { + for (ssfidx = 57; ssfidx != 392; ++ssfidx) if (table_fmt[ssfidx] == null) { + SSF__load(stag.nf, ssfidx); + break; + } + } + break; + case "column": + if (state[state.length - 1][0] !== /*'Table'*/ + "table") break; + if (Rn[1] === "/") break; + csty = xlml_parsexmltag(Rn[0]); + if (csty.Hidden) { + csty.hidden = true; + delete csty.Hidden; + } + if (csty.Width) csty.wpx = parseInt(csty.Width, 10); + if (!seencol && csty.wpx > 10) { + seencol = true; + MDW = DEF_MDW; + for (var _col = 0; _col < cstys.length; ++_col) if (cstys[_col]) process_col(cstys[_col]); + } + if (seencol) process_col(csty); + cstys[csty.Index - 1 || cstys.length] = csty; + for (var i7 = 0; i7 < +csty.Span; ++i7) cstys[cstys.length] = dup(csty); + break; + case "namedrange": + if (Rn[1] === "/") break; + if (!Workbook.Names) Workbook.Names = []; + var _NamedRange = parsexmltag(Rn[0]); + var _DefinedName = { + Name: xlml_prefix_dname(_NamedRange.Name), + Ref: rc_to_a1(_NamedRange.RefersTo.slice(1), { r: 0, c: 0 }) + }; + if (Workbook.Sheets.length > 0) _DefinedName.Sheet = Workbook.Sheets.length - 1; + Workbook.Names.push(_DefinedName); + break; + case "namedcell": + break; + case "b": + break; + case "i": + break; + case "u": + break; + case "s": + break; + case "em": + break; + case "h2": + break; + case "h3": + break; + case "sub": + break; + case "sup": + break; + case "span": + break; + case "alignment": + break; + case "borders": + break; + case "border": + break; + case "font": + if (Rn[0].slice(-2) === "/>") break; + else if (Rn[1] === "/") ss += str2.slice(fidx, Rn.index); + else fidx = Rn.index + Rn[0].length; + break; + case "interior": + if (!opts.cellStyles) break; + stag.Interior = xlml_parsexmltag(Rn[0]); + break; + case "protection": + break; + case "author": + case "title": + case "description": + case "created": + case "keywords": + case "subject": + case "category": + case "company": + case "lastauthor": + case "lastsaved": + case "lastprinted": + case "version": + case "revision": + case "totaltime": + case "hyperlinkbase": + case "manager": + case "contentstatus": + case "identifier": + case "language": + case "appname": + if (Rn[0].slice(-2) === "/>") break; + else if (Rn[1] === "/") xlml_set_prop(Props, raw_Rn3, str2.slice(pidx, Rn.index)); + else pidx = Rn.index + Rn[0].length; + break; + case "paragraphs": + break; + case "styles": + case "workbook": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + } else state.push([Rn[3], false]); + break; + case "comment": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + xlml_clean_comment(comment); + comments.push(comment); + } else { + state.push([Rn[3], false]); + tmp = xlml_parsexmltag(Rn[0]); + if (!parsexmlbool(tmp["ShowAlways"] || "0")) comments.hidden = true; + comment = { a: tmp.Author }; + } + break; + case "autofilter": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + var AutoFilter = xlml_parsexmltag(Rn[0]); + cursheet["!autofilter"] = { ref: rc_to_a1(AutoFilter.Range).replace(/\$/g, "") }; + state.push([Rn[3], true]); + } + break; + case "name": + break; + case "datavalidation": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + } else { + if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]); + } + break; + case "pixelsperinch": + break; + case "componentoptions": + case "documentproperties": + case "customdocumentproperties": + case "officedocumentsettings": + case "pivottable": + case "pivotcache": + case "names": + case "mapinfo": + case "pagebreaks": + case "querytable": + case "sorting": + case "schema": + //case 'data' /*case 'data'*/: + case "conditionalformatting": + case "smarttagtype": + case "smarttags": + case "excelworkbook": + case "workbookoptions": + case "worksheetoptions": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw new Error("Bad state: " + tmp.join("|")); + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]); + break; + case "null": + break; + default: + if (state.length == 0 && Rn[3] == "document") return parse_fods(str2, opts); + if (state.length == 0 && Rn[3] == "uof") return parse_fods(str2, opts); + var seen = true; + switch (state[state.length - 1][0]) { + /* OfficeDocumentSettings */ + case "officedocumentsettings": + switch (Rn[3]) { + case "allowpng": + break; + case "removepersonalinformation": + break; + case "downloadcomponents": + break; + case "locationofcomponents": + break; + case "colors": + break; + case "color": + break; + case "index": + break; + case "rgb": + break; + case "targetscreensize": + break; + case "readonlyrecommended": + break; + default: + seen = false; + } + break; + /* ComponentOptions */ + case "componentoptions": + switch (Rn[3]) { + case "toolbar": + break; + case "hideofficelogo": + break; + case "spreadsheetautofit": + break; + case "label": + break; + case "caption": + break; + case "maxheight": + break; + case "maxwidth": + break; + case "nextsheetnumber": + break; + default: + seen = false; + } + break; + /* ExcelWorkbook */ + case "excelworkbook": + switch (Rn[3]) { + case "date1904": + Workbook.WBProps.date1904 = true; + break; + case "hidehorizontalscrollbar": + break; + case "hideverticalscrollbar": + break; + case "hideworkbooktabs": + break; + case "windowheight": + break; + case "windowwidth": + break; + case "windowtopx": + break; + case "windowtopy": + break; + case "tabratio": + break; + case "protectstructure": + break; + case "protectwindow": + break; + case "protectwindows": + break; + case "activesheet": + break; + case "displayinknotes": + break; + case "firstvisiblesheet": + break; + case "supbook": + break; + case "sheetname": + break; + case "sheetindex": + break; + case "sheetindexfirst": + break; + case "sheetindexlast": + break; + case "dll": + break; + case "acceptlabelsinformulas": + break; + case "donotsavelinkvalues": + break; + case "iteration": + break; + case "maxiterations": + break; + case "maxchange": + break; + case "path": + break; + case "xct": + break; + case "count": + break; + case "selectedsheets": + break; + case "calculation": + break; + case "uncalced": + break; + case "startupprompt": + break; + case "crn": + break; + case "externname": + break; + case "formula": + break; + case "colfirst": + break; + case "collast": + break; + case "wantadvise": + break; + case "boolean": + break; + case "error": + break; + case "text": + break; + case "ole": + break; + case "noautorecover": + break; + case "publishobjects": + break; + case "donotcalculatebeforesave": + break; + case "number": + break; + case "refmoder1c1": + break; + case "embedsavesmarttags": + break; + default: + seen = false; + } + break; + /* WorkbookOptions */ + case "workbookoptions": + switch (Rn[3]) { + case "owcversion": + break; + case "height": + break; + case "width": + break; + default: + seen = false; + } + break; + /* WorksheetOptions */ + case "worksheetoptions": + switch (Rn[3]) { + case "visible": + if (Rn[0].slice(-2) === "/>") { + } else if (Rn[1] === "/") switch (str2.slice(pidx, Rn.index)) { + case "SheetHidden": + wsprops.Hidden = 1; + break; + case "SheetVeryHidden": + wsprops.Hidden = 2; + break; + } + else pidx = Rn.index + Rn[0].length; + break; + case "header": + if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml"); + if (!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet["!margins"].header = +parsexmltag(Rn[0]).Margin; + break; + case "footer": + if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml"); + if (!isNaN(+parsexmltag(Rn[0]).Margin)) cursheet["!margins"].footer = +parsexmltag(Rn[0]).Margin; + break; + case "pagemargins": + var pagemargins = parsexmltag(Rn[0]); + if (!cursheet["!margins"]) default_margins(cursheet["!margins"] = {}, "xlml"); + if (!isNaN(+pagemargins.Top)) cursheet["!margins"].top = +pagemargins.Top; + if (!isNaN(+pagemargins.Left)) cursheet["!margins"].left = +pagemargins.Left; + if (!isNaN(+pagemargins.Right)) cursheet["!margins"].right = +pagemargins.Right; + if (!isNaN(+pagemargins.Bottom)) cursheet["!margins"].bottom = +pagemargins.Bottom; + break; + case "displayrighttoleft": + if (!Workbook.Views) Workbook.Views = []; + if (!Workbook.Views[0]) Workbook.Views[0] = {}; + Workbook.Views[0].RTL = true; + break; + case "freezepanes": + break; + case "frozennosplit": + break; + case "splithorizontal": + case "splitvertical": + break; + case "donotdisplaygridlines": + break; + case "activerow": + break; + case "activecol": + break; + case "toprowbottompane": + break; + case "leftcolumnrightpane": + break; + case "unsynced": + break; + case "print": + break; + case "printerrors": + break; + case "panes": + break; + case "scale": + break; + case "pane": + break; + case "number": + break; + case "layout": + break; + case "pagesetup": + break; + case "selected": + break; + case "protectobjects": + break; + case "enableselection": + break; + case "protectscenarios": + break; + case "validprinterinfo": + break; + case "horizontalresolution": + break; + case "verticalresolution": + break; + case "numberofcopies": + break; + case "activepane": + break; + case "toprowvisible": + break; + case "leftcolumnvisible": + break; + case "fittopage": + break; + case "rangeselection": + break; + case "papersizeindex": + break; + case "pagelayoutzoom": + break; + case "pagebreakzoom": + break; + case "filteron": + break; + case "fitwidth": + break; + case "fitheight": + break; + case "commentslayout": + break; + case "zoom": + break; + case "lefttoright": + break; + case "gridlines": + break; + case "allowsort": + break; + case "allowfilter": + break; + case "allowinsertrows": + break; + case "allowdeleterows": + break; + case "allowinsertcols": + break; + case "allowdeletecols": + break; + case "allowinserthyperlinks": + break; + case "allowformatcells": + break; + case "allowsizecols": + break; + case "allowsizerows": + break; + case "nosummaryrowsbelowdetail": + if (!cursheet["!outline"]) cursheet["!outline"] = {}; + cursheet["!outline"].above = true; + break; + case "tabcolorindex": + break; + case "donotdisplayheadings": + break; + case "showpagelayoutzoom": + break; + case "nosummarycolumnsrightdetail": + if (!cursheet["!outline"]) cursheet["!outline"] = {}; + cursheet["!outline"].left = true; + break; + case "blackandwhite": + break; + case "donotdisplayzeros": + break; + case "displaypagebreak": + break; + case "rowcolheadings": + break; + case "donotdisplayoutline": + break; + case "noorientation": + break; + case "allowusepivottables": + break; + case "zeroheight": + break; + case "viewablerange": + break; + case "selection": + break; + case "protectcontents": + break; + default: + seen = false; + } + break; + /* PivotTable */ + case "pivottable": + case "pivotcache": + switch (Rn[3]) { + case "immediateitemsondrop": + break; + case "showpagemultipleitemlabel": + break; + case "compactrowindent": + break; + case "location": + break; + case "pivotfield": + break; + case "orientation": + break; + case "layoutform": + break; + case "layoutsubtotallocation": + break; + case "layoutcompactrow": + break; + case "position": + break; + case "pivotitem": + break; + case "datatype": + break; + case "datafield": + break; + case "sourcename": + break; + case "parentfield": + break; + case "ptlineitems": + break; + case "ptlineitem": + break; + case "countofsameitems": + break; + case "item": + break; + case "itemtype": + break; + case "ptsource": + break; + case "cacheindex": + break; + case "consolidationreference": + break; + case "filename": + break; + case "reference": + break; + case "nocolumngrand": + break; + case "norowgrand": + break; + case "blanklineafteritems": + break; + case "hidden": + break; + case "subtotal": + break; + case "basefield": + break; + case "mapchilditems": + break; + case "function": + break; + case "refreshonfileopen": + break; + case "printsettitles": + break; + case "mergelabels": + break; + case "defaultversion": + break; + case "refreshname": + break; + case "refreshdate": + break; + case "refreshdatecopy": + break; + case "versionlastrefresh": + break; + case "versionlastupdate": + break; + case "versionupdateablemin": + break; + case "versionrefreshablemin": + break; + case "calculation": + break; + default: + seen = false; + } + break; + /* PageBreaks */ + case "pagebreaks": + switch (Rn[3]) { + case "colbreaks": + break; + case "colbreak": + break; + case "rowbreaks": + break; + case "rowbreak": + break; + case "colstart": + break; + case "colend": + break; + case "rowend": + break; + default: + seen = false; + } + break; + /* AutoFilter */ + case "autofilter": + switch (Rn[3]) { + case "autofiltercolumn": + break; + case "autofiltercondition": + break; + case "autofilterand": + break; + case "autofilteror": + break; + default: + seen = false; + } + break; + /* QueryTable */ + case "querytable": + switch (Rn[3]) { + case "id": + break; + case "autoformatfont": + break; + case "autoformatpattern": + break; + case "querysource": + break; + case "querytype": + break; + case "enableredirections": + break; + case "refreshedinxl9": + break; + case "urlstring": + break; + case "htmltables": + break; + case "connection": + break; + case "commandtext": + break; + case "refreshinfo": + break; + case "notitles": + break; + case "nextid": + break; + case "columninfo": + break; + case "overwritecells": + break; + case "donotpromptforfile": + break; + case "textwizardsettings": + break; + case "source": + break; + case "number": + break; + case "decimal": + break; + case "thousandseparator": + break; + case "trailingminusnumbers": + break; + case "formatsettings": + break; + case "fieldtype": + break; + case "delimiters": + break; + case "tab": + break; + case "comma": + break; + case "autoformatname": + break; + case "versionlastedit": + break; + case "versionlastrefresh": + break; + default: + seen = false; + } + break; + case "datavalidation": + switch (Rn[3]) { + case "range": + break; + case "type": + break; + case "min": + break; + case "max": + break; + case "sort": + break; + case "descending": + break; + case "order": + break; + case "casesensitive": + break; + case "value": + break; + case "errorstyle": + break; + case "errormessage": + break; + case "errortitle": + break; + case "inputmessage": + break; + case "inputtitle": + break; + case "combohide": + break; + case "inputhide": + break; + case "condition": + break; + case "qualifier": + break; + case "useblank": + break; + case "value1": + break; + case "value2": + break; + case "format": + break; + case "cellrangelist": + break; + default: + seen = false; + } + break; + case "sorting": + case "conditionalformatting": + switch (Rn[3]) { + case "range": + break; + case "type": + break; + case "min": + break; + case "max": + break; + case "sort": + break; + case "descending": + break; + case "order": + break; + case "casesensitive": + break; + case "value": + break; + case "errorstyle": + break; + case "errormessage": + break; + case "errortitle": + break; + case "cellrangelist": + break; + case "inputmessage": + break; + case "inputtitle": + break; + case "combohide": + break; + case "inputhide": + break; + case "condition": + break; + case "qualifier": + break; + case "useblank": + break; + case "value1": + break; + case "value2": + break; + case "format": + break; + default: + seen = false; + } + break; + /* MapInfo (schema) */ + case "mapinfo": + case "schema": + case "data": + switch (Rn[3]) { + case "map": + break; + case "entry": + break; + case "range": + break; + case "xpath": + break; + case "field": + break; + case "xsdtype": + break; + case "filteron": + break; + case "aggregate": + break; + case "elementtype": + break; + case "attributetype": + break; + /* These are from xsd (XML Schema Definition) */ + case "schema": + case "element": + case "complextype": + case "datatype": + case "all": + case "attribute": + case "extends": + break; + case "row": + break; + default: + seen = false; + } + break; + /* SmartTags (can be anything) */ + case "smarttags": + break; + default: + seen = false; + break; + } + if (seen) break; + if (Rn[3].match(/!\[CDATA/)) break; + if (!state[state.length - 1][1]) throw "Unrecognized tag: " + Rn[3] + "|" + state.join("|"); + if (state[state.length - 1][0] === /*'CustomDocumentProperties'*/ + "customdocumentproperties") { + if (Rn[0].slice(-2) === "/>") break; + else if (Rn[1] === "/") xlml_set_custprop(Custprops, raw_Rn3, cp, str2.slice(pidx, Rn.index)); + else { + cp = Rn; + pidx = Rn.index + Rn[0].length; + } + break; + } + if (opts.WTF) throw "Unrecognized tag: " + Rn[3] + "|" + state.join("|"); + } + var out = {}; + if (!opts.bookSheets && !opts.bookProps) out.Sheets = sheets; + out.SheetNames = sheetnames; + out.Workbook = Workbook; + out.SSF = dup(table_fmt); + out.Props = Props; + out.Custprops = Custprops; + out.bookType = "xlml"; + return out; +} +function parse_xlml(data, opts) { + fix_read_opts(opts = opts || {}); + switch (opts.type || "base64") { + case "base64": + return parse_xlml_xml(Base64_decode(data), opts); + case "binary": + case "buffer": + case "file": + return parse_xlml_xml(data, opts); + case "array": + return parse_xlml_xml(a2s(data), opts); + } +} +function parse_compobj(obj) { + var v4 = {}; + var o9 = obj.content; + o9.l = 28; + v4.AnsiUserType = o9.read_shift(0, "lpstr-ansi"); + v4.AnsiClipboardFormat = parse_ClipboardFormatOrAnsiString(o9); + if (o9.length - o9.l <= 4) return v4; + var m4 = o9.read_shift(4); + if (m4 == 0 || m4 > 40) return v4; + o9.l -= 4; + v4.Reserved1 = o9.read_shift(0, "lpstr-ansi"); + if (o9.length - o9.l <= 4) return v4; + m4 = o9.read_shift(4); + if (m4 !== 1907505652) return v4; + v4.UnicodeClipboardFormat = parse_ClipboardFormatOrUnicodeString(o9); + m4 = o9.read_shift(4); + if (m4 == 0 || m4 > 40) return v4; + o9.l -= 4; + v4.Reserved2 = o9.read_shift(0, "lpwstr"); +} +function slurp(RecordType, R3, blob, length, opts) { + var l5 = length; + var bufs = []; + var d4 = blob.slice(blob.l, blob.l + l5); + if (opts && opts.enc && opts.enc.insitu && d4.length > 0) switch (RecordType) { + case 9: + case 521: + case 1033: + case 2057: + case 47: + case 405: + case 225: + case 406: + case 312: + case 404: + case 10: + break; + case 133: + break; + default: + opts.enc.insitu(d4); + } + bufs.push(d4); + blob.l += l5; + var nextrt = __readUInt16LE(blob, blob.l), next = XLSRecordEnum[nextrt]; + var start = 0; + while (next != null && CONTINUE_RT.indexOf(nextrt) > -1) { + l5 = __readUInt16LE(blob, blob.l + 2); + start = blob.l + 4; + if (nextrt == 2066) start += 4; + else if (nextrt == 2165 || nextrt == 2175) { + start += 12; + } + d4 = blob.slice(start, blob.l + 4 + l5); + bufs.push(d4); + blob.l += 4 + l5; + next = XLSRecordEnum[nextrt = __readUInt16LE(blob, blob.l)]; + } + var b4 = bconcat(bufs); + prep_blob(b4, 0); + var ll = 0; + b4.lens = []; + for (var j3 = 0; j3 < bufs.length; ++j3) { + b4.lens.push(ll); + ll += bufs[j3].length; + } + if (b4.length < length) throw "XLS Record 0x" + RecordType.toString(16) + " Truncated: " + b4.length + " < " + length; + return R3.f(b4, b4.length, opts); +} +function safe_format_xf(p4, opts, date1904) { + if (p4.t === "z") return; + if (!p4.XF) return; + var fmtid = 0; + try { + fmtid = p4.z || p4.XF.numFmtId || 0; + if (opts.cellNF && p4.z == null) p4.z = table_fmt[fmtid]; + } catch (e9) { + if (opts.WTF) throw e9; + } + if (!opts || opts.cellText !== false) try { + if (p4.t === "e") { + p4.w = p4.w || BErr[p4.v]; + } else if (fmtid === 0 || fmtid == "General") { + if (p4.t === "n") { + if ((p4.v | 0) === p4.v) p4.w = p4.v.toString(10); + else p4.w = SSF_general_num(p4.v); + } else p4.w = SSF_general(p4.v); + } else p4.w = SSF_format(fmtid, p4.v, { date1904: !!date1904, dateNF: opts && opts.dateNF }); + } catch (e9) { + if (opts.WTF) throw e9; + } + if (opts.cellDates && fmtid && p4.t == "n" && fmt_is_date(table_fmt[fmtid] || String(fmtid))) { + var _d = SSF_parse_date_code(p4.v + (date1904 ? 1462 : 0)); + if (_d) { + p4.t = "d"; + p4.v = new Date(Date.UTC(_d.y, _d.m - 1, _d.d, _d.H, _d.M, _d.S, _d.u)); + } + } +} +function make_cell(val2, ixfe, t6) { + return { v: val2, ixfe, t: t6 }; +} +function parse_workbook(blob, options) { + var wb = { opts: {} }; + var Sheets = {}; + if (DENSE != null && options.dense == null) options.dense = DENSE; + var out = {}; + if (options.dense) out["!data"] = []; + var Directory = {}; + var range2 = {}; + var last_formula = null; + var sst = []; + var cur_sheet = ""; + var Preamble = {}; + var lastcell, last_cell = "", cc, cmnt, rngC, rngR; + var sharedf = {}; + var arrayf = []; + var temp_val; + var country; + var XFs = []; + var palette = []; + var Workbook = { Sheets: [], WBProps: { date1904: false }, Views: [{}] }, wsprops = {}; + var biff4w = false; + var get_rgb = function getrgb(icv) { + if (icv < 8) return XLSIcv[icv]; + if (icv < 64) return palette[icv - 8] || XLSIcv[icv]; + return XLSIcv[icv]; + }; + var process_cell_style = function pcs(line, options2) { + var xfd = line.XF.data; + if (!xfd || !xfd.patternType || !options2 || !options2.cellStyles) return; + line.s = {}; + line.s.patternType = xfd.patternType; + var t6; + if (t6 = rgb2Hex(get_rgb(xfd.icvFore))) { + line.s.fgColor = { rgb: t6 }; + } + if (t6 = rgb2Hex(get_rgb(xfd.icvBack))) { + line.s.bgColor = { rgb: t6 }; + } + }; + var addcell = function addcell2(cell, line, options2) { + if (!biff4w && file_depth > 1) return; + if (options2.sheetRows && cell.r >= options2.sheetRows) return; + if (options2.cellStyles && line.XF && line.XF.data) process_cell_style(line, options2); + delete line.ixfe; + delete line.XF; + lastcell = cell; + last_cell = encode_cell(cell); + if (!range2 || !range2.s || !range2.e) range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + if (cell.r < range2.s.r) range2.s.r = cell.r; + if (cell.c < range2.s.c) range2.s.c = cell.c; + if (cell.r + 1 > range2.e.r) range2.e.r = cell.r + 1; + if (cell.c + 1 > range2.e.c) range2.e.c = cell.c + 1; + if (options2.cellFormula && line.f) { + for (var afi = 0; afi < arrayf.length; ++afi) { + if (arrayf[afi][0].s.c > cell.c || arrayf[afi][0].s.r > cell.r) continue; + if (arrayf[afi][0].e.c < cell.c || arrayf[afi][0].e.r < cell.r) continue; + line.F = encode_range(arrayf[afi][0]); + if (arrayf[afi][0].s.c != cell.c || arrayf[afi][0].s.r != cell.r) delete line.f; + if (line.f) line.f = "" + stringify_formula(arrayf[afi][1], range2, cell, supbooks, opts); + break; + } + } + { + if (options2.dense) { + if (!out["!data"][cell.r]) out["!data"][cell.r] = []; + out["!data"][cell.r][cell.c] = line; + } else out[last_cell] = line; + } + }; + var opts = { + enc: false, + // encrypted + sbcch: 0, + // cch in the preceding SupBook + snames: [], + // sheetnames + sharedf, + // shared formulae by address + arrayf, + // array formulae array + rrtabid: [], + // RRTabId + lastuser: "", + // Last User from WriteAccess + biff: 8, + // BIFF version + codepage: 0, + // CP from CodePage record + winlocked: 0, + // fLockWn from WinProtect + cellStyles: !!options && !!options.cellStyles, + WTF: !!options && !!options.wtf + }; + if (options.password) opts.password = options.password; + var themes; + var merges = []; + var objects = []; + var colinfo = [], rowinfo = []; + var seencol = false; + var supbooks = []; + supbooks.SheetNames = opts.snames; + supbooks.sharedf = opts.sharedf; + supbooks.arrayf = opts.arrayf; + supbooks.names = []; + supbooks.XTI = []; + var last_RT = 0; + var file_depth = 0; + var BIFF2Fmt = 0, BIFF2FmtTable = []; + var FilterDatabases = []; + var last_lbl; + opts.codepage = 1200; + set_cp(1200); + var seen_codepage = false; + while (blob.l < blob.length - 1) { + var s6 = blob.l; + var RecordType = blob.read_shift(2); + if (RecordType === 0 && last_RT === 10) break; + var length = blob.l === blob.length ? 0 : blob.read_shift(2); + var R3 = XLSRecordEnum[RecordType]; + if (file_depth == 0 && [9, 521, 1033, 2057].indexOf(RecordType) == -1) break; + if (R3 && R3.f) { + if (options.bookSheets) { + if (last_RT === 133 && RecordType !== 133) break; + } + last_RT = RecordType; + if (R3.r === 2 || R3.r == 12) { + var rt = blob.read_shift(2); + length -= 2; + if (!opts.enc && rt !== RecordType && ((rt & 255) << 8 | rt >> 8) !== RecordType) throw new Error("rt mismatch: " + rt + "!=" + RecordType); + if (R3.r == 12) { + blob.l += 10; + length -= 10; + } + } + var val2 = {}; + if (RecordType === 10) val2 = /*::(*/ + R3.f(blob, length, opts); + else val2 = /*::(*/ + slurp(RecordType, R3, blob, length, opts); + if (file_depth == 0 && [9, 521, 1033, 2057].indexOf(last_RT) === -1) continue; + switch (RecordType) { + case 34: + wb.opts.Date1904 = Workbook.WBProps.date1904 = val2; + break; + case 134: + wb.opts.WriteProtect = true; + break; + case 47: + if (!opts.enc) blob.l = 0; + opts.enc = val2; + if (!options.password) throw new Error("File is password-protected"); + if (val2.valid == null) throw new Error("Encryption scheme unsupported"); + if (!val2.valid) throw new Error("Password is incorrect"); + break; + case 92: + opts.lastuser = val2; + break; + case 66: + var cpval = Number(val2); + switch (cpval) { + case 21010: + cpval = 1200; + break; + case 32768: + cpval = 1e4; + break; + case 32769: + cpval = 1252; + break; + } + set_cp(opts.codepage = cpval); + seen_codepage = true; + break; + case 317: + opts.rrtabid = val2; + break; + case 25: + opts.winlocked = val2; + break; + case 439: + wb.opts["RefreshAll"] = val2; + break; + case 12: + wb.opts["CalcCount"] = val2; + break; + case 16: + wb.opts["CalcDelta"] = val2; + break; + case 17: + wb.opts["CalcIter"] = val2; + break; + case 13: + wb.opts["CalcMode"] = val2; + break; + case 14: + wb.opts["CalcPrecision"] = val2; + break; + case 95: + wb.opts["CalcSaveRecalc"] = val2; + break; + case 15: + opts.CalcRefMode = val2; + break; + // TODO: implement R1C1 + case 2211: + wb.opts.FullCalc = val2; + break; + case 129: + if (val2.fDialog) out["!type"] = "dialog"; + if (!val2.fBelow) (out["!outline"] || (out["!outline"] = {})).above = true; + if (!val2.fRight) (out["!outline"] || (out["!outline"] = {})).left = true; + break; + // TODO + case 67: + /* BIFF2XF */ + case 579: + /* BIFF3XF */ + case 1091: + /* BIFF4XF */ + case 224: + XFs.push(val2); + break; + case 430: + supbooks.push([val2]); + supbooks[supbooks.length - 1].XTI = []; + break; + case 35: + case 547: + supbooks[supbooks.length - 1].push(val2); + break; + case 24: + case 536: + last_lbl = { + Name: val2.Name, + Ref: stringify_formula(val2.rgce, range2, null, supbooks, opts) + }; + if (val2.itab > 0) last_lbl.Sheet = val2.itab - 1; + supbooks.names.push(last_lbl); + if (!supbooks[0]) { + supbooks[0] = []; + supbooks[0].XTI = []; + } + supbooks[supbooks.length - 1].push(val2); + if (val2.Name == "_xlnm._FilterDatabase" && val2.itab > 0) { + if (val2.rgce && val2.rgce[0] && val2.rgce[0][0] && val2.rgce[0][0][0] == "PtgArea3d") + FilterDatabases[val2.itab - 1] = { ref: encode_range(val2.rgce[0][0][1][2]) }; + } + break; + case 22: + opts.ExternCount = val2; + break; + case 23: + if (supbooks.length == 0) { + supbooks[0] = []; + supbooks[0].XTI = []; + } + supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val2); + supbooks.XTI = supbooks.XTI.concat(val2); + break; + case 2196: + if (opts.biff < 8) break; + if (last_lbl != null) last_lbl.Comment = val2[1]; + break; + case 18: + out["!protect"] = val2; + break; + /* for sheet or book */ + case 19: + if (val2 !== 0 && opts.WTF) console.error("Password verifier: " + val2); + break; + case 133: + { + Directory[opts.biff == 4 ? opts.snames.length : val2.pos] = val2; + opts.snames.push(val2.name); + } + break; + case 10: + { + if (--file_depth ? !biff4w : biff4w) break; + if (range2.e) { + if (range2.e.r > 0 && range2.e.c > 0) { + range2.e.r--; + range2.e.c--; + out["!ref"] = encode_range(range2); + if (options.sheetRows && options.sheetRows <= range2.e.r) { + var tmpri = range2.e.r; + range2.e.r = options.sheetRows - 1; + out["!fullref"] = out["!ref"]; + out["!ref"] = encode_range(range2); + range2.e.r = tmpri; + } + range2.e.r++; + range2.e.c++; + } + if (merges.length > 0) out["!merges"] = merges; + if (objects.length > 0) out["!objects"] = objects; + if (colinfo.length > 0) out["!cols"] = colinfo; + if (rowinfo.length > 0) out["!rows"] = rowinfo; + Workbook.Sheets.push(wsprops); + } + if (cur_sheet === "") Preamble = out; + else Sheets[cur_sheet] = out; + out = {}; + if (options.dense) out["!data"] = []; + } + break; + case 9: + case 521: + case 1033: + case 2057: + { + if (opts.biff === 8) opts.biff = { + 9: 2, + 521: 3, + 1033: 4 + }[RecordType] || { + 512: 2, + 768: 3, + 1024: 4, + 1280: 5, + 1536: 8, + 2: 2, + 7: 2 + }[val2.BIFFVer] || 8; + opts.biffguess = val2.BIFFVer == 0; + if (val2.BIFFVer == 0 && val2.dt == 4096) { + opts.biff = 5; + seen_codepage = true; + set_cp(opts.codepage = 28591); + } + if (opts.biff == 4 && val2.dt & 256) biff4w = true; + if (opts.biff == 8 && val2.BIFFVer == 0 && val2.dt == 16) opts.biff = 2; + if (file_depth++ && !biff4w) break; + out = {}; + if (options.dense) out["!data"] = []; + if (opts.biff < 8 && !seen_codepage) { + seen_codepage = true; + set_cp(opts.codepage = options.codepage || 1252); + } + if (opts.biff == 4 && biff4w) { + cur_sheet = (Directory[opts.snames.indexOf(cur_sheet) + 1] || { name: "" }).name; + } else if (opts.biff < 5 || val2.BIFFVer == 0 && val2.dt == 4096) { + if (cur_sheet === "") cur_sheet = "Sheet1"; + range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + var fakebs8 = { pos: blob.l - length, name: cur_sheet }; + Directory[fakebs8.pos] = fakebs8; + opts.snames.push(cur_sheet); + } else cur_sheet = (Directory[s6] || { name: "" }).name; + if (val2.dt == 32) out["!type"] = "chart"; + if (val2.dt == 64) out["!type"] = "macro"; + merges = []; + objects = []; + opts.arrayf = arrayf = []; + colinfo = []; + rowinfo = []; + seencol = false; + wsprops = { Hidden: (Directory[s6] || { hs: 0 }).hs, name: cur_sheet }; + } + break; + case 515: + case 3: + case 2: + { + if (out["!type"] == "chart") { + if (options.dense ? (out["!data"][val2.r] || [])[val2.c] : out[encode_col(val2.c) + encode_row(val2.r)]) ++val2.c; + } + temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe] || {}, v: val2.val, t: "n" }; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: val2.c, r: val2.r }, temp_val, options); + } + break; + case 5: + case 517: + { + temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], v: val2.val, t: val2.t }; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: val2.c, r: val2.r }, temp_val, options); + } + break; + case 638: + { + temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], v: val2.rknum, t: "n" }; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: val2.c, r: val2.r }, temp_val, options); + } + break; + case 189: + { + for (var j3 = val2.c; j3 <= val2.C; ++j3) { + var ixfe = val2.rkrec[j3 - val2.c][0]; + temp_val = { ixfe, XF: XFs[ixfe], v: val2.rkrec[j3 - val2.c][1], t: "n" }; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: j3, r: val2.r }, temp_val, options); + } + } + break; + case 6: + case 518: + case 1030: + { + if (val2.val == "String") { + last_formula = val2; + break; + } + temp_val = make_cell(val2.val, val2.cell.ixfe, val2.tt); + temp_val.XF = XFs[temp_val.ixfe]; + if (options.cellFormula) { + var _f = val2.formula; + if (_f && _f[0] && _f[0][0] && _f[0][0][0] == "PtgExp") { + var _fr = _f[0][0][1][0], _fc = _f[0][0][1][1]; + var _fe = encode_cell({ r: _fr, c: _fc }); + if (sharedf[_fe]) temp_val.f = "" + stringify_formula(val2.formula, range2, val2.cell, supbooks, opts); + else temp_val.F = ((options.dense ? (out["!data"][_fr] || [])[_fc] : out[_fe]) || {}).F; + } else temp_val.f = "" + stringify_formula(val2.formula, range2, val2.cell, supbooks, opts); + } + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell(val2.cell, temp_val, options); + last_formula = val2; + } + break; + case 7: + case 519: + { + if (last_formula) { + last_formula.val = val2; + temp_val = make_cell(val2, last_formula.cell.ixfe, "s"); + temp_val.XF = XFs[temp_val.ixfe]; + if (options.cellFormula) { + temp_val.f = "" + stringify_formula(last_formula.formula, range2, last_formula.cell, supbooks, opts); + } + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell(last_formula.cell, temp_val, options); + last_formula = null; + } else throw new Error("String record expects Formula"); + } + break; + case 33: + case 545: + { + arrayf.push(val2); + var _arraystart = encode_cell(val2[0].s); + cc = options.dense ? (out["!data"][val2[0].s.r] || [])[val2[0].s.c] : out[_arraystart]; + if (options.cellFormula && cc) { + if (!last_formula) break; + if (!_arraystart || !cc) break; + cc.f = "" + stringify_formula(val2[1], range2, val2[0], supbooks, opts); + cc.F = encode_range(val2[0]); + } + } + break; + case 1212: + { + if (!options.cellFormula) break; + if (last_cell) { + if (!last_formula) break; + sharedf[encode_cell(last_formula.cell)] = val2[0]; + cc = options.dense ? (out["!data"][last_formula.cell.r] || [])[last_formula.cell.c] : out[encode_cell(last_formula.cell)]; + (cc || {}).f = "" + stringify_formula(val2[0], range2, lastcell, supbooks, opts); + } + } + break; + case 253: + temp_val = make_cell(sst[val2.isst].t, val2.ixfe, "s"); + if (sst[val2.isst].h) temp_val.h = sst[val2.isst].h; + temp_val.XF = XFs[temp_val.ixfe]; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: val2.c, r: val2.r }, temp_val, options); + break; + case 513: + if (options.sheetStubs) { + temp_val = { ixfe: val2.ixfe, XF: XFs[val2.ixfe], t: "z" }; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: val2.c, r: val2.r }, temp_val, options); + } + break; + case 190: + if (options.sheetStubs) { + for (var _j = val2.c; _j <= val2.C; ++_j) { + var _ixfe = val2.ixfe[_j - val2.c]; + temp_val = { ixfe: _ixfe, XF: XFs[_ixfe], t: "z" }; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: _j, r: val2.r }, temp_val, options); + } + } + break; + case 214: + case 516: + case 4: + temp_val = make_cell(val2.val, val2.ixfe, "s"); + temp_val.XF = XFs[temp_val.ixfe]; + if (BIFF2Fmt > 0) temp_val.z = temp_val.XF && temp_val.XF.numFmtId && BIFF2FmtTable[temp_val.XF.numFmtId] || BIFF2FmtTable[temp_val.ixfe >> 8 & 63]; + safe_format_xf(temp_val, options, wb.opts.Date1904); + addcell({ c: val2.c, r: val2.r }, temp_val, options); + break; + case 0: + case 512: + { + if (file_depth === 1) range2 = val2; + } + break; + case 252: + { + sst = val2; + } + break; + case 1054: + { + if (opts.biff >= 3 && opts.biff <= 4) { + BIFF2FmtTable[BIFF2Fmt++] = val2[1]; + for (var b4idx = 0; b4idx < BIFF2Fmt + 163; ++b4idx) if (table_fmt[b4idx] == val2[1]) break; + if (b4idx >= 163) SSF__load(val2[1], BIFF2Fmt + 163); + } else SSF__load(val2[1], val2[0]); + } + break; + case 30: + { + BIFF2FmtTable[BIFF2Fmt++] = val2; + for (var b2idx = 0; b2idx < BIFF2Fmt + 163; ++b2idx) if (table_fmt[b2idx] == val2) break; + if (b2idx >= 163) SSF__load(val2, BIFF2Fmt + 163); + } + break; + case 229: + merges = merges.concat(val2); + break; + case 93: + objects[val2.cmo[0]] = opts.lastobj = val2; + break; + case 438: + opts.lastobj.TxO = val2; + break; + case 127: + opts.lastobj.ImData = val2; + break; + case 440: + { + for (rngR = val2[0].s.r; rngR <= val2[0].e.r; ++rngR) + for (rngC = val2[0].s.c; rngC <= val2[0].e.c; ++rngC) { + cc = options.dense ? (out["!data"][rngR] || [])[rngC] : out[encode_cell({ c: rngC, r: rngR })]; + if (cc) cc.l = val2[1]; + } + } + break; + case 2048: + { + for (rngR = val2[0].s.r; rngR <= val2[0].e.r; ++rngR) + for (rngC = val2[0].s.c; rngC <= val2[0].e.c; ++rngC) { + cc = options.dense ? (out["!data"][rngR] || [])[rngC] : out[encode_cell({ c: rngC, r: rngR })]; + if (cc && cc.l) cc.l.Tooltip = val2[1]; + } + } + break; + case 28: + { + cc = options.dense ? (out["!data"][val2[0].r] || [])[val2[0].c] : out[encode_cell(val2[0])]; + if (!cc) { + if (options.dense) { + if (!out["!data"][val2[0].r]) out["!data"][val2[0].r] = []; + cc = out["!data"][val2[0].r][val2[0].c] = { t: "z" }; + } else { + cc = out[encode_cell(val2[0])] = { t: "z" }; + } + range2.e.r = Math.max(range2.e.r, val2[0].r); + range2.s.r = Math.min(range2.s.r, val2[0].r); + range2.e.c = Math.max(range2.e.c, val2[0].c); + range2.s.c = Math.min(range2.s.c, val2[0].c); + } + if (!cc.c) cc.c = []; + if (opts.biff <= 5 && opts.biff >= 2) cmnt = { a: "SheetJ5", t: val2[1] }; + else { + var noteobj = objects[val2[2]]; + cmnt = { a: val2[1], t: noteobj.TxO.t }; + if (val2[3] != null && !(val2[3] & 2)) cc.c.hidden = true; + } + cc.c.push(cmnt); + } + break; + case 2173: + update_xfext(XFs[val2.ixfe], val2.ext); + break; + case 125: + { + if (!opts.cellStyles) break; + while (val2.e >= val2.s) { + colinfo[val2.e--] = { width: val2.w / 256, level: val2.level || 0, hidden: !!(val2.flags & 1) }; + if (!seencol) { + seencol = true; + find_mdw_colw(val2.w / 256); + } + process_col(colinfo[val2.e + 1]); + } + } + break; + case 520: + { + var rowobj = {}; + if (val2.level != null) { + rowinfo[val2.r] = rowobj; + rowobj.level = val2.level; + } + if (val2.hidden) { + rowinfo[val2.r] = rowobj; + rowobj.hidden = true; + } + if (val2.hpt) { + rowinfo[val2.r] = rowobj; + rowobj.hpt = val2.hpt; + rowobj.hpx = pt2px(val2.hpt); + } + } + break; + case 38: + case 39: + case 40: + case 41: + if (!out["!margins"]) default_margins(out["!margins"] = {}); + out["!margins"][{ 38: "left", 39: "right", 40: "top", 41: "bottom" }[RecordType]] = val2; + break; + case 161: + if (!out["!margins"]) default_margins(out["!margins"] = {}); + out["!margins"].header = val2.header; + out["!margins"].footer = val2.footer; + break; + case 574: + if (val2.RTL) Workbook.Views[0].RTL = true; + break; + case 146: + palette = val2; + break; + case 2198: + themes = val2; + break; + case 140: + country = val2; + break; + case 442: + { + if (!cur_sheet) Workbook.WBProps.CodeName = val2 || "ThisWorkbook"; + else wsprops.CodeName = val2 || wsprops.name; + } + break; + } + } else { + if (!R3) console.error("Missing Info for XLS Record 0x" + RecordType.toString(16)); + blob.l += length; + } + } + wb.SheetNames = keys(Directory).sort(function(a3, b4) { + return Number(a3) - Number(b4); + }).map(function(x2) { + return Directory[x2].name; + }); + if (!options.bookSheets) wb.Sheets = Sheets; + if (!wb.SheetNames.length && Preamble["!ref"]) { + wb.SheetNames.push("Sheet1"); + if (wb.Sheets) wb.Sheets["Sheet1"] = Preamble; + } else wb.Preamble = Preamble; + if (wb.Sheets) FilterDatabases.forEach(function(r8, i7) { + wb.Sheets[wb.SheetNames[i7]]["!autofilter"] = r8; + }); + wb.Strings = sst; + wb.SSF = dup(table_fmt); + if (opts.enc) wb.Encryption = opts.enc; + if (themes) wb.Themes = themes; + wb.Metadata = {}; + if (country !== void 0) wb.Metadata.Country = country; + if (supbooks.names.length > 0) Workbook.Names = supbooks.names; + wb.Workbook = Workbook; + return wb; +} +function parse_xls_props(cfb, props, o9) { + var DSI = CFB.find(cfb, "/!DocumentSummaryInformation"); + if (DSI && DSI.size > 0) try { + var DocSummary = parse_PropertySetStream(DSI, DocSummaryPIDDSI, PSCLSID.DSI); + for (var d4 in DocSummary) props[d4] = DocSummary[d4]; + } catch (e9) { + if (o9.WTF) throw e9; + } + var SI = CFB.find(cfb, "/!SummaryInformation"); + if (SI && SI.size > 0) try { + var Summary = parse_PropertySetStream(SI, SummaryPIDSI, PSCLSID.SI); + for (var s6 in Summary) if (props[s6] == null) props[s6] = Summary[s6]; + } catch (e9) { + if (o9.WTF) throw e9; + } + if (props.HeadingPairs && props.TitlesOfParts) { + load_props_pairs(props.HeadingPairs, props.TitlesOfParts, props, o9); + delete props.HeadingPairs; + delete props.TitlesOfParts; + } +} +function parse_xlscfb(cfb, options) { + if (!options) options = {}; + fix_read_opts(options); + reset_cp(); + if (options.codepage) set_ansi(options.codepage); + var CompObj, WB; + if (cfb.FullPaths) { + if (CFB.find(cfb, "/encryption")) throw new Error("File is password-protected"); + CompObj = CFB.find(cfb, "!CompObj"); + WB = CFB.find(cfb, "/Workbook") || CFB.find(cfb, "/Book"); + } else { + switch (options.type) { + case "base64": + cfb = s2a(Base64_decode(cfb)); + break; + case "binary": + cfb = s2a(cfb); + break; + case "buffer": + break; + case "array": + if (!Array.isArray(cfb)) cfb = Array.prototype.slice.call(cfb); + break; + } + prep_blob(cfb, 0); + WB = { content: cfb }; + } + var WorkbookP; + var _data; + if (CompObj) parse_compobj(CompObj); + if (options.bookProps && !options.bookSheets) WorkbookP = {}; + else { + var T3 = has_buf ? "buffer" : "array"; + if (WB && WB.content) WorkbookP = parse_workbook(WB.content, options); + else if ((_data = CFB.find(cfb, "PerfectOffice_MAIN")) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T3, options)); + else if ((_data = CFB.find(cfb, "NativeContent_MAIN")) && _data.content) WorkbookP = WK_.to_workbook(_data.content, (options.type = T3, options)); + else if ((_data = CFB.find(cfb, "MN0")) && _data.content) throw new Error("Unsupported Works 4 for Mac file"); + else throw new Error("Cannot find Workbook stream"); + if (options.bookVBA && cfb.FullPaths && CFB.find(cfb, "/_VBA_PROJECT_CUR/VBA/dir")) WorkbookP.vbaraw = make_vba_xls(cfb); + } + var props = {}; + if (cfb.FullPaths) parse_xls_props( + /*::((*/ + cfb, + props, + options + ); + WorkbookP.Props = WorkbookP.Custprops = props; + if (options.bookFiles) WorkbookP.cfb = cfb; + return WorkbookP; +} +function write_biff_rec(ba, type, payload, length) { + var t6 = type; + if (isNaN(t6)) return; + var len = length || (payload || []).length || 0; + var o9 = ba.next(4); + o9.write_shift(2, t6); + o9.write_shift(2, len); + if ( + /*:: len != null &&*/ + len > 0 && is_buf(payload) + ) ba.push(payload); +} +function html_to_sheet(str2, _opts) { + var opts = _opts || {}; + var dense = opts.dense != null ? opts.dense : DENSE; + var ws = {}; + if (dense) ws["!data"] = []; + str2 = str_remove_ng(str2, ""); + var mtch = str2.match(/"); + var mtch2 = str2.match(/<\/table/i); + var i7 = mtch.index, j3 = mtch2 && mtch2.index || str2.length; + var rows = split_regex(str2.slice(i7, j3), /(:?]*>)/i, ""); + var R3 = -1, C3 = 0, RS = 0, CS = 0; + var range2 = { s: { r: 1e7, c: 1e7 }, e: { r: 0, c: 0 } }; + var merges = []; + for (i7 = 0; i7 < rows.length; ++i7) { + var row = rows[i7].trim(); + var hd = row.slice(0, 3).toLowerCase(); + if (hd == "/i); + for (j3 = 0; j3 < cells.length; ++j3) { + var cell = cells[j3].trim(); + if (!cell.match(/")) > -1) m4 = m4.slice(cc + 1); + for (var midx = 0; midx < merges.length; ++midx) { + var _merge = merges[midx]; + if (_merge.s.c == C3 && _merge.s.r < R3 && R3 <= _merge.e.r) { + C3 = _merge.e.c + 1; + midx = -1; + } + } + var tag = parsexmltag(cell.slice(0, cell.indexOf(">"))); + CS = tag.colspan ? +tag.colspan : 1; + if ((RS = +tag.rowspan) > 1 || CS > 1) merges.push({ s: { r: R3, c: C3 }, e: { r: R3 + (RS || 1) - 1, c: C3 + CS - 1 } }); + var _t = tag.t || tag["data-t"] || ""; + if (!m4.length) { + C3 += CS; + continue; + } + m4 = htmldecode(m4); + if (range2.s.r > R3) range2.s.r = R3; + if (range2.e.r < R3) range2.e.r = R3; + if (range2.s.c > C3) range2.s.c = C3; + if (range2.e.c < C3) range2.e.c = C3; + if (!m4.length) { + C3 += CS; + continue; + } + var o9 = { t: "s", v: m4 }; + if (opts.raw || !m4.trim().length || _t == "s") { + } else if (m4 === "TRUE") o9 = { t: "b", v: true }; + else if (m4 === "FALSE") o9 = { t: "b", v: false }; + else if (!isNaN(fuzzynum(m4))) o9 = { t: "n", v: fuzzynum(m4) }; + else if (!isNaN(fuzzydate(m4).getDate())) { + o9 = { t: "d", v: parseDate(m4) }; + if (opts.UTC === false) o9.v = utc_to_local(o9.v); + if (!opts.cellDates) o9 = { t: "n", v: datenum(o9.v) }; + o9.z = opts.dateNF || table_fmt[14]; + } else if (m4.charCodeAt(0) == 35 && RBErr[m4] != null) { + o9.t = "e"; + o9.w = m4; + o9.v = RBErr[m4]; + } + if (o9.cellText !== false) o9.w = m4; + if (dense) { + if (!ws["!data"][R3]) ws["!data"][R3] = []; + ws["!data"][R3][C3] = o9; + } else ws[encode_cell({ r: R3, c: C3 })] = o9; + C3 += CS; + } + } + ws["!ref"] = encode_range(range2); + if (merges.length) ws["!merges"] = merges; + return ws; +} +function make_html_row(ws, r8, R3, o9) { + var M4 = ws["!merges"] || []; + var oo = []; + var sp = {}; + var dense = ws["!data"] != null; + for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + var RS = 0, CS = 0; + for (var j3 = 0; j3 < M4.length; ++j3) { + if (M4[j3].s.r > R3 || M4[j3].s.c > C3) continue; + if (M4[j3].e.r < R3 || M4[j3].e.c < C3) continue; + if (M4[j3].s.r < R3 || M4[j3].s.c < C3) { + RS = -1; + break; + } + RS = M4[j3].e.r - M4[j3].s.r + 1; + CS = M4[j3].e.c - M4[j3].s.c + 1; + break; + } + if (RS < 0) continue; + var coord = encode_col(C3) + encode_row(R3); + var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord]; + if (cell && cell.t == "n" && cell.v != null && !isFinite(cell.v)) { + if (isNaN(cell.v)) cell = { t: "e", v: 36, w: BErr[36] }; + else cell = { t: "e", v: 7, w: BErr[7] }; + } + var w3 = cell && cell.v != null && (cell.h || escapehtml(cell.w || (format_cell(cell), cell.w) || "")) || ""; + sp = {}; + if (RS > 1) sp.rowspan = RS; + if (CS > 1) sp.colspan = CS; + if (o9.editable) w3 = '' + w3 + ""; + else if (cell) { + sp["data-t"] = cell && cell.t || "z"; + if (cell.v != null) sp["data-v"] = escapehtml(cell.v instanceof Date ? cell.v.toISOString() : cell.v); + if (cell.z != null) sp["data-z"] = cell.z; + if (cell.l && (cell.l.Target || "#").charAt(0) != "#") w3 = '' + w3 + ""; + } + sp.id = (o9.id || "sjs") + "-" + coord; + oo.push(writextag("td", w3, sp)); + } + var preamble = ""; + return preamble + oo.join("") + ""; +} +function html_to_workbook(str2, opts) { + var mtch = str_match_xml_ig(str2, "table"); + if (!mtch || mtch.length == 0) throw new Error("Invalid HTML: could not find
"); + if (mtch.length == 1) { + var w3 = sheet_to_workbook(html_to_sheet(mtch[0], opts), opts); + w3.bookType = "html"; + return w3; + } + var wb = book_new(); + mtch.forEach(function(s6, idx) { + book_append_sheet(wb, html_to_sheet(s6, opts), "Sheet" + (idx + 1)); + }); + wb.bookType = "html"; + return wb; +} +function make_html_preamble(ws, R3, o9) { + var out = []; + return out.join("") + ""; +} +function sheet_to_html(ws, opts) { + var o9 = opts || {}; + var header = o9.header != null ? o9.header : HTML_BEGIN; + var footer = o9.footer != null ? o9.footer : HTML_END; + var out = [header]; + var r8 = decode_range(ws["!ref"] || "A1"); + out.push(make_html_preamble(ws, r8, o9)); + if (ws["!ref"]) for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) out.push(make_html_row(ws, r8, R3, o9)); + out.push("
" + footer); + return out.join(""); +} +function sheet_add_dom(ws, table, _opts) { + var rows = table.rows; + if (!rows) { + throw "Unsupported origin when " + table.tagName + " is not a TABLE"; + } + var opts = _opts || {}; + var dense = ws["!data"] != null; + var or_R = 0, or_C = 0; + if (opts.origin != null) { + if (typeof opts.origin == "number") or_R = opts.origin; + else { + var _origin2 = typeof opts.origin == "string" ? decode_cell(opts.origin) : opts.origin; + or_R = _origin2.r; + or_C = _origin2.c; + } + } + var sheetRows = Math.min(opts.sheetRows || 1e7, rows.length); + var range2 = { s: { r: 0, c: 0 }, e: { r: or_R, c: or_C } }; + if (ws["!ref"]) { + var _range = decode_range(ws["!ref"]); + range2.s.r = Math.min(range2.s.r, _range.s.r); + range2.s.c = Math.min(range2.s.c, _range.s.c); + range2.e.r = Math.max(range2.e.r, _range.e.r); + range2.e.c = Math.max(range2.e.c, _range.e.c); + if (or_R == -1) range2.e.r = or_R = _range.e.r + 1; + } + var merges = [], midx = 0; + var rowinfo = ws["!rows"] || (ws["!rows"] = []); + var _R = 0, R3 = 0, _C = 0, C3 = 0, RS = 0, CS = 0; + if (!ws["!cols"]) ws["!cols"] = []; + for (; _R < rows.length && R3 < sheetRows; ++_R) { + var row = rows[_R]; + if (is_dom_element_hidden(row)) { + if (opts.display) continue; + rowinfo[R3] = { hidden: true }; + } + var elts = row.cells; + for (_C = C3 = 0; _C < elts.length; ++_C) { + var elt = elts[_C]; + if (opts.display && is_dom_element_hidden(elt)) continue; + var v4 = elt.hasAttribute("data-v") ? elt.getAttribute("data-v") : elt.hasAttribute("v") ? elt.getAttribute("v") : htmldecode(elt.innerHTML); + var z3 = elt.getAttribute("data-z") || elt.getAttribute("z"); + for (midx = 0; midx < merges.length; ++midx) { + var m4 = merges[midx]; + if (m4.s.c == C3 + or_C && m4.s.r < R3 + or_R && R3 + or_R <= m4.e.r) { + C3 = m4.e.c + 1 - or_C; + midx = -1; + } + } + CS = +elt.getAttribute("colspan") || 1; + if ((RS = +elt.getAttribute("rowspan") || 1) > 1 || CS > 1) merges.push({ s: { r: R3 + or_R, c: C3 + or_C }, e: { r: R3 + or_R + (RS || 1) - 1, c: C3 + or_C + (CS || 1) - 1 } }); + var o9 = { t: "s", v: v4 }; + var _t = elt.getAttribute("data-t") || elt.getAttribute("t") || ""; + if (v4 != null) { + if (v4.length == 0) o9.t = _t || "z"; + else if (opts.raw || v4.trim().length == 0 || _t == "s") { + } else if (_t == "e" && BErr[+v4]) o9 = { t: "e", v: +v4, w: BErr[+v4] }; + else if (v4 === "TRUE") o9 = { t: "b", v: true }; + else if (v4 === "FALSE") o9 = { t: "b", v: false }; + else if (!isNaN(fuzzynum(v4))) o9 = { t: "n", v: fuzzynum(v4) }; + else if (!isNaN(fuzzydate(v4).getDate())) { + o9 = { t: "d", v: parseDate(v4) }; + if (opts.UTC) o9.v = local_to_utc(o9.v); + if (!opts.cellDates) o9 = { t: "n", v: datenum(o9.v) }; + o9.z = opts.dateNF || table_fmt[14]; + } else if (v4.charCodeAt(0) == 35 && RBErr[v4] != null) o9 = { t: "e", v: RBErr[v4], w: v4 }; + } + if (o9.z === void 0 && z3 != null) o9.z = z3; + var l5 = "", Aelts = elt.getElementsByTagName("A"); + if (Aelts && Aelts.length) { + for (var Aelti = 0; Aelti < Aelts.length; ++Aelti) if (Aelts[Aelti].hasAttribute("href")) { + l5 = Aelts[Aelti].getAttribute("href"); + if (l5.charAt(0) != "#") break; + } + } + if (l5 && l5.charAt(0) != "#" && l5.slice(0, 11).toLowerCase() != "javascript:") o9.l = { Target: l5 }; + if (dense) { + if (!ws["!data"][R3 + or_R]) ws["!data"][R3 + or_R] = []; + ws["!data"][R3 + or_R][C3 + or_C] = o9; + } else ws[encode_cell({ c: C3 + or_C, r: R3 + or_R })] = o9; + if (range2.e.c < C3 + or_C) range2.e.c = C3 + or_C; + C3 += CS; + } + ++R3; + } + if (merges.length) ws["!merges"] = (ws["!merges"] || []).concat(merges); + range2.e.r = Math.max(range2.e.r, R3 - 1 + or_R); + ws["!ref"] = encode_range(range2); + if (R3 >= sheetRows) ws["!fullref"] = encode_range((range2.e.r = rows.length - _R + R3 - 1 + or_R, range2)); + return ws; +} +function parse_dom_table(table, _opts) { + var opts = _opts || {}; + var ws = {}; + if (opts.dense) ws["!data"] = []; + return sheet_add_dom(ws, table, _opts); +} +function table_to_book(table, opts) { + var o9 = sheet_to_workbook(parse_dom_table(table, opts), opts); + return o9; +} +function is_dom_element_hidden(element) { + var display = ""; + var get_computed_style = get_get_computed_style_function(element); + if (get_computed_style) display = get_computed_style(element).getPropertyValue("display"); + if (!display) display = element.style && element.style.display; + return display === "none"; +} +function get_get_computed_style_function(element) { + if (element.ownerDocument.defaultView && typeof element.ownerDocument.defaultView.getComputedStyle === "function") return element.ownerDocument.defaultView.getComputedStyle; + if (typeof getComputedStyle === "function") return getComputedStyle; + return null; +} +function parse_text_p(text3) { + var fixed = text3.replace(/[\t\r\n]/g, " ").trim().replace(/ +/g, " ").replace(//g, " ").replace(//g, function($$, $1) { + return Array(parseInt($1, 10) + 1).join(" "); + }).replace(/]*\/>/g, " ").replace(//g, "\n"); + var v4 = unescapexml(fixed.replace(/<[^<>]*>/g, "")); + return [v4]; +} +function parse_ods_styles(d4, _opts, _nfm) { + var number_format_map = _nfm || {}; + var str2 = xlml_normalize(d4); + xlmlregex.lastIndex = 0; + str2 = remove_doctype(str_remove_ng(str2, "")); + var Rn, NFtag, NF = "", tNF = "", y4, etpos = 0, tidx = -1, infmt = false, payload = ""; + while (Rn = xlmlregex.exec(str2)) { + switch (Rn[3] = Rn[3].replace(/_[\s\S]*$/, "")) { + /* Number Format Definitions */ + case "number-style": + // 16.29.2 + case "currency-style": + // 16.29.8 + case "percentage-style": + // 16.29.10 + case "date-style": + // 16.29.11 + case "time-style": + // 16.29.19 + case "text-style": + if (Rn[1] === "/") { + infmt = false; + if (NFtag["truncate-on-overflow"] == "false") { + if (NF.match(/h/)) NF = NF.replace(/h+/, "[$&]"); + else if (NF.match(/m/)) NF = NF.replace(/m+/, "[$&]"); + else if (NF.match(/s/)) NF = NF.replace(/s+/, "[$&]"); + } + number_format_map[NFtag.name] = NF; + NF = ""; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + infmt = true; + NF = ""; + NFtag = parsexmltag(Rn[0], false); + } + break; + // LibreOffice bug https://bugs.documentfoundation.org/show_bug.cgi?id=149484 + case "boolean-style": + if (Rn[1] === "/") { + infmt = false; + number_format_map[NFtag.name] = "General"; + NF = ""; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + infmt = true; + NF = ""; + NFtag = parsexmltag(Rn[0], false); + } + break; + /* Number Format Elements */ + case "boolean": + NF += "General"; + break; + case "text": + if (Rn[1] === "/") { + payload = str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length); + if (payload == "%" && NFtag[0] == " 16.29.17 + case "quarter": + console.error("Excel does not support ODS format token " + Rn[3]); + break; + case "fill-character": + if (Rn[1] === "/") { + payload = str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length); + NF += '"' + payload.replace(/"/g, '""') + '"*'; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + tidx = xlmlregex.lastIndex; + } + break; + case "scientific-number": + y4 = parsexmltag(Rn[0], false); + NF += "0." + fill("0", +y4["min-decimal-places"] || +y4["decimal-places"] || 2) + fill("?", +y4["decimal-places"] - +y4["min-decimal-places"] || 0) + "E" + (parsexmlbool(y4["forced-exponent-sign"]) ? "+" : "") + fill("0", +y4["min-exponent-digits"] || 2); + break; + case "fraction": + y4 = parsexmltag(Rn[0], false); + if (!+y4["min-integer-digits"]) NF += "#"; + else NF += fill("0", +y4["min-integer-digits"]); + NF += " "; + NF += fill("?", +y4["min-numerator-digits"] || 1); + NF += "/"; + if (+y4["denominator-value"]) NF += y4["denominator-value"]; + else NF += fill("?", +y4["min-denominator-digits"] || 1); + break; + case "currency-symbol": + if (Rn[1] === "/") { + NF += '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"'; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + tidx = xlmlregex.lastIndex; + } else NF += "$"; + break; + case "text-properties": + y4 = parsexmltag(Rn[0], false); + switch ((y4["color"] || "").toLowerCase().replace("#", "")) { + case "ff0000": + case "red": + NF = "[Red]" + NF; + break; + } + break; + case "text-content": + NF += "@"; + break; + case "map": + y4 = parsexmltag(Rn[0], false); + if (unescapexml(y4["condition"]) == "value()>=0") NF = number_format_map[y4["apply-style-name"]] + ";" + NF; + else console.error("ODS number format may be incorrect: " + y4["condition"]); + break; + case "number": + if (Rn[1] === "/") break; + y4 = parsexmltag(Rn[0], false); + tNF = ""; + tNF += fill("0", +y4["min-integer-digits"] || 1); + if (parsexmlbool(y4["grouping"])) tNF = commaify(fill("#", Math.max(0, 4 - tNF.length)) + tNF); + if (+y4["min-decimal-places"] || +y4["decimal-places"]) tNF += "."; + if (+y4["min-decimal-places"]) tNF += fill("0", +y4["min-decimal-places"] || 1); + if (+y4["decimal-places"] - (+y4["min-decimal-places"] || 0)) tNF += fill("0", +y4["decimal-places"] - (+y4["min-decimal-places"] || 0)); + NF += tNF; + break; + case "embedded-text": + if (Rn[1] === "/") { + if (etpos == 0) NF += '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"'; + else NF = NF.slice(0, etpos) + '"' + str2.slice(tidx, xlmlregex.lastIndex - Rn[0].length).replace(/"/g, '""') + '"' + NF.slice(etpos); + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + tidx = xlmlregex.lastIndex; + etpos = -+parsexmltag(Rn[0], false)["position"] || 0; + } + break; + } + } + return number_format_map; +} +function parse_content_xml(d4, _opts, _nfm) { + var opts = _opts || {}; + if (DENSE != null && opts.dense == null) opts.dense = DENSE; + var str2 = xlml_normalize(d4); + var state = [], tmp; + var tag; + var nfidx, NF = "", pidx = 0; + var sheetag; + var rowtag; + var Sheets = {}, SheetNames = []; + var ws = {}; + if (opts.dense) ws["!data"] = []; + var Rn, q2; + var ctag = { value: "" }, ctag2 = {}; + var textp = "", textpidx = 0, textptag, oldtextp = "", oldtextpidx = 0; + var textR = [], oldtextR = []; + var R3 = -1, C3 = -1, range2 = { s: { r: 1e6, c: 1e7 }, e: { r: 0, c: 0 } }; + var row_ol = 0; + var number_format_map = _nfm || {}, styles2 = {}; + var merges = [], mrange = {}, mR = 0, mC = 0; + var rowinfo = [], rowpeat = 1, colpeat = 1; + var arrayf = []; + var WB = { Names: [], WBProps: {} }; + var atag = {}; + var _Ref = ["", ""]; + var comments = [], comment = {}; + var creator = "", creatoridx = 0; + var isstub = false, intable = false; + var i7 = 0; + xlmlregex.lastIndex = 0; + str2 = remove_doctype(str_remove_ng(str2, "")); + while (Rn = xlmlregex.exec(str2)) switch (Rn[3] = Rn[3].replace(/_[\s\S]*$/, "")) { + case "table": + case "\u5DE5\u4F5C\u8868": + if (Rn[1] === "/") { + if (range2.e.c >= range2.s.c && range2.e.r >= range2.s.r) ws["!ref"] = encode_range(range2); + else ws["!ref"] = "A1:A1"; + if (opts.sheetRows > 0 && opts.sheetRows <= range2.e.r) { + ws["!fullref"] = ws["!ref"]; + range2.e.r = opts.sheetRows - 1; + ws["!ref"] = encode_range(range2); + } + if (merges.length) ws["!merges"] = merges; + if (rowinfo.length) ws["!rows"] = rowinfo; + sheetag.name = sheetag["\u540D\u79F0"] || sheetag.name; + if (typeof JSON !== "undefined") JSON.stringify(sheetag); + SheetNames.push(sheetag.name); + Sheets[sheetag.name] = ws; + intable = false; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + sheetag = parsexmltag(Rn[0], false); + R3 = C3 = -1; + range2.s.r = range2.s.c = 1e7; + range2.e.r = range2.e.c = 0; + ws = {}; + if (opts.dense) ws["!data"] = []; + merges = []; + rowinfo = []; + intable = true; + } + break; + case "table-row-group": + if (Rn[1] === "/") --row_ol; + else ++row_ol; + break; + case "table-row": + case "\u884C": + if (Rn[1] === "/") { + R3 += rowpeat; + rowpeat = 1; + break; + } + rowtag = parsexmltag(Rn[0], false); + if (rowtag["\u884C\u53F7"]) R3 = rowtag["\u884C\u53F7"] - 1; + else if (R3 == -1) R3 = 0; + rowpeat = +rowtag["number-rows-repeated"] || 1; + if (rowpeat < 10) { + for (i7 = 0; i7 < rowpeat; ++i7) if (row_ol > 0) rowinfo[R3 + i7] = { level: row_ol }; + } + C3 = -1; + break; + case "covered-table-cell": + if (Rn[1] !== "/") { + ++C3; + ctag = parsexmltag(Rn[0], false); + colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10) || 1; + if (opts.sheetStubs) { + while (colpeat-- > 0) { + if (opts.dense) { + if (!ws["!data"][R3]) ws["!data"][R3] = []; + ws["!data"][R3][C3] = { t: "z" }; + } else ws[encode_cell({ r: R3, c: C3 })] = { t: "z" }; + ++C3; + } + --C3; + } else C3 += colpeat - 1; + } + textp = ""; + textR = []; + break; + /* stub */ + case "table-cell": + case "\u6570\u636E": + if (Rn[0].charAt(Rn[0].length - 2) === "/") { + ++C3; + ctag = parsexmltag(Rn[0], false); + colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10) || 1; + q2 = { + t: "z", + v: null + /*:: , z:null, w:"",c:[]*/ + }; + if (ctag.formula && opts.cellFormula != false) q2.f = ods_to_csf_formula(unescapexml(ctag.formula)); + if (ctag["style-name"] && styles2[ctag["style-name"]]) q2.z = styles2[ctag["style-name"]]; + if ((ctag["\u6570\u636E\u7C7B\u578B"] || ctag["value-type"]) == "string") { + q2.t = "s"; + q2.v = unescapexml(ctag["string-value"] || ""); + if (opts.dense) { + if (!ws["!data"][R3]) ws["!data"][R3] = []; + ws["!data"][R3][C3] = q2; + } else { + ws[encode_col(C3) + encode_row(R3)] = q2; + } + } + C3 += colpeat - 1; + } else if (Rn[1] !== "/") { + ++C3; + textp = oldtextp = ""; + textpidx = oldtextpidx = 0; + textR = []; + oldtextR = []; + colpeat = 1; + var rptR = rowpeat ? R3 + rowpeat - 1 : R3; + if (C3 > range2.e.c) range2.e.c = C3; + if (C3 < range2.s.c) range2.s.c = C3; + if (R3 < range2.s.r) range2.s.r = R3; + if (rptR > range2.e.r) range2.e.r = rptR; + ctag = parsexmltag(Rn[0], false); + ctag2 = parsexmltagraw(Rn[0], true); + comments = []; + comment = {}; + q2 = { + t: ctag["\u6570\u636E\u7C7B\u578B"] || ctag["value-type"], + v: null + /*:: , z:null, w:"",c:[]*/ + }; + if (ctag["style-name"] && styles2[ctag["style-name"]]) q2.z = styles2[ctag["style-name"]]; + if (opts.cellFormula) { + if (ctag.formula) ctag.formula = unescapexml(ctag.formula); + if (ctag["number-matrix-columns-spanned"] && ctag["number-matrix-rows-spanned"]) { + mR = parseInt(ctag["number-matrix-rows-spanned"], 10) || 0; + mC = parseInt(ctag["number-matrix-columns-spanned"], 10) || 0; + mrange = { s: { r: R3, c: C3 }, e: { r: R3 + mR - 1, c: C3 + mC - 1 } }; + q2.F = encode_range(mrange); + arrayf.push([mrange, q2.F]); + } + if (ctag.formula) q2.f = ods_to_csf_formula(ctag.formula); + else for (i7 = 0; i7 < arrayf.length; ++i7) + if (R3 >= arrayf[i7][0].s.r && R3 <= arrayf[i7][0].e.r) { + if (C3 >= arrayf[i7][0].s.c && C3 <= arrayf[i7][0].e.c) + q2.F = arrayf[i7][1]; + } + } + if (ctag["number-columns-spanned"] || ctag["number-rows-spanned"]) { + mR = parseInt(ctag["number-rows-spanned"] || "1", 10) || 1; + mC = parseInt(ctag["number-columns-spanned"] || "1", 10) || 1; + if (mR * mC > 1) { + mrange = { s: { r: R3, c: C3 }, e: { r: R3 + mR - 1, c: C3 + mC - 1 } }; + merges.push(mrange); + } + } + if (ctag["number-columns-repeated"]) colpeat = parseInt(ctag["number-columns-repeated"], 10); + switch (q2.t) { + case "boolean": + q2.t = "b"; + q2.v = parsexmlbool(ctag["boolean-value"]) || +ctag["boolean-value"] >= 1; + break; + case "float": + q2.t = "n"; + q2.v = parseFloat(ctag.value); + if (opts.cellDates && q2.z && fmt_is_date(q2.z)) { + q2.v = numdate(q2.v + (WB.WBProps.date1904 ? 1462 : 0)); + q2.t = typeof q2.v == "number" ? "n" : "d"; + } + break; + case "percentage": + q2.t = "n"; + q2.v = parseFloat(ctag.value); + break; + case "currency": + q2.t = "n"; + q2.v = parseFloat(ctag.value); + break; + case "date": + q2.t = "d"; + q2.v = parseDate(ctag["date-value"], WB.WBProps.date1904); + if (!opts.cellDates) { + q2.t = "n"; + q2.v = datenum(q2.v, WB.WBProps.date1904); + } + if (!q2.z) q2.z = "m/d/yy"; + break; + /* NOTE: for `time`, Excel ODS export incorrectly uses durations relative to 1900 epoch even if 1904 is specified */ + case "time": + q2.t = "n"; + q2.v = parse_isodur(ctag["time-value"]) / 86400; + if (opts.cellDates) { + q2.v = numdate(q2.v); + q2.t = typeof q2.v == "number" ? "n" : "d"; + } + if (!q2.z) q2.z = "HH:MM:SS"; + break; + case "number": + q2.t = "n"; + q2.v = parseFloat(ctag["\u6570\u636E\u6570\u503C"]); + break; + default: + if (q2.t === "string" || q2.t === "text" || !q2.t) { + q2.t = "s"; + if (ctag["string-value"] != null) { + textp = unescapexml(ctag["string-value"]); + textR = []; + } + } else throw new Error("Unsupported value type " + q2.t); + } + } else { + isstub = false; + if (ctag2["calcext:value-type"] == "error" && RBErr[textp] != null) { + q2.t = "e"; + q2.w = textp; + q2.v = RBErr[textp]; + } + if (q2.t === "s") { + q2.v = textp || ""; + if (textR.length) q2.R = textR; + isstub = textpidx == 0; + } + if (atag.Target) q2.l = atag; + if (comments.length > 0) { + q2.c = comments; + comments = []; + } + if (textp && opts.cellText !== false) q2.w = textp; + if (isstub) { + q2.t = "z"; + delete q2.v; + } + if (!isstub || opts.sheetStubs) { + if (!(opts.sheetRows && opts.sheetRows <= R3)) { + for (var rpt = 0; rpt < rowpeat; ++rpt) { + colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10); + if (opts.dense) { + if (!ws["!data"][R3 + rpt]) ws["!data"][R3 + rpt] = []; + ws["!data"][R3 + rpt][C3] = rpt == 0 ? q2 : dup(q2); + while (--colpeat > 0) ws["!data"][R3 + rpt][C3 + colpeat] = dup(q2); + } else { + ws[encode_cell({ r: R3 + rpt, c: C3 })] = q2; + while (--colpeat > 0) ws[encode_cell({ r: R3 + rpt, c: C3 + colpeat })] = dup(q2); + } + if (range2.e.c <= C3) range2.e.c = C3; + } + } + } + colpeat = parseInt(ctag["number-columns-repeated"] || "1", 10); + C3 += colpeat - 1; + colpeat = 0; + q2 = { + /*:: t:"", v:null, z:null, w:"",c:[]*/ + }; + textp = ""; + textR = []; + } + atag = {}; + break; + // 9.1.4 + /* pure state */ + case "document": + // TODO: is the root for FODS + case "document-content": + case "\u7535\u5B50\u8868\u683C\u6587\u6863": + // 3.1.3.2 + case "spreadsheet": + case "\u4E3B\u4F53": + // 3.7 + case "scripts": + // 3.12 + case "styles": + // TODO + case "font-face-decls": + // 3.14 + case "master-styles": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], true]); + break; + case "annotation": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp; + comment.t = textp; + if (textR.length) comment.R = textR; + comment.a = creator; + comments.push(comment); + textp = oldtextp; + textpidx = oldtextpidx; + textR = oldtextR; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + state.push([Rn[3], false]); + var annotag = parsexmltag(Rn[0], true); + if (!(annotag["display"] && parsexmlbool(annotag["display"]))) comments.hidden = true; + oldtextp = textp; + oldtextpidx = textpidx; + oldtextR = textR; + textp = ""; + textpidx = 0; + textR = []; + } + creator = ""; + creatoridx = 0; + break; + case "creator": + if (Rn[1] === "/") { + creator = str2.slice(creatoridx, Rn.index); + } else creatoridx = Rn.index + Rn[0].length; + break; + /* ignore state */ + case "meta": + case "\u5143\u6570\u636E": + // TODO: FODS/UOF + case "settings": + // TODO: + case "config-item-set": + // TODO: + case "config-item-map-indexed": + // TODO: + case "config-item-map-entry": + // TODO: + case "config-item-map-named": + // TODO: + case "shapes": + // 9.2.8 + case "frame": + // 10.4.2 + case "text-box": + // 10.4.3 + case "image": + // 10.4.4 + case "data-pilot-tables": + // 9.6.2 + case "list-style": + // 16.30 + case "form": + // 13.13 + case "dde-links": + // 9.8 + case "event-listeners": + // TODO + case "chart": + if (Rn[1] === "/") { + if ((tmp = state.pop())[0] !== Rn[3]) throw "Bad state: " + tmp; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") state.push([Rn[3], false]); + textp = ""; + textpidx = 0; + textR = []; + break; + case "scientific-number": + // + case "currency-symbol": + // + case "fill-character": + break; + case "text-style": + // 16.27.25 + case "boolean-style": + // 16.27.23 + case "number-style": + // 16.27.2 + case "currency-style": + // 16.29.8 + case "percentage-style": + // 16.27.9 + case "date-style": + // 16.27.10 + case "time-style": + if (Rn[1] === "/") { + var xlmlidx = xlmlregex.lastIndex; + parse_ods_styles(str2.slice(nfidx, xlmlregex.lastIndex), _opts, number_format_map); + xlmlregex.lastIndex = xlmlidx; + } else if (Rn[0].charAt(Rn[0].length - 2) !== "/") { + nfidx = xlmlregex.lastIndex - Rn[0].length; + } + break; + case "script": + break; + // 3.13 + case "libraries": + break; + // TODO: + case "automatic-styles": + break; + // 3.15.3 + case "default-style": + // TODO: + case "page-layout": + break; + // TODO: + case "style": + { + var styletag = parsexmltag(Rn[0], false); + if (styletag["family"] == "table-cell" && number_format_map[styletag["data-style-name"]]) styles2[styletag["name"]] = number_format_map[styletag["data-style-name"]]; + } + break; + case "map": + break; + // 16.3 + case "font-face": + break; + // 16.21 + case "paragraph-properties": + break; + // 17.6 + case "table-properties": + break; + // 17.15 + case "table-column-properties": + break; + // 17.16 + case "table-row-properties": + break; + // 17.17 + case "table-cell-properties": + break; + // 17.18 + case "number": + break; + case "fraction": + break; + // TODO 16.27.6 + case "day": + // 16.27.11 + case "month": + // 16.27.12 + case "year": + // 16.27.13 + case "era": + // 16.27.14 + case "day-of-week": + // 16.27.15 + case "week-of-year": + // 16.27.16 + case "quarter": + // 16.27.17 + case "hours": + // 16.27.19 + case "minutes": + // 16.27.20 + case "seconds": + // 16.27.21 + case "am-pm": + break; + case "boolean": + break; + // 16.27.24 + case "text": + if (Rn[0].slice(-2) === "/>") break; + else if (Rn[1] === "/") switch (state[state.length - 1][0]) { + case "number-style": + case "date-style": + case "time-style": + NF += str2.slice(pidx, Rn.index); + break; + } + else pidx = Rn.index + Rn[0].length; + break; + case "named-range": + tag = parsexmltag(Rn[0], false); + _Ref = ods_to_csf_3D(tag["cell-range-address"]); + var nrange = { Name: tag.name, Ref: _Ref[0] + "!" + _Ref[1] }; + if (intable) nrange.Sheet = SheetNames.length; + WB.Names.push(nrange); + break; + case "text-content": + break; + // 16.27.27 + case "text-properties": + break; + // 16.27.27 + case "embedded-text": + break; + // 16.27.4 + case "body": + case "\u7535\u5B50\u8868\u683C": + break; + // 3.3 16.9.6 19.726.3 + case "forms": + break; + // 12.25.2 13.2 + case "table-column": + break; + // 9.1.6 + case "table-header-rows": + break; + // 9.1.7 + case "table-rows": + break; + // 9.1.12 + /* TODO: outline levels */ + case "table-column-group": + break; + // 9.1.10 + case "table-header-columns": + break; + // 9.1.11 + case "table-columns": + break; + // 9.1.12 + case "null-date": + tag = parsexmltag(Rn[0], false); + switch (tag["date-value"]) { + case "1904-01-01": + WB.WBProps.date1904 = true; + break; + } + break; + case "graphic-properties": + break; + // 17.21 + case "calculation-settings": + break; + // 9.4.1 + case "named-expressions": + break; + // 9.4.11 + case "label-range": + break; + // 9.4.9 + case "label-ranges": + break; + // 9.4.10 + case "named-expression": + break; + // 9.4.13 + case "sort": + break; + // 9.4.19 + case "sort-by": + break; + // 9.4.20 + case "sort-groups": + break; + // 9.4.22 + case "tab": + break; + // 6.1.4 + case "line-break": + break; + // 6.1.5 + case "span": + break; + // 6.1.7 + case "p": + case "\u6587\u672C\u4E32": + if (["master-styles"].indexOf(state[state.length - 1][0]) > -1) break; + if (Rn[1] === "/" && (!ctag || !ctag["string-value"])) { + var ptp = parse_text_p(str2.slice(textpidx, Rn.index), textptag); + textp = (textp.length > 0 ? textp + "\n" : "") + ptp[0]; + } else if (Rn[0].slice(-2) == "/>") { + textp += "\n"; + } else { + textptag = parsexmltag(Rn[0], false); + textpidx = Rn.index + Rn[0].length; + } + break; + // + case "s": + break; + // + case "database-range": + if (Rn[1] === "/") break; + try { + _Ref = ods_to_csf_3D(parsexmltag(Rn[0])["target-range-address"]); + Sheets[_Ref[0]]["!autofilter"] = { ref: _Ref[1] }; + } catch (e9) { + } + break; + case "date": + break; + // <*:date> + case "object": + break; + // 10.4.6.2 + case "title": + case "\u6807\u9898": + break; + // <*:title> OR + case "desc": + break; + // <*:desc> + case "binary-data": + break; + // 10.4.5 TODO: b64 blob + /* 9.2 Advanced Tables */ + case "table-source": + break; + // 9.2.6 + case "scenario": + break; + // 9.2.6 + case "iteration": + break; + // 9.4.3 + case "content-validations": + break; + // 9.4.4 + /* 9.5 Filters */ + case "filter": + break; + // 9.5.2 + case "filter-and": + break; + // 9.5.3 + case "filter-or": + break; + // 9.5.4 + case "filter-condition": + break; + // 9.5.5 + case "filter-set-item": + break; + // 9.5.6 + case "list-level-style-bullet": + break; + // 16.31 + case "page-count": + break; + // TODO + case "time": + break; + // TODO + /* 9.3 Advanced Table Cells */ + case "cell-range-source": + break; + // 9.3.1 + case "property": + break; + // 13.8 + case "a": + if (Rn[1] !== "/") { + atag = parsexmltag(Rn[0], false); + if (!atag.href) break; + atag.Target = unescapexml(atag.href); + delete atag.href; + if (atag.Target.charAt(0) == "#" && atag.Target.indexOf(".") > -1) { + _Ref = ods_to_csf_3D(atag.Target.slice(1)); + atag.Target = "#" + _Ref[0] + "!" + _Ref[1]; + } else if (atag.Target.match(/^\.\.[\\\/]/)) atag.Target = atag.Target.slice(3); + } + break; + /* non-standard */ + case "table-protection": + break; + case "data-pilot-grand-total": + break; + // > 1 & 1431655765; + x2 = (x2 & 858993459) + (x2 >> 2 & 858993459); + return (x2 + (x2 >> 4) & 252645135) * 16843009 >>> 24; +} +function readDecimal128LE(buf, offset) { + var exp = (buf[offset + 15] & 127) << 7 | buf[offset + 14] >> 1; + var mantissa = buf[offset + 14] & 1; + for (var j3 = offset + 13; j3 >= offset; --j3) + mantissa = mantissa * 256 + buf[j3]; + return (buf[offset + 15] & 128 ? -mantissa : mantissa) * Math.pow(10, exp - 6176); +} +function parse_varint49(buf, ptr) { + var l5 = ptr.l; + var usz = buf[l5] & 127; + varint: + if (buf[l5++] >= 128) { + usz |= (buf[l5] & 127) << 7; + if (buf[l5++] < 128) + break varint; + usz |= (buf[l5] & 127) << 14; + if (buf[l5++] < 128) + break varint; + usz |= (buf[l5] & 127) << 21; + if (buf[l5++] < 128) + break varint; + usz += (buf[l5] & 127) * Math.pow(2, 28); + ++l5; + if (buf[l5++] < 128) + break varint; + usz += (buf[l5] & 127) * Math.pow(2, 35); + ++l5; + if (buf[l5++] < 128) + break varint; + usz += (buf[l5] & 127) * Math.pow(2, 42); + ++l5; + if (buf[l5++] < 128) + break varint; + } + ptr.l = l5; + return usz; +} +function varint_to_i32(buf) { + var l5 = 0, i32 = buf[l5] & 127; + if (buf[l5++] < 128) + return i32; + i32 |= (buf[l5] & 127) << 7; + if (buf[l5++] < 128) + return i32; + i32 |= (buf[l5] & 127) << 14; + if (buf[l5++] < 128) + return i32; + i32 |= (buf[l5] & 127) << 21; + if (buf[l5++] < 128) + return i32; + i32 |= (buf[l5] & 15) << 28; + return i32; +} +function parse_shallow(buf) { + var out = [], ptr = { l: 0 }; + while (ptr.l < buf.length) { + var off = ptr.l; + var num = parse_varint49(buf, ptr); + var type = num & 7; + num = num / 8 | 0; + var data; + var l5 = ptr.l; + switch (type) { + case 0: + { + while (buf[l5++] >= 128) + ; + data = buf[subarray](ptr.l, l5); + ptr.l = l5; + } + break; + case 1: + { + data = buf[subarray](l5, l5 + 8); + ptr.l = l5 + 8; + } + break; + case 2: + { + var len = parse_varint49(buf, ptr); + data = buf[subarray](ptr.l, ptr.l + len); + ptr.l += len; + } + break; + case 5: + { + data = buf[subarray](l5, l5 + 4); + ptr.l = l5 + 4; + } + break; + default: + throw new Error("PB Type ".concat(type, " for Field ").concat(num, " at offset ").concat(off)); + } + var v4 = { data, type }; + if (out[num] == null) + out[num] = []; + out[num].push(v4); + } + return out; +} +function mappa(data, cb) { + return (data == null ? void 0 : data.map(function(d4) { + return cb(d4.data); + })) || []; +} +function parse_iwa_file(buf) { + var _a7; + var out = [], ptr = { l: 0 }; + while (ptr.l < buf.length) { + var len = parse_varint49(buf, ptr); + var ai = parse_shallow(buf[subarray](ptr.l, ptr.l + len)); + ptr.l += len; + var res = { + id: varint_to_i32(ai[1][0].data), + messages: [] + }; + ai[2].forEach(function(b4) { + var mi = parse_shallow(b4.data); + var fl = varint_to_i32(mi[3][0].data); + res.messages.push({ + meta: mi, + data: buf[subarray](ptr.l, ptr.l + fl) + }); + ptr.l += fl; + }); + if ((_a7 = ai[3]) == null ? void 0 : _a7[0]) + res.merge = varint_to_i32(ai[3][0].data) >>> 0 > 0; + out.push(res); + } + return out; +} +function parse_snappy_chunk(type, buf) { + if (type != 0) + throw new Error("Unexpected Snappy chunk type ".concat(type)); + var ptr = { l: 0 }; + var usz = parse_varint49(buf, ptr); + var chunks = []; + var l5 = ptr.l; + while (l5 < buf.length) { + var tag = buf[l5] & 3; + if (tag == 0) { + var len = buf[l5++] >> 2; + if (len < 60) + ++len; + else { + var c6 = len - 59; + len = buf[l5]; + if (c6 > 1) + len |= buf[l5 + 1] << 8; + if (c6 > 2) + len |= buf[l5 + 2] << 16; + if (c6 > 3) + len |= buf[l5 + 3] << 24; + len >>>= 0; + len++; + l5 += c6; + } + chunks.push(buf[subarray](l5, l5 + len)); + l5 += len; + continue; + } else { + var offset = 0, length = 0; + if (tag == 1) { + length = (buf[l5] >> 2 & 7) + 4; + offset = (buf[l5++] & 224) << 3; + offset |= buf[l5++]; + } else { + length = (buf[l5++] >> 2) + 1; + if (tag == 2) { + offset = buf[l5] | buf[l5 + 1] << 8; + l5 += 2; + } else { + offset = (buf[l5] | buf[l5 + 1] << 8 | buf[l5 + 2] << 16 | buf[l5 + 3] << 24) >>> 0; + l5 += 4; + } + } + if (offset == 0) + throw new Error("Invalid offset 0"); + var j3 = chunks.length - 1, off = offset; + while (j3 >= 0 && off >= chunks[j3].length) { + off -= chunks[j3].length; + --j3; + } + if (j3 < 0) { + if (off == 0) + off = chunks[j3 = 0].length; + else + throw new Error("Invalid offset beyond length"); + } + if (length < off) + chunks.push(chunks[j3][subarray](chunks[j3].length - off, chunks[j3].length - off + length)); + else { + if (off > 0) { + chunks.push(chunks[j3][subarray](chunks[j3].length - off)); + length -= off; + } + ++j3; + while (length >= chunks[j3].length) { + chunks.push(chunks[j3]); + length -= chunks[j3].length; + ++j3; + } + if (length) + chunks.push(chunks[j3][subarray](0, length)); + } + if (chunks.length > 25) + chunks = [u8concat(chunks)]; + } + } + var clen = 0; + for (var u8i = 0; u8i < chunks.length; ++u8i) + clen += chunks[u8i].length; + if (clen != usz) + throw new Error("Unexpected length: ".concat(clen, " != ").concat(usz)); + return chunks; +} +function decompress_iwa_file(buf) { + if (Array.isArray(buf)) + buf = new Uint8Array(buf); + var out = []; + var l5 = 0; + while (l5 < buf.length) { + var t6 = buf[l5++]; + var len = buf[l5] | buf[l5 + 1] << 8 | buf[l5 + 2] << 16; + l5 += 3; + out.push.apply(out, parse_snappy_chunk(t6, buf[subarray](l5, l5 + len))); + l5 += len; + } + if (l5 !== buf.length) + throw new Error("data is not a valid framed stream!"); + return out.length == 1 ? out[0] : u8concat(out); +} +function numbers_format_cell(cell, t6, flags, ofmt, nfmt) { + var _a7, _b, _c, _d; + var ctype = t6 & 255, ver = t6 >> 8; + var fmt = ver >= 5 ? nfmt : ofmt; + dur: + if (flags & (ver > 4 ? 8 : 4) && cell.t == "n" && ctype == 7) { + var dstyle = ((_a7 = fmt[7]) == null ? void 0 : _a7[0]) ? varint_to_i32(fmt[7][0].data) : -1; + if (dstyle == -1) + break dur; + var dmin = ((_b = fmt[15]) == null ? void 0 : _b[0]) ? varint_to_i32(fmt[15][0].data) : -1; + var dmax = ((_c = fmt[16]) == null ? void 0 : _c[0]) ? varint_to_i32(fmt[16][0].data) : -1; + var auto = ((_d = fmt[40]) == null ? void 0 : _d[0]) ? varint_to_i32(fmt[40][0].data) : -1; + var d4 = cell.v, dd = d4; + autodur: + if (auto) { + if (d4 == 0) { + dmin = dmax = 2; + break autodur; + } + if (d4 >= 604800) + dmin = 1; + else if (d4 >= 86400) + dmin = 2; + else if (d4 >= 3600) + dmin = 4; + else if (d4 >= 60) + dmin = 8; + else if (d4 >= 1) + dmin = 16; + else + dmin = 32; + if (Math.floor(d4) != d4) + dmax = 32; + else if (d4 % 60) + dmax = 16; + else if (d4 % 3600) + dmax = 8; + else if (d4 % 86400) + dmax = 4; + else if (d4 % 604800) + dmax = 2; + if (dmax < dmin) + dmax = dmin; + } + if (dmin == -1 || dmax == -1) + break dur; + var dstr = [], zstr = []; + if (dmin == 1) { + dd = d4 / 604800; + if (dmax == 1) { + zstr.push('d"d"'); + } else { + dd |= 0; + d4 -= 604800 * dd; + } + dstr.push(dd + (dstyle == 2 ? " week" + (dd == 1 ? "" : "s") : dstyle == 1 ? "w" : "")); + } + if (dmin <= 2 && dmax >= 2) { + dd = d4 / 86400; + if (dmax > 2) { + dd |= 0; + d4 -= 86400 * dd; + } + zstr.push('d"d"'); + dstr.push(dd + (dstyle == 2 ? " day" + (dd == 1 ? "" : "s") : dstyle == 1 ? "d" : "")); + } + if (dmin <= 4 && dmax >= 4) { + dd = d4 / 3600; + if (dmax > 4) { + dd |= 0; + d4 -= 3600 * dd; + } + zstr.push((dmin >= 4 ? "[h]" : "h") + '"h"'); + dstr.push(dd + (dstyle == 2 ? " hour" + (dd == 1 ? "" : "s") : dstyle == 1 ? "h" : "")); + } + if (dmin <= 8 && dmax >= 8) { + dd = d4 / 60; + if (dmax > 8) { + dd |= 0; + d4 -= 60 * dd; + } + zstr.push((dmin >= 8 ? "[m]" : "m") + '"m"'); + if (dstyle == 0) + dstr.push((dmin == 8 && dmax == 8 || dd >= 10 ? "" : "0") + dd); + else + dstr.push(dd + (dstyle == 2 ? " minute" + (dd == 1 ? "" : "s") : dstyle == 1 ? "m" : "")); + } + if (dmin <= 16 && dmax >= 16) { + dd = d4; + if (dmax > 16) { + dd |= 0; + d4 -= dd; + } + zstr.push((dmin >= 16 ? "[s]" : "s") + '"s"'); + if (dstyle == 0) + dstr.push((dmax == 16 && dmin == 16 || dd >= 10 ? "" : "0") + dd); + else + dstr.push(dd + (dstyle == 2 ? " second" + (dd == 1 ? "" : "s") : dstyle == 1 ? "s" : "")); + } + if (dmax >= 32) { + dd = Math.round(1e3 * d4); + if (dmin < 32) + zstr.push('.000"ms"'); + if (dstyle == 0) + dstr.push((dd >= 100 ? "" : dd >= 10 ? "0" : "00") + dd); + else + dstr.push(dd + (dstyle == 2 ? " millisecond" + (dd == 1 ? "" : "s") : dstyle == 1 ? "ms" : "")); + } + cell.w = dstr.join(dstyle == 0 ? ":" : " "); + cell.z = zstr.join(dstyle == 0 ? '":"' : " "); + if (dstyle == 0) + cell.w = cell.w.replace(/:(\d\d\d)$/, ".$1"); + } +} +function parse_old_storage(buf, lut, v4, opts) { + var dv = u8_to_dataview(buf); + var flags = dv.getUint32(4, true); + var ridx = -1, sidx = -1, zidx = -1, ieee = NaN, dc = 0, dt = new Date(Date.UTC(2001, 0, 1)); + var doff = v4 > 1 ? 12 : 8; + if (flags & 2) { + zidx = dv.getUint32(doff, true); + doff += 4; + } + doff += popcnt(flags & (v4 > 1 ? 3468 : 396)) * 4; + if (flags & 512) { + ridx = dv.getUint32(doff, true); + doff += 4; + } + doff += popcnt(flags & (v4 > 1 ? 12288 : 4096)) * 4; + if (flags & 16) { + sidx = dv.getUint32(doff, true); + doff += 4; + } + if (flags & 32) { + ieee = dv.getFloat64(doff, true); + doff += 8; + } + if (flags & 64) { + dt.setTime(dt.getTime() + (dc = dv.getFloat64(doff, true)) * 1e3); + doff += 8; + } + if (v4 > 1) { + flags = dv.getUint32(8, true) >>> 16; + if (flags & 255) { + if (zidx == -1) + zidx = dv.getUint32(doff, true); + doff += 4; + } + } + var ret; + var t6 = buf[v4 >= 4 ? 1 : 2]; + switch (t6) { + case 0: + return void 0; + case 2: + ret = { t: "n", v: ieee }; + break; + case 3: + ret = { t: "s", v: lut.sst[sidx] }; + break; + case 5: + { + if (opts == null ? void 0 : opts.cellDates) + ret = { t: "d", v: dt }; + else + ret = { t: "n", v: dc / 86400 + 35430, z: table_fmt[14] }; + } + break; + case 6: + ret = { t: "b", v: ieee > 0 }; + break; + case 7: + ret = { t: "n", v: ieee }; + break; + case 8: + ret = { t: "e", v: 0 }; + break; + case 9: + { + if (ridx > -1) { + var rts = lut.rsst[ridx]; + ret = { t: "s", v: rts.v }; + if (rts.l) + ret.l = { Target: rts.l }; + } else + throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4))); + } + break; + default: + throw new Error("Unsupported cell type ".concat(buf[subarray](0, 4))); + } + if (zidx > -1) + numbers_format_cell(ret, t6 | v4 << 8, flags, lut.ofmt[zidx], lut.nfmt[zidx]); + if (t6 == 7) + ret.v /= 86400; + return ret; +} +function parse_new_storage(buf, lut, opts) { + var dv = u8_to_dataview(buf); + var flags = dv.getUint32(4, true); + var fields = dv.getUint32(8, true); + var doff = 12; + var ridx = -1, sidx = -1, zidx = -1, d128 = NaN, ieee = NaN, dc = 0, dt = new Date(Date.UTC(2001, 0, 1)), eidx = -1, fidx = -1; + if (fields & 1) { + d128 = readDecimal128LE(buf, doff); + doff += 16; + } + if (fields & 2) { + ieee = dv.getFloat64(doff, true); + doff += 8; + } + if (fields & 4) { + dt.setTime(dt.getTime() + (dc = dv.getFloat64(doff, true)) * 1e3); + doff += 8; + } + if (fields & 8) { + sidx = dv.getUint32(doff, true); + doff += 4; + } + if (fields & 16) { + ridx = dv.getUint32(doff, true); + doff += 4; + } + doff += popcnt(fields & 480) * 4; + if (fields & 512) { + fidx = dv.getUint32(doff, true); + doff += 4; + } + doff += popcnt(fields & 1024) * 4; + if (fields & 2048) { + eidx = dv.getUint32(doff, true); + doff += 4; + } + var ret; + var t6 = buf[1]; + switch (t6) { + case 0: + ret = { t: "z" }; + break; + case 2: + ret = { t: "n", v: d128 }; + break; + case 3: + ret = { t: "s", v: lut.sst[sidx] }; + break; + case 5: + { + if (opts == null ? void 0 : opts.cellDates) + ret = { t: "d", v: dt }; + else + ret = { t: "n", v: dc / 86400 + 35430, z: table_fmt[14] }; + } + break; + case 6: + ret = { t: "b", v: ieee > 0 }; + break; + case 7: + ret = { t: "n", v: ieee }; + break; + case 8: + ret = { t: "e", v: 0 }; + break; + case 9: + { + if (ridx > -1) { + var rts = lut.rsst[ridx]; + ret = { t: "s", v: rts.v }; + if (rts.l) + ret.l = { Target: rts.l }; + } else + throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4))); + } + break; + case 10: + ret = { t: "n", v: d128 }; + break; + default: + throw new Error("Unsupported cell type ".concat(buf[1], " : ").concat(fields & 31, " : ").concat(buf[subarray](0, 4))); + } + doff += popcnt(fields & 4096) * 4; + if (fields & 516096) { + if (zidx == -1) + zidx = dv.getUint32(doff, true); + doff += 4; + } + if (fields & 524288) { + var cmntidx = dv.getUint32(doff, true); + doff += 4; + if (lut.cmnt[cmntidx]) + ret.c = iwa_to_s5s_comment(lut.cmnt[cmntidx]); + } + if (zidx > -1) + numbers_format_cell(ret, t6 | 5 << 8, fields >> 13, lut.ofmt[zidx], lut.nfmt[zidx]); + if (t6 == 7) + ret.v /= 86400; + return ret; +} +function parse_cell_storage(buf, lut, opts) { + switch (buf[0]) { + case 0: + case 1: + case 2: + case 3: + case 4: + return parse_old_storage(buf, lut, buf[0], opts); + case 5: + return parse_new_storage(buf, lut, opts); + default: + throw new Error("Unsupported payload version ".concat(buf[0])); + } +} +function parse_TSP_Reference(buf) { + var pb = parse_shallow(buf); + return varint_to_i32(pb[1][0].data); +} +function parse_TST_TableDataList(M4, root) { + var pb = parse_shallow(root.data); + var type = varint_to_i32(pb[1][0].data); + var entries = pb[3]; + var data = []; + (entries || []).forEach(function(entry) { + var _a7, _b; + var le2 = parse_shallow(entry.data); + if (!le2[1]) + return; + var key = varint_to_i32(le2[1][0].data) >>> 0; + switch (type) { + case 1: + data[key] = u8str(le2[3][0].data); + break; + case 8: + { + var rt = M4[parse_TSP_Reference(le2[9][0].data)][0]; + var rtp = parse_shallow(rt.data); + var rtpref = M4[parse_TSP_Reference(rtp[1][0].data)][0]; + var mtype = varint_to_i32(rtpref.meta[1][0].data); + if (mtype != 2001) + throw new Error("2000 unexpected reference to ".concat(mtype)); + var tswpsa = parse_shallow(rtpref.data); + var richtext = { v: tswpsa[3].map(function(x2) { + return u8str(x2.data); + }).join("") }; + data[key] = richtext; + sfields: + if ((_a7 = tswpsa == null ? void 0 : tswpsa[11]) == null ? void 0 : _a7[0]) { + var smartfields = (_b = parse_shallow(tswpsa[11][0].data)) == null ? void 0 : _b[1]; + if (!smartfields) + break sfields; + smartfields.forEach(function(sf) { + var _a22, _b2, _c; + var attr = parse_shallow(sf.data); + if ((_a22 = attr[2]) == null ? void 0 : _a22[0]) { + var obj = M4[parse_TSP_Reference((_b2 = attr[2]) == null ? void 0 : _b2[0].data)][0]; + var objtype = varint_to_i32(obj.meta[1][0].data); + switch (objtype) { + case 2032: + var hlink = parse_shallow(obj.data); + if (((_c = hlink == null ? void 0 : hlink[2]) == null ? void 0 : _c[0]) && !richtext.l) + richtext.l = u8str(hlink[2][0].data); + break; + case 2039: + break; + default: + console.log("unrecognized ObjectAttribute type ".concat(objtype)); + } + } + }); + } + } + break; + case 2: + data[key] = parse_shallow(le2[6][0].data); + break; + case 3: + data[key] = parse_shallow(le2[5][0].data); + break; + case 10: + { + var cs = M4[parse_TSP_Reference(le2[10][0].data)][0]; + data[key] = parse_TSD_CommentStorageArchive(M4, cs.data); + } + break; + default: + throw type; + } + }); + return data; +} +function parse_TST_TileRowInfo(u8, type) { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n; + var pb = parse_shallow(u8); + var R3 = varint_to_i32(pb[1][0].data) >>> 0; + var cnt = varint_to_i32(pb[2][0].data) >>> 0; + var wide_offsets = ((_b = (_a7 = pb[8]) == null ? void 0 : _a7[0]) == null ? void 0 : _b.data) && varint_to_i32(pb[8][0].data) > 0 || false; + var used_storage_u8, used_storage; + if (((_d = (_c = pb[7]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) && type != 0) { + used_storage_u8 = (_f = (_e2 = pb[7]) == null ? void 0 : _e2[0]) == null ? void 0 : _f.data; + used_storage = (_h = (_g = pb[6]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data; + } else if (((_j = (_i = pb[4]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) && type != 1) { + used_storage_u8 = (_l = (_k = pb[4]) == null ? void 0 : _k[0]) == null ? void 0 : _l.data; + used_storage = (_n = (_m = pb[3]) == null ? void 0 : _m[0]) == null ? void 0 : _n.data; + } else + throw "NUMBERS Tile missing ".concat(type, " cell storage"); + var width = wide_offsets ? 4 : 1; + var used_storage_offsets = u8_to_dataview(used_storage_u8); + var offsets = []; + for (var C3 = 0; C3 < used_storage_u8.length / 2; ++C3) { + var off = used_storage_offsets.getUint16(C3 * 2, true); + if (off < 65535) + offsets.push([C3, off]); + } + if (offsets.length != cnt) + throw "Expected ".concat(cnt, " cells, found ").concat(offsets.length); + var cells = []; + for (C3 = 0; C3 < offsets.length - 1; ++C3) + cells[offsets[C3][0]] = used_storage[subarray](offsets[C3][1] * width, offsets[C3 + 1][1] * width); + if (offsets.length >= 1) + cells[offsets[offsets.length - 1][0]] = used_storage[subarray](offsets[offsets.length - 1][1] * width); + return { R: R3, cells }; +} +function parse_TST_Tile(M4, root) { + var _a7; + var pb = parse_shallow(root.data); + var storage2 = -1; + if ((_a7 = pb == null ? void 0 : pb[7]) == null ? void 0 : _a7[0]) { + if (varint_to_i32(pb[7][0].data) >>> 0) + storage2 = 1; + else + storage2 = 0; + } + var ri = mappa(pb[5], function(u8) { + return parse_TST_TileRowInfo(u8, storage2); + }); + return { + nrows: varint_to_i32(pb[4][0].data) >>> 0, + data: ri.reduce(function(acc, x2) { + if (!acc[x2.R]) + acc[x2.R] = []; + x2.cells.forEach(function(cell, C3) { + if (acc[x2.R][C3]) + throw new Error("Duplicate cell r=".concat(x2.R, " c=").concat(C3)); + acc[x2.R][C3] = cell; + }); + return acc; + }, []) + }; +} +function parse_TSD_CommentStorageArchive(M4, data) { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j; + var out = { t: "", a: "" }; + var csp = parse_shallow(data); + if ((_b = (_a7 = csp == null ? void 0 : csp[1]) == null ? void 0 : _a7[0]) == null ? void 0 : _b.data) + out.t = u8str((_d = (_c = csp == null ? void 0 : csp[1]) == null ? void 0 : _c[0]) == null ? void 0 : _d.data) || ""; + if ((_f = (_e2 = csp == null ? void 0 : csp[3]) == null ? void 0 : _e2[0]) == null ? void 0 : _f.data) { + var as = M4[parse_TSP_Reference((_h = (_g = csp == null ? void 0 : csp[3]) == null ? void 0 : _g[0]) == null ? void 0 : _h.data)][0]; + var asp = parse_shallow(as.data); + if ((_j = (_i = asp[1]) == null ? void 0 : _i[0]) == null ? void 0 : _j.data) + out.a = u8str(asp[1][0].data); + } + if (csp == null ? void 0 : csp[4]) { + out.replies = []; + csp[4].forEach(function(pi) { + var cs = M4[parse_TSP_Reference(pi.data)][0]; + out.replies.push(parse_TSD_CommentStorageArchive(M4, cs.data)); + }); + } + return out; +} +function iwa_to_s5s_comment(iwa) { + var out = []; + out.push({ t: iwa.t || "", a: iwa.a, T: iwa.replies && iwa.replies.length > 0 }); + if (iwa.replies) + iwa.replies.forEach(function(reply) { + out.push({ t: reply.t || "", a: reply.a, T: true }); + }); + return out; +} +function parse_TST_TableModelArchive(M4, root, ws, opts) { + var _a7, _b, _c, _d, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n; + var pb = parse_shallow(root.data); + var range2 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + range2.e.r = (varint_to_i32(pb[6][0].data) >>> 0) - 1; + if (range2.e.r < 0) + throw new Error("Invalid row varint ".concat(pb[6][0].data)); + range2.e.c = (varint_to_i32(pb[7][0].data) >>> 0) - 1; + if (range2.e.c < 0) + throw new Error("Invalid col varint ".concat(pb[7][0].data)); + ws["!ref"] = encode_range(range2); + var dense = ws["!data"] != null, dws = ws; + var store = parse_shallow(pb[4][0].data); + var lut = numbers_lut_new(); + if ((_a7 = store[4]) == null ? void 0 : _a7[0]) + lut.sst = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[4][0].data)][0]); + if ((_b = store[6]) == null ? void 0 : _b[0]) + lut.fmla = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[6][0].data)][0]); + if ((_c = store[11]) == null ? void 0 : _c[0]) + lut.ofmt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[11][0].data)][0]); + if ((_d = store[12]) == null ? void 0 : _d[0]) + lut.ferr = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[12][0].data)][0]); + if ((_e2 = store[17]) == null ? void 0 : _e2[0]) + lut.rsst = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[17][0].data)][0]); + if ((_f = store[19]) == null ? void 0 : _f[0]) + lut.cmnt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[19][0].data)][0]); + if ((_g = store[22]) == null ? void 0 : _g[0]) + lut.nfmt = parse_TST_TableDataList(M4, M4[parse_TSP_Reference(store[22][0].data)][0]); + var tile = parse_shallow(store[3][0].data); + var _R = 0; + if (!((_h = store[9]) == null ? void 0 : _h[0])) + throw "NUMBERS file missing row tree"; + var rtt = parse_shallow(store[9][0].data)[1].map(function(p4) { + return parse_shallow(p4.data); + }); + rtt.forEach(function(kv) { + _R = varint_to_i32(kv[1][0].data); + var tidx = varint_to_i32(kv[2][0].data); + var t6 = tile[1][tidx]; + if (!t6) + throw "NUMBERS missing tile " + tidx; + var tl = parse_shallow(t6.data); + var ref2 = M4[parse_TSP_Reference(tl[2][0].data)][0]; + var mtype2 = varint_to_i32(ref2.meta[1][0].data); + if (mtype2 != 6002) + throw new Error("6001 unexpected reference to ".concat(mtype2)); + var _tile = parse_TST_Tile(M4, ref2); + _tile.data.forEach(function(row, R3) { + row.forEach(function(buf, C3) { + var res = parse_cell_storage(buf, lut, opts); + if (res) { + if (dense) { + if (!dws["!data"][_R + R3]) + dws["!data"][_R + R3] = []; + dws["!data"][_R + R3][C3] = res; + } else { + ws[encode_col(C3) + encode_row(_R + R3)] = res; + } + } + }); + }); + _R += _tile.nrows; + }); + if ((_i = store[13]) == null ? void 0 : _i[0]) { + var ref = M4[parse_TSP_Reference(store[13][0].data)][0]; + var mtype = varint_to_i32(ref.meta[1][0].data); + if (mtype != 6144) + throw new Error("Expected merge type 6144, found ".concat(mtype)); + ws["!merges"] = (_j = parse_shallow(ref.data)) == null ? void 0 : _j[1].map(function(pi) { + var merge2 = parse_shallow(pi.data); + var origin = u8_to_dataview(parse_shallow(merge2[1][0].data)[1][0].data), size = u8_to_dataview(parse_shallow(merge2[2][0].data)[1][0].data); + return { + s: { r: origin.getUint16(0, true), c: origin.getUint16(2, true) }, + e: { + r: origin.getUint16(0, true) + size.getUint16(0, true) - 1, + c: origin.getUint16(2, true) + size.getUint16(2, true) - 1 + } + }; + }); + } + if (!((_k = ws["!merges"]) == null ? void 0 : _k.length) && ((_l = pb[47]) == null ? void 0 : _l[0])) { + var merge_owner = parse_shallow(pb[47][0].data); + if ((_m = merge_owner[2]) == null ? void 0 : _m[0]) { + var formula_store = parse_shallow(merge_owner[2][0].data); + if ((_n = formula_store[3]) == null ? void 0 : _n[0]) { + ws["!merges"] = mappa(formula_store[3], function(u5) { + var _a22, _b2, _c2, _d2, _e22; + var formula_pair = parse_shallow(u5); + var formula = parse_shallow(formula_pair[2][0].data); + var AST_node_array = parse_shallow(formula[1][0].data); + if (!((_a22 = AST_node_array[1]) == null ? void 0 : _a22[0])) + return; + var AST_node0 = parse_shallow(AST_node_array[1][0].data); + var AST_node_type = varint_to_i32(AST_node0[1][0].data); + if (AST_node_type != 67) + return; + var AST_colon_tract = parse_shallow(AST_node0[40][0].data); + if (!((_b2 = AST_colon_tract[3]) == null ? void 0 : _b2[0]) || !((_c2 = AST_colon_tract[4]) == null ? void 0 : _c2[0])) + return; + var colrange = parse_shallow(AST_colon_tract[3][0].data); + var rowrange = parse_shallow(AST_colon_tract[4][0].data); + var c6 = varint_to_i32(colrange[1][0].data); + var C3 = ((_d2 = colrange[2]) == null ? void 0 : _d2[0]) ? varint_to_i32(colrange[2][0].data) : c6; + var r8 = varint_to_i32(rowrange[1][0].data); + var R3 = ((_e22 = rowrange[2]) == null ? void 0 : _e22[0]) ? varint_to_i32(rowrange[2][0].data) : r8; + return { s: { r: r8, c: c6 }, e: { r: R3, c: C3 } }; + }).filter(function(x2) { + return x2 != null; + }); + } + } + } +} +function parse_TST_TableInfoArchive(M4, root, opts) { + var pb = parse_shallow(root.data); + var out = { "!ref": "A1" }; + if (opts == null ? void 0 : opts.dense) + out["!data"] = []; + var tableref = M4[parse_TSP_Reference(pb[2][0].data)]; + var mtype = varint_to_i32(tableref[0].meta[1][0].data); + if (mtype != 6001) + throw new Error("6000 unexpected reference to ".concat(mtype)); + parse_TST_TableModelArchive(M4, tableref[0], out, opts); + return out; +} +function parse_TN_SheetArchive(M4, root, opts) { + var _a7; + var pb = parse_shallow(root.data); + var out = { + name: ((_a7 = pb[1]) == null ? void 0 : _a7[0]) ? u8str(pb[1][0].data) : "", + sheets: [] + }; + var shapeoffs = mappa(pb[2], parse_TSP_Reference); + shapeoffs.forEach(function(off) { + M4[off].forEach(function(m4) { + var mtype = varint_to_i32(m4.meta[1][0].data); + if (mtype == 6e3) + out.sheets.push(parse_TST_TableInfoArchive(M4, m4, opts)); + }); + }); + return out; +} +function parse_TN_DocumentArchive(M4, root, opts) { + var _a7; + var out = book_new(); + out.Workbook = { WBProps: { date1904: true } }; + var pb = parse_shallow(root.data); + if ((_a7 = pb[2]) == null ? void 0 : _a7[0]) + throw new Error("Keynote presentations are not supported"); + var sheetoffs = mappa(pb[1], parse_TSP_Reference); + sheetoffs.forEach(function(off) { + M4[off].forEach(function(m4) { + var mtype = varint_to_i32(m4.meta[1][0].data); + if (mtype == 2) { + var root2 = parse_TN_SheetArchive(M4, m4, opts); + root2.sheets.forEach(function(sheet, idx) { + book_append_sheet(out, sheet, idx == 0 ? root2.name : root2.name + "_" + idx, true); + }); + } + }); + }); + if (out.SheetNames.length == 0) + throw new Error("Empty NUMBERS file"); + out.bookType = "numbers"; + return out; +} +function parse_numbers_iwa(cfb, opts) { + var _a7, _b, _c, _d, _e2, _f, _g; + var M4 = {}, indices = []; + cfb.FullPaths.forEach(function(p4) { + if (p4.match(/\.iwpv2/)) + throw new Error("Unsupported password protection"); + }); + cfb.FileIndex.forEach(function(s6) { + if (!s6.name.match(/\.iwa$/)) + return; + if (s6.content[0] != 0) + return; + var o9; + try { + o9 = decompress_iwa_file(s6.content); + } catch (e9) { + return console.log("?? " + s6.content.length + " " + (e9.message || e9)); + } + var packets; + try { + packets = parse_iwa_file(o9); + } catch (e9) { + return console.log("## " + (e9.message || e9)); + } + packets.forEach(function(packet) { + M4[packet.id] = packet.messages; + indices.push(packet.id); + }); + }); + if (!indices.length) + throw new Error("File has no messages"); + if (((_c = (_b = (_a7 = M4 == null ? void 0 : M4[1]) == null ? void 0 : _a7[0].meta) == null ? void 0 : _b[1]) == null ? void 0 : _c[0].data) && varint_to_i32(M4[1][0].meta[1][0].data) == 1e4) + throw new Error("Pages documents are not supported"); + var docroot = ((_g = (_f = (_e2 = (_d = M4 == null ? void 0 : M4[1]) == null ? void 0 : _d[0]) == null ? void 0 : _e2.meta) == null ? void 0 : _f[1]) == null ? void 0 : _g[0].data) && varint_to_i32(M4[1][0].meta[1][0].data) == 1 && M4[1][0]; + if (!docroot) + indices.forEach(function(idx) { + M4[idx].forEach(function(iwam) { + var mtype = varint_to_i32(iwam.meta[1][0].data) >>> 0; + if (mtype == 1) { + if (!docroot) + docroot = iwam; + else + throw new Error("Document has multiple roots"); + } + }); + }); + if (!docroot) + throw new Error("Cannot find Document root"); + return parse_TN_DocumentArchive(M4, docroot, opts); +} +function fix_opts_func(defaults4) { + return function fix_opts(opts) { + for (var i7 = 0; i7 != defaults4.length; ++i7) { + var d4 = defaults4[i7]; + if (opts[d4[0]] === void 0) opts[d4[0]] = d4[1]; + if (d4[2] === "n") opts[d4[0]] = Number(opts[d4[0]]); + } + }; +} +function fix_read_opts(opts) { + fix_opts_func([ + ["cellNF", false], + /* emit cell number format string as .z */ + ["cellHTML", true], + /* emit html string as .h */ + ["cellFormula", true], + /* emit formulae as .f */ + ["cellStyles", false], + /* emits style/theme as .s */ + ["cellText", true], + /* emit formatted text as .w */ + ["cellDates", false], + /* emit date cells with type `d` */ + ["sheetStubs", false], + /* emit empty cells */ + ["sheetRows", 0, "n"], + /* read n rows (0 = read all rows) */ + ["bookDeps", false], + /* parse calculation chains */ + ["bookSheets", false], + /* only try to get sheet names (no Sheets) */ + ["bookProps", false], + /* only try to get properties (no Sheets) */ + ["bookFiles", false], + /* include raw file structure (keys, files, cfb) */ + ["bookVBA", false], + /* include vba raw data (vbaraw) */ + ["password", ""], + /* password */ + ["WTF", false] + /* WTF mode (throws errors) */ + ])(opts); +} +function get_sheet_type(n7) { + if (RELS.WS.indexOf(n7) > -1) return "sheet"; + if (RELS.CS && n7 == RELS.CS) return "chart"; + if (RELS.DS && n7 == RELS.DS) return "dialog"; + if (RELS.MS && n7 == RELS.MS) return "macro"; + return n7 && n7.length ? n7 : "sheet"; +} +function safe_parse_wbrels(wbrels, sheets) { + if (!wbrels) return 0; + try { + wbrels = sheets.map(function pwbr(w3) { + if (!w3.id) w3.id = w3.strRelID; + return [w3.name, wbrels["!id"][w3.id].Target, get_sheet_type(wbrels["!id"][w3.id].Type)]; + }); + } catch (e9) { + return null; + } + return !wbrels || wbrels.length === 0 ? null : wbrels; +} +function parse_sheet_legacy_drawing(sheet, type, zip, path6, idx, opts, wb, comments) { + if (!sheet || !sheet["!legdrawel"]) return; + var dfile = resolve_path(sheet["!legdrawel"].Target, path6); + var draw2 = getzipstr(zip, dfile, true); + if (draw2) parse_vml(utf8read(draw2), sheet, comments || []); +} +function safe_parse_sheet(zip, path6, relsPath, sheet, idx, sheetRels, sheets, stype, opts, wb, themes, styles2) { + try { + sheetRels[sheet] = parse_rels(getzipstr(zip, relsPath, true), path6); + var data = getzipdata(zip, path6); + var _ws; + switch (stype) { + case "sheet": + _ws = parse_ws(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2); + break; + case "chart": + _ws = parse_cs(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2); + if (!_ws || !_ws["!drawel"]) break; + var dfile = resolve_path(_ws["!drawel"].Target, path6); + var drelsp = get_rels_path(dfile); + var draw2 = parse_drawing(getzipstr(zip, dfile, true), parse_rels(getzipstr(zip, drelsp, true), dfile)); + var chartp = resolve_path(draw2, dfile); + var crelsp = get_rels_path(chartp); + _ws = parse_chart(getzipstr(zip, chartp, true), chartp, opts, parse_rels(getzipstr(zip, crelsp, true), chartp), wb, _ws); + break; + case "macro": + _ws = parse_ms(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2); + break; + case "dialog": + _ws = parse_ds(data, path6, idx, opts, sheetRels[sheet], wb, themes, styles2); + break; + default: + throw new Error("Unrecognized sheet type " + stype); + } + sheets[sheet] = _ws; + var comments = [], tcomments = []; + if (sheetRels && sheetRels[sheet]) keys(sheetRels[sheet]).forEach(function(n7) { + var dfile2 = ""; + if (sheetRels[sheet][n7].Type == RELS.CMNT) { + dfile2 = resolve_path(sheetRels[sheet][n7].Target, path6); + comments = parse_cmnt(getzipdata(zip, dfile2, true), dfile2, opts); + if (!comments || !comments.length) return; + sheet_insert_comments(_ws, comments, false); + } + if (sheetRels[sheet][n7].Type == RELS.TCMNT) { + dfile2 = resolve_path(sheetRels[sheet][n7].Target, path6); + tcomments = tcomments.concat(parse_tcmnt_xml(getzipdata(zip, dfile2, true), opts)); + } + }); + if (tcomments && tcomments.length) sheet_insert_comments(_ws, tcomments, true, opts.people || []); + parse_sheet_legacy_drawing(_ws, stype, zip, path6, idx, opts, wb, comments); + } catch (e9) { + if (opts.WTF) throw e9; + } +} +function strip_front_slash(x2) { + return x2.charAt(0) == "/" ? x2.slice(1) : x2; +} +function parse_zip(zip, opts) { + make_ssf(); + opts = opts || {}; + fix_read_opts(opts); + if (safegetzipfile(zip, "META-INF/manifest.xml")) return parse_ods(zip, opts); + if (safegetzipfile(zip, "objectdata.xml")) return parse_ods(zip, opts); + if (safegetzipfile(zip, "Index/Document.iwa")) { + if (typeof Uint8Array == "undefined") throw new Error("NUMBERS file parsing requires Uint8Array support"); + if (typeof parse_numbers_iwa != "undefined") { + if (zip.FileIndex) return parse_numbers_iwa(zip, opts); + var _zip = CFB.utils.cfb_new(); + zipentries(zip).forEach(function(e9) { + zip_add_file(_zip, e9, getzipbin(zip, e9)); + }); + return parse_numbers_iwa(_zip, opts); + } + throw new Error("Unsupported NUMBERS file"); + } + if (!safegetzipfile(zip, "[Content_Types].xml")) { + if (safegetzipfile(zip, "index.xml.gz")) throw new Error("Unsupported NUMBERS 08 file"); + if (safegetzipfile(zip, "index.xml")) throw new Error("Unsupported NUMBERS 09 file"); + var index_zip = CFB.find(zip, "Index.zip"); + if (index_zip) { + opts = dup(opts); + delete opts.type; + if (typeof index_zip.content == "string") opts.type = "binary"; + if (typeof Bun !== "undefined" && Buffer.isBuffer(index_zip.content)) return readSync(new Uint8Array(index_zip.content), opts); + return readSync(index_zip.content, opts); + } + throw new Error("Unsupported ZIP file"); + } + var entries = zipentries(zip); + var dir = parse_ct(getzipstr(zip, "[Content_Types].xml")); + var xlsb = false; + var sheets, binname; + if (dir.workbooks.length === 0) { + binname = "xl/workbook.xml"; + if (getzipdata(zip, binname, true)) dir.workbooks.push(binname); + } + if (dir.workbooks.length === 0) { + binname = "xl/workbook.bin"; + if (!getzipdata(zip, binname, true)) throw new Error("Could not find workbook"); + dir.workbooks.push(binname); + xlsb = true; + } + if (dir.workbooks[0].slice(-3) == "bin") xlsb = true; + var themes = {}; + var styles2 = {}; + if (!opts.bookSheets && !opts.bookProps) { + strs = []; + if (dir.sst) try { + strs = parse_sst(getzipdata(zip, strip_front_slash(dir.sst)), dir.sst, opts); + } catch (e9) { + if (opts.WTF) throw e9; + } + if (opts.cellStyles && dir.themes.length) themes = parse_theme_xml(getzipstr(zip, dir.themes[0].replace(/^\//, ""), true) || "", opts); + if (dir.style) styles2 = parse_sty(getzipdata(zip, strip_front_slash(dir.style)), dir.style, themes, opts); + } + dir.links.map(function(link) { + try { + var rels = parse_rels(getzipstr(zip, get_rels_path(strip_front_slash(link))), link); + return parse_xlink(getzipdata(zip, strip_front_slash(link)), rels, link, opts); + } catch (e9) { + } + }); + var wb = parse_wb(getzipdata(zip, strip_front_slash(dir.workbooks[0])), dir.workbooks[0], opts); + var props = {}, propdata = ""; + if (dir.coreprops.length) { + propdata = getzipdata(zip, strip_front_slash(dir.coreprops[0]), true); + if (propdata) props = parse_core_props(propdata); + if (dir.extprops.length !== 0) { + propdata = getzipdata(zip, strip_front_slash(dir.extprops[0]), true); + if (propdata) parse_ext_props(propdata, props, opts); + } + } + var custprops = {}; + if (!opts.bookSheets || opts.bookProps) { + if (dir.custprops.length !== 0) { + propdata = getzipstr(zip, strip_front_slash(dir.custprops[0]), true); + if (propdata) custprops = parse_cust_props(propdata, opts); + } + } + var out = {}; + if (opts.bookSheets || opts.bookProps) { + if (wb.Sheets) sheets = wb.Sheets.map(function pluck(x2) { + return x2.name; + }); + else if (props.Worksheets && props.SheetNames.length > 0) sheets = props.SheetNames; + if (opts.bookProps) { + out.Props = props; + out.Custprops = custprops; + } + if (opts.bookSheets && typeof sheets !== "undefined") out.SheetNames = sheets; + if (opts.bookSheets ? out.SheetNames : opts.bookProps) return out; + } + sheets = {}; + var deps = {}; + if (opts.bookDeps && dir.calcchain) deps = parse_cc(getzipdata(zip, strip_front_slash(dir.calcchain)), dir.calcchain, opts); + var i7 = 0; + var sheetRels = {}; + var path6, relsPath; + { + var wbsheets = wb.Sheets; + props.Worksheets = wbsheets.length; + props.SheetNames = []; + for (var j3 = 0; j3 != wbsheets.length; ++j3) { + props.SheetNames[j3] = wbsheets[j3].name; + } + } + var wbext = xlsb ? "bin" : "xml"; + var wbrelsi = dir.workbooks[0].lastIndexOf("/"); + var wbrelsfile = (dir.workbooks[0].slice(0, wbrelsi + 1) + "_rels/" + dir.workbooks[0].slice(wbrelsi + 1) + ".rels").replace(/^\//, ""); + if (!safegetzipfile(zip, wbrelsfile)) wbrelsfile = "xl/_rels/workbook." + wbext + ".rels"; + var wbrels = parse_rels(getzipstr(zip, wbrelsfile, true), wbrelsfile.replace(/_rels.*/, "s5s")); + if ((dir.metadata || []).length >= 1) { + opts.xlmeta = parse_xlmeta(getzipdata(zip, strip_front_slash(dir.metadata[0])), dir.metadata[0], opts); + } + if ((dir.people || []).length >= 1) { + opts.people = parse_people_xml(getzipdata(zip, strip_front_slash(dir.people[0])), opts); + } + if (wbrels) wbrels = safe_parse_wbrels(wbrels, wb.Sheets); + var nmode = getzipdata(zip, "xl/worksheets/sheet.xml", true) ? 1 : 0; + wsloop: for (i7 = 0; i7 != props.Worksheets; ++i7) { + var stype = "sheet"; + if (wbrels && wbrels[i7]) { + path6 = "xl/" + wbrels[i7][1].replace(/[\/]?xl\//, ""); + if (!safegetzipfile(zip, path6)) path6 = wbrels[i7][1]; + if (!safegetzipfile(zip, path6)) path6 = wbrelsfile.replace(/_rels\/[\S\s]*$/, "") + wbrels[i7][1]; + stype = wbrels[i7][2]; + } else { + path6 = "xl/worksheets/sheet" + (i7 + 1 - nmode) + "." + wbext; + path6 = path6.replace(/sheet0\./, "sheet."); + } + relsPath = path6.replace(/^(.*)(\/)([^\/]*)$/, "$1/_rels/$3.rels"); + if (opts && opts.sheets != null) switch (typeof opts.sheets) { + case "number": + if (i7 != opts.sheets) continue wsloop; + break; + case "string": + if (props.SheetNames[i7].toLowerCase() != opts.sheets.toLowerCase()) continue wsloop; + break; + default: + if (Array.isArray && Array.isArray(opts.sheets)) { + var snjseen = false; + for (var snj = 0; snj != opts.sheets.length; ++snj) { + if (typeof opts.sheets[snj] == "number" && opts.sheets[snj] == i7) snjseen = 1; + if (typeof opts.sheets[snj] == "string" && opts.sheets[snj].toLowerCase() == props.SheetNames[i7].toLowerCase()) snjseen = 1; + } + if (!snjseen) continue wsloop; + } + } + safe_parse_sheet(zip, path6, relsPath, props.SheetNames[i7], i7, sheetRels, sheets, stype, opts, wb, themes, styles2); + } + out = { + Directory: dir, + Workbook: wb, + Props: props, + Custprops: custprops, + Deps: deps, + Sheets: sheets, + SheetNames: props.SheetNames, + Strings: strs, + Styles: styles2, + Themes: themes, + SSF: dup(table_fmt) + }; + if (opts && opts.bookFiles) { + if (zip.files) { + out.keys = entries; + out.files = zip.files; + } else { + out.keys = []; + out.files = {}; + zip.FullPaths.forEach(function(p4, idx) { + p4 = p4.replace(/^Root Entry[\/]/, ""); + out.keys.push(p4); + out.files[p4] = zip.FileIndex[idx]; + }); + } + } + if (opts && opts.bookVBA) { + if (dir.vba.length > 0) out.vbaraw = getzipdata(zip, strip_front_slash(dir.vba[0]), true); + else if (dir.defaults && dir.defaults.bin === CT_VBA) out.vbaraw = getzipdata(zip, "xl/vbaProject.bin", true); + } + out.bookType = xlsb ? "xlsb" : "xlsx"; + return out; +} +function parse_xlsxcfb(cfb, _opts) { + var opts = _opts || {}; + var f4 = "Workbook", data = CFB.find(cfb, f4); + try { + f4 = "/!DataSpaces/Version"; + data = CFB.find(cfb, f4); + if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4); + parse_DataSpaceVersionInfo(data.content); + f4 = "/!DataSpaces/DataSpaceMap"; + data = CFB.find(cfb, f4); + if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4); + var dsm = parse_DataSpaceMap(data.content); + if (dsm.length !== 1 || dsm[0].comps.length !== 1 || dsm[0].comps[0].t !== 0 || dsm[0].name !== "StrongEncryptionDataSpace" || dsm[0].comps[0].v !== "EncryptedPackage") + throw new Error("ECMA-376 Encrypted file bad " + f4); + f4 = "/!DataSpaces/DataSpaceInfo/StrongEncryptionDataSpace"; + data = CFB.find(cfb, f4); + if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4); + var seds = parse_DataSpaceDefinition(data.content); + if (seds.length != 1 || seds[0] != "StrongEncryptionTransform") + throw new Error("ECMA-376 Encrypted file bad " + f4); + f4 = "/!DataSpaces/TransformInfo/StrongEncryptionTransform/!Primary"; + data = CFB.find(cfb, f4); + if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4); + parse_Primary(data.content); + } catch (e9) { + } + f4 = "/EncryptionInfo"; + data = CFB.find(cfb, f4); + if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4); + var einfo = parse_EncryptionInfo(data.content); + f4 = "/EncryptedPackage"; + data = CFB.find(cfb, f4); + if (!data || !data.content) throw new Error("ECMA-376 Encrypted file missing " + f4); + if (einfo[0] == 4 && typeof decrypt_agile !== "undefined") return decrypt_agile(einfo[1], data.content, opts.password || "", opts); + if (einfo[0] == 2 && typeof decrypt_std76 !== "undefined") return decrypt_std76(einfo[1], data.content, opts.password || "", opts); + throw new Error("File is password-protected"); +} +function firstbyte(f4, o9) { + var x2 = ""; + switch ((o9 || {}).type || "base64") { + case "buffer": + return [f4[0], f4[1], f4[2], f4[3], f4[4], f4[5], f4[6], f4[7]]; + case "base64": + x2 = Base64_decode(f4.slice(0, 12)); + break; + case "binary": + x2 = f4; + break; + case "array": + return [f4[0], f4[1], f4[2], f4[3], f4[4], f4[5], f4[6], f4[7]]; + default: + throw new Error("Unrecognized type " + (o9 && o9.type || "undefined")); + } + return [x2.charCodeAt(0), x2.charCodeAt(1), x2.charCodeAt(2), x2.charCodeAt(3), x2.charCodeAt(4), x2.charCodeAt(5), x2.charCodeAt(6), x2.charCodeAt(7)]; +} +function read_cfb(cfb, opts) { + if (CFB.find(cfb, "EncryptedPackage")) return parse_xlsxcfb(cfb, opts); + return parse_xlscfb(cfb, opts); +} +function read_zip(data, opts) { + var zip, d4 = data; + var o9 = opts || {}; + if (!o9.type) o9.type = has_buf && Buffer.isBuffer(data) ? "buffer" : "base64"; + zip = zip_read(d4, o9); + return parse_zip(zip, o9); +} +function read_plaintext(data, o9) { + var i7 = 0; + main: while (i7 < data.length) switch (data.charCodeAt(i7)) { + case 10: + case 13: + case 32: + ++i7; + break; + case 60: + return parse_xlml(data.slice(i7), o9); + default: + break main; + } + return PRN.to_workbook(data, o9); +} +function read_plaintext_raw(data, o9) { + var str2 = "", bytes = firstbyte(data, o9); + switch (o9.type) { + case "base64": + str2 = Base64_decode(data); + break; + case "binary": + str2 = data; + break; + case "buffer": + str2 = data.toString("binary"); + break; + case "array": + str2 = cc2str(data); + break; + default: + throw new Error("Unrecognized type " + o9.type); + } + if (bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) str2 = utf8read(str2); + o9.type = "binary"; + return read_plaintext(str2, o9); +} +function read_utf16(data, o9) { + var d4 = data; + if (o9.type == "base64") d4 = Base64_decode(d4); + if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer) d4 = new Uint8Array(data); + d4 = typeof $cptable !== "undefined" ? $cptable.utils.decode(1200, d4.slice(2), "str") : has_buf && Buffer.isBuffer(data) ? data.slice(2).toString("utf16le") : typeof Uint8Array !== "undefined" && d4 instanceof Uint8Array ? typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le").decode(d4.slice(2)) : utf16lereadu(d4.slice(2)) : utf16leread(d4.slice(2)); + o9.type = "binary"; + return read_plaintext(d4, o9); +} +function bstrify(data) { + return !data.match(/[^\x00-\x7F]/) ? data : utf8write(data); +} +function read_prn(data, d4, o9, str2) { + if (str2) { + o9.type = "string"; + return PRN.to_workbook(data, o9); + } + return PRN.to_workbook(d4, o9); +} +function readSync(data, opts) { + reset_cp(); + var o9 = opts || {}; + if (o9.codepage && typeof $cptable === "undefined") console.error("Codepage tables are not loaded. Non-ASCII characters may not give expected results"); + if (typeof ArrayBuffer !== "undefined" && data instanceof ArrayBuffer) return readSync(new Uint8Array(data), (o9 = dup(o9), o9.type = "array", o9)); + if (typeof Int8Array !== "undefined" && data instanceof Int8Array) return readSync(new Uint8Array(data.buffer, data.byteOffset, data.length), o9); + if (typeof Uint8Array !== "undefined" && data instanceof Uint8Array && !o9.type) o9.type = typeof Deno !== "undefined" ? "buffer" : "array"; + var d4 = data, n7 = [0, 0, 0, 0], str2 = false; + if (o9.cellStyles) { + o9.cellNF = true; + o9.sheetStubs = true; + } + _ssfopts = {}; + if (o9.dateNF) _ssfopts.dateNF = o9.dateNF; + if (!o9.type) o9.type = has_buf && Buffer.isBuffer(data) ? "buffer" : "base64"; + if (o9.type == "file") { + o9.type = has_buf ? "buffer" : "binary"; + d4 = read_binary(data); + if (typeof Uint8Array !== "undefined" && !has_buf) o9.type = "array"; + } + if (o9.type == "string") { + str2 = true; + o9.type = "binary"; + o9.codepage = 65001; + d4 = bstrify(data); + } + if (o9.type == "array" && typeof Uint8Array !== "undefined" && data instanceof Uint8Array && typeof ArrayBuffer !== "undefined") { + var ab = new ArrayBuffer(3), vu = new Uint8Array(ab); + vu.foo = "bar"; + if (!vu.foo) { + o9 = dup(o9); + o9.type = "array"; + return readSync(ab2a(d4), o9); + } + } + switch ((n7 = firstbyte(d4, o9))[0]) { + case 208: + if (n7[1] === 207 && n7[2] === 17 && n7[3] === 224 && n7[4] === 161 && n7[5] === 177 && n7[6] === 26 && n7[7] === 225) return read_cfb(CFB.read(d4, o9), o9); + break; + case 9: + if (n7[1] <= 8) return parse_xlscfb(d4, o9); + break; + case 60: + return parse_xlml(d4, o9); + case 73: + if (n7[1] === 73 && n7[2] === 42 && n7[3] === 0) throw new Error("TIFF Image File is not a spreadsheet"); + if (n7[1] === 68) return read_wb_ID(d4, o9); + break; + case 84: + if (n7[1] === 65 && n7[2] === 66 && n7[3] === 76) return DIF.to_workbook(d4, o9); + break; + case 80: + return n7[1] === 75 && n7[2] < 9 && n7[3] < 9 ? read_zip(d4, o9) : read_prn(data, d4, o9, str2); + case 239: + return n7[3] === 60 ? parse_xlml(d4, o9) : read_prn(data, d4, o9, str2); + case 255: + if (n7[1] === 254) { + return read_utf16(d4, o9); + } else if (n7[1] === 0 && n7[2] === 2 && n7[3] === 0) return WK_.to_workbook(d4, o9); + break; + case 0: + if (n7[1] === 0) { + if (n7[2] >= 2 && n7[3] === 0) return WK_.to_workbook(d4, o9); + if (n7[2] === 0 && (n7[3] === 8 || n7[3] === 9)) return WK_.to_workbook(d4, o9); + } + break; + case 3: + case 131: + case 139: + case 140: + return DBF.to_workbook(d4, o9); + case 123: + if (n7[1] === 92 && n7[2] === 114 && n7[3] === 116) return rtf_to_workbook(d4, o9); + break; + case 10: + case 13: + case 32: + return read_plaintext_raw(d4, o9); + case 137: + if (n7[1] === 80 && n7[2] === 78 && n7[3] === 71) throw new Error("PNG Image File is not a spreadsheet"); + break; + case 8: + if (n7[1] === 231) throw new Error("Unsupported Multiplan 1.x file!"); + break; + case 12: + if (n7[1] === 236) throw new Error("Unsupported Multiplan 2.x file!"); + if (n7[1] === 237) throw new Error("Unsupported Multiplan 3.x file!"); + break; + } + if (DBF_SUPPORTED_VERSIONS.indexOf(n7[0]) > -1 && n7[2] <= 12 && n7[3] <= 31) return DBF.to_workbook(d4, o9); + return read_prn(data, d4, o9, str2); +} +function make_json_row(sheet, r8, R3, cols, header, hdr, o9) { + var rr = encode_row(R3); + var defval = o9.defval, raw = o9.raw || !Object.prototype.hasOwnProperty.call(o9, "raw"); + var isempty = true, dense = sheet["!data"] != null; + var row = header === 1 ? [] : {}; + if (header !== 1) { + if (Object.defineProperty) try { + Object.defineProperty(row, "__rowNum__", { value: R3, enumerable: false }); + } catch (e9) { + row.__rowNum__ = R3; + } + else row.__rowNum__ = R3; + } + if (!dense || sheet["!data"][R3]) for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + var val2 = dense ? (sheet["!data"][R3] || [])[C3] : sheet[cols[C3] + rr]; + if (val2 == null || val2.t === void 0) { + if (defval === void 0) continue; + if (hdr[C3] != null) { + row[hdr[C3]] = defval; + } + continue; + } + var v4 = val2.v; + switch (val2.t) { + case "z": + if (v4 == null) break; + continue; + case "e": + v4 = v4 == 0 ? null : void 0; + break; + case "s": + case "b": + case "n": + if (!val2.z || !fmt_is_date(val2.z)) break; + v4 = numdate(v4); + if (typeof v4 == "number") break; + /* falls through */ + case "d": + if (!(o9 && (o9.UTC || o9.raw === false))) v4 = utc_to_local(new Date(v4)); + break; + default: + throw new Error("unrecognized type " + val2.t); + } + if (hdr[C3] != null) { + if (v4 == null) { + if (val2.t == "e" && v4 === null) row[hdr[C3]] = null; + else if (defval !== void 0) row[hdr[C3]] = defval; + else if (raw && v4 === null) row[hdr[C3]] = null; + else continue; + } else { + row[hdr[C3]] = (val2.t === "n" && typeof o9.rawNumbers === "boolean" ? o9.rawNumbers : raw) ? v4 : format_cell(val2, v4, o9); + } + if (v4 != null) isempty = false; + } + } + return { row, isempty }; +} +function sheet_to_json(sheet, opts) { + if (sheet == null || sheet["!ref"] == null) return []; + var val2 = { t: "n", v: 0 }, header = 0, offset = 1, hdr = [], v4 = 0, vv = ""; + var r8 = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + var o9 = opts || {}; + var range2 = o9.range != null ? o9.range : sheet["!ref"]; + if (o9.header === 1) header = 1; + else if (o9.header === "A") header = 2; + else if (Array.isArray(o9.header)) header = 3; + else if (o9.header == null) header = 0; + switch (typeof range2) { + case "string": + r8 = safe_decode_range(range2); + break; + case "number": + r8 = safe_decode_range(sheet["!ref"]); + r8.s.r = range2; + break; + default: + r8 = range2; + } + if (header > 0) offset = 0; + var rr = encode_row(r8.s.r); + var cols = []; + var out = []; + var outi = 0, counter = 0; + var dense = sheet["!data"] != null; + var R3 = r8.s.r, C3 = 0; + var header_cnt = {}; + if (dense && !sheet["!data"][R3]) sheet["!data"][R3] = []; + var colinfo = o9.skipHidden && sheet["!cols"] || []; + var rowinfo = o9.skipHidden && sheet["!rows"] || []; + for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + if ((colinfo[C3] || {}).hidden) continue; + cols[C3] = encode_col(C3); + val2 = dense ? sheet["!data"][R3][C3] : sheet[cols[C3] + rr]; + switch (header) { + case 1: + hdr[C3] = C3 - r8.s.c; + break; + case 2: + hdr[C3] = cols[C3]; + break; + case 3: + hdr[C3] = o9.header[C3 - r8.s.c]; + break; + default: + if (val2 == null) val2 = { w: "__EMPTY", t: "s" }; + vv = v4 = format_cell(val2, null, o9); + counter = header_cnt[v4] || 0; + if (!counter) header_cnt[v4] = 1; + else { + do { + vv = v4 + "_" + counter++; + } while (header_cnt[vv]); + header_cnt[v4] = counter; + header_cnt[vv] = 1; + } + hdr[C3] = vv; + } + } + for (R3 = r8.s.r + offset; R3 <= r8.e.r; ++R3) { + if ((rowinfo[R3] || {}).hidden) continue; + var row = make_json_row(sheet, r8, R3, cols, header, hdr, o9); + if (row.isempty === false || (header === 1 ? o9.blankrows !== false : !!o9.blankrows)) out[outi++] = row.row; + } + out.length = outi; + return out; +} +function make_csv_row(sheet, r8, R3, cols, fs, rs, FS, w3, o9) { + var isempty = true; + var row = [], txt = "", rr = encode_row(R3); + var dense = sheet["!data"] != null; + var datarow = dense && sheet["!data"][R3] || []; + for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + if (!cols[C3]) continue; + var val2 = dense ? datarow[C3] : sheet[cols[C3] + rr]; + if (val2 == null) txt = ""; + else if (val2.v != null) { + isempty = false; + txt = "" + (o9.rawNumbers && val2.t == "n" ? val2.v : format_cell(val2, null, o9)); + for (var i7 = 0, cc = 0; i7 !== txt.length; ++i7) if ((cc = txt.charCodeAt(i7)) === fs || cc === rs || cc === 34 || o9.forceQuotes) { + txt = '"' + txt.replace(qreg, '""') + '"'; + break; + } + if (txt == "ID" && w3 == 0 && row.length == 0) txt = '"ID"'; + } else if (val2.f != null && !val2.F) { + isempty = false; + txt = "=" + val2.f; + if (txt.indexOf(",") >= 0) txt = '"' + txt.replace(qreg, '""') + '"'; + } else txt = ""; + row.push(txt); + } + if (o9.strip) while (row[row.length - 1] === "") --row.length; + if (o9.blankrows === false && isempty) return null; + return row.join(FS); +} +function sheet_to_csv(sheet, opts) { + var out = []; + var o9 = opts == null ? {} : opts; + if (sheet == null || sheet["!ref"] == null) return ""; + var r8 = safe_decode_range(sheet["!ref"]); + var FS = o9.FS !== void 0 ? o9.FS : ",", fs = FS.charCodeAt(0); + var RS = o9.RS !== void 0 ? o9.RS : "\n", rs = RS.charCodeAt(0); + var row = "", cols = []; + var colinfo = o9.skipHidden && sheet["!cols"] || []; + var rowinfo = o9.skipHidden && sheet["!rows"] || []; + for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) if (!(colinfo[C3] || {}).hidden) cols[C3] = encode_col(C3); + var w3 = 0; + for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + if ((rowinfo[R3] || {}).hidden) continue; + row = make_csv_row(sheet, r8, R3, cols, fs, rs, FS, w3, o9); + if (row == null) { + continue; + } + if (row || o9.blankrows !== false) out.push((w3++ ? RS : "") + row); + } + return out.join(""); +} +function sheet_to_txt(sheet, opts) { + if (!opts) opts = {}; + opts.FS = " "; + opts.RS = "\n"; + var s6 = sheet_to_csv(sheet, opts); + if (typeof $cptable == "undefined" || opts.type == "string") return s6; + var o9 = $cptable.utils.encode(1200, s6, "str"); + return String.fromCharCode(255) + String.fromCharCode(254) + o9; +} +function sheet_to_formulae(sheet, opts) { + var y4 = "", x2, val2 = ""; + if (sheet == null || sheet["!ref"] == null) return []; + var r8 = safe_decode_range(sheet["!ref"]), rr = "", cols = [], C3; + var cmds = []; + var dense = sheet["!data"] != null; + for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) cols[C3] = encode_col(C3); + for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + rr = encode_row(R3); + for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + y4 = cols[C3] + rr; + x2 = dense ? (sheet["!data"][R3] || [])[C3] : sheet[y4]; + val2 = ""; + if (x2 === void 0) continue; + else if (x2.F != null) { + y4 = x2.F; + if (!x2.f) continue; + val2 = x2.f; + if (y4.indexOf(":") == -1) y4 = y4 + ":" + y4; + } + if (x2.f != null) val2 = x2.f; + else if (opts && opts.values === false) continue; + else if (x2.t == "z") continue; + else if (x2.t == "n" && x2.v != null) val2 = "" + x2.v; + else if (x2.t == "b") val2 = x2.v ? "TRUE" : "FALSE"; + else if (x2.w !== void 0) val2 = "'" + x2.w; + else if (x2.v === void 0) continue; + else if (x2.t == "s") val2 = "'" + x2.v; + else val2 = "" + x2.v; + cmds[cmds.length] = y4 + "=" + val2; + } + } + return cmds; +} +function sheet_add_json(_ws, js, opts) { + var o9 = opts || {}; + var dense = _ws ? _ws["!data"] != null : o9.dense; + if (DENSE != null && dense == null) dense = DENSE; + var offset = +!o9.skipHeader; + var ws = _ws || {}; + if (!_ws && dense) ws["!data"] = []; + var _R = 0, _C = 0; + if (ws && o9.origin != null) { + if (typeof o9.origin == "number") _R = o9.origin; + else { + var _origin2 = typeof o9.origin == "string" ? decode_cell(o9.origin) : o9.origin; + _R = _origin2.r; + _C = _origin2.c; + } + } + var range2 = { s: { c: 0, r: 0 }, e: { c: _C, r: _R + js.length - 1 + offset } }; + if (ws["!ref"]) { + var _range = safe_decode_range(ws["!ref"]); + range2.e.c = Math.max(range2.e.c, _range.e.c); + range2.e.r = Math.max(range2.e.r, _range.e.r); + if (_R == -1) { + _R = _range.e.r + 1; + range2.e.r = _R + js.length - 1 + offset; + } + } else { + if (_R == -1) { + _R = 0; + range2.e.r = js.length - 1 + offset; + } + } + var hdr = o9.header || [], C3 = 0; + var ROW = []; + js.forEach(function(JS, R3) { + if (dense && !ws["!data"][_R + R3 + offset]) ws["!data"][_R + R3 + offset] = []; + if (dense) ROW = ws["!data"][_R + R3 + offset]; + keys(JS).forEach(function(k2) { + if ((C3 = hdr.indexOf(k2)) == -1) hdr[C3 = hdr.length] = k2; + var v4 = JS[k2]; + var t6 = "z"; + var z3 = ""; + var ref = dense ? "" : encode_col(_C + C3) + encode_row(_R + R3 + offset); + var cell = dense ? ROW[_C + C3] : ws[ref]; + if (v4 && typeof v4 === "object" && !(v4 instanceof Date)) { + if (dense) ROW[_C + C3] = v4; + else ws[ref] = v4; + } else { + if (typeof v4 == "number") t6 = "n"; + else if (typeof v4 == "boolean") t6 = "b"; + else if (typeof v4 == "string") t6 = "s"; + else if (v4 instanceof Date) { + t6 = "d"; + if (!o9.UTC) v4 = local_to_utc(v4); + if (!o9.cellDates) { + t6 = "n"; + v4 = datenum(v4); + } + z3 = cell != null && cell.z && fmt_is_date(cell.z) ? cell.z : o9.dateNF || table_fmt[14]; + } else if (v4 === null && o9.nullError) { + t6 = "e"; + v4 = 0; + } + if (!cell) { + if (!dense) ws[ref] = cell = { t: t6, v: v4 }; + else ROW[_C + C3] = cell = { t: t6, v: v4 }; + } else { + cell.t = t6; + cell.v = v4; + delete cell.w; + delete cell.R; + if (z3) cell.z = z3; + } + if (z3) cell.z = z3; + } + }); + }); + range2.e.c = Math.max(range2.e.c, _C + hdr.length - 1); + var __R = encode_row(_R); + if (dense && !ws["!data"][_R]) ws["!data"][_R] = []; + if (offset) for (C3 = 0; C3 < hdr.length; ++C3) { + if (dense) ws["!data"][_R][C3 + _C] = { t: "s", v: hdr[C3] }; + else ws[encode_col(C3 + _C) + __R] = { t: "s", v: hdr[C3] }; + } + ws["!ref"] = encode_range(range2); + return ws; +} +function json_to_sheet(js, opts) { + return sheet_add_json(null, js, opts); +} +function ws_get_cell_stub(ws, R3, C3) { + if (typeof R3 == "string") { + if (ws["!data"] != null) { + var RC = decode_cell(R3); + if (!ws["!data"][RC.r]) ws["!data"][RC.r] = []; + return ws["!data"][RC.r][RC.c] || (ws["!data"][RC.r][RC.c] = { t: "z" }); + } + return ws[R3] || (ws[R3] = { t: "z" }); + } + if (typeof R3 != "number") return ws_get_cell_stub(ws, encode_cell(R3)); + return ws_get_cell_stub(ws, encode_col(C3 || 0) + encode_row(R3)); +} +function wb_sheet_idx(wb, sh) { + if (typeof sh == "number") { + if (sh >= 0 && wb.SheetNames.length > sh) return sh; + throw new Error("Cannot find sheet # " + sh); + } else if (typeof sh == "string") { + var idx = wb.SheetNames.indexOf(sh); + if (idx > -1) return idx; + throw new Error("Cannot find sheet name |" + sh + "|"); + } else throw new Error("Cannot find sheet |" + sh + "|"); +} +function book_new(ws, wsname) { + var wb = { SheetNames: [], Sheets: {} }; + if (ws) book_append_sheet(wb, ws, wsname || "Sheet1"); + return wb; +} +function book_append_sheet(wb, ws, name, roll) { + var i7 = 1; + if (!name) { + for (; i7 <= 65535; ++i7, name = void 0) if (wb.SheetNames.indexOf(name = "Sheet" + i7) == -1) break; + } + if (!name || wb.SheetNames.length >= 65535) throw new Error("Too many worksheets"); + if (roll && wb.SheetNames.indexOf(name) >= 0 && name.length < 32) { + var m4 = name.match(/\d+$/); + i7 = m4 && +m4[0] || 0; + var root = m4 && name.slice(0, m4.index) || name; + for (++i7; i7 <= 65535; ++i7) if (wb.SheetNames.indexOf(name = root + i7) == -1) break; + } + check_ws_name(name); + if (wb.SheetNames.indexOf(name) >= 0) throw new Error("Worksheet with name |" + name + "| already exists!"); + wb.SheetNames.push(name); + wb.Sheets[name] = ws; + return name; +} +function book_set_sheet_visibility(wb, sh, vis) { + if (!wb.Workbook) wb.Workbook = {}; + if (!wb.Workbook.Sheets) wb.Workbook.Sheets = []; + var idx = wb_sheet_idx(wb, sh); + if (!wb.Workbook.Sheets[idx]) wb.Workbook.Sheets[idx] = {}; + switch (vis) { + case 0: + case 1: + case 2: + break; + default: + throw new Error("Bad sheet visibility setting " + vis); + } + wb.Workbook.Sheets[idx].Hidden = vis; +} +function cell_set_number_format(cell, fmt) { + cell.z = fmt; + return cell; +} +function cell_set_hyperlink(cell, target, tooltip) { + if (!target) { + delete cell.l; + } else { + cell.l = { Target: target }; + if (tooltip) cell.l.Tooltip = tooltip; + } + return cell; +} +function cell_set_internal_link(cell, range2, tooltip) { + return cell_set_hyperlink(cell, "#" + range2, tooltip); +} +function cell_add_comment(cell, text3, author) { + if (!cell.c) cell.c = []; + cell.c.push({ t: text3, a: author || "SheetJS" }); +} +function sheet_set_array_formula(ws, range2, formula, dynamic) { + var rng = typeof range2 != "string" ? range2 : safe_decode_range(range2); + var rngstr = typeof range2 == "string" ? range2 : encode_range(range2); + for (var R3 = rng.s.r; R3 <= rng.e.r; ++R3) for (var C3 = rng.s.c; C3 <= rng.e.c; ++C3) { + var cell = ws_get_cell_stub(ws, R3, C3); + cell.t = "n"; + cell.F = rngstr; + delete cell.v; + if (R3 == rng.s.r && C3 == rng.s.c) { + cell.f = formula; + if (dynamic) cell.D = true; + } + } + var wsr = decode_range(ws["!ref"]); + if (wsr.s.r > rng.s.r) wsr.s.r = rng.s.r; + if (wsr.s.c > rng.s.c) wsr.s.c = rng.s.c; + if (wsr.e.r < rng.e.r) wsr.e.r = rng.e.r; + if (wsr.e.c < rng.e.c) wsr.e.c = rng.e.c; + ws["!ref"] = encode_range(wsr); + return ws; +} +var XLSX, current_codepage, current_ansi, $cptable, VALID_ANSI, CS2CP, set_ansi, set_cp, debom, _getchar, _getansi, DENSE, DIF_XL, Base64_map, has_buf, Buffer_from, buf_utf16le, s2a, bconcat, chr0, chr1, p2_32, days, months, table_fmt, SSF_default_map, SSF_default_str, pct1, frac1, dec1, closeparen, phone, SSF_abstime, cfregex2, SSFImplicit, dateNFregex, bad_formats, CRC32, CFB, _fs, dnthresh, dnthresh1, dnthresh2, pdre1, pdre2, pdre3, FDRE1, FDRE2, FDISO, utc_append_works, lower_months, split_regex, xml_boundary, str_match_xml_ns, str_match_xml_ns_g, str_remove_xml_ns_g, str_match_xml_ig, XML_HEADER, attregexg, tagregex1, tagregex2, tagregex, nsregex, nsregex2, encodings, rencoding, unescapexml, decregex, htmlcharegex, xlml_fixstr, utf8corpus, utf8read, utf8write, htmldecode, vtvregex, vtmregex, wtregex, xlmlregex, XMLNS, XMLNS_main, ___toBuffer, __toBuffer, ___utf16le, __utf16le, ___hexlify, __hexlify, ___utf8, __utf8, ___lpstr, __lpstr, ___cpstr, __cpstr, ___lpwstr, __lpwstr, ___lpp4, __lpp4, ___8lpp4, __8lpp4, ___double, __double, is_buf, __readUInt8, __readUInt16LE, __readInt16LE, __readUInt32LE, __readInt32LE, __readInt32BE, __writeUInt32LE, __writeInt32LE, __writeUInt16LE, parse_BrtCommentText, parse_XLSBCodeName, parse_XLNameWideString, parse_RelID, parse_UncheckedRfX, VT_I2, VT_I4, VT_BOOL, VT_VARIANT, VT_UI4, VT_FILETIME, VT_BLOB, VT_CF, VT_VECTOR_VARIANT, VT_VECTOR_LPSTR, VT_STRING, VT_USTR, VT_CUSTOM, DocSummaryPIDDSI, SummaryPIDSI, CountryEnum, XLSFillPattern, _XLSIcv, XLSIcv, BErr, RBErr, XLSLblBuiltIn, ct2type, RELS, CT_ODS, CORE_PROPS, EXT_PROPS, custregex, XLMLDocPropsMap, evert_XLMLDPM, parse_Ref, FtTab, parse_BIFF2Format, parse_XLHeaderFooter, parse_BIFF5OT, parse_Blank, parse_Scl, parse_String, DBF_SUPPORTED_VERSIONS, DBF, SYLK, DIF, ETH, PRN, WK_, parse_rs, rs_to_html, sitregex, sirregex, sstr1, sstr2, crypto_CreateXorArray_Method1, crypto_DecryptData_Method1, crypto_MakeXorDecryptor, DEF_MDW, MAX_MDW, MIN_MDW, MDW, DEF_PPI, PPI, XLMLPatternTypeMap, cellXF_uint, cellXF_bool, parse_sty_xml, parse_BrtFill, parse_BrtBorder, XLSXThemeClrScheme, parse_BrtCommentAuthor, CT_VBA, rc_to_a1, crefregex, a1_to_rc, parse_PtgMemErr, parse_PtgMemNoMem, parse_PtgTbl, parse_PtgElfCol, parse_PtgElfColS, parse_PtgElfColSV, parse_PtgElfColV, parse_PtgElfRadical, parse_PtgElfRadicalLel, parse_PtgElfRadicalS, parse_PtgElfRw, parse_PtgElfRwV, PtgListRT, PtgTypes, PtgDupes, Ptg18, Ptg19, PtgBinOp, parse_XLSBArrayParsedFormula, parse_XLSBCellParsedFormula, parse_XLSBNameParsedFormula, parse_XLSBSharedParsedFormula, Cetab, Ftab, FtabArgc, strs, _ssfopts, mergecregex, hlinkregex, dimregex, colregex, afregex, marginregex, sheetprregex, sviewregex, parse_ws_xml_data, parse_BrtWsDim, parse_BrtMergeCell, BrtMarginKeys, WBPropsDef, WBViewDef, SheetDef, CalcPrDef, badchars, wbnsregex, attregexg2, attregex2, XLMLFormatMap, CONTINUE_RT, PSCLSID, XLSBRecordEnum, XLSRecordEnum, HTML_BEGIN, HTML_END, subarray, numbers_lut_new, qreg, utils, version3; +var init_xlsx = __esm({ + "../pi-mono/node_modules/xlsx/xlsx.mjs"() { + init_process_shim(); + XLSX = {}; + XLSX.version = "0.20.3"; + current_codepage = 1200; + current_ansi = 1252; + VALID_ANSI = [874, 932, 936, 949, 950, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1e4]; + CS2CP = { + 0: 1252, + /* ANSI */ + 1: 65001, + /* DEFAULT */ + 2: 65001, + /* SYMBOL */ + 77: 1e4, + /* MAC */ + 128: 932, + /* SHIFTJIS */ + 129: 949, + /* HANGUL */ + 130: 1361, + /* JOHAB */ + 134: 936, + /* GB2312 */ + 136: 950, + /* CHINESEBIG5 */ + 161: 1253, + /* GREEK */ + 162: 1254, + /* TURKISH */ + 163: 1258, + /* VIETNAMESE */ + 177: 1255, + /* HEBREW */ + 178: 1256, + /* ARABIC */ + 186: 1257, + /* BALTIC */ + 204: 1251, + /* RUSSIAN */ + 222: 874, + /* THAI */ + 238: 1250, + /* EASTEUROPE */ + 255: 1252, + /* OEM */ + 69: 6969 + /* MISC */ + }; + set_ansi = function(cp) { + if (VALID_ANSI.indexOf(cp) == -1) return; + current_ansi = CS2CP[0] = cp; + }; + set_cp = function(cp) { + current_codepage = cp; + set_ansi(cp); + }; + debom = function(data) { + var c1 = data.charCodeAt(0), c22 = data.charCodeAt(1); + if (c1 == 255 && c22 == 254) return utf16leread(data.slice(2)); + if (c1 == 254 && c22 == 255) return utf16beread(data.slice(2)); + if (c1 == 65279) return data.slice(1); + return data; + }; + _getchar = function _gc1(x2) { + return String.fromCharCode(x2); + }; + _getansi = function _ga1(x2) { + return String.fromCharCode(x2); + }; + DENSE = null; + DIF_XL = true; + Base64_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + has_buf = /* @__PURE__ */ (function() { + return typeof Buffer !== "undefined" && typeof process !== "undefined" && typeof process.versions !== "undefined" && !!process.versions.node; + })(); + Buffer_from = /* @__PURE__ */ (function() { + if (typeof Buffer !== "undefined") { + var nbfs = !Buffer.from; + if (!nbfs) try { + Buffer.from("foo", "utf8"); + } catch (e9) { + nbfs = true; + } + return nbfs ? function(buf, enc) { + return enc ? new Buffer(buf, enc) : new Buffer(buf); + } : Buffer.from.bind(Buffer); + } + return function() { + }; + })(); + buf_utf16le = /* @__PURE__ */ (function() { + if (typeof Buffer === "undefined") return false; + var x2 = Buffer_from([65, 0]); + if (!x2) return false; + var o9 = x2.toString("utf16le"); + return o9.length == 1; + })(); + s2a = function s2a2(s6) { + if (has_buf) return Buffer_from(s6, "binary"); + return s6.split("").map(function(x2) { + return x2.charCodeAt(0) & 255; + }); + }; + bconcat = has_buf ? function(bufs) { + return Buffer.concat(bufs.map(function(buf) { + return Buffer.isBuffer(buf) ? buf : Buffer_from(buf); + })); + } : function(bufs) { + if (typeof Uint8Array !== "undefined") { + var i7 = 0, maxlen = 0; + for (i7 = 0; i7 < bufs.length; ++i7) maxlen += bufs[i7].length; + var o9 = new Uint8Array(maxlen); + var len = 0; + for (i7 = 0, maxlen = 0; i7 < bufs.length; maxlen += len, ++i7) { + len = bufs[i7].length; + if (bufs[i7] instanceof Uint8Array) o9.set(bufs[i7], maxlen); + else if (typeof bufs[i7] == "string") o9.set(new Uint8Array(s2a(bufs[i7])), maxlen); + else o9.set(new Uint8Array(bufs[i7]), maxlen); + } + return o9; + } + return [].concat.apply([], bufs.map(function(buf) { + return Array.isArray(buf) ? buf : [].slice.call(buf); + })); + }; + chr0 = /\u0000/g; + chr1 = /[\u0001-\u0006]/g; + p2_32 = /* @__PURE__ */ Math.pow(2, 32); + days = [ + ["Sun", "Sunday"], + ["Mon", "Monday"], + ["Tue", "Tuesday"], + ["Wed", "Wednesday"], + ["Thu", "Thursday"], + ["Fri", "Friday"], + ["Sat", "Saturday"] + ]; + months = [ + ["J", "Jan", "January"], + ["F", "Feb", "February"], + ["M", "Mar", "March"], + ["A", "Apr", "April"], + ["M", "May", "May"], + ["J", "Jun", "June"], + ["J", "Jul", "July"], + ["A", "Aug", "August"], + ["S", "Sep", "September"], + ["O", "Oct", "October"], + ["N", "Nov", "November"], + ["D", "Dec", "December"] + ]; + table_fmt = { + 0: "General", + 1: "0", + 2: "0.00", + 3: "#,##0", + 4: "#,##0.00", + 9: "0%", + 10: "0.00%", + 11: "0.00E+00", + 12: "# ?/?", + 13: "# ??/??", + 14: "m/d/yy", + 15: "d-mmm-yy", + 16: "d-mmm", + 17: "mmm-yy", + 18: "h:mm AM/PM", + 19: "h:mm:ss AM/PM", + 20: "h:mm", + 21: "h:mm:ss", + 22: "m/d/yy h:mm", + 37: "#,##0 ;(#,##0)", + 38: "#,##0 ;[Red](#,##0)", + 39: "#,##0.00;(#,##0.00)", + 40: "#,##0.00;[Red](#,##0.00)", + 45: "mm:ss", + 46: "[h]:mm:ss", + 47: "mmss.0", + 48: "##0.0E+0", + 49: "@", + 56: '"\u4E0A\u5348/\u4E0B\u5348 "hh"\u6642"mm"\u5206"ss"\u79D2 "' + }; + SSF_default_map = { + 5: 37, + 6: 38, + 7: 39, + 8: 40, + // 5 -> 37 ... 8 -> 40 + 23: 0, + 24: 0, + 25: 0, + 26: 0, + // 23 -> 0 ... 26 -> 0 + 27: 14, + 28: 14, + 29: 14, + 30: 14, + 31: 14, + // 27 -> 14 ... 31 -> 14 + 50: 14, + 51: 14, + 52: 14, + 53: 14, + 54: 14, + // 50 -> 14 ... 58 -> 14 + 55: 14, + 56: 14, + 57: 14, + 58: 14, + 59: 1, + 60: 2, + 61: 3, + 62: 4, + // 59 -> 1 ... 62 -> 4 + 67: 9, + 68: 10, + // 67 -> 9 ... 68 -> 10 + 69: 12, + 70: 13, + 71: 14, + // 69 -> 12 ... 71 -> 14 + 72: 14, + 73: 15, + 74: 16, + 75: 17, + // 72 -> 14 ... 75 -> 17 + 76: 20, + 77: 21, + 78: 22, + // 76 -> 20 ... 78 -> 22 + 79: 45, + 80: 46, + 81: 47, + // 79 -> 45 ... 81 -> 47 + 82: 0 + // 82 -> 0 ... 65536 -> 0 (omitted) + }; + SSF_default_str = { + // 5 -- Currency, 0 decimal, black negative + 5: '"$"#,##0_);\\("$"#,##0\\)', + 63: '"$"#,##0_);\\("$"#,##0\\)', + // 6 -- Currency, 0 decimal, red negative + 6: '"$"#,##0_);[Red]\\("$"#,##0\\)', + 64: '"$"#,##0_);[Red]\\("$"#,##0\\)', + // 7 -- Currency, 2 decimal, black negative + 7: '"$"#,##0.00_);\\("$"#,##0.00\\)', + 65: '"$"#,##0.00_);\\("$"#,##0.00\\)', + // 8 -- Currency, 2 decimal, red negative + 8: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', + 66: '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', + // 41 -- Accounting, 0 decimal, No Symbol + 41: '_(* #,##0_);_(* \\(#,##0\\);_(* "-"_);_(@_)', + // 42 -- Accounting, 0 decimal, $ Symbol + 42: '_("$"* #,##0_);_("$"* \\(#,##0\\);_("$"* "-"_);_(@_)', + // 43 -- Accounting, 2 decimal, No Symbol + 43: '_(* #,##0.00_);_(* \\(#,##0.00\\);_(* "-"??_);_(@_)', + // 44 -- Accounting, 2 decimal, $ Symbol + 44: '_("$"* #,##0.00_);_("$"* \\(#,##0.00\\);_("$"* "-"??_);_(@_)' + }; + pct1 = /%/g; + frac1 = /# (\?+)( ?)\/( ?)(\d+)/; + dec1 = /^#*0*\.([0#]+)/; + closeparen = /\)[^)]*[0#]/; + phone = /\(###\) ###\\?-####/; + SSF_abstime = /\[[HhMmSs\u0E0A\u0E19\u0E17]*\]/; + cfregex2 = /\[(=|>[=]?|<[>=]?)(-?\d+(?:\.\d*)?)\]/; + SSFImplicit = { + "5": '"$"#,##0_);\\("$"#,##0\\)', + "6": '"$"#,##0_);[Red]\\("$"#,##0\\)', + "7": '"$"#,##0.00_);\\("$"#,##0.00\\)', + "8": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', + "23": "General", + "24": "General", + "25": "General", + "26": "General", + "27": "m/d/yy", + "28": "m/d/yy", + "29": "m/d/yy", + "30": "m/d/yy", + "31": "m/d/yy", + "32": "h:mm:ss", + "33": "h:mm:ss", + "34": "h:mm:ss", + "35": "h:mm:ss", + "36": "m/d/yy", + "41": '_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)', + "42": '_("$"* #,##0_);_("$"* (#,##0);_("$"* "-"_);_(@_)', + "43": '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)', + "44": '_("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)', + "50": "m/d/yy", + "51": "m/d/yy", + "52": "m/d/yy", + "53": "m/d/yy", + "54": "m/d/yy", + "55": "m/d/yy", + "56": "m/d/yy", + "57": "m/d/yy", + "58": "m/d/yy", + "59": "0", + "60": "0.00", + "61": "#,##0", + "62": "#,##0.00", + "63": '"$"#,##0_);\\("$"#,##0\\)', + "64": '"$"#,##0_);[Red]\\("$"#,##0\\)', + "65": '"$"#,##0.00_);\\("$"#,##0.00\\)', + "66": '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)', + "67": "0%", + "68": "0.00%", + "69": "# ?/?", + "70": "# ??/??", + "71": "m/d/yy", + "72": "m/d/yy", + "73": "d-mmm-yy", + "74": "d-mmm", + "75": "mmm-yy", + "76": "h:mm", + "77": "h:mm:ss", + "78": "m/d/yy h:mm", + "79": "mm:ss", + "80": "[h]:mm:ss", + "81": "mmss.0" + }; + dateNFregex = /[dD]+|[mM]+|[yYeE]+|[Hh]+|[Ss]+/g; + bad_formats = { + "d.m": "d\\.m" + // Issue #2571 Google Sheets writes invalid format 'd.m', correct format is 'd"."m' or 'd\\.m' + }; + CRC32 = /* @__PURE__ */ (function() { + var CRC322 = {}; + CRC322.version = "1.2.0"; + function signed_crc_table() { + var c6 = 0, table = new Array(256); + for (var n7 = 0; n7 != 256; ++n7) { + c6 = n7; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + c6 = c6 & 1 ? -306674912 ^ c6 >>> 1 : c6 >>> 1; + table[n7] = c6; + } + return typeof Int32Array !== "undefined" ? new Int32Array(table) : table; + } + var T0 = signed_crc_table(); + function slice_by_16_tables(T10) { + var c6 = 0, v4 = 0, n7 = 0, table = typeof Int32Array !== "undefined" ? new Int32Array(4096) : new Array(4096); + for (n7 = 0; n7 != 256; ++n7) table[n7] = T10[n7]; + for (n7 = 0; n7 != 256; ++n7) { + v4 = T10[n7]; + for (c6 = 256 + n7; c6 < 4096; c6 += 256) v4 = table[c6] = v4 >>> 8 ^ T10[v4 & 255]; + } + var out = []; + for (n7 = 1; n7 != 16; ++n7) out[n7 - 1] = typeof Int32Array !== "undefined" && typeof table.subarray == "function" ? table.subarray(n7 * 256, n7 * 256 + 256) : table.slice(n7 * 256, n7 * 256 + 256); + return out; + } + var TT = slice_by_16_tables(T0); + var T1 = TT[0], T22 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; + var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; + var Tb = TT[10], Tc2 = TT[11], Td = TT[12], Te2 = TT[13], Tf = TT[14]; + function crc32_bstr(bstr, seed) { + var C3 = seed ^ -1; + for (var i7 = 0, L3 = bstr.length; i7 < L3; ) C3 = C3 >>> 8 ^ T0[(C3 ^ bstr.charCodeAt(i7++)) & 255]; + return ~C3; + } + function crc32_buf(B3, seed) { + var C3 = seed ^ -1, L3 = B3.length - 15, i7 = 0; + for (; i7 < L3; ) C3 = Tf[B3[i7++] ^ C3 & 255] ^ Te2[B3[i7++] ^ C3 >> 8 & 255] ^ Td[B3[i7++] ^ C3 >> 16 & 255] ^ Tc2[B3[i7++] ^ C3 >>> 24] ^ Tb[B3[i7++]] ^ Ta[B3[i7++]] ^ T9[B3[i7++]] ^ T8[B3[i7++]] ^ T7[B3[i7++]] ^ T6[B3[i7++]] ^ T5[B3[i7++]] ^ T4[B3[i7++]] ^ T3[B3[i7++]] ^ T22[B3[i7++]] ^ T1[B3[i7++]] ^ T0[B3[i7++]]; + L3 += 15; + while (i7 < L3) C3 = C3 >>> 8 ^ T0[(C3 ^ B3[i7++]) & 255]; + return ~C3; + } + function crc32_str(str2, seed) { + var C3 = seed ^ -1; + for (var i7 = 0, L3 = str2.length, c6 = 0, d4 = 0; i7 < L3; ) { + c6 = str2.charCodeAt(i7++); + if (c6 < 128) { + C3 = C3 >>> 8 ^ T0[(C3 ^ c6) & 255]; + } else if (c6 < 2048) { + C3 = C3 >>> 8 ^ T0[(C3 ^ (192 | c6 >> 6 & 31)) & 255]; + C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 & 63)) & 255]; + } else if (c6 >= 55296 && c6 < 57344) { + c6 = (c6 & 1023) + 64; + d4 = str2.charCodeAt(i7++) & 1023; + C3 = C3 >>> 8 ^ T0[(C3 ^ (240 | c6 >> 8 & 7)) & 255]; + C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 >> 2 & 63)) & 255]; + C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | d4 >> 6 & 15 | (c6 & 3) << 4)) & 255]; + C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | d4 & 63)) & 255]; + } else { + C3 = C3 >>> 8 ^ T0[(C3 ^ (224 | c6 >> 12 & 15)) & 255]; + C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 >> 6 & 63)) & 255]; + C3 = C3 >>> 8 ^ T0[(C3 ^ (128 | c6 & 63)) & 255]; + } + } + return ~C3; + } + CRC322.table = T0; + CRC322.bstr = crc32_bstr; + CRC322.buf = crc32_buf; + CRC322.str = crc32_str; + return CRC322; + })(); + CFB = /* @__PURE__ */ (function _CFB() { + var exports = ( + /*::(*/ + {} + ); + exports.version = "1.2.2"; + function namecmp(l5, r8) { + var L3 = l5.split("/"), R3 = r8.split("/"); + for (var i8 = 0, c6 = 0, Z2 = Math.min(L3.length, R3.length); i8 < Z2; ++i8) { + if (c6 = L3[i8].length - R3[i8].length) return c6; + if (L3[i8] != R3[i8]) return L3[i8] < R3[i8] ? -1 : 1; + } + return L3.length - R3.length; + } + function dirname(p4) { + if (p4.charAt(p4.length - 1) == "/") return p4.slice(0, -1).indexOf("/") === -1 ? p4 : dirname(p4.slice(0, -1)); + var c6 = p4.lastIndexOf("/"); + return c6 === -1 ? p4 : p4.slice(0, c6 + 1); + } + function filename(p4) { + if (p4.charAt(p4.length - 1) == "/") return filename(p4.slice(0, -1)); + var c6 = p4.lastIndexOf("/"); + return c6 === -1 ? p4 : p4.slice(c6 + 1); + } + function write_dos_date(buf, date) { + if (typeof date === "string") date = new Date(date); + var hms = date.getHours(); + hms = hms << 6 | date.getMinutes(); + hms = hms << 5 | date.getSeconds() >>> 1; + buf.write_shift(2, hms); + var ymd = date.getFullYear() - 1980; + ymd = ymd << 4 | date.getMonth() + 1; + ymd = ymd << 5 | date.getDate(); + buf.write_shift(2, ymd); + } + function parse_dos_date(buf) { + var hms = buf.read_shift(2) & 65535; + var ymd = buf.read_shift(2) & 65535; + var val2 = /* @__PURE__ */ new Date(); + var d4 = ymd & 31; + ymd >>>= 5; + var m4 = ymd & 15; + ymd >>>= 4; + val2.setMilliseconds(0); + val2.setFullYear(ymd + 1980); + val2.setMonth(m4 - 1); + val2.setDate(d4); + var S5 = hms & 31; + hms >>>= 5; + var M4 = hms & 63; + hms >>>= 6; + val2.setHours(hms); + val2.setMinutes(M4); + val2.setSeconds(S5 << 1); + return val2; + } + function parse_extra_field(blob) { + prep_blob(blob, 0); + var o9 = ( + /*::(*/ + {} + ); + var flags = 0; + while (blob.l <= blob.length - 4) { + var type = blob.read_shift(2); + var sz = blob.read_shift(2), tgt = blob.l + sz; + var p4 = {}; + switch (type) { + /* UNIX-style Timestamps */ + case 21589: + { + flags = blob.read_shift(1); + if (flags & 1) p4.mtime = blob.read_shift(4); + if (sz > 5) { + if (flags & 2) p4.atime = blob.read_shift(4); + if (flags & 4) p4.ctime = blob.read_shift(4); + } + if (p4.mtime) p4.mt = new Date(p4.mtime * 1e3); + } + break; + /* ZIP64 Extended Information Field */ + case 1: + { + var sz1 = blob.read_shift(4), sz2 = blob.read_shift(4); + p4.usz = sz2 * Math.pow(2, 32) + sz1; + sz1 = blob.read_shift(4); + sz2 = blob.read_shift(4); + p4.csz = sz2 * Math.pow(2, 32) + sz1; + } + break; + } + blob.l = tgt; + o9[type] = p4; + } + return o9; + } + var fs; + function get_fs() { + return fs || (fs = _fs); + } + function parse3(file, options) { + if (file[0] == 80 && file[1] == 75) return parse_zip2(file, options); + if ((file[0] | 32) == 109 && (file[1] | 32) == 105) return parse_mad(file, options); + if (file.length < 512) throw new Error("CFB file size " + file.length + " < 512"); + var mver = 3; + var ssz = 512; + var nmfs = 0; + var difat_sec_cnt = 0; + var dir_start = 0; + var minifat_start = 0; + var difat_start = 0; + var fat_addrs = []; + var blob = ( + /*::(*/ + file.slice(0, 512) + ); + prep_blob(blob, 0); + var mv = check_get_mver(blob); + mver = mv[0]; + switch (mver) { + case 3: + ssz = 512; + break; + case 4: + ssz = 4096; + break; + case 0: + if (mv[1] == 0) return parse_zip2(file, options); + /* falls through */ + default: + throw new Error("Major Version: Expected 3 or 4 saw " + mver); + } + if (ssz !== 512) { + blob = /*::(*/ + file.slice(0, ssz); + prep_blob( + blob, + 28 + /* blob.l */ + ); + } + var header = file.slice(0, ssz); + check_shifts(blob, mver); + var dir_cnt = blob.read_shift(4, "i"); + if (mver === 3 && dir_cnt !== 0) throw new Error("# Directory Sectors: Expected 0 saw " + dir_cnt); + blob.l += 4; + dir_start = blob.read_shift(4, "i"); + blob.l += 4; + blob.chk("00100000", "Mini Stream Cutoff Size: "); + minifat_start = blob.read_shift(4, "i"); + nmfs = blob.read_shift(4, "i"); + difat_start = blob.read_shift(4, "i"); + difat_sec_cnt = blob.read_shift(4, "i"); + for (var q3 = -1, j3 = 0; j3 < 109; ++j3) { + q3 = blob.read_shift(4, "i"); + if (q3 < 0) break; + fat_addrs[j3] = q3; + } + var sectors = sectorify(file, ssz); + sleuth_fat(difat_start, difat_sec_cnt, sectors, ssz, fat_addrs); + var sector_list = make_sector_list(sectors, dir_start, fat_addrs, ssz); + if (dir_start < sector_list.length) sector_list[dir_start].name = "!Directory"; + if (nmfs > 0 && minifat_start !== ENDOFCHAIN) sector_list[minifat_start].name = "!MiniFAT"; + sector_list[fat_addrs[0]].name = "!FAT"; + sector_list.fat_addrs = fat_addrs; + sector_list.ssz = ssz; + var files = {}, Paths = [], FileIndex = [], FullPaths = []; + read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, minifat_start); + build_full_paths(FileIndex, FullPaths, Paths); + Paths.shift(); + var o9 = { + FileIndex, + FullPaths + }; + if (options && options.raw) o9.raw = { header, sectors }; + return o9; + } + function check_get_mver(blob) { + if (blob[blob.l] == 80 && blob[blob.l + 1] == 75) return [0, 0]; + blob.chk(HEADER_SIGNATURE, "Header Signature: "); + blob.l += 16; + var mver = blob.read_shift(2, "u"); + return [blob.read_shift(2, "u"), mver]; + } + function check_shifts(blob, mver) { + var shift = 9; + blob.l += 2; + switch (shift = blob.read_shift(2)) { + case 9: + if (mver != 3) throw new Error("Sector Shift: Expected 9 saw " + shift); + break; + case 12: + if (mver != 4) throw new Error("Sector Shift: Expected 12 saw " + shift); + break; + default: + throw new Error("Sector Shift: Expected 9 or 12 saw " + shift); + } + blob.chk("0600", "Mini Sector Shift: "); + blob.chk("000000000000", "Reserved: "); + } + function sectorify(file, ssz) { + var nsectors = Math.ceil(file.length / ssz) - 1; + var sectors = []; + for (var i8 = 1; i8 < nsectors; ++i8) sectors[i8 - 1] = file.slice(i8 * ssz, (i8 + 1) * ssz); + sectors[nsectors - 1] = file.slice(nsectors * ssz); + return sectors; + } + function build_full_paths(FI, FP, Paths) { + var i8 = 0, L3 = 0, R3 = 0, C3 = 0, j3 = 0, pl = Paths.length; + var dad = [], q3 = []; + for (; i8 < pl; ++i8) { + dad[i8] = q3[i8] = i8; + FP[i8] = Paths[i8]; + } + for (; j3 < q3.length; ++j3) { + i8 = q3[j3]; + L3 = FI[i8].L; + R3 = FI[i8].R; + C3 = FI[i8].C; + if (dad[i8] === i8) { + if (L3 !== -1 && dad[L3] !== L3) dad[i8] = dad[L3]; + if (R3 !== -1 && dad[R3] !== R3) dad[i8] = dad[R3]; + } + if (C3 !== -1) dad[C3] = i8; + if (L3 !== -1 && i8 != dad[i8]) { + dad[L3] = dad[i8]; + if (q3.lastIndexOf(L3) < j3) q3.push(L3); + } + if (R3 !== -1 && i8 != dad[i8]) { + dad[R3] = dad[i8]; + if (q3.lastIndexOf(R3) < j3) q3.push(R3); + } + } + for (i8 = 1; i8 < pl; ++i8) if (dad[i8] === i8) { + if (R3 !== -1 && dad[R3] !== R3) dad[i8] = dad[R3]; + else if (L3 !== -1 && dad[L3] !== L3) dad[i8] = dad[L3]; + } + for (i8 = 1; i8 < pl; ++i8) { + if (FI[i8].type === 0) continue; + j3 = i8; + if (j3 != dad[j3]) do { + j3 = dad[j3]; + FP[i8] = FP[j3] + "/" + FP[i8]; + } while (j3 !== 0 && -1 !== dad[j3] && j3 != dad[j3]); + dad[i8] = -1; + } + FP[0] += "/"; + for (i8 = 1; i8 < pl; ++i8) { + if (FI[i8].type !== 2) FP[i8] += "/"; + } + } + function get_mfat_entry(entry, payload, mini) { + var start = entry.start, size = entry.size; + var o9 = []; + var idx = start; + while (mini && size > 0 && idx >= 0) { + o9.push(payload.slice(idx * MSSZ, idx * MSSZ + MSSZ)); + size -= MSSZ; + idx = __readInt32LE(mini, idx * 4); + } + if (o9.length === 0) return new_buf(0); + return bconcat(o9).slice(0, entry.size); + } + function sleuth_fat(idx, cnt, sectors, ssz, fat_addrs) { + var q3 = ENDOFCHAIN; + if (idx === ENDOFCHAIN) { + if (cnt !== 0) throw new Error("DIFAT chain shorter than expected"); + } else if (idx !== -1) { + var sector = sectors[idx], m4 = (ssz >>> 2) - 1; + if (!sector) return; + for (var i8 = 0; i8 < m4; ++i8) { + if ((q3 = __readInt32LE(sector, i8 * 4)) === ENDOFCHAIN) break; + fat_addrs.push(q3); + } + if (cnt >= 1) sleuth_fat(__readInt32LE(sector, ssz - 4), cnt - 1, sectors, ssz, fat_addrs); + } + } + function get_sector_list(sectors, start, fat_addrs, ssz, chkd) { + var buf = [], buf_chain = []; + if (!chkd) chkd = []; + var modulus = ssz - 1, j3 = 0, jj = 0; + for (j3 = start; j3 >= 0; ) { + chkd[j3] = true; + buf[buf.length] = j3; + buf_chain.push(sectors[j3]); + var addr = fat_addrs[Math.floor(j3 * 4 / ssz)]; + jj = j3 * 4 & modulus; + if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j3 + " 4 " + ssz); + if (!sectors[addr]) break; + j3 = __readInt32LE(sectors[addr], jj); + } + return { nodes: buf, data: __toBuffer([buf_chain]) }; + } + function make_sector_list(sectors, dir_start, fat_addrs, ssz) { + var sl = sectors.length, sector_list = []; + var chkd = [], buf = [], buf_chain = []; + var modulus = ssz - 1, i8 = 0, j3 = 0, k2 = 0, jj = 0; + for (i8 = 0; i8 < sl; ++i8) { + buf = []; + k2 = i8 + dir_start; + if (k2 >= sl) k2 -= sl; + if (chkd[k2]) continue; + buf_chain = []; + var seen = []; + for (j3 = k2; j3 >= 0; ) { + seen[j3] = true; + chkd[j3] = true; + buf[buf.length] = j3; + buf_chain.push(sectors[j3]); + var addr = fat_addrs[Math.floor(j3 * 4 / ssz)]; + jj = j3 * 4 & modulus; + if (ssz < 4 + jj) throw new Error("FAT boundary crossed: " + j3 + " 4 " + ssz); + if (!sectors[addr]) break; + j3 = __readInt32LE(sectors[addr], jj); + if (seen[j3]) break; + } + sector_list[k2] = { nodes: buf, data: __toBuffer([buf_chain]) }; + } + return sector_list; + } + function read_directory(dir_start, sector_list, sectors, Paths, nmfs, files, FileIndex, mini) { + var minifat_store = 0, pl = Paths.length ? 2 : 0; + var sector = sector_list[dir_start].data; + var i8 = 0, namelen = 0, name; + for (; i8 < sector.length; i8 += 128) { + var blob = ( + /*::(*/ + sector.slice(i8, i8 + 128) + ); + prep_blob(blob, 64); + namelen = blob.read_shift(2); + name = __utf16le(blob, 0, namelen - pl); + Paths.push(name); + var o9 = { + name, + type: blob.read_shift(1), + color: blob.read_shift(1), + L: blob.read_shift(4, "i"), + R: blob.read_shift(4, "i"), + C: blob.read_shift(4, "i"), + clsid: blob.read_shift(16), + state: blob.read_shift(4, "i"), + start: 0, + size: 0 + }; + var ctime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2); + if (ctime !== 0) o9.ct = read_date(blob, blob.l - 8); + var mtime = blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2) + blob.read_shift(2); + if (mtime !== 0) o9.mt = read_date(blob, blob.l - 8); + o9.start = blob.read_shift(4, "i"); + o9.size = blob.read_shift(4, "i"); + if (o9.size < 0 && o9.start < 0) { + o9.size = o9.type = 0; + o9.start = ENDOFCHAIN; + o9.name = ""; + } + if (o9.type === 5) { + minifat_store = o9.start; + if (nmfs > 0 && minifat_store !== ENDOFCHAIN) sector_list[minifat_store].name = "!StreamData"; + } else if (o9.size >= 4096) { + o9.storage = "fat"; + if (sector_list[o9.start] === void 0) sector_list[o9.start] = get_sector_list(sectors, o9.start, sector_list.fat_addrs, sector_list.ssz); + sector_list[o9.start].name = o9.name; + o9.content = sector_list[o9.start].data.slice(0, o9.size); + } else { + o9.storage = "minifat"; + if (o9.size < 0) o9.size = 0; + else if (minifat_store !== ENDOFCHAIN && o9.start !== ENDOFCHAIN && sector_list[minifat_store]) { + o9.content = get_mfat_entry(o9, sector_list[minifat_store].data, (sector_list[mini] || {}).data); + } + } + if (o9.content) prep_blob(o9.content, 0); + files[name] = o9; + FileIndex.push(o9); + } + } + function read_date(blob, offset) { + return new Date((__readUInt32LE(blob, offset + 4) / 1e7 * Math.pow(2, 32) + __readUInt32LE(blob, offset) / 1e7 - 11644473600) * 1e3); + } + function read_file(filename2, options) { + get_fs(); + return parse3(fs.readFileSync(filename2), options); + } + function read(blob, options) { + var type = options && options.type; + if (!type) { + if (has_buf && Buffer.isBuffer(blob)) type = "buffer"; + } + switch (type || "base64") { + case "file": + return read_file(blob, options); + case "base64": + return parse3(s2a(Base64_decode(blob)), options); + case "binary": + return parse3(s2a(blob), options); + } + return parse3( + /*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */ + blob, + options + ); + } + function init_cfb(cfb, opts) { + var o9 = opts || {}, root = o9.root || "Root Entry"; + if (!cfb.FullPaths) cfb.FullPaths = []; + if (!cfb.FileIndex) cfb.FileIndex = []; + if (cfb.FullPaths.length !== cfb.FileIndex.length) throw new Error("inconsistent CFB structure"); + if (cfb.FullPaths.length === 0) { + cfb.FullPaths[0] = root + "/"; + cfb.FileIndex[0] = { name: root, type: 5 }; + } + if (o9.CLSID) cfb.FileIndex[0].clsid = o9.CLSID; + seed_cfb(cfb); + } + function seed_cfb(cfb) { + var nm = "Sh33tJ5"; + if (CFB.find(cfb, "/" + nm)) return; + var p4 = new_buf(4); + p4[0] = 55; + p4[1] = p4[3] = 50; + p4[2] = 54; + cfb.FileIndex.push({ name: nm, type: 2, content: p4, size: 4, L: 69, R: 69, C: 69 }); + cfb.FullPaths.push(cfb.FullPaths[0] + nm); + rebuild_cfb(cfb); + } + function rebuild_cfb(cfb, f4) { + init_cfb(cfb); + var gc = false, s6 = false; + for (var i8 = cfb.FullPaths.length - 1; i8 >= 0; --i8) { + var _file = cfb.FileIndex[i8]; + switch (_file.type) { + case 0: + if (s6) gc = true; + else { + cfb.FileIndex.pop(); + cfb.FullPaths.pop(); + } + break; + case 1: + case 2: + case 5: + s6 = true; + if (isNaN(_file.R * _file.L * _file.C)) gc = true; + if (_file.R > -1 && _file.L > -1 && _file.R == _file.L) gc = true; + break; + default: + gc = true; + break; + } + } + if (!gc && !f4) return; + var now = new Date(1987, 1, 19), j3 = 0; + var fullPaths = Object.create ? /* @__PURE__ */ Object.create(null) : {}; + var data = []; + for (i8 = 0; i8 < cfb.FullPaths.length; ++i8) { + fullPaths[cfb.FullPaths[i8]] = true; + if (cfb.FileIndex[i8].type === 0) continue; + data.push([cfb.FullPaths[i8], cfb.FileIndex[i8]]); + } + for (i8 = 0; i8 < data.length; ++i8) { + var dad = dirname(data[i8][0]); + s6 = fullPaths[dad]; + while (!s6) { + while (dirname(dad) && !fullPaths[dirname(dad)]) dad = dirname(dad); + data.push([dad, { + name: filename(dad).replace("/", ""), + type: 1, + clsid: HEADER_CLSID, + ct: now, + mt: now, + content: null + }]); + fullPaths[dad] = true; + dad = dirname(data[i8][0]); + s6 = fullPaths[dad]; + } + } + data.sort(function(x2, y4) { + return namecmp(x2[0], y4[0]); + }); + cfb.FullPaths = []; + cfb.FileIndex = []; + for (i8 = 0; i8 < data.length; ++i8) { + cfb.FullPaths[i8] = data[i8][0]; + cfb.FileIndex[i8] = data[i8][1]; + } + for (i8 = 0; i8 < data.length; ++i8) { + var elt = cfb.FileIndex[i8]; + var nm = cfb.FullPaths[i8]; + elt.name = filename(nm).replace("/", ""); + elt.L = elt.R = elt.C = -(elt.color = 1); + elt.size = elt.content ? elt.content.length : 0; + elt.start = 0; + elt.clsid = elt.clsid || HEADER_CLSID; + if (i8 === 0) { + elt.C = data.length > 1 ? 1 : -1; + elt.size = 0; + elt.type = 5; + } else if (nm.slice(-1) == "/") { + for (j3 = i8 + 1; j3 < data.length; ++j3) if (dirname(cfb.FullPaths[j3]) == nm) break; + elt.C = j3 >= data.length ? -1 : j3; + for (j3 = i8 + 1; j3 < data.length; ++j3) if (dirname(cfb.FullPaths[j3]) == dirname(nm)) break; + elt.R = j3 >= data.length ? -1 : j3; + elt.type = 1; + } else { + if (dirname(cfb.FullPaths[i8 + 1] || "") == dirname(nm)) elt.R = i8 + 1; + elt.type = 2; + } + } + } + function _write(cfb, options) { + var _opts = options || {}; + if (_opts.fileType == "mad") return write_mad(cfb, _opts); + rebuild_cfb(cfb); + switch (_opts.fileType) { + case "zip": + return write_zip(cfb, _opts); + } + var L3 = (function(cfb2) { + var mini_size = 0, fat_size = 0; + for (var i9 = 0; i9 < cfb2.FileIndex.length; ++i9) { + var file2 = cfb2.FileIndex[i9]; + if (!file2.content) continue; + var flen2 = file2.content.length; + if (flen2 > 0) { + if (flen2 < 4096) mini_size += flen2 + 63 >> 6; + else fat_size += flen2 + 511 >> 9; + } + } + var dir_cnt = cfb2.FullPaths.length + 3 >> 2; + var mini_cnt = mini_size + 7 >> 3; + var mfat_cnt = mini_size + 127 >> 7; + var fat_base = mini_cnt + fat_size + dir_cnt + mfat_cnt; + var fat_cnt = fat_base + 127 >> 7; + var difat_cnt = fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127); + while (fat_base + fat_cnt + difat_cnt + 127 >> 7 > fat_cnt) difat_cnt = ++fat_cnt <= 109 ? 0 : Math.ceil((fat_cnt - 109) / 127); + var L4 = [1, difat_cnt, fat_cnt, mfat_cnt, dir_cnt, fat_size, mini_size, 0]; + cfb2.FileIndex[0].size = mini_size << 6; + L4[7] = (cfb2.FileIndex[0].start = L4[0] + L4[1] + L4[2] + L4[3] + L4[4] + L4[5]) + (L4[6] + 7 >> 3); + return L4; + })(cfb); + var o9 = new_buf(L3[7] << 9); + var i8 = 0, T3 = 0; + { + for (i8 = 0; i8 < 8; ++i8) o9.write_shift(1, HEADER_SIG[i8]); + for (i8 = 0; i8 < 8; ++i8) o9.write_shift(2, 0); + o9.write_shift(2, 62); + o9.write_shift(2, 3); + o9.write_shift(2, 65534); + o9.write_shift(2, 9); + o9.write_shift(2, 6); + for (i8 = 0; i8 < 3; ++i8) o9.write_shift(2, 0); + o9.write_shift(4, 0); + o9.write_shift(4, L3[2]); + o9.write_shift(4, L3[0] + L3[1] + L3[2] + L3[3] - 1); + o9.write_shift(4, 0); + o9.write_shift(4, 1 << 12); + o9.write_shift(4, L3[3] ? L3[0] + L3[1] + L3[2] - 1 : ENDOFCHAIN); + o9.write_shift(4, L3[3]); + o9.write_shift(-4, L3[1] ? L3[0] - 1 : ENDOFCHAIN); + o9.write_shift(4, L3[1]); + for (i8 = 0; i8 < 109; ++i8) o9.write_shift(-4, i8 < L3[2] ? L3[1] + i8 : -1); + } + if (L3[1]) { + for (T3 = 0; T3 < L3[1]; ++T3) { + for (; i8 < 236 + T3 * 127; ++i8) o9.write_shift(-4, i8 < L3[2] ? L3[1] + i8 : -1); + o9.write_shift(-4, T3 === L3[1] - 1 ? ENDOFCHAIN : T3 + 1); + } + } + var chainit = function(w3) { + for (T3 += w3; i8 < T3 - 1; ++i8) o9.write_shift(-4, i8 + 1); + if (w3) { + ++i8; + o9.write_shift(-4, ENDOFCHAIN); + } + }; + T3 = i8 = 0; + for (T3 += L3[1]; i8 < T3; ++i8) o9.write_shift(-4, consts.DIFSECT); + for (T3 += L3[2]; i8 < T3; ++i8) o9.write_shift(-4, consts.FATSECT); + chainit(L3[3]); + chainit(L3[4]); + var j3 = 0, flen = 0; + var file = cfb.FileIndex[0]; + for (; j3 < cfb.FileIndex.length; ++j3) { + file = cfb.FileIndex[j3]; + if (!file.content) continue; + flen = file.content.length; + if (flen < 4096) continue; + file.start = T3; + chainit(flen + 511 >> 9); + } + chainit(L3[6] + 7 >> 3); + while (o9.l & 511) o9.write_shift(-4, consts.ENDOFCHAIN); + T3 = i8 = 0; + for (j3 = 0; j3 < cfb.FileIndex.length; ++j3) { + file = cfb.FileIndex[j3]; + if (!file.content) continue; + flen = file.content.length; + if (!flen || flen >= 4096) continue; + file.start = T3; + chainit(flen + 63 >> 6); + } + while (o9.l & 511) o9.write_shift(-4, consts.ENDOFCHAIN); + for (i8 = 0; i8 < L3[4] << 2; ++i8) { + var nm = cfb.FullPaths[i8]; + if (!nm || nm.length === 0) { + for (j3 = 0; j3 < 17; ++j3) o9.write_shift(4, 0); + for (j3 = 0; j3 < 3; ++j3) o9.write_shift(4, -1); + for (j3 = 0; j3 < 12; ++j3) o9.write_shift(4, 0); + continue; + } + file = cfb.FileIndex[i8]; + if (i8 === 0) file.start = file.size ? file.start - 1 : ENDOFCHAIN; + var _nm = i8 === 0 && _opts.root || file.name; + if (_nm.length > 31) { + console.error("Name " + _nm + " will be truncated to " + _nm.slice(0, 31)); + _nm = _nm.slice(0, 31); + } + flen = 2 * (_nm.length + 1); + o9.write_shift(64, _nm, "utf16le"); + o9.write_shift(2, flen); + o9.write_shift(1, file.type); + o9.write_shift(1, file.color); + o9.write_shift(-4, file.L); + o9.write_shift(-4, file.R); + o9.write_shift(-4, file.C); + if (!file.clsid) for (j3 = 0; j3 < 4; ++j3) o9.write_shift(4, 0); + else o9.write_shift(16, file.clsid, "hex"); + o9.write_shift(4, file.state || 0); + o9.write_shift(4, 0); + o9.write_shift(4, 0); + o9.write_shift(4, 0); + o9.write_shift(4, 0); + o9.write_shift(4, file.start); + o9.write_shift(4, file.size); + o9.write_shift(4, 0); + } + for (i8 = 1; i8 < cfb.FileIndex.length; ++i8) { + file = cfb.FileIndex[i8]; + if (file.size >= 4096) { + o9.l = file.start + 1 << 9; + if (has_buf && Buffer.isBuffer(file.content)) { + file.content.copy(o9, o9.l, 0, file.size); + o9.l += file.size + 511 & -512; + } else { + for (j3 = 0; j3 < file.size; ++j3) o9.write_shift(1, file.content[j3]); + for (; j3 & 511; ++j3) o9.write_shift(1, 0); + } + } + } + for (i8 = 1; i8 < cfb.FileIndex.length; ++i8) { + file = cfb.FileIndex[i8]; + if (file.size > 0 && file.size < 4096) { + if (has_buf && Buffer.isBuffer(file.content)) { + file.content.copy(o9, o9.l, 0, file.size); + o9.l += file.size + 63 & -64; + } else { + for (j3 = 0; j3 < file.size; ++j3) o9.write_shift(1, file.content[j3]); + for (; j3 & 63; ++j3) o9.write_shift(1, 0); + } + } + } + if (has_buf) { + o9.l = o9.length; + } else { + while (o9.l < o9.length) o9.write_shift(1, 0); + } + return o9; + } + function find2(cfb, path6) { + var UCFullPaths = cfb.FullPaths.map(function(x2) { + return x2.toUpperCase(); + }); + var UCPaths = UCFullPaths.map(function(x2) { + var y4 = x2.split("/"); + return y4[y4.length - (x2.slice(-1) == "/" ? 2 : 1)]; + }); + var k2 = false; + if (path6.charCodeAt(0) === 47) { + k2 = true; + path6 = UCFullPaths[0].slice(0, -1) + path6; + } else k2 = path6.indexOf("/") !== -1; + var UCPath = path6.toUpperCase(); + var w3 = k2 === true ? UCFullPaths.indexOf(UCPath) : UCPaths.indexOf(UCPath); + if (w3 !== -1) return cfb.FileIndex[w3]; + var m4 = !UCPath.match(chr1); + UCPath = UCPath.replace(chr0, ""); + if (m4) UCPath = UCPath.replace(chr1, "!"); + for (w3 = 0; w3 < UCFullPaths.length; ++w3) { + if ((m4 ? UCFullPaths[w3].replace(chr1, "!") : UCFullPaths[w3]).replace(chr0, "") == UCPath) return cfb.FileIndex[w3]; + if ((m4 ? UCPaths[w3].replace(chr1, "!") : UCPaths[w3]).replace(chr0, "") == UCPath) return cfb.FileIndex[w3]; + } + return null; + } + var MSSZ = 64; + var ENDOFCHAIN = -2; + var HEADER_SIGNATURE = "d0cf11e0a1b11ae1"; + var HEADER_SIG = [208, 207, 17, 224, 161, 177, 26, 225]; + var HEADER_CLSID = "00000000000000000000000000000000"; + var consts = { + /* 2.1 Compund File Sector Numbers and Types */ + MAXREGSECT: -6, + DIFSECT: -4, + FATSECT: -3, + ENDOFCHAIN, + FREESECT: -1, + /* 2.2 Compound File Header */ + HEADER_SIGNATURE, + HEADER_MINOR_VERSION: "3e00", + MAXREGSID: -6, + NOSTREAM: -1, + HEADER_CLSID, + /* 2.6.1 Compound File Directory Entry */ + EntryTypes: ["unknown", "storage", "stream", "lockbytes", "property", "root"] + }; + function write_file(cfb, filename2, options) { + get_fs(); + var o9 = _write(cfb, options); + fs.writeFileSync(filename2, o9); + } + function a2s2(o9) { + var out = new Array(o9.length); + for (var i8 = 0; i8 < o9.length; ++i8) out[i8] = String.fromCharCode(o9[i8]); + return out.join(""); + } + function write(cfb, options) { + var o9 = _write(cfb, options); + switch (options && options.type || "buffer") { + case "file": + get_fs(); + fs.writeFileSync(options.filename, o9); + return o9; + case "binary": + return typeof o9 == "string" ? o9 : a2s2(o9); + case "base64": + return Base64_encode(typeof o9 == "string" ? o9 : a2s2(o9)); + case "buffer": + if (has_buf) return Buffer.isBuffer(o9) ? o9 : Buffer_from(o9); + /* falls through */ + case "array": + return typeof o9 == "string" ? s2a(o9) : o9; + } + return o9; + } + var _zlib; + function use_zlib(zlib) { + try { + var InflateRaw = zlib.InflateRaw; + var InflRaw = new InflateRaw(); + InflRaw._processChunk(new Uint8Array([3, 0]), InflRaw._finishFlushFlag); + if (InflRaw.bytesRead) _zlib = zlib; + else throw new Error("zlib does not expose bytesRead"); + } catch (e9) { + console.error("cannot use native zlib: " + (e9.message || e9)); + } + } + function _inflateRawSync(payload, usz) { + if (!_zlib) return _inflate(payload, usz); + var InflateRaw = _zlib.InflateRaw; + var InflRaw = new InflateRaw(); + var out = InflRaw._processChunk(payload.slice(payload.l), InflRaw._finishFlushFlag); + payload.l += InflRaw.bytesRead; + return out; + } + function _deflateRawSync(payload) { + return _zlib ? _zlib.deflateRawSync(payload) : _deflate(payload); + } + var CLEN_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var LEN_LN = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258]; + var DST_LN = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577]; + function bit_swap_8(n7) { + var t6 = (n7 << 1 | n7 << 11) & 139536 | (n7 << 5 | n7 << 15) & 558144; + return (t6 >> 16 | t6 >> 8 | t6) & 255; + } + var use_typed_arrays = typeof Uint8Array !== "undefined"; + var bitswap8 = use_typed_arrays ? new Uint8Array(1 << 8) : []; + for (var q2 = 0; q2 < 1 << 8; ++q2) bitswap8[q2] = bit_swap_8(q2); + function bit_swap_n(n7, b4) { + var rev = bitswap8[n7 & 255]; + if (b4 <= 8) return rev >>> 8 - b4; + rev = rev << 8 | bitswap8[n7 >> 8 & 255]; + if (b4 <= 16) return rev >>> 16 - b4; + rev = rev << 8 | bitswap8[n7 >> 16 & 255]; + return rev >>> 24 - b4; + } + function read_bits_2(buf, bl) { + var w3 = bl & 7, h7 = bl >>> 3; + return (buf[h7] | (w3 <= 6 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 3; + } + function read_bits_3(buf, bl) { + var w3 = bl & 7, h7 = bl >>> 3; + return (buf[h7] | (w3 <= 5 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 7; + } + function read_bits_4(buf, bl) { + var w3 = bl & 7, h7 = bl >>> 3; + return (buf[h7] | (w3 <= 4 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 15; + } + function read_bits_5(buf, bl) { + var w3 = bl & 7, h7 = bl >>> 3; + return (buf[h7] | (w3 <= 3 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 31; + } + function read_bits_7(buf, bl) { + var w3 = bl & 7, h7 = bl >>> 3; + return (buf[h7] | (w3 <= 1 ? 0 : buf[h7 + 1] << 8)) >>> w3 & 127; + } + function read_bits_n(buf, bl, n7) { + var w3 = bl & 7, h7 = bl >>> 3, f4 = (1 << n7) - 1; + var v4 = buf[h7] >>> w3; + if (n7 < 8 - w3) return v4 & f4; + v4 |= buf[h7 + 1] << 8 - w3; + if (n7 < 16 - w3) return v4 & f4; + v4 |= buf[h7 + 2] << 16 - w3; + if (n7 < 24 - w3) return v4 & f4; + v4 |= buf[h7 + 3] << 24 - w3; + return v4 & f4; + } + function write_bits_3(buf, bl, v4) { + var w3 = bl & 7, h7 = bl >>> 3; + if (w3 <= 5) buf[h7] |= (v4 & 7) << w3; + else { + buf[h7] |= v4 << w3 & 255; + buf[h7 + 1] = (v4 & 7) >> 8 - w3; + } + return bl + 3; + } + function write_bits_1(buf, bl, v4) { + var w3 = bl & 7, h7 = bl >>> 3; + v4 = (v4 & 1) << w3; + buf[h7] |= v4; + return bl + 1; + } + function write_bits_8(buf, bl, v4) { + var w3 = bl & 7, h7 = bl >>> 3; + v4 <<= w3; + buf[h7] |= v4 & 255; + v4 >>>= 8; + buf[h7 + 1] = v4; + return bl + 8; + } + function write_bits_16(buf, bl, v4) { + var w3 = bl & 7, h7 = bl >>> 3; + v4 <<= w3; + buf[h7] |= v4 & 255; + v4 >>>= 8; + buf[h7 + 1] = v4 & 255; + buf[h7 + 2] = v4 >>> 8; + return bl + 16; + } + function realloc(b4, sz) { + var L3 = b4.length, M4 = 2 * L3 > sz ? 2 * L3 : sz + 5, i8 = 0; + if (L3 >= sz) return b4; + if (has_buf) { + var o9 = new_unsafe_buf(M4); + if (b4.copy) b4.copy(o9); + else for (; i8 < b4.length; ++i8) o9[i8] = b4[i8]; + return o9; + } else if (use_typed_arrays) { + var a3 = new Uint8Array(M4); + if (a3.set) a3.set(b4); + else for (; i8 < L3; ++i8) a3[i8] = b4[i8]; + return a3; + } + b4.length = M4; + return b4; + } + function zero_fill_array(n7) { + var o9 = new Array(n7); + for (var i8 = 0; i8 < n7; ++i8) o9[i8] = 0; + return o9; + } + function build_tree(clens, cmap, MAX) { + var maxlen = 1, w3 = 0, i8 = 0, j3 = 0, ccode = 0, L3 = clens.length; + var bl_count = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32); + for (i8 = 0; i8 < 32; ++i8) bl_count[i8] = 0; + for (i8 = L3; i8 < MAX; ++i8) clens[i8] = 0; + L3 = clens.length; + var ctree = use_typed_arrays ? new Uint16Array(L3) : zero_fill_array(L3); + for (i8 = 0; i8 < L3; ++i8) { + bl_count[w3 = clens[i8]]++; + if (maxlen < w3) maxlen = w3; + ctree[i8] = 0; + } + bl_count[0] = 0; + for (i8 = 1; i8 <= maxlen; ++i8) bl_count[i8 + 16] = ccode = ccode + bl_count[i8 - 1] << 1; + for (i8 = 0; i8 < L3; ++i8) { + ccode = clens[i8]; + if (ccode != 0) ctree[i8] = bl_count[ccode + 16]++; + } + var cleni = 0; + for (i8 = 0; i8 < L3; ++i8) { + cleni = clens[i8]; + if (cleni != 0) { + ccode = bit_swap_n(ctree[i8], maxlen) >> maxlen - cleni; + for (j3 = (1 << maxlen + 4 - cleni) - 1; j3 >= 0; --j3) + cmap[ccode | j3 << cleni] = cleni & 15 | i8 << 4; + } + } + return maxlen; + } + var fix_lmap = use_typed_arrays ? new Uint16Array(512) : zero_fill_array(512); + var fix_dmap = use_typed_arrays ? new Uint16Array(32) : zero_fill_array(32); + if (!use_typed_arrays) { + for (var i7 = 0; i7 < 512; ++i7) fix_lmap[i7] = 0; + for (i7 = 0; i7 < 32; ++i7) fix_dmap[i7] = 0; + } + (function() { + var dlens = []; + var i8 = 0; + for (; i8 < 32; i8++) dlens.push(5); + build_tree(dlens, fix_dmap, 32); + var clens = []; + i8 = 0; + for (; i8 <= 143; i8++) clens.push(8); + for (; i8 <= 255; i8++) clens.push(9); + for (; i8 <= 279; i8++) clens.push(7); + for (; i8 <= 287; i8++) clens.push(8); + build_tree(clens, fix_lmap, 288); + })(); + var _deflateRaw = /* @__PURE__ */ (function _deflateRawIIFE() { + var DST_LN_RE = use_typed_arrays ? new Uint8Array(32768) : []; + var j3 = 0, k2 = 0; + for (; j3 < DST_LN.length - 1; ++j3) { + for (; k2 < DST_LN[j3 + 1]; ++k2) DST_LN_RE[k2] = j3; + } + for (; k2 < 32768; ++k2) DST_LN_RE[k2] = 29; + var LEN_LN_RE = use_typed_arrays ? new Uint8Array(259) : []; + for (j3 = 0, k2 = 0; j3 < LEN_LN.length - 1; ++j3) { + for (; k2 < LEN_LN[j3 + 1]; ++k2) LEN_LN_RE[k2] = j3; + } + function write_stored(data, out) { + var boff = 0; + while (boff < data.length) { + var L3 = Math.min(65535, data.length - boff); + var h7 = boff + L3 == data.length; + out.write_shift(1, +h7); + out.write_shift(2, L3); + out.write_shift(2, ~L3 & 65535); + while (L3-- > 0) out[out.l++] = data[boff++]; + } + return out.l; + } + function write_huff_fixed(data, out) { + var bl = 0; + var boff = 0; + var addrs = use_typed_arrays ? new Uint16Array(32768) : []; + while (boff < data.length) { + var L3 = ( + /* data.length - boff; */ + Math.min(65535, data.length - boff) + ); + if (L3 < 10) { + bl = write_bits_3(out, bl, +!!(boff + L3 == data.length)); + if (bl & 7) bl += 8 - (bl & 7); + out.l = bl / 8 | 0; + out.write_shift(2, L3); + out.write_shift(2, ~L3 & 65535); + while (L3-- > 0) out[out.l++] = data[boff++]; + bl = out.l * 8; + continue; + } + bl = write_bits_3(out, bl, +!!(boff + L3 == data.length) + 2); + var hash = 0; + while (L3-- > 0) { + var d4 = data[boff]; + hash = (hash << 5 ^ d4) & 32767; + var match2 = -1, mlen = 0; + if (match2 = addrs[hash]) { + match2 |= boff & ~32767; + if (match2 > boff) match2 -= 32768; + if (match2 < boff) while (data[match2 + mlen] == data[boff + mlen] && mlen < 250) ++mlen; + } + if (mlen > 2) { + d4 = LEN_LN_RE[mlen]; + if (d4 <= 22) bl = write_bits_8(out, bl, bitswap8[d4 + 1] >> 1) - 1; + else { + write_bits_8(out, bl, 3); + bl += 5; + write_bits_8(out, bl, bitswap8[d4 - 23] >> 5); + bl += 3; + } + var len_eb = d4 < 8 ? 0 : d4 - 4 >> 2; + if (len_eb > 0) { + write_bits_16(out, bl, mlen - LEN_LN[d4]); + bl += len_eb; + } + d4 = DST_LN_RE[boff - match2]; + bl = write_bits_8(out, bl, bitswap8[d4] >> 3); + bl -= 3; + var dst_eb = d4 < 4 ? 0 : d4 - 2 >> 1; + if (dst_eb > 0) { + write_bits_16(out, bl, boff - match2 - DST_LN[d4]); + bl += dst_eb; + } + for (var q3 = 0; q3 < mlen; ++q3) { + addrs[hash] = boff & 32767; + hash = (hash << 5 ^ data[boff]) & 32767; + ++boff; + } + L3 -= mlen - 1; + } else { + if (d4 <= 143) d4 = d4 + 48; + else bl = write_bits_1(out, bl, 1); + bl = write_bits_8(out, bl, bitswap8[d4]); + addrs[hash] = boff & 32767; + ++boff; + } + } + bl = write_bits_8(out, bl, 0) - 1; + } + out.l = (bl + 7) / 8 | 0; + return out.l; + } + return function _deflateRaw2(data, out) { + if (data.length < 8) return write_stored(data, out); + return write_huff_fixed(data, out); + }; + })(); + function _deflate(data) { + var buf = new_buf(50 + Math.floor(data.length * 1.1)); + var off = _deflateRaw(data, buf); + return buf.slice(0, off); + } + var dyn_lmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768); + var dyn_dmap = use_typed_arrays ? new Uint16Array(32768) : zero_fill_array(32768); + var dyn_cmap = use_typed_arrays ? new Uint16Array(128) : zero_fill_array(128); + var dyn_len_1 = 1, dyn_len_2 = 1; + function dyn(data, boff) { + var _HLIT = read_bits_5(data, boff) + 257; + boff += 5; + var _HDIST = read_bits_5(data, boff) + 1; + boff += 5; + var _HCLEN = read_bits_4(data, boff) + 4; + boff += 4; + var w3 = 0; + var clens = use_typed_arrays ? new Uint8Array(19) : zero_fill_array(19); + var ctree = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + var maxlen = 1; + var bl_count = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8); + var next_code = use_typed_arrays ? new Uint8Array(8) : zero_fill_array(8); + var L3 = clens.length; + for (var i8 = 0; i8 < _HCLEN; ++i8) { + clens[CLEN_ORDER[i8]] = w3 = read_bits_3(data, boff); + if (maxlen < w3) maxlen = w3; + bl_count[w3]++; + boff += 3; + } + var ccode = 0; + bl_count[0] = 0; + for (i8 = 1; i8 <= maxlen; ++i8) next_code[i8] = ccode = ccode + bl_count[i8 - 1] << 1; + for (i8 = 0; i8 < L3; ++i8) if ((ccode = clens[i8]) != 0) ctree[i8] = next_code[ccode]++; + var cleni = 0; + for (i8 = 0; i8 < L3; ++i8) { + cleni = clens[i8]; + if (cleni != 0) { + ccode = bitswap8[ctree[i8]] >> 8 - cleni; + for (var j3 = (1 << 7 - cleni) - 1; j3 >= 0; --j3) dyn_cmap[ccode | j3 << cleni] = cleni & 7 | i8 << 3; + } + } + var hcodes = []; + maxlen = 1; + for (; hcodes.length < _HLIT + _HDIST; ) { + ccode = dyn_cmap[read_bits_7(data, boff)]; + boff += ccode & 7; + switch (ccode >>>= 3) { + case 16: + w3 = 3 + read_bits_2(data, boff); + boff += 2; + ccode = hcodes[hcodes.length - 1]; + while (w3-- > 0) hcodes.push(ccode); + break; + case 17: + w3 = 3 + read_bits_3(data, boff); + boff += 3; + while (w3-- > 0) hcodes.push(0); + break; + case 18: + w3 = 11 + read_bits_7(data, boff); + boff += 7; + while (w3-- > 0) hcodes.push(0); + break; + default: + hcodes.push(ccode); + if (maxlen < ccode) maxlen = ccode; + break; + } + } + var h12 = hcodes.slice(0, _HLIT), h23 = hcodes.slice(_HLIT); + for (i8 = _HLIT; i8 < 286; ++i8) h12[i8] = 0; + for (i8 = _HDIST; i8 < 30; ++i8) h23[i8] = 0; + dyn_len_1 = build_tree(h12, dyn_lmap, 286); + dyn_len_2 = build_tree(h23, dyn_dmap, 30); + return boff; + } + function inflate(data, usz) { + if (data[0] == 3 && !(data[1] & 3)) { + return [new_raw_buf(usz), 2]; + } + var boff = 0; + var header = 0; + var outbuf = new_unsafe_buf(usz ? usz : 1 << 18); + var woff = 0; + var OL = outbuf.length >>> 0; + var max_len_1 = 0, max_len_2 = 0; + while ((header & 1) == 0) { + header = read_bits_3(data, boff); + boff += 3; + if (header >>> 1 == 0) { + if (boff & 7) boff += 8 - (boff & 7); + var sz = data[boff >>> 3] | data[(boff >>> 3) + 1] << 8; + boff += 32; + if (sz > 0) { + if (!usz && OL < woff + sz) { + outbuf = realloc(outbuf, woff + sz); + OL = outbuf.length; + } + while (sz-- > 0) { + outbuf[woff++] = data[boff >>> 3]; + boff += 8; + } + } + continue; + } else if (header >> 1 == 1) { + max_len_1 = 9; + max_len_2 = 5; + } else { + boff = dyn(data, boff); + max_len_1 = dyn_len_1; + max_len_2 = dyn_len_2; + } + for (; ; ) { + if (!usz && OL < woff + 32767) { + outbuf = realloc(outbuf, woff + 32767); + OL = outbuf.length; + } + var bits = read_bits_n(data, boff, max_len_1); + var code = header >>> 1 == 1 ? fix_lmap[bits] : dyn_lmap[bits]; + boff += code & 15; + code >>>= 4; + if ((code >>> 8 & 255) === 0) outbuf[woff++] = code; + else if (code == 256) break; + else { + code -= 257; + var len_eb = code < 8 ? 0 : code - 4 >> 2; + if (len_eb > 5) len_eb = 0; + var tgt = woff + LEN_LN[code]; + if (len_eb > 0) { + tgt += read_bits_n(data, boff, len_eb); + boff += len_eb; + } + bits = read_bits_n(data, boff, max_len_2); + code = header >>> 1 == 1 ? fix_dmap[bits] : dyn_dmap[bits]; + boff += code & 15; + code >>>= 4; + var dst_eb = code < 4 ? 0 : code - 2 >> 1; + var dst = DST_LN[code]; + if (dst_eb > 0) { + dst += read_bits_n(data, boff, dst_eb); + boff += dst_eb; + } + if (!usz && OL < tgt) { + outbuf = realloc(outbuf, tgt + 100); + OL = outbuf.length; + } + while (woff < tgt) { + outbuf[woff] = outbuf[woff - dst]; + ++woff; + } + } + } + } + if (usz) return [outbuf, boff + 7 >>> 3]; + return [outbuf.slice(0, woff), boff + 7 >>> 3]; + } + function _inflate(payload, usz) { + var data = payload.slice(payload.l || 0); + var out = inflate(data, usz); + payload.l += out[1]; + return out[0]; + } + function warn_or_throw(wrn, msg) { + if (wrn) { + if (typeof console !== "undefined") console.error(msg); + } else throw new Error(msg); + } + function parse_zip2(file, options) { + var blob = ( + /*::(*/ + file + ); + prep_blob(blob, 0); + var FileIndex = [], FullPaths = []; + var o9 = { + FileIndex, + FullPaths + }; + init_cfb(o9, { root: options.root }); + var i8 = blob.length - 4; + while ((blob[i8] != 80 || blob[i8 + 1] != 75 || blob[i8 + 2] != 5 || blob[i8 + 3] != 6) && i8 >= 0) --i8; + blob.l = i8 + 4; + blob.l += 4; + var fcnt = blob.read_shift(2); + blob.l += 6; + var start_cd = blob.read_shift(4); + blob.l = start_cd; + for (i8 = 0; i8 < fcnt; ++i8) { + blob.l += 20; + var csz = blob.read_shift(4); + var usz = blob.read_shift(4); + var namelen = blob.read_shift(2); + var efsz = blob.read_shift(2); + var fcsz = blob.read_shift(2); + blob.l += 8; + var offset = blob.read_shift(4); + var EF = parse_extra_field( + /*::(*/ + blob.slice(blob.l + namelen, blob.l + namelen + efsz) + /*:: :any)*/ + ); + blob.l += namelen + efsz + fcsz; + var L3 = blob.l; + blob.l = offset + 4; + if (EF && EF[1]) { + if ((EF[1] || {}).usz) usz = EF[1].usz; + if ((EF[1] || {}).csz) csz = EF[1].csz; + } + parse_local_file(blob, csz, usz, o9, EF); + blob.l = L3; + } + return o9; + } + function parse_local_file(blob, csz, usz, o9, EF) { + blob.l += 2; + var flags = blob.read_shift(2); + var meth = blob.read_shift(2); + var date = parse_dos_date(blob); + if (flags & 8257) throw new Error("Unsupported ZIP encryption"); + var crc32 = blob.read_shift(4); + var _csz = blob.read_shift(4); + var _usz = blob.read_shift(4); + var namelen = blob.read_shift(2); + var efsz = blob.read_shift(2); + var name = ""; + for (var i8 = 0; i8 < namelen; ++i8) name += String.fromCharCode(blob[blob.l++]); + if (efsz) { + var ef = parse_extra_field( + /*::(*/ + blob.slice(blob.l, blob.l + efsz) + /*:: :any)*/ + ); + if ((ef[21589] || {}).mt) date = ef[21589].mt; + if ((ef[1] || {}).usz) _usz = ef[1].usz; + if ((ef[1] || {}).csz) _csz = ef[1].csz; + if (EF) { + if ((EF[21589] || {}).mt) date = EF[21589].mt; + if ((EF[1] || {}).usz) _usz = EF[1].usz; + if ((EF[1] || {}).csz) _csz = EF[1].csz; + } + } + blob.l += efsz; + var data = blob.slice(blob.l, blob.l + _csz); + switch (meth) { + case 8: + data = _inflateRawSync(blob, _usz); + break; + case 0: + blob.l += _csz; + break; + // TODO: scan for magic number + default: + throw new Error("Unsupported ZIP Compression method " + meth); + } + var wrn = false; + if (flags & 8) { + crc32 = blob.read_shift(4); + if (crc32 == 134695760) { + crc32 = blob.read_shift(4); + wrn = true; + } + _csz = blob.read_shift(4); + _usz = blob.read_shift(4); + } + if (_csz != csz) warn_or_throw(wrn, "Bad compressed size: " + csz + " != " + _csz); + if (_usz != usz) warn_or_throw(wrn, "Bad uncompressed size: " + usz + " != " + _usz); + cfb_add(o9, name, data, { unsafe: true, mt: date }); + } + function write_zip(cfb, options) { + var _opts = options || {}; + var out = [], cdirs = []; + var o9 = new_buf(1); + var method = _opts.compression ? 8 : 0, flags = 0; + var desc = false; + if (desc) flags |= 8; + var i8 = 0, j3 = 0; + var start_cd = 0, fcnt = 0; + var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0]; + var crcs = []; + var sz_cd = 0; + for (i8 = 1; i8 < cfb.FullPaths.length; ++i8) { + fp = cfb.FullPaths[i8].slice(root.length); + fi = cfb.FileIndex[i8]; + if (!fi.size || !fi.content || Array.isArray(fi.content) && fi.content.length == 0 || fp == "Sh33tJ5") continue; + var start = start_cd; + var namebuf = new_buf(fp.length); + for (j3 = 0; j3 < fp.length; ++j3) namebuf.write_shift(1, fp.charCodeAt(j3) & 127); + namebuf = namebuf.slice(0, namebuf.l); + crcs[fcnt] = typeof fi.content == "string" ? CRC32.bstr(fi.content, 0) : CRC32.buf( + /*::((*/ + fi.content, + 0 + ); + var outbuf = typeof fi.content == "string" ? s2a(fi.content) : fi.content; + if (method == 8) outbuf = _deflateRawSync(outbuf); + o9 = new_buf(30); + o9.write_shift(4, 67324752); + o9.write_shift(2, 20); + o9.write_shift(2, flags); + o9.write_shift(2, method); + if (fi.mt) write_dos_date(o9, fi.mt); + else o9.write_shift(4, 0); + o9.write_shift(-4, flags & 8 ? 0 : crcs[fcnt]); + o9.write_shift(4, flags & 8 ? 0 : outbuf.length); + o9.write_shift(4, flags & 8 ? 0 : ( + /*::(*/ + fi.content.length + )); + o9.write_shift(2, namebuf.length); + o9.write_shift(2, 0); + start_cd += o9.length; + out.push(o9); + start_cd += namebuf.length; + out.push(namebuf); + start_cd += outbuf.length; + out.push(outbuf); + if (flags & 8) { + o9 = new_buf(12); + o9.write_shift(-4, crcs[fcnt]); + o9.write_shift(4, outbuf.length); + o9.write_shift( + 4, + /*::(*/ + fi.content.length + ); + start_cd += o9.l; + out.push(o9); + } + o9 = new_buf(46); + o9.write_shift(4, 33639248); + o9.write_shift(2, 0); + o9.write_shift(2, 20); + o9.write_shift(2, flags); + o9.write_shift(2, method); + o9.write_shift(4, 0); + o9.write_shift(-4, crcs[fcnt]); + o9.write_shift(4, outbuf.length); + o9.write_shift( + 4, + /*::(*/ + fi.content.length + ); + o9.write_shift(2, namebuf.length); + o9.write_shift(2, 0); + o9.write_shift(2, 0); + o9.write_shift(2, 0); + o9.write_shift(2, 0); + o9.write_shift(4, 0); + o9.write_shift(4, start); + sz_cd += o9.l; + cdirs.push(o9); + sz_cd += namebuf.length; + cdirs.push(namebuf); + ++fcnt; + } + o9 = new_buf(22); + o9.write_shift(4, 101010256); + o9.write_shift(2, 0); + o9.write_shift(2, 0); + o9.write_shift(2, fcnt); + o9.write_shift(2, fcnt); + o9.write_shift(4, sz_cd); + o9.write_shift(4, start_cd); + o9.write_shift(2, 0); + return bconcat([bconcat(out), bconcat(cdirs), o9]); + } + var ContentTypeMap = { + "htm": "text/html", + "xml": "text/xml", + "gif": "image/gif", + "jpg": "image/jpeg", + "png": "image/png", + "mso": "application/x-mso", + "thmx": "application/vnd.ms-officetheme", + "sh33tj5": "application/octet-stream" + }; + function get_content_type(fi, fp) { + if (fi.ctype) return fi.ctype; + var ext2 = fi.name || "", m4 = ext2.match(/\.([^\.]+)$/); + if (m4 && ContentTypeMap[m4[1]]) return ContentTypeMap[m4[1]]; + if (fp) { + m4 = (ext2 = fp).match(/[\.\\]([^\.\\])+$/); + if (m4 && ContentTypeMap[m4[1]]) return ContentTypeMap[m4[1]]; + } + return "application/octet-stream"; + } + function write_base64_76(bstr) { + var data = Base64_encode(bstr); + var o9 = []; + for (var i8 = 0; i8 < data.length; i8 += 76) o9.push(data.slice(i8, i8 + 76)); + return o9.join("\r\n") + "\r\n"; + } + function write_quoted_printable(text3) { + var encoded = text3.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF=]/g, function(c6) { + var w3 = c6.charCodeAt(0).toString(16).toUpperCase(); + return "=" + (w3.length == 1 ? "0" + w3 : w3); + }); + encoded = encoded.replace(/ $/mg, "=20").replace(/\t$/mg, "=09"); + if (encoded.charAt(0) == "\n") encoded = "=0D" + encoded.slice(1); + encoded = encoded.replace(/\r(?!\n)/mg, "=0D").replace(/\n\n/mg, "\n=0A").replace(/([^\r\n])\n/mg, "$1=0A"); + var o9 = [], split = encoded.split("\r\n"); + for (var si = 0; si < split.length; ++si) { + var str2 = split[si]; + if (str2.length == 0) { + o9.push(""); + continue; + } + for (var i8 = 0; i8 < str2.length; ) { + var end = 76; + var tmp = str2.slice(i8, i8 + end); + if (tmp.charAt(end - 1) == "=") end--; + else if (tmp.charAt(end - 2) == "=") end -= 2; + else if (tmp.charAt(end - 3) == "=") end -= 3; + tmp = str2.slice(i8, i8 + end); + i8 += end; + if (i8 < str2.length) tmp += "="; + o9.push(tmp); + } + } + return o9.join("\r\n"); + } + function parse_quoted_printable(data) { + var o9 = []; + for (var di = 0; di < data.length; ++di) { + var line = data[di]; + while (di <= data.length && line.charAt(line.length - 1) == "=") line = line.slice(0, line.length - 1) + data[++di]; + o9.push(line); + } + for (var oi = 0; oi < o9.length; ++oi) o9[oi] = o9[oi].replace(/[=][0-9A-Fa-f]{2}/g, function($$) { + return String.fromCharCode(parseInt($$.slice(1), 16)); + }); + return s2a(o9.join("\r\n")); + } + function parse_mime(cfb, data, root) { + var fname = "", cte = "", ctype = "", fdata; + var di = 0; + for (; di < 10; ++di) { + var line = data[di]; + if (!line || line.match(/^\s*$/)) break; + var m4 = line.match(/^([^:]*?):\s*([^\s].*)$/); + if (m4) switch (m4[1].toLowerCase()) { + case "content-location": + fname = m4[2].trim(); + break; + case "content-type": + ctype = m4[2].trim(); + break; + case "content-transfer-encoding": + cte = m4[2].trim(); + break; + } + } + ++di; + switch (cte.toLowerCase()) { + case "base64": + fdata = s2a(Base64_decode(data.slice(di).join(""))); + break; + case "quoted-printable": + fdata = parse_quoted_printable(data.slice(di)); + break; + default: + throw new Error("Unsupported Content-Transfer-Encoding " + cte); + } + var file = cfb_add(cfb, fname.slice(root.length), fdata, { unsafe: true }); + if (ctype) file.ctype = ctype; + } + function parse_mad(file, options) { + if (a2s2(file.slice(0, 13)).toLowerCase() != "mime-version:") throw new Error("Unsupported MAD header"); + var root = options && options.root || ""; + var data = (has_buf && Buffer.isBuffer(file) ? file.toString("binary") : a2s2(file)).split("\r\n"); + var di = 0, row = ""; + for (di = 0; di < data.length; ++di) { + row = data[di]; + if (!/^Content-Location:/i.test(row)) continue; + row = row.slice(row.indexOf("file")); + if (!root) root = row.slice(0, row.lastIndexOf("/") + 1); + if (row.slice(0, root.length) == root) continue; + while (root.length > 0) { + root = root.slice(0, root.length - 1); + root = root.slice(0, root.lastIndexOf("/") + 1); + if (row.slice(0, root.length) == root) break; + } + } + var mboundary = (data[1] || "").match(/boundary="(.*?)"/); + if (!mboundary) throw new Error("MAD cannot find boundary"); + var boundary = "--" + (mboundary[1] || ""); + var FileIndex = [], FullPaths = []; + var o9 = { + FileIndex, + FullPaths + }; + init_cfb(o9); + var start_di, fcnt = 0; + for (di = 0; di < data.length; ++di) { + var line = data[di]; + if (line !== boundary && line !== boundary + "--") continue; + if (fcnt++) parse_mime(o9, data.slice(start_di, di), root); + start_di = di; + } + return o9; + } + function write_mad(cfb, options) { + var opts = options || {}; + var boundary = opts.boundary || "SheetJS"; + boundary = "------=" + boundary; + var out = [ + "MIME-Version: 1.0", + 'Content-Type: multipart/related; boundary="' + boundary.slice(2) + '"', + "", + "", + "" + ]; + var root = cfb.FullPaths[0], fp = root, fi = cfb.FileIndex[0]; + for (var i8 = 1; i8 < cfb.FullPaths.length; ++i8) { + fp = cfb.FullPaths[i8].slice(root.length); + fi = cfb.FileIndex[i8]; + if (!fi.size || !fi.content || fp == "Sh33tJ5") continue; + fp = fp.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7E-\xFF]/g, function(c6) { + return "_x" + c6.charCodeAt(0).toString(16) + "_"; + }).replace(/[\u0080-\uFFFF]/g, function(u5) { + return "_u" + u5.charCodeAt(0).toString(16) + "_"; + }); + var ca = fi.content; + var cstr = has_buf && Buffer.isBuffer(ca) ? ca.toString("binary") : a2s2(ca); + var dispcnt = 0, L3 = Math.min(1024, cstr.length), cc = 0; + for (var csl = 0; csl <= L3; ++csl) if ((cc = cstr.charCodeAt(csl)) >= 32 && cc < 128) ++dispcnt; + var qp = dispcnt >= L3 * 4 / 5; + out.push(boundary); + out.push("Content-Location: " + (opts.root || "file:///C:/SheetJS/") + fp); + out.push("Content-Transfer-Encoding: " + (qp ? "quoted-printable" : "base64")); + out.push("Content-Type: " + get_content_type(fi, fp)); + out.push(""); + out.push(qp ? write_quoted_printable(cstr) : write_base64_76(cstr)); + } + out.push(boundary + "--\r\n"); + return out.join("\r\n"); + } + function cfb_new(opts) { + var o9 = {}; + init_cfb(o9, opts); + return o9; + } + function cfb_add(cfb, name, content, opts) { + var unsafe = opts && opts.unsafe; + if (!unsafe) init_cfb(cfb); + var file = !unsafe && CFB.find(cfb, name); + if (!file) { + var fpath = cfb.FullPaths[0]; + if (name.slice(0, fpath.length) == fpath) fpath = name; + else { + if (fpath.slice(-1) != "/") fpath += "/"; + fpath = (fpath + name).replace("//", "/"); + } + file = { name: filename(name), type: 2 }; + cfb.FileIndex.push(file); + cfb.FullPaths.push(fpath); + if (!unsafe) CFB.utils.cfb_gc(cfb); + } + file.content = content; + file.size = content ? content.length : 0; + if (opts) { + if (opts.CLSID) file.clsid = opts.CLSID; + if (opts.mt) file.mt = opts.mt; + if (opts.ct) file.ct = opts.ct; + } + return file; + } + function cfb_del(cfb, name) { + init_cfb(cfb); + var file = CFB.find(cfb, name); + if (file) { + for (var j3 = 0; j3 < cfb.FileIndex.length; ++j3) if (cfb.FileIndex[j3] == file) { + cfb.FileIndex.splice(j3, 1); + cfb.FullPaths.splice(j3, 1); + return true; + } + } + return false; + } + function cfb_mov(cfb, old_name, new_name) { + init_cfb(cfb); + var file = CFB.find(cfb, old_name); + if (file) { + for (var j3 = 0; j3 < cfb.FileIndex.length; ++j3) if (cfb.FileIndex[j3] == file) { + cfb.FileIndex[j3].name = filename(new_name); + cfb.FullPaths[j3] = new_name; + return true; + } + } + return false; + } + function cfb_gc(cfb) { + rebuild_cfb(cfb, true); + } + exports.find = find2; + exports.read = read; + exports.parse = parse3; + exports.write = write; + exports.writeFile = write_file; + exports.utils = { + cfb_new, + cfb_add, + cfb_del, + cfb_mov, + cfb_gc, + ReadShift, + CheckField, + prep_blob, + bconcat, + use_zlib, + _deflateRaw: _deflate, + _inflateRaw: _inflate, + consts + }; + return exports; + })(); + dnthresh = /* @__PURE__ */ Date.UTC(1899, 11, 30, 0, 0, 0); + dnthresh1 = /* @__PURE__ */ Date.UTC(1899, 11, 31, 0, 0, 0); + dnthresh2 = /* @__PURE__ */ Date.UTC(1904, 0, 1, 0, 0, 0); + pdre1 = /^(\d+):(\d+)(:\d+)?(\.\d+)?$/; + pdre2 = /^(\d+)-(\d+)-(\d+)$/; + pdre3 = /^(\d+)-(\d+)-(\d+)[T ](\d+):(\d+)(:\d+)?(\.\d+)?$/; + FDRE1 = /^(0?\d|1[0-2])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))\s+([ap])m?$/; + FDRE2 = /^([01]?\d|2[0-3])(?:|:([0-5]?\d)(?:|(\.\d+)(?:|:([0-5]?\d))|:([0-5]?\d)(|\.\d+)))$/; + FDISO = /^(\d+)-(\d+)-(\d+)[T ](\d+):(\d+)(:\d+)(\.\d+)?[Z]?$/; + utc_append_works = (/* @__PURE__ */ new Date("6/9/69 00:00 UTC")).valueOf() == -177984e5; + lower_months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]; + split_regex = /* @__PURE__ */ (function() { + var safe_split_regex = "abacaba".split(/(:?b)/i).length == 5; + return function split_regex2(str2, re2, def) { + if (safe_split_regex || typeof re2 == "string") return str2.split(re2); + var p4 = str2.split(re2), o9 = [p4[0]]; + for (var i7 = 1; i7 < p4.length; ++i7) { + o9.push(def); + o9.push(p4[i7]); + } + return o9; + }; + })(); + xml_boundary = { " ": 1, " ": 1, "\r": 1, "\n": 1, ">": 1 }; + str_match_xml_ns = /* @__PURE__ */ (function() { + var str_match_xml_ns_cache = {}; + return function str_match_xml_ns2(str2, tag) { + var res = str_match_xml_ns_cache[tag]; + if (!res) str_match_xml_ns_cache[tag] = res = [ + new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"), + new RegExp("", "g") + ]; + res[0].lastIndex = res[1].lastIndex = 0; + var m4 = res[0].exec(str2); + if (!m4) return null; + var si = m4.index; + var sf = res[0].lastIndex; + res[1].lastIndex = res[0].lastIndex; + m4 = res[1].exec(str2); + if (!m4) return null; + var ei = m4.index; + var ef = res[1].lastIndex; + return [str2.slice(si, ef), str2.slice(sf, ei)]; + }; + })(); + str_match_xml_ns_g = /* @__PURE__ */ (function() { + var str_match_xml_ns_cache = {}; + return function str_match_xml_ns2(str2, tag) { + var out = []; + var res = str_match_xml_ns_cache[tag]; + if (!res) str_match_xml_ns_cache[tag] = res = [ + new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"), + new RegExp("", "g") + ]; + res[0].lastIndex = res[1].lastIndex = 0; + var m4; + while (m4 = res[0].exec(str2)) { + var si = m4.index; + res[1].lastIndex = res[0].lastIndex; + m4 = res[1].exec(str2); + if (!m4) return null; + var ef = res[1].lastIndex; + out.push(str2.slice(si, ef)); + res[0].lastIndex = res[1].lastIndex; + } + return out.length == 0 ? null : out; + }; + })(); + str_remove_xml_ns_g = /* @__PURE__ */ (function() { + var str_remove_xml_ns_cache = {}; + return function str_remove_xml_ns_g2(str2, tag) { + var out = []; + var res = str_remove_xml_ns_cache[tag]; + if (!res) str_remove_xml_ns_cache[tag] = res = [ + new RegExp("<(?:\\w+:)?" + tag + "\\b[^<>]*>", "g"), + new RegExp("", "g") + ]; + res[0].lastIndex = res[1].lastIndex = 0; + var m4; + var si = 0, ef = 0; + while (m4 = res[0].exec(str2)) { + si = m4.index; + out.push(str2.slice(ef, si)); + ef = si; + res[1].lastIndex = res[0].lastIndex; + m4 = res[1].exec(str2); + if (!m4) return null; + ef = res[1].lastIndex; + res[0].lastIndex = res[1].lastIndex; + } + out.push(str2.slice(ef)); + return out.length == 0 ? "" : out.join(""); + }; + })(); + str_match_xml_ig = /* @__PURE__ */ (function() { + var str_match_xml_ns_cache = {}; + return function str_match_xml_ns2(str2, tag) { + var out = []; + var res = str_match_xml_ns_cache[tag]; + if (!res) str_match_xml_ns_cache[tag] = res = [ + new RegExp("<" + tag + "\\b[^<>]*>", "ig"), + new RegExp("", "ig") + ]; + res[0].lastIndex = res[1].lastIndex = 0; + var m4; + while (m4 = res[0].exec(str2)) { + var si = m4.index; + res[1].lastIndex = res[0].lastIndex; + m4 = res[1].exec(str2); + if (!m4) return null; + var ef = res[1].lastIndex; + out.push(str2.slice(si, ef)); + res[0].lastIndex = res[1].lastIndex; + } + return out.length == 0 ? null : out; + }; + })(); + XML_HEADER = '\r\n'; + attregexg = /\s([^"\s?>\/]+)\s*=\s*((?:")([^"]*)(?:")|(?:')([^']*)(?:')|([^'">\s]+))/g; + tagregex1 = /<[\/\?]?[a-zA-Z0-9:_-]+(?:\s+[^"\s?<>\/]+\s*=\s*(?:"[^"]*"|'[^']*'|[^'"<>\s=]+))*\s*[\/\?]?>/mg; + tagregex2 = /<[^<>]*>/g; + tagregex = /* @__PURE__ */ XML_HEADER.match(tagregex1) ? tagregex1 : tagregex2; + nsregex = /<\w*:/; + nsregex2 = /<(\/?)\w+:/; + encodings = { + """: '"', + "'": "'", + ">": ">", + "<": "<", + "&": "&" + }; + rencoding = /* @__PURE__ */ evert(encodings); + unescapexml = /* @__PURE__ */ (function() { + var encregex = /&(?:quot|apos|gt|lt|amp|#x?([\da-fA-F]+));/ig, coderegex = /_x([\da-fA-F]{4})_/ig; + function raw_unescapexml(text3) { + var s6 = text3 + "", i7 = s6.indexOf(" -1 ? 16 : 10)) || $$; + }).replace(coderegex, function(m4, c6) { + return String.fromCharCode(parseInt(c6, 16)); + }); + var j3 = s6.indexOf("]]>"); + return raw_unescapexml(s6.slice(0, i7)) + s6.slice(i7 + 9, j3) + raw_unescapexml(s6.slice(j3 + 3)); + } + return function unescapexml2(text3, xlsx) { + var out = raw_unescapexml(text3); + return xlsx ? out.replace(/\r\n/g, "\n") : out; + }; + })(); + decregex = /[&<>'"]/g; + htmlcharegex = /[\u0000-\u001f]/g; + xlml_fixstr = /* @__PURE__ */ (function() { + var entregex = /&#(\d+);/g; + function entrepl($$, $1) { + return String.fromCharCode(parseInt($1, 10)); + } + return function xlml_fixstr2(str2) { + return str2.replace(entregex, entrepl); + }; + })(); + utf8corpus = "foo bar baz\xE2\x98\x83\xF0\x9F\x8D\xA3"; + utf8read = has_buf && (/* @__PURE__ */ utf8readc(utf8corpus) == /* @__PURE__ */ utf8reada(utf8corpus) && utf8readc || /* @__PURE__ */ utf8readb(utf8corpus) == /* @__PURE__ */ utf8reada(utf8corpus) && utf8readb) || utf8reada; + utf8write = has_buf ? function(data) { + return Buffer_from(data, "utf8").toString("binary"); + } : function(orig) { + var out = [], i7 = 0, c6 = 0, d4 = 0; + while (i7 < orig.length) { + c6 = orig.charCodeAt(i7++); + switch (true) { + case c6 < 128: + out.push(String.fromCharCode(c6)); + break; + case c6 < 2048: + out.push(String.fromCharCode(192 + (c6 >> 6))); + out.push(String.fromCharCode(128 + (c6 & 63))); + break; + case (c6 >= 55296 && c6 < 57344): + c6 -= 55296; + d4 = orig.charCodeAt(i7++) - 56320 + (c6 << 10); + out.push(String.fromCharCode(240 + (d4 >> 18 & 7))); + out.push(String.fromCharCode(144 + (d4 >> 12 & 63))); + out.push(String.fromCharCode(128 + (d4 >> 6 & 63))); + out.push(String.fromCharCode(128 + (d4 & 63))); + break; + default: + out.push(String.fromCharCode(224 + (c6 >> 12))); + out.push(String.fromCharCode(128 + (c6 >> 6 & 63))); + out.push(String.fromCharCode(128 + (c6 & 63))); + } + } + return out.join(""); + }; + htmldecode = /* @__PURE__ */ (function() { + var entities = [ + ["nbsp", " "], + ["middot", "\xB7"], + ["quot", '"'], + ["apos", "'"], + ["gt", ">"], + ["lt", "<"], + ["amp", "&"] + ].map(function(x2) { + return [new RegExp("&" + x2[0] + ";", "ig"), x2[1]]; + }); + return function htmldecode2(str2) { + var o9 = str2.replace(/^[\t\n\r ]+/, "").replace(/(^|[^\t\n\r ])[\t\n\r ]+$/, "$1").replace(/>\s+/g, ">").replace(/\b\s+/g, "\n").replace(/<[^<>]*>/g, ""); + for (var i7 = 0; i7 < entities.length; ++i7) o9 = o9.replace(entities[i7][0], entities[i7][1]); + return o9; + }; + })(); + vtvregex = /<\/?(?:vt:)?variant>/g; + vtmregex = /<(?:vt:)([^<"'>]*)>([\s\S]*):\/"]+)(?:\s+[^<>=?"'\s]+="[^"]*?")*\s*[\/]?>/mg; + XMLNS = { + CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/metadata/core-properties", + CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties", + EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties", + CT: "http://schemas.openxmlformats.org/package/2006/content-types", + RELS: "http://schemas.openxmlformats.org/package/2006/relationships", + TCMNT: "http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments", + "dc": "http://purl.org/dc/elements/1.1/", + "dcterms": "http://purl.org/dc/terms/", + "dcmitype": "http://purl.org/dc/dcmitype/", + "mx": "http://schemas.microsoft.com/office/mac/excel/2008/main", + "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships", + "sjs": "http://schemas.openxmlformats.org/package/2006/sheetjs/core-properties", + "vt": "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes", + "xsi": "http://www.w3.org/2001/XMLSchema-instance", + "xsd": "http://www.w3.org/2001/XMLSchema" + }; + XMLNS_main = [ + "http://schemas.openxmlformats.org/spreadsheetml/2006/main", + "http://purl.oclc.org/ooxml/spreadsheetml/main", + "http://schemas.microsoft.com/office/excel/2006/main", + "http://schemas.microsoft.com/office/excel/2006/2" + ]; + ___toBuffer = function(bufs) { + var x2 = [], w3 = 10240; + for (var i7 = 0; i7 < bufs[0].length; ++i7) if (bufs[0][i7]) for (var j3 = 0, L3 = bufs[0][i7].length; j3 < L3; j3 += w3) x2.push.apply(x2, bufs[0][i7].slice(j3, j3 + w3)); + return x2; + }; + __toBuffer = has_buf ? function(bufs) { + return bufs[0].length > 0 && Buffer.isBuffer(bufs[0][0]) ? Buffer.concat(bufs[0].map(function(x2) { + return Buffer.isBuffer(x2) ? x2 : Buffer_from(x2); + })) : ___toBuffer(bufs); + } : ___toBuffer; + ___utf16le = function(b4, s6, e9) { + var ss = []; + for (var i7 = s6; i7 < e9; i7 += 2) ss.push(String.fromCharCode(__readUInt16LE(b4, i7))); + return ss.join("").replace(chr0, ""); + }; + __utf16le = has_buf ? function(b4, s6, e9) { + if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___utf16le(b4, s6, e9); + return b4.toString("utf16le", s6, e9).replace(chr0, ""); + } : ___utf16le; + ___hexlify = function(b4, s6, l5) { + var ss = []; + for (var i7 = s6; i7 < s6 + l5; ++i7) ss.push(("0" + b4[i7].toString(16)).slice(-2)); + return ss.join(""); + }; + __hexlify = has_buf ? function(b4, s6, l5) { + return Buffer.isBuffer(b4) ? b4.toString("hex", s6, s6 + l5) : ___hexlify(b4, s6, l5); + } : ___hexlify; + ___utf8 = function(b4, s6, e9) { + var ss = []; + for (var i7 = s6; i7 < e9; i7++) ss.push(String.fromCharCode(__readUInt8(b4, i7))); + return ss.join(""); + }; + __utf8 = has_buf ? function utf8_b(b4, s6, e9) { + return Buffer.isBuffer(b4) ? b4.toString("utf8", s6, e9) : ___utf8(b4, s6, e9); + } : ___utf8; + ___lpstr = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : ""; + }; + __lpstr = ___lpstr; + ___cpstr = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : ""; + }; + __cpstr = ___cpstr; + ___lpwstr = function(b4, i7) { + var len = 2 * __readUInt32LE(b4, i7); + return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len - 1) : ""; + }; + __lpwstr = ___lpwstr; + ___lpp4 = function lpp4_(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? __utf16le(b4, i7 + 4, i7 + 4 + len) : ""; + }; + __lpp4 = ___lpp4; + ___8lpp4 = function(b4, i7) { + var len = __readUInt32LE(b4, i7); + return len > 0 ? __utf8(b4, i7 + 4, i7 + 4 + len) : ""; + }; + __8lpp4 = ___8lpp4; + ___double = function(b4, idx) { + return read_double_le(b4, idx); + }; + __double = ___double; + is_buf = function is_buf_a(a3) { + return Array.isArray(a3) || typeof Uint8Array !== "undefined" && a3 instanceof Uint8Array; + }; + if (has_buf) { + __lpstr = function lpstr_b(b4, i7) { + if (!Buffer.isBuffer(b4)) return ___lpstr(b4, i7); + var len = b4.readUInt32LE(i7); + return len > 0 ? b4.toString("utf8", i7 + 4, i7 + 4 + len - 1) : ""; + }; + __cpstr = function cpstr_b(b4, i7) { + if (!Buffer.isBuffer(b4)) return ___cpstr(b4, i7); + var len = b4.readUInt32LE(i7); + return len > 0 ? b4.toString("utf8", i7 + 4, i7 + 4 + len - 1) : ""; + }; + __lpwstr = function lpwstr_b(b4, i7) { + if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___lpwstr(b4, i7); + var len = 2 * b4.readUInt32LE(i7); + return b4.toString("utf16le", i7 + 4, i7 + 4 + len - 1); + }; + __lpp4 = function lpp4_b(b4, i7) { + if (!Buffer.isBuffer(b4) || !buf_utf16le) return ___lpp4(b4, i7); + var len = b4.readUInt32LE(i7); + return b4.toString("utf16le", i7 + 4, i7 + 4 + len); + }; + __8lpp4 = function lpp4_8b(b4, i7) { + if (!Buffer.isBuffer(b4)) return ___8lpp4(b4, i7); + var len = b4.readUInt32LE(i7); + return b4.toString("utf8", i7 + 4, i7 + 4 + len); + }; + __double = function double_(b4, i7) { + if (Buffer.isBuffer(b4)) return b4.readDoubleLE(i7); + return ___double(b4, i7); + }; + is_buf = function is_buf_b(a3) { + return Buffer.isBuffer(a3) || Array.isArray(a3) || typeof Uint8Array !== "undefined" && a3 instanceof Uint8Array; + }; + } + if (typeof $cptable !== "undefined") cpdoit(); + __readUInt8 = function(b4, idx) { + return b4[idx]; + }; + __readUInt16LE = function(b4, idx) { + return b4[idx + 1] * (1 << 8) + b4[idx]; + }; + __readInt16LE = function(b4, idx) { + var u5 = b4[idx + 1] * (1 << 8) + b4[idx]; + return u5 < 32768 ? u5 : (65535 - u5 + 1) * -1; + }; + __readUInt32LE = function(b4, idx) { + return b4[idx + 3] * (1 << 24) + (b4[idx + 2] << 16) + (b4[idx + 1] << 8) + b4[idx]; + }; + __readInt32LE = function(b4, idx) { + return b4[idx + 3] << 24 | b4[idx + 2] << 16 | b4[idx + 1] << 8 | b4[idx]; + }; + __readInt32BE = function(b4, idx) { + return b4[idx] << 24 | b4[idx + 1] << 16 | b4[idx + 2] << 8 | b4[idx + 3]; + }; + __writeUInt32LE = function(b4, val2, idx) { + b4[idx] = val2 & 255; + b4[idx + 1] = val2 >>> 8 & 255; + b4[idx + 2] = val2 >>> 16 & 255; + b4[idx + 3] = val2 >>> 24 & 255; + }; + __writeInt32LE = function(b4, val2, idx) { + b4[idx] = val2 & 255; + b4[idx + 1] = val2 >> 8 & 255; + b4[idx + 2] = val2 >> 16 & 255; + b4[idx + 3] = val2 >> 24 & 255; + }; + __writeUInt16LE = function(b4, val2, idx) { + b4[idx] = val2 & 255; + b4[idx + 1] = val2 >>> 8 & 255; + }; + parse_BrtCommentText = parse_RichStr; + parse_XLSBCodeName = parse_XLWideString; + parse_XLNameWideString = parse_XLWideString; + parse_RelID = parse_XLNullableWideString; + parse_UncheckedRfX = parse_RfX; + VT_I2 = 2; + VT_I4 = 3; + VT_BOOL = 11; + VT_VARIANT = 12; + VT_UI4 = 19; + VT_FILETIME = 64; + VT_BLOB = 65; + VT_CF = 71; + VT_VECTOR_VARIANT = 4108; + VT_VECTOR_LPSTR = 4126; + VT_STRING = 80; + VT_USTR = 81; + VT_CUSTOM = [VT_STRING, VT_USTR]; + DocSummaryPIDDSI = { + 1: { n: "CodePage", t: VT_I2 }, + 2: { n: "Category", t: VT_STRING }, + 3: { n: "PresentationFormat", t: VT_STRING }, + 4: { n: "ByteCount", t: VT_I4 }, + 5: { n: "LineCount", t: VT_I4 }, + 6: { n: "ParagraphCount", t: VT_I4 }, + 7: { n: "SlideCount", t: VT_I4 }, + 8: { n: "NoteCount", t: VT_I4 }, + 9: { n: "HiddenCount", t: VT_I4 }, + 10: { n: "MultimediaClipCount", t: VT_I4 }, + 11: { n: "ScaleCrop", t: VT_BOOL }, + 12: { + n: "HeadingPairs", + t: VT_VECTOR_VARIANT + /* VT_VECTOR | VT_VARIANT */ + }, + 13: { + n: "TitlesOfParts", + t: VT_VECTOR_LPSTR + /* VT_VECTOR | VT_LPSTR */ + }, + 14: { n: "Manager", t: VT_STRING }, + 15: { n: "Company", t: VT_STRING }, + 16: { n: "LinksUpToDate", t: VT_BOOL }, + 17: { n: "CharacterCount", t: VT_I4 }, + 19: { n: "SharedDoc", t: VT_BOOL }, + 22: { n: "HyperlinksChanged", t: VT_BOOL }, + 23: { n: "AppVersion", t: VT_I4, p: "version" }, + 24: { n: "DigSig", t: VT_BLOB }, + 26: { n: "ContentType", t: VT_STRING }, + 27: { n: "ContentStatus", t: VT_STRING }, + 28: { n: "Language", t: VT_STRING }, + 29: { n: "Version", t: VT_STRING }, + 255: {}, + /* [MS-OLEPS] 2.18 */ + 2147483648: { n: "Locale", t: VT_UI4 }, + 2147483651: { n: "Behavior", t: VT_UI4 }, + 1919054434: {} + }; + SummaryPIDSI = { + 1: { n: "CodePage", t: VT_I2 }, + 2: { n: "Title", t: VT_STRING }, + 3: { n: "Subject", t: VT_STRING }, + 4: { n: "Author", t: VT_STRING }, + 5: { n: "Keywords", t: VT_STRING }, + 6: { n: "Comments", t: VT_STRING }, + 7: { n: "Template", t: VT_STRING }, + 8: { n: "LastAuthor", t: VT_STRING }, + 9: { n: "RevNumber", t: VT_STRING }, + 10: { n: "EditTime", t: VT_FILETIME }, + 11: { n: "LastPrinted", t: VT_FILETIME }, + 12: { n: "CreatedDate", t: VT_FILETIME }, + 13: { n: "ModifiedDate", t: VT_FILETIME }, + 14: { n: "PageCount", t: VT_I4 }, + 15: { n: "WordCount", t: VT_I4 }, + 16: { n: "CharCount", t: VT_I4 }, + 17: { n: "Thumbnail", t: VT_CF }, + 18: { n: "Application", t: VT_STRING }, + 19: { n: "DocSecurity", t: VT_I4 }, + 255: {}, + /* [MS-OLEPS] 2.18 */ + 2147483648: { n: "Locale", t: VT_UI4 }, + 2147483651: { n: "Behavior", t: VT_UI4 }, + 1919054434: {} + }; + CountryEnum = { + 1: "US", + // United States + 2: "CA", + // Canada + 3: "", + // Latin America (except Brazil) + 7: "RU", + // Russia + 20: "EG", + // Egypt + 30: "GR", + // Greece + 31: "NL", + // Netherlands + 32: "BE", + // Belgium + 33: "FR", + // France + 34: "ES", + // Spain + 36: "HU", + // Hungary + 39: "IT", + // Italy + 41: "CH", + // Switzerland + 43: "AT", + // Austria + 44: "GB", + // United Kingdom + 45: "DK", + // Denmark + 46: "SE", + // Sweden + 47: "NO", + // Norway + 48: "PL", + // Poland + 49: "DE", + // Germany + 52: "MX", + // Mexico + 55: "BR", + // Brazil + 61: "AU", + // Australia + 64: "NZ", + // New Zealand + 66: "TH", + // Thailand + 81: "JP", + // Japan + 82: "KR", + // Korea + 84: "VN", + // Viet Nam + 86: "CN", + // China + 90: "TR", + // Turkey + 105: "JS", + // Ramastan + 213: "DZ", + // Algeria + 216: "MA", + // Morocco + 218: "LY", + // Libya + 351: "PT", + // Portugal + 354: "IS", + // Iceland + 358: "FI", + // Finland + 420: "CZ", + // Czech Republic + 886: "TW", + // Taiwan + 961: "LB", + // Lebanon + 962: "JO", + // Jordan + 963: "SY", + // Syria + 964: "IQ", + // Iraq + 965: "KW", + // Kuwait + 966: "SA", + // Saudi Arabia + 971: "AE", + // United Arab Emirates + 972: "IL", + // Israel + 974: "QA", + // Qatar + 981: "IR", + // Iran + 65535: "US" + // United States + }; + XLSFillPattern = [ + null, + "solid", + "mediumGray", + "darkGray", + "lightGray", + "darkHorizontal", + "darkVertical", + "darkDown", + "darkUp", + "darkGrid", + "darkTrellis", + "lightHorizontal", + "lightVertical", + "lightDown", + "lightUp", + "lightGrid", + "lightTrellis", + "gray125", + "gray0625" + ]; + _XLSIcv = /* @__PURE__ */ rgbify([ + /* Color Constants */ + 0, + 16777215, + 16711680, + 65280, + 255, + 16776960, + 16711935, + 65535, + /* Overridable Defaults */ + 0, + 16777215, + 16711680, + 65280, + 255, + 16776960, + 16711935, + 65535, + 8388608, + 32768, + 128, + 8421376, + 8388736, + 32896, + 12632256, + 8421504, + 10066431, + 10040166, + 16777164, + 13434879, + 6684774, + 16744576, + 26316, + 13421823, + 128, + 16711935, + 16776960, + 65535, + 8388736, + 8388608, + 32896, + 255, + 52479, + 13434879, + 13434828, + 16777113, + 10079487, + 16751052, + 13408767, + 16764057, + 3368703, + 3394764, + 10079232, + 16763904, + 16750848, + 16737792, + 6710937, + 9868950, + 13158, + 3381606, + 13056, + 3355392, + 10040064, + 10040166, + 3355545, + 3355443, + /* Other entries to appease BIFF8/12 */ + 0, + /* 0x40 icvForeground ?? */ + 16777215, + /* 0x41 icvBackground ?? */ + 0, + /* 0x42 icvFrame ?? */ + 0, + /* 0x43 icv3D ?? */ + 0, + /* 0x44 icv3DText ?? */ + 0, + /* 0x45 icv3DHilite ?? */ + 0, + /* 0x46 icv3DShadow ?? */ + 0, + /* 0x47 icvHilite ?? */ + 0, + /* 0x48 icvCtlText ?? */ + 0, + /* 0x49 icvCtlScrl ?? */ + 0, + /* 0x4A icvCtlInv ?? */ + 0, + /* 0x4B icvCtlBody ?? */ + 0, + /* 0x4C icvCtlFrame ?? */ + 0, + /* 0x4D icvCtlFore ?? */ + 0, + /* 0x4E icvCtlBack ?? */ + 0, + /* 0x4F icvCtlNeutral */ + 0, + /* 0x50 icvInfoBk ?? */ + 0 + /* 0x51 icvInfoText ?? */ + ]); + XLSIcv = /* @__PURE__ */ dup(_XLSIcv); + BErr = { + 0: "#NULL!", + 7: "#DIV/0!", + 15: "#VALUE!", + 23: "#REF!", + 29: "#NAME?", + 36: "#NUM!", + 42: "#N/A", + 43: "#GETTING_DATA", + 255: "#WTF?" + }; + RBErr = { + "#NULL!": 0, + "#DIV/0!": 7, + "#VALUE!": 15, + "#REF!": 23, + "#NAME?": 29, + "#NUM!": 36, + "#N/A": 42, + "#GETTING_DATA": 43, + "#WTF?": 255 + }; + XLSLblBuiltIn = [ + "_xlnm.Consolidate_Area", + "_xlnm.Auto_Open", + "_xlnm.Auto_Close", + "_xlnm.Extract", + "_xlnm.Database", + "_xlnm.Criteria", + "_xlnm.Print_Area", + "_xlnm.Print_Titles", + "_xlnm.Recorder", + "_xlnm.Data_Form", + "_xlnm.Auto_Activate", + "_xlnm.Auto_Deactivate", + "_xlnm.Sheet_Title", + "_xlnm._FilterDatabase" + ]; + ct2type = { + /* Workbook */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": "workbooks", + "application/vnd.ms-excel.sheet.macroEnabled.main+xml": "workbooks", + "application/vnd.ms-excel.sheet.binary.macroEnabled.main": "workbooks", + "application/vnd.ms-excel.addin.macroEnabled.main+xml": "workbooks", + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": "workbooks", + /* Worksheet */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": "sheets", + "application/vnd.ms-excel.worksheet": "sheets", + "application/vnd.ms-excel.binIndexWs": "TODO", + /* Binary Index */ + /* Chartsheet */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": "charts", + "application/vnd.ms-excel.chartsheet": "charts", + /* Macrosheet */ + "application/vnd.ms-excel.macrosheet+xml": "macros", + "application/vnd.ms-excel.macrosheet": "macros", + "application/vnd.ms-excel.intlmacrosheet": "TODO", + "application/vnd.ms-excel.binIndexMs": "TODO", + /* Binary Index */ + /* Dialogsheet */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": "dialogs", + "application/vnd.ms-excel.dialogsheet": "dialogs", + /* Shared Strings */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml": "strs", + "application/vnd.ms-excel.sharedStrings": "strs", + /* Styles */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": "styles", + "application/vnd.ms-excel.styles": "styles", + /* File Properties */ + "application/vnd.openxmlformats-package.core-properties+xml": "coreprops", + "application/vnd.openxmlformats-officedocument.custom-properties+xml": "custprops", + "application/vnd.openxmlformats-officedocument.extended-properties+xml": "extprops", + /* Custom Data Properties */ + "application/vnd.openxmlformats-officedocument.customXmlProperties+xml": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.customProperty": "TODO", + /* Comments */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": "comments", + "application/vnd.ms-excel.comments": "comments", + "application/vnd.ms-excel.threadedcomments+xml": "threadedcomments", + "application/vnd.ms-excel.person+xml": "people", + /* Metadata (Stock/Geography and Dynamic Array) */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetMetadata+xml": "metadata", + "application/vnd.ms-excel.sheetMetadata": "metadata", + /* PivotTable */ + "application/vnd.ms-excel.pivotTable": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotTable+xml": "TODO", + /* Chart Objects */ + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": "TODO", + /* Chart Colors */ + "application/vnd.ms-office.chartcolorstyle+xml": "TODO", + /* Chart Style */ + "application/vnd.ms-office.chartstyle+xml": "TODO", + /* Chart Advanced */ + "application/vnd.ms-office.chartex+xml": "TODO", + /* Calculation Chain */ + "application/vnd.ms-excel.calcChain": "calcchains", + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcChain+xml": "calcchains", + /* Printer Settings */ + "application/vnd.openxmlformats-officedocument.spreadsheetml.printerSettings": "TODO", + /* ActiveX */ + "application/vnd.ms-office.activeX": "TODO", + "application/vnd.ms-office.activeX+xml": "TODO", + /* Custom Toolbars */ + "application/vnd.ms-excel.attachedToolbars": "TODO", + /* External Data Connections */ + "application/vnd.ms-excel.connections": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": "TODO", + /* External Links */ + "application/vnd.ms-excel.externalLink": "links", + "application/vnd.openxmlformats-officedocument.spreadsheetml.externalLink+xml": "links", + /* PivotCache */ + "application/vnd.ms-excel.pivotCacheDefinition": "TODO", + "application/vnd.ms-excel.pivotCacheRecords": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheDefinition+xml": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotCacheRecords+xml": "TODO", + /* Query Table */ + "application/vnd.ms-excel.queryTable": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.queryTable+xml": "TODO", + /* Shared Workbook */ + "application/vnd.ms-excel.userNames": "TODO", + "application/vnd.ms-excel.revisionHeaders": "TODO", + "application/vnd.ms-excel.revisionLog": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionHeaders+xml": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionLog+xml": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.userNames+xml": "TODO", + /* Single Cell Table */ + "application/vnd.ms-excel.tableSingleCells": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.tableSingleCells+xml": "TODO", + /* Slicer */ + "application/vnd.ms-excel.slicer": "TODO", + "application/vnd.ms-excel.slicerCache": "TODO", + "application/vnd.ms-excel.slicer+xml": "TODO", + "application/vnd.ms-excel.slicerCache+xml": "TODO", + /* Sort Map */ + "application/vnd.ms-excel.wsSortMap": "TODO", + /* Table */ + "application/vnd.ms-excel.table": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": "TODO", + /* Themes */ + "application/vnd.openxmlformats-officedocument.theme+xml": "themes", + /* Theme Override */ + "application/vnd.openxmlformats-officedocument.themeOverride+xml": "TODO", + /* Timeline */ + "application/vnd.ms-excel.Timeline+xml": "TODO", + /* verify */ + "application/vnd.ms-excel.TimelineCache+xml": "TODO", + /* verify */ + /* VBA */ + "application/vnd.ms-office.vbaProject": "vba", + "application/vnd.ms-office.vbaProjectSignature": "TODO", + /* Volatile Dependencies */ + "application/vnd.ms-office.volatileDependencies": "TODO", + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatileDependencies+xml": "TODO", + /* Control Properties */ + "application/vnd.ms-excel.controlproperties+xml": "TODO", + /* Data Model */ + "application/vnd.openxmlformats-officedocument.model+data": "TODO", + /* Survey */ + "application/vnd.ms-excel.Survey+xml": "TODO", + /* Drawing */ + "application/vnd.openxmlformats-officedocument.drawing+xml": "drawings", + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": "TODO", + "application/vnd.openxmlformats-officedocument.drawingml.diagramColors+xml": "TODO", + "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml": "TODO", + "application/vnd.openxmlformats-officedocument.drawingml.diagramLayout+xml": "TODO", + "application/vnd.openxmlformats-officedocument.drawingml.diagramStyle+xml": "TODO", + /* VML */ + "application/vnd.openxmlformats-officedocument.vmlDrawing": "TODO", + "application/vnd.openxmlformats-package.relationships+xml": "rels", + "application/vnd.openxmlformats-officedocument.oleObject": "TODO", + /* Image */ + "image/png": "TODO", + "sheet": "js" + }; + RELS = { + WB: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", + SHEET: "http://sheetjs.openxmlformats.org/officeDocument/2006/relationships/officeDocument", + HLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink", + VML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing", + XPATH: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath", + XMISS: "http://schemas.microsoft.com/office/2006/relationships/xlExternalLinkPath/xlPathMissing", + XLINK: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLink", + CXML: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml", + CXMLP: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXmlProps", + CMNT: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments", + CORE_PROPS: "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", + EXT_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", + CUST_PROPS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties", + SST: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings", + STY: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles", + THEME: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme", + CHART: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart", + CHARTEX: "http://schemas.microsoft.com/office/2014/relationships/chartEx", + CS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartsheet", + WS: [ + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet", + "http://purl.oclc.org/ooxml/officeDocument/relationships/worksheet" + ], + DS: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/dialogsheet", + MS: "http://schemas.microsoft.com/office/2006/relationships/xlMacrosheet", + IMG: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image", + DRAW: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing", + XLMETA: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sheetMetadata", + TCMNT: "http://schemas.microsoft.com/office/2017/10/relationships/threadedComment", + PEOPLE: "http://schemas.microsoft.com/office/2017/10/relationships/person", + CONN: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/connections", + VBA: "http://schemas.microsoft.com/office/2006/relationships/vbaProject" + }; + CT_ODS = "application/vnd.oasis.opendocument.spreadsheet"; + CORE_PROPS = [ + ["cp:category", "Category"], + ["cp:contentStatus", "ContentStatus"], + ["cp:keywords", "Keywords"], + ["cp:lastModifiedBy", "LastAuthor"], + ["cp:lastPrinted", "LastPrinted"], + ["cp:revision", "RevNumber"], + ["cp:version", "Version"], + ["dc:creator", "Author"], + ["dc:description", "Comments"], + ["dc:identifier", "Identifier"], + ["dc:language", "Language"], + ["dc:subject", "Subject"], + ["dc:title", "Title"], + ["dcterms:created", "CreatedDate", "date"], + ["dcterms:modified", "ModifiedDate", "date"] + ]; + EXT_PROPS = [ + ["Application", "Application", "string"], + ["AppVersion", "AppVersion", "string"], + ["Company", "Company", "string"], + ["DocSecurity", "DocSecurity", "string"], + ["Manager", "Manager", "string"], + ["HyperlinksChanged", "HyperlinksChanged", "bool"], + ["SharedDoc", "SharedDoc", "bool"], + ["LinksUpToDate", "LinksUpToDate", "bool"], + ["ScaleCrop", "ScaleCrop", "bool"], + ["HeadingPairs", "HeadingPairs", "raw"], + ["TitlesOfParts", "TitlesOfParts", "raw"] + ]; + custregex = /<[^<>]+>[^<]*/g; + XLMLDocPropsMap = { + Title: "Title", + Subject: "Subject", + Author: "Author", + Keywords: "Keywords", + Comments: "Description", + LastAuthor: "LastAuthor", + RevNumber: "Revision", + Application: "AppName", + /* TotalTime: 'TotalTime', */ + LastPrinted: "LastPrinted", + CreatedDate: "Created", + ModifiedDate: "LastSaved", + /* Pages */ + /* Words */ + /* Characters */ + Category: "Category", + /* PresentationFormat */ + Manager: "Manager", + Company: "Company", + /* Guid */ + /* HyperlinkBase */ + /* Bytes */ + /* Lines */ + /* Paragraphs */ + /* CharactersWithSpaces */ + AppVersion: "Version", + ContentStatus: "ContentStatus", + /* NOTE: missing from schema */ + Identifier: "Identifier", + /* NOTE: missing from schema */ + Language: "Language" + /* NOTE: missing from schema */ + }; + parse_Ref = parse_RefU; + FtTab = { + 0: parse_FtSkip, + /* FtEnd */ + 4: parse_FtSkip, + /* FtMacro */ + 5: parse_FtSkip, + /* FtButton */ + 6: parse_FtSkip, + /* FtGmo */ + 7: parse_FtCf, + /* FtCf */ + 8: parse_FtSkip, + /* FtPioGrbit */ + 9: parse_FtSkip, + /* FtPictFmla */ + 10: parse_FtSkip, + /* FtCbls */ + 11: parse_FtSkip, + /* FtRbo */ + 12: parse_FtSkip, + /* FtSbs */ + 13: parse_FtNts, + /* FtNts */ + 14: parse_FtSkip, + /* FtSbsFmla */ + 15: parse_FtSkip, + /* FtGboData */ + 16: parse_FtSkip, + /* FtEdoData */ + 17: parse_FtSkip, + /* FtRboData */ + 18: parse_FtSkip, + /* FtCblsData */ + 19: parse_FtSkip, + /* FtLbsData */ + 20: parse_FtSkip, + /* FtCblsFmla */ + 21: parse_FtCmo + }; + parse_BIFF2Format = parse_XLUnicodeString2; + parse_XLHeaderFooter = parse_OptXLUnicodeString; + parse_BIFF5OT = { + 8: function(blob, length) { + var tgt = blob.l + length; + blob.l += 10; + var cf = blob.read_shift(2); + blob.l += 4; + blob.l += 2; + blob.l += 2; + blob.l += 2; + blob.l += 4; + var cchName = blob.read_shift(1); + blob.l += cchName; + blob.l = tgt; + return { fmt: cf }; + } + }; + parse_Blank = parse_XLSCell; + parse_Scl = parseuint16a; + parse_String = parse_XLUnicodeString; + DBF_SUPPORTED_VERSIONS = [2, 3, 48, 49, 131, 139, 140, 245]; + DBF = /* @__PURE__ */ (function() { + var dbf_codepage_map = { + /* Code Pages Supported by Visual FoxPro */ + 1: 437, + 2: 850, + 3: 1252, + 4: 1e4, + 100: 852, + 101: 866, + 102: 865, + 103: 861, + 104: 895, + 105: 620, + 106: 737, + 107: 857, + 120: 950, + 121: 949, + 122: 936, + 123: 932, + 124: 874, + 125: 1255, + 126: 1256, + 150: 10007, + 151: 10029, + 152: 10006, + 200: 1250, + 201: 1251, + 202: 1254, + 203: 1253, + /* shapefile DBF extension */ + 0: 20127, + 8: 865, + 9: 437, + 10: 850, + 11: 437, + 13: 437, + 14: 850, + 15: 437, + 16: 850, + 17: 437, + 18: 850, + 19: 932, + 20: 850, + 21: 437, + 22: 850, + 23: 865, + 24: 437, + 25: 437, + 26: 850, + 27: 437, + 28: 863, + 29: 850, + 31: 852, + 34: 852, + 35: 852, + 36: 860, + 37: 850, + 38: 866, + 55: 850, + 64: 852, + 77: 936, + 78: 949, + 79: 950, + 80: 874, + 87: 1252, + 88: 1252, + 89: 1252, + 108: 863, + 134: 737, + 135: 852, + 136: 857, + 204: 1257, + 255: 16969 + }; + var dbf_reverse_map = evert({ + 1: 437, + 2: 850, + 3: 1252, + 4: 1e4, + 100: 852, + 101: 866, + 102: 865, + 103: 861, + 104: 895, + 105: 620, + 106: 737, + 107: 857, + 120: 950, + 121: 949, + 122: 936, + 123: 932, + 124: 874, + 125: 1255, + 126: 1256, + 150: 10007, + 151: 10029, + 152: 10006, + 200: 1250, + 201: 1251, + 202: 1254, + 203: 1253, + 0: 20127 + }); + function dbf_to_aoa(buf, opts) { + var out = []; + var d4 = new_raw_buf(1); + switch (opts.type) { + case "base64": + d4 = s2a(Base64_decode(buf)); + break; + case "binary": + d4 = s2a(buf); + break; + case "buffer": + case "array": + d4 = buf; + break; + } + prep_blob(d4, 0); + var ft = d4.read_shift(1); + var memo = !!(ft & 136); + var vfp = false, l7 = false; + switch (ft) { + case 2: + break; + // dBASE II + case 3: + break; + // dBASE III + case 48: + vfp = true; + memo = true; + break; + // VFP + case 49: + vfp = true; + memo = true; + break; + // VFP with autoincrement + // 0x43 dBASE IV SQL table files + // 0x63 dBASE IV SQL system files + case 131: + break; + // dBASE III with memo + case 139: + break; + // dBASE IV with memo + case 140: + l7 = true; + break; + // dBASE Level 7 with memo + // case 0xCB dBASE IV SQL table files with memo + case 245: + break; + // FoxPro 2.x with memo + // case 0xFB FoxBASE + default: + throw new Error("DBF Unsupported Version: " + ft.toString(16)); + } + var nrow = 0, fpos = 521; + if (ft == 2) nrow = d4.read_shift(2); + d4.l += 3; + if (ft != 2) nrow = d4.read_shift(4); + if (nrow > 1048576) nrow = 1e6; + if (ft != 2) fpos = d4.read_shift(2); + var rlen = d4.read_shift(2); + var current_cp = opts.codepage || 1252; + if (ft != 2) { + d4.l += 16; + d4.read_shift(1); + if (d4[d4.l] !== 0) current_cp = dbf_codepage_map[d4[d4.l]]; + d4.l += 1; + d4.l += 2; + } + if (l7) d4.l += 36; + var fields = [], field = {}; + var hend = Math.min(d4.length, ft == 2 ? 521 : fpos - 10 - (vfp ? 264 : 0)); + var ww = l7 ? 32 : 11; + while (d4.l < hend && d4[d4.l] != 13) { + field = {}; + field.name = (typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, d4.slice(d4.l, d4.l + ww)) : a2s(d4.slice(d4.l, d4.l + ww))).replace(/[\u0000\r\n][\S\s]*$/g, ""); + d4.l += ww; + field.type = String.fromCharCode(d4.read_shift(1)); + if (ft != 2 && !l7) field.offset = d4.read_shift(4); + field.len = d4.read_shift(1); + if (ft == 2) field.offset = d4.read_shift(2); + field.dec = d4.read_shift(1); + if (field.name.length) fields.push(field); + if (ft != 2) d4.l += l7 ? 13 : 14; + switch (field.type) { + case "B": + if ((!vfp || field.len != 8) && opts.WTF) console.log("Skipping " + field.name + ":" + field.type); + break; + case "G": + // General (FoxPro and dBASE L7) + case "P": + if (opts.WTF) console.log("Skipping " + field.name + ":" + field.type); + break; + case "+": + // Autoincrement (dBASE L7 only) + case "0": + // _NullFlags (VFP only) + case "@": + // Timestamp (dBASE L7 only) + case "C": + // Character (dBASE II) + case "D": + // Date (dBASE III) + case "F": + // Float (dBASE IV) + case "I": + // Long (VFP and dBASE L7) + case "L": + // Logical (dBASE II) + case "M": + // Memo (dBASE III) + case "N": + // Number (dBASE II) + case "O": + // Double (dBASE L7 only) + case "T": + // Datetime (VFP only) + case "Y": + break; + default: + throw new Error("Unknown Field Type: " + field.type); + } + } + if (d4[d4.l] !== 13) d4.l = fpos - 1; + if (d4.read_shift(1) !== 13) throw new Error("DBF Terminator not found " + d4.l + " " + d4[d4.l]); + d4.l = fpos; + var R3 = 0, C3 = 0; + out[0] = []; + for (C3 = 0; C3 != fields.length; ++C3) out[0][C3] = fields[C3].name; + while (nrow-- > 0) { + if (d4[d4.l] === 42) { + d4.l += rlen; + continue; + } + ++d4.l; + out[++R3] = []; + C3 = 0; + for (C3 = 0; C3 != fields.length; ++C3) { + var dd = d4.slice(d4.l, d4.l + fields[C3].len); + d4.l += fields[C3].len; + prep_blob(dd, 0); + var s6 = typeof $cptable !== "undefined" ? $cptable.utils.decode(current_cp, dd) : a2s(dd); + switch (fields[C3].type) { + case "C": + if (s6.trim().length) out[R3][C3] = s6.replace(/([^\s])\s+$/, "$1"); + break; + case "D": + if (s6.length === 8) { + out[R3][C3] = new Date(Date.UTC(+s6.slice(0, 4), +s6.slice(4, 6) - 1, +s6.slice(6, 8), 0, 0, 0, 0)); + if (!(opts && opts.UTC)) { + out[R3][C3] = utc_to_local(out[R3][C3]); + } + } else out[R3][C3] = s6; + break; + case "F": + out[R3][C3] = parseFloat(s6.trim()); + break; + case "+": + case "I": + out[R3][C3] = l7 ? dd.read_shift(-4, "i") ^ 2147483648 : dd.read_shift(4, "i"); + break; + case "L": + switch (s6.trim().toUpperCase()) { + case "Y": + case "T": + out[R3][C3] = true; + break; + case "N": + case "F": + out[R3][C3] = false; + break; + case "": + case "\0": + case "?": + break; + default: + throw new Error("DBF Unrecognized L:|" + s6 + "|"); + } + break; + case "M": + if (!memo) throw new Error("DBF Unexpected MEMO for type " + ft.toString(16)); + out[R3][C3] = "##MEMO##" + (l7 ? parseInt(s6.trim(), 10) : dd.read_shift(4)); + break; + case "N": + s6 = s6.replace(/\u0000/g, "").trim(); + if (s6 && s6 != ".") out[R3][C3] = +s6 || 0; + break; + case "@": + out[R3][C3] = new Date(dd.read_shift(-8, "f") - 621356832e5); + break; + case "T": + { + var hi = dd.read_shift(4), lo = dd.read_shift(4); + if (hi == 0 && lo == 0) break; + out[R3][C3] = new Date((hi - 2440588) * 864e5 + lo); + if (!(opts && opts.UTC)) out[R3][C3] = utc_to_local(out[R3][C3]); + } + break; + case "Y": + out[R3][C3] = dd.read_shift(4, "i") / 1e4 + dd.read_shift(4, "i") / 1e4 * Math.pow(2, 32); + break; + case "O": + out[R3][C3] = -dd.read_shift(-8, "f"); + break; + case "B": + if (vfp && fields[C3].len == 8) { + out[R3][C3] = dd.read_shift(8, "f"); + break; + } + /* falls through */ + case "G": + case "P": + dd.l += fields[C3].len; + break; + case "0": + if (fields[C3].name === "_NullFlags") break; + /* falls through */ + default: + throw new Error("DBF Unsupported data type " + fields[C3].type); + } + } + } + if (ft != 2) { + if (d4.l < d4.length && d4[d4.l++] != 26) throw new Error("DBF EOF Marker missing " + (d4.l - 1) + " of " + d4.length + " " + d4[d4.l - 1].toString(16)); + } + if (opts && opts.sheetRows) out = out.slice(0, opts.sheetRows); + opts.DBF = fields; + return out; + } + function dbf_to_sheet(buf, opts) { + var o9 = opts || {}; + if (!o9.dateNF) o9.dateNF = "yyyymmdd"; + var ws = aoa_to_sheet(dbf_to_aoa(buf, o9), o9); + ws["!cols"] = o9.DBF.map(function(field) { + return { + wch: field.len, + DBF: field + }; + }); + delete o9.DBF; + return ws; + } + function dbf_to_workbook(buf, opts) { + try { + var o9 = sheet_to_workbook(dbf_to_sheet(buf, opts), opts); + o9.bookType = "dbf"; + return o9; + } catch (e9) { + if (opts && opts.WTF) throw e9; + } + return { SheetNames: [], Sheets: {} }; + } + var _RLEN = { "B": 8, "C": 250, "L": 1, "D": 8, "?": 0, "": 0 }; + function sheet_to_dbf(ws, opts) { + if (!ws["!ref"]) throw new Error("Cannot export empty sheet to DBF"); + var o9 = opts || {}; + var old_cp = current_codepage; + if (+o9.codepage >= 0) set_cp(+o9.codepage); + if (o9.type == "string") throw new Error("Cannot write DBF to JS string"); + var ba = buf_array(); + var aoa = sheet_to_json(ws, { header: 1, raw: true, cellDates: true }); + var headers = aoa[0], data = aoa.slice(1), cols = ws["!cols"] || []; + var i7 = 0, j3 = 0, hcnt = 0, rlen = 1; + for (i7 = 0; i7 < headers.length; ++i7) { + if (((cols[i7] || {}).DBF || {}).name) { + headers[i7] = cols[i7].DBF.name; + ++hcnt; + continue; + } + if (headers[i7] == null) continue; + ++hcnt; + if (typeof headers[i7] === "number") headers[i7] = headers[i7].toString(10); + if (typeof headers[i7] !== "string") throw new Error("DBF Invalid column name " + headers[i7] + " |" + typeof headers[i7] + "|"); + if (headers.indexOf(headers[i7]) !== i7) { + for (j3 = 0; j3 < 1024; ++j3) + if (headers.indexOf(headers[i7] + "_" + j3) == -1) { + headers[i7] += "_" + j3; + break; + } + } + } + var range2 = safe_decode_range(ws["!ref"]); + var coltypes = []; + var colwidths = []; + var coldecimals = []; + for (i7 = 0; i7 <= range2.e.c - range2.s.c; ++i7) { + var guess = "", _guess = "", maxlen = 0; + var col = []; + for (j3 = 0; j3 < data.length; ++j3) { + if (data[j3][i7] != null) col.push(data[j3][i7]); + } + if (col.length == 0 || headers[i7] == null) { + coltypes[i7] = "?"; + continue; + } + for (j3 = 0; j3 < col.length; ++j3) { + switch (typeof col[j3]) { + /* TODO: check if L2 compat is desired */ + case "number": + _guess = "B"; + break; + case "string": + _guess = "C"; + break; + case "boolean": + _guess = "L"; + break; + case "object": + _guess = col[j3] instanceof Date ? "D" : "C"; + break; + default: + _guess = "C"; + } + maxlen = Math.max(maxlen, (typeof $cptable !== "undefined" && typeof col[j3] == "string" ? $cptable.utils.encode(current_ansi, col[j3]) : String(col[j3])).length); + guess = guess && guess != _guess ? "C" : _guess; + } + if (maxlen > 250) maxlen = 250; + _guess = ((cols[i7] || {}).DBF || {}).type; + if (_guess == "C") { + if (cols[i7].DBF.len > maxlen) maxlen = cols[i7].DBF.len; + } + if (guess == "B" && _guess == "N") { + guess = "N"; + coldecimals[i7] = cols[i7].DBF.dec; + maxlen = cols[i7].DBF.len; + } + colwidths[i7] = guess == "C" || _guess == "N" ? maxlen : _RLEN[guess] || 0; + rlen += colwidths[i7]; + coltypes[i7] = guess; + } + var h7 = ba.next(32); + h7.write_shift(4, 318902576); + h7.write_shift(4, data.length); + h7.write_shift(2, 296 + 32 * hcnt); + h7.write_shift(2, rlen); + for (i7 = 0; i7 < 4; ++i7) h7.write_shift(4, 0); + var cp = +dbf_reverse_map[ + /*::String(*/ + current_codepage + /*::)*/ + ] || 3; + h7.write_shift(4, 0 | cp << 8); + if (dbf_codepage_map[cp] != +o9.codepage) { + if (o9.codepage) console.error("DBF Unsupported codepage " + current_codepage + ", using 1252"); + current_codepage = 1252; + } + for (i7 = 0, j3 = 0; i7 < headers.length; ++i7) { + if (headers[i7] == null) continue; + var hf = ba.next(32); + var _f = (headers[i7].slice(-10) + "\0\0\0\0\0\0\0\0\0\0\0").slice(0, 11); + hf.write_shift(1, _f, "sbcs"); + hf.write_shift(1, coltypes[i7] == "?" ? "C" : coltypes[i7], "sbcs"); + hf.write_shift(4, j3); + hf.write_shift(1, colwidths[i7] || _RLEN[coltypes[i7]] || 0); + hf.write_shift(1, coldecimals[i7] || 0); + hf.write_shift(1, 2); + hf.write_shift(4, 0); + hf.write_shift(1, 0); + hf.write_shift(4, 0); + hf.write_shift(4, 0); + j3 += colwidths[i7] || _RLEN[coltypes[i7]] || 0; + } + var hb = ba.next(264); + hb.write_shift(4, 13); + for (i7 = 0; i7 < 65; ++i7) hb.write_shift(4, 0); + for (i7 = 0; i7 < data.length; ++i7) { + var rout = ba.next(rlen); + rout.write_shift(1, 0); + for (j3 = 0; j3 < headers.length; ++j3) { + if (headers[j3] == null) continue; + switch (coltypes[j3]) { + case "L": + rout.write_shift(1, data[i7][j3] == null ? 63 : data[i7][j3] ? 84 : 70); + break; + case "B": + rout.write_shift(8, data[i7][j3] || 0, "f"); + break; + case "N": + var _n = "0"; + if (typeof data[i7][j3] == "number") _n = data[i7][j3].toFixed(coldecimals[j3] || 0); + if (_n.length > colwidths[j3]) _n = _n.slice(0, colwidths[j3]); + for (hcnt = 0; hcnt < colwidths[j3] - _n.length; ++hcnt) rout.write_shift(1, 32); + rout.write_shift(1, _n, "sbcs"); + break; + case "D": + if (!data[i7][j3]) rout.write_shift(8, "00000000", "sbcs"); + else { + rout.write_shift(4, ("0000" + data[i7][j3].getFullYear()).slice(-4), "sbcs"); + rout.write_shift(2, ("00" + (data[i7][j3].getMonth() + 1)).slice(-2), "sbcs"); + rout.write_shift(2, ("00" + data[i7][j3].getDate()).slice(-2), "sbcs"); + } + break; + case "C": + var _l = rout.l; + var _s = String(data[i7][j3] != null ? data[i7][j3] : "").slice(0, colwidths[j3]); + rout.write_shift(1, _s, "cpstr"); + _l += colwidths[j3] - rout.l; + for (hcnt = 0; hcnt < _l; ++hcnt) rout.write_shift(1, 32); + break; + } + } + } + current_codepage = old_cp; + ba.next(1).write_shift(1, 26); + return ba.end(); + } + return { + to_workbook: dbf_to_workbook, + to_sheet: dbf_to_sheet, + from_sheet: sheet_to_dbf + }; + })(); + SYLK = /* @__PURE__ */ (function() { + var sylk_escapes = { + AA: "\xC0", + BA: "\xC1", + CA: "\xC2", + DA: 195, + HA: "\xC4", + JA: 197, + AE: "\xC8", + BE: "\xC9", + CE: "\xCA", + HE: "\xCB", + AI: "\xCC", + BI: "\xCD", + CI: "\xCE", + HI: "\xCF", + AO: "\xD2", + BO: "\xD3", + CO: "\xD4", + DO: 213, + HO: "\xD6", + AU: "\xD9", + BU: "\xDA", + CU: "\xDB", + HU: "\xDC", + Aa: "\xE0", + Ba: "\xE1", + Ca: "\xE2", + Da: 227, + Ha: "\xE4", + Ja: 229, + Ae: "\xE8", + Be: "\xE9", + Ce: "\xEA", + He: "\xEB", + Ai: "\xEC", + Bi: "\xED", + Ci: "\xEE", + Hi: "\xEF", + Ao: "\xF2", + Bo: "\xF3", + Co: "\xF4", + Do: 245, + Ho: "\xF6", + Au: "\xF9", + Bu: "\xFA", + Cu: "\xFB", + Hu: "\xFC", + KC: "\xC7", + Kc: "\xE7", + q: "\xE6", + z: "\u0153", + a: "\xC6", + j: "\u0152", + DN: 209, + Dn: 241, + Hy: 255, + S: 169, + c: 170, + R: 174, + "B ": 180, + 0: 176, + 1: 177, + 2: 178, + 3: 179, + 5: 181, + 6: 182, + 7: 183, + Q: 185, + k: 186, + b: 208, + i: 216, + l: 222, + s: 240, + y: 248, + "!": 161, + '"': 162, + "#": 163, + "(": 164, + "%": 165, + "'": 167, + "H ": 168, + "+": 171, + ";": 187, + "<": 188, + "=": 189, + ">": 190, + "?": 191, + "{": 223 + }; + var sylk_char_regex = new RegExp("\x1BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g, "\\$1").replace("{", "\\{") + "|\\|)", "gm"); + try { + sylk_char_regex = new RegExp("\x1BN(" + keys(sylk_escapes).join("|").replace(/\|\|\|/, "|\\||").replace(/([?()+])/g, "\\$1") + "|\\|)", "gm"); + } catch (e9) { + } + var sylk_char_fn = function(_3, $1) { + var o9 = sylk_escapes[$1]; + return typeof o9 == "number" ? _getansi(o9) : o9; + }; + var decode_sylk_char = function($$, $1, $22) { + var newcc = $1.charCodeAt(0) - 32 << 4 | $22.charCodeAt(0) - 48; + return newcc == 59 ? $$ : _getansi(newcc); + }; + sylk_escapes["|"] = 254; + var encode_sylk_str = function($$) { + return $$.replace(/\n/g, "\x1B :").replace(/\r/g, "\x1B ="); + }; + function sylk_to_aoa(d4, opts) { + switch (opts.type) { + case "base64": + return sylk_to_aoa_str(Base64_decode(d4), opts); + case "binary": + return sylk_to_aoa_str(d4, opts); + case "buffer": + return sylk_to_aoa_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts); + case "array": + return sylk_to_aoa_str(cc2str(d4), opts); + } + throw new Error("Unrecognized type " + opts.type); + } + function sylk_to_aoa_str(str2, opts) { + var records = str2.split(/[\n\r]+/), R3 = -1, C3 = -1, ri = 0, rj = 0, arr = []; + var formats = []; + var next_cell_format = null; + var sht = {}, rowinfo = [], colinfo = [], cw = []; + var Mval = 0, j3; + var wb = { Workbook: { WBProps: {}, Names: [] } }; + if (+opts.codepage >= 0) set_cp(+opts.codepage); + for (; ri !== records.length; ++ri) { + Mval = 0; + var rstr = records[ri].trim().replace(/\x1B([\x20-\x2F])([\x30-\x3F])/g, decode_sylk_char).replace(sylk_char_regex, sylk_char_fn); + var record = rstr.replace(/;;/g, "\0").split(";").map(function(x2) { + return x2.replace(/\u0000/g, ";"); + }); + var RT = record[0], val2; + if (rstr.length > 0) switch (RT) { + case "ID": + break; + /* header */ + case "E": + break; + /* EOF */ + case "B": + break; + /* dimensions */ + case "O": + for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) { + case "V": + { + var d1904 = parseInt(record[rj].slice(1), 10); + if (d1904 >= 1 && d1904 <= 4) wb.Workbook.WBProps.date1904 = true; + } + break; + } + break; + case "W": + break; + /* window */ + case "P": + switch (record[1].charAt(0)) { + case "P": + formats.push(rstr.slice(3).replace(/;;/g, ";")); + break; + } + break; + case "NN": + { + var nn = { Sheet: 0 }; + for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) { + case "N": + nn.Name = record[rj].slice(1); + break; + case "E": + nn.Ref = (opts && opts.sheet || "Sheet1") + "!" + rc_to_a1(record[rj].slice(1)); + break; + } + wb.Workbook.Names.push(nn); + } + break; + // case 'NE': // ?? + // case 'NU': // ?? + case "C": + var C_seen_K = false, C_seen_X = false, C_seen_S = false, C_seen_E = false, _R = -1, _C = -1, formula = "", cell_t = "z"; + var cmnt = ""; + for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) { + case "A": + cmnt = record[rj].slice(1); + break; + // TODO: comment + case "X": + C3 = parseInt(record[rj].slice(1), 10) - 1; + C_seen_X = true; + break; + case "Y": + R3 = parseInt(record[rj].slice(1), 10) - 1; + if (!C_seen_X) C3 = 0; + for (j3 = arr.length; j3 <= R3; ++j3) arr[j3] = []; + break; + case "K": + val2 = record[rj].slice(1); + if (val2.charAt(0) === '"') { + val2 = val2.slice(1, val2.length - 1); + cell_t = "s"; + } else if (val2 === "TRUE" || val2 === "FALSE") { + val2 = val2 === "TRUE"; + cell_t = "b"; + } else if (val2.charAt(0) == "#" && RBErr[val2] != null) { + cell_t = "e"; + val2 = RBErr[val2]; + } else if (!isNaN(fuzzynum(val2))) { + val2 = fuzzynum(val2); + cell_t = "n"; + if (next_cell_format !== null && fmt_is_date(next_cell_format) && opts.cellDates) { + val2 = numdate(wb.Workbook.WBProps.date1904 ? val2 + 1462 : val2); + cell_t = typeof val2 == "number" ? "n" : "d"; + } + } + if (typeof $cptable !== "undefined" && typeof val2 == "string" && (opts || {}).type != "string" && (opts || {}).codepage) val2 = $cptable.utils.decode(opts.codepage, val2); + C_seen_K = true; + break; + case "E": + C_seen_E = true; + formula = rc_to_a1(record[rj].slice(1), { r: R3, c: C3 }); + break; + case "S": + C_seen_S = true; + break; + case "G": + break; + // unknown + case "R": + _R = parseInt(record[rj].slice(1), 10) - 1; + break; + case "C": + _C = parseInt(record[rj].slice(1), 10) - 1; + break; + // case 'P': // ?? + // case 'D': // ?? + default: + if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr); + } + if (C_seen_K) { + if (!arr[R3][C3]) arr[R3][C3] = { t: cell_t, v: val2 }; + else { + arr[R3][C3].t = cell_t; + arr[R3][C3].v = val2; + } + if (next_cell_format) arr[R3][C3].z = next_cell_format; + if (opts.cellText !== false && next_cell_format) arr[R3][C3].w = SSF_format(arr[R3][C3].z, arr[R3][C3].v, { date1904: wb.Workbook.WBProps.date1904 }); + next_cell_format = null; + } + if (C_seen_S) { + if (C_seen_E) throw new Error("SYLK shared formula cannot have own formula"); + var shrbase = _R > -1 && arr[_R][_C]; + if (!shrbase || !shrbase[1]) throw new Error("SYLK shared formula cannot find base"); + formula = shift_formula_str(shrbase[1], { r: R3 - _R, c: C3 - _C }); + } + if (formula) { + if (!arr[R3][C3]) arr[R3][C3] = { t: "n", f: formula }; + else arr[R3][C3].f = formula; + } + if (cmnt) { + if (!arr[R3][C3]) arr[R3][C3] = { t: "z" }; + arr[R3][C3].c = [{ a: "SheetJSYLK", t: cmnt }]; + } + break; + case "F": + var F_seen = 0; + for (rj = 1; rj < record.length; ++rj) switch (record[rj].charAt(0)) { + case "X": + C3 = parseInt(record[rj].slice(1), 10) - 1; + ++F_seen; + break; + case "Y": + R3 = parseInt(record[rj].slice(1), 10) - 1; + for (j3 = arr.length; j3 <= R3; ++j3) arr[j3] = []; + break; + case "M": + Mval = parseInt(record[rj].slice(1), 10) / 20; + break; + case "F": + break; + /* ??? */ + case "G": + break; + /* hide grid */ + case "P": + next_cell_format = formats[parseInt(record[rj].slice(1), 10)]; + break; + case "S": + break; + /* cell style */ + case "D": + break; + /* column */ + case "N": + break; + /* font */ + case "W": + cw = record[rj].slice(1).split(" "); + for (j3 = parseInt(cw[0], 10); j3 <= parseInt(cw[1], 10); ++j3) { + Mval = parseInt(cw[2], 10); + colinfo[j3 - 1] = Mval === 0 ? { hidden: true } : { wch: Mval }; + } + break; + case "C": + C3 = parseInt(record[rj].slice(1), 10) - 1; + if (!colinfo[C3]) colinfo[C3] = {}; + break; + case "R": + R3 = parseInt(record[rj].slice(1), 10) - 1; + if (!rowinfo[R3]) rowinfo[R3] = {}; + if (Mval > 0) { + rowinfo[R3].hpt = Mval; + rowinfo[R3].hpx = pt2px(Mval); + } else if (Mval === 0) rowinfo[R3].hidden = true; + break; + // case 'K': // ?? + // case 'E': // ?? + default: + if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr); + } + if (F_seen < 1) next_cell_format = null; + break; + default: + if (opts && opts.WTF) throw new Error("SYLK bad record " + rstr); + } + } + if (rowinfo.length > 0) sht["!rows"] = rowinfo; + if (colinfo.length > 0) sht["!cols"] = colinfo; + colinfo.forEach(function(col) { + process_col(col); + }); + if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows); + return [arr, sht, wb]; + } + function sylk_to_workbook(d4, opts) { + var aoasht = sylk_to_aoa(d4, opts); + var aoa = aoasht[0], ws = aoasht[1], wb = aoasht[2]; + var _opts = dup(opts); + _opts.date1904 = (((wb || {}).Workbook || {}).WBProps || {}).date1904; + var o9 = aoa_to_sheet(aoa, _opts); + keys(ws).forEach(function(k2) { + o9[k2] = ws[k2]; + }); + var outwb = sheet_to_workbook(o9, opts); + keys(wb).forEach(function(k2) { + outwb[k2] = wb[k2]; + }); + outwb.bookType = "sylk"; + return outwb; + } + function write_ws_cell_sylk(cell, ws, R3, C3, opts, date1904) { + var o9 = "C;Y" + (R3 + 1) + ";X" + (C3 + 1) + ";K"; + switch (cell.t) { + case "n": + o9 += isFinite(cell.v) ? cell.v || 0 : BErr[isNaN(cell.v) ? 36 : 7]; + if (cell.f && !cell.F) o9 += ";E" + a1_to_rc(cell.f, { r: R3, c: C3 }); + break; + case "b": + o9 += cell.v ? "TRUE" : "FALSE"; + break; + case "e": + o9 += cell.w || BErr[cell.v] || cell.v; + break; + case "d": + o9 += datenum(parseDate(cell.v, date1904), date1904); + break; + case "s": + o9 += '"' + (cell.v == null ? "" : String(cell.v)).replace(/"/g, "").replace(/;/g, ";;") + '"'; + break; + } + return o9; + } + function write_ws_cmnt_sylk(cmnt, R3, C3) { + var o9 = "C;Y" + (R3 + 1) + ";X" + (C3 + 1) + ";A"; + o9 += encode_sylk_str(cmnt.map(function(c6) { + return c6.t; + }).join("")); + return o9; + } + function write_ws_cols_sylk(out, cols) { + cols.forEach(function(col, i7) { + var rec = "F;W" + (i7 + 1) + " " + (i7 + 1) + " "; + if (col.hidden) rec += "0"; + else { + if (typeof col.width == "number" && !col.wpx) col.wpx = width2px(col.width); + if (typeof col.wpx == "number" && !col.wch) col.wch = px2char(col.wpx); + if (typeof col.wch == "number") rec += Math.round(col.wch); + } + if (rec.charAt(rec.length - 1) != " ") out.push(rec); + }); + } + function write_ws_rows_sylk(out, rows) { + rows.forEach(function(row, i7) { + var rec = "F;"; + if (row.hidden) rec += "M0;"; + else if (row.hpt) rec += "M" + 20 * row.hpt + ";"; + else if (row.hpx) rec += "M" + 20 * px2pt(row.hpx) + ";"; + if (rec.length > 2) out.push(rec + "R" + (i7 + 1)); + }); + } + function sheet_to_sylk(ws, opts, wb) { + if (!opts) opts = {}; + opts._formats = ["General"]; + var preamble = ["ID;PSheetJS;N;E"], o9 = []; + var r8 = safe_decode_range(ws["!ref"] || "A1"), cell; + var dense = ws["!data"] != null; + var RS = "\r\n"; + var d1904 = (((wb || {}).Workbook || {}).WBProps || {}).date1904; + var _lastfmt = "General"; + preamble.push("P;PGeneral"); + var R3 = r8.s.r, C3 = r8.s.c, p4 = []; + if (ws["!ref"]) for (R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + if (dense && !ws["!data"][R3]) continue; + p4 = []; + for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + cell = dense ? ws["!data"][R3][C3] : ws[encode_col(C3) + encode_row(R3)]; + if (!cell || !cell.c) continue; + p4.push(write_ws_cmnt_sylk(cell.c, R3, C3)); + } + if (p4.length) o9.push(p4.join(RS)); + } + if (ws["!ref"]) for (R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + if (dense && !ws["!data"][R3]) continue; + p4 = []; + for (C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + cell = dense ? ws["!data"][R3][C3] : ws[encode_col(C3) + encode_row(R3)]; + if (!cell || cell.v == null && (!cell.f || cell.F)) continue; + if ((cell.z || (cell.t == "d" ? table_fmt[14] : "General")) != _lastfmt) { + var ifmt = opts._formats.indexOf(cell.z); + if (ifmt == -1) { + opts._formats.push(cell.z); + ifmt = opts._formats.length - 1; + preamble.push("P;P" + cell.z.replace(/;/g, ";;")); + } + p4.push("F;P" + ifmt + ";Y" + (R3 + 1) + ";X" + (C3 + 1)); + } + p4.push(write_ws_cell_sylk(cell, ws, R3, C3, opts, d1904)); + } + o9.push(p4.join(RS)); + } + preamble.push("F;P0;DG0G8;M255"); + if (ws["!cols"]) write_ws_cols_sylk(preamble, ws["!cols"]); + if (ws["!rows"]) write_ws_rows_sylk(preamble, ws["!rows"]); + if (ws["!ref"]) preamble.push("B;Y" + (r8.e.r - r8.s.r + 1) + ";X" + (r8.e.c - r8.s.c + 1) + ";D" + [r8.s.c, r8.s.r, r8.e.c, r8.e.r].join(" ")); + preamble.push("O;L;D;B" + (d1904 ? ";V4" : "") + ";K47;G100 0.001"); + delete opts._formats; + return preamble.join(RS) + RS + o9.join(RS) + RS + "E" + RS; + } + return { + to_workbook: sylk_to_workbook, + from_sheet: sheet_to_sylk + }; + })(); + DIF = /* @__PURE__ */ (function() { + function dif_to_aoa(d4, opts) { + switch (opts.type) { + case "base64": + return dif_to_aoa_str(Base64_decode(d4), opts); + case "binary": + return dif_to_aoa_str(d4, opts); + case "buffer": + return dif_to_aoa_str(has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4), opts); + case "array": + return dif_to_aoa_str(cc2str(d4), opts); + } + throw new Error("Unrecognized type " + opts.type); + } + function dif_to_aoa_str(str2, opts) { + var records = str2.split("\n"), R3 = -1, C3 = -1, ri = 0, arr = []; + for (; ri !== records.length; ++ri) { + if (records[ri].trim() === "BOT") { + arr[++R3] = []; + C3 = 0; + continue; + } + if (R3 < 0) continue; + var metadata = records[ri].trim().split(","); + var type = metadata[0], value = metadata[1]; + ++ri; + var data = records[ri] || ""; + while ((data.match(/["]/g) || []).length & 1 && ri < records.length - 1) data += "\n" + records[++ri]; + data = data.trim(); + switch (+type) { + case -1: + if (data === "BOT") { + arr[++R3] = []; + C3 = 0; + continue; + } else if (data !== "EOD") throw new Error("Unrecognized DIF special command " + data); + break; + case 0: + if (data === "TRUE") arr[R3][C3] = true; + else if (data === "FALSE") arr[R3][C3] = false; + else if (!isNaN(fuzzynum(value))) arr[R3][C3] = fuzzynum(value); + else if (!isNaN(fuzzydate(value).getDate())) { + arr[R3][C3] = parseDate(value); + if (!(opts && opts.UTC)) { + arr[R3][C3] = utc_to_local(arr[R3][C3]); + } + } else arr[R3][C3] = value; + ++C3; + break; + case 1: + data = data.slice(1, data.length - 1); + data = data.replace(/""/g, '"'); + if (DIF_XL && data && data.match(/^=".*"$/)) data = data.slice(2, -1); + arr[R3][C3++] = data !== "" ? data : null; + break; + } + if (data === "EOD") break; + } + if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows); + return arr; + } + function dif_to_sheet(str2, opts) { + return aoa_to_sheet(dif_to_aoa(str2, opts), opts); + } + function dif_to_workbook(str2, opts) { + var o9 = sheet_to_workbook(dif_to_sheet(str2, opts), opts); + o9.bookType = "dif"; + return o9; + } + function make_value(v4, s6) { + return "0," + String(v4) + "\r\n" + s6; + } + function make_value_str(s6) { + return '1,0\r\n"' + s6.replace(/"/g, '""') + '"'; + } + function sheet_to_dif(ws) { + var _DIF_XL = DIF_XL; + if (!ws["!ref"]) throw new Error("Cannot export empty sheet to DIF"); + var r8 = safe_decode_range(ws["!ref"]); + var dense = ws["!data"] != null; + var o9 = [ + 'TABLE\r\n0,1\r\n"sheetjs"\r\n', + "VECTORS\r\n0," + (r8.e.r - r8.s.r + 1) + '\r\n""\r\n', + "TUPLES\r\n0," + (r8.e.c - r8.s.c + 1) + '\r\n""\r\n', + 'DATA\r\n0,0\r\n""\r\n' + ]; + for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + var row = dense ? ws["!data"][R3] : []; + var p4 = "-1,0\r\nBOT\r\n"; + for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + var cell = dense ? row && row[C3] : ws[encode_cell({ r: R3, c: C3 })]; + if (cell == null) { + p4 += '1,0\r\n""\r\n'; + continue; + } + switch (cell.t) { + case "n": + if (_DIF_XL) { + if (cell.w != null) p4 += "0," + cell.w + "\r\nV"; + else if (cell.v != null) p4 += make_value(cell.v, "V"); + else if (cell.f != null && !cell.F) p4 += make_value_str("=" + cell.f); + else p4 += '1,0\r\n""'; + } else { + if (cell.v == null) p4 += '1,0\r\n""'; + else p4 += make_value(cell.v, "V"); + } + break; + case "b": + p4 += cell.v ? make_value(1, "TRUE") : make_value(0, "FALSE"); + break; + case "s": + p4 += make_value_str(!_DIF_XL || isNaN(+cell.v) ? cell.v : '="' + cell.v + '"'); + break; + case "d": + if (!cell.w) cell.w = SSF_format(cell.z || table_fmt[14], datenum(parseDate(cell.v))); + if (_DIF_XL) p4 += make_value(cell.w, "V"); + else p4 += make_value_str(cell.w); + break; + default: + p4 += '1,0\r\n""'; + } + p4 += "\r\n"; + } + o9.push(p4); + } + return o9.join("") + "-1,0\r\nEOD"; + } + return { + to_workbook: dif_to_workbook, + to_sheet: dif_to_sheet, + from_sheet: sheet_to_dif + }; + })(); + ETH = /* @__PURE__ */ (function() { + function decode5(s6) { + return s6.replace(/\\b/g, "\\").replace(/\\c/g, ":").replace(/\\n/g, "\n"); + } + function encode2(s6) { + return s6.replace(/\\/g, "\\b").replace(/:/g, "\\c").replace(/\n/g, "\\n"); + } + function eth_to_aoa(str2, opts) { + var records = str2.split("\n"), R3 = -1, C3 = -1, ri = 0, arr = []; + for (; ri !== records.length; ++ri) { + var record = records[ri].trim().split(":"); + if (record[0] !== "cell") continue; + var addr = decode_cell(record[1]); + if (arr.length <= addr.r) { + for (R3 = arr.length; R3 <= addr.r; ++R3) if (!arr[R3]) arr[R3] = []; + } + R3 = addr.r; + C3 = addr.c; + switch (record[2]) { + case "t": + arr[R3][C3] = decode5(record[3]); + break; + case "v": + arr[R3][C3] = +record[3]; + break; + case "vtf": + var _f = record[record.length - 1]; + /* falls through */ + case "vtc": + switch (record[3]) { + case "nl": + arr[R3][C3] = +record[4] ? true : false; + break; + default: + arr[R3][C3] = record[record.length - 1].charAt(0) == "#" ? { t: "e", v: RBErr[record[record.length - 1]] } : +record[4]; + break; + } + if (record[2] == "vtf") arr[R3][C3] = [arr[R3][C3], _f]; + } + } + if (opts && opts.sheetRows) arr = arr.slice(0, opts.sheetRows); + return arr; + } + function eth_to_sheet(d4, opts) { + return aoa_to_sheet(eth_to_aoa(d4, opts), opts); + } + function eth_to_workbook(d4, opts) { + return sheet_to_workbook(eth_to_sheet(d4, opts), opts); + } + var header = [ + "socialcalc:version:1.5", + "MIME-Version: 1.0", + "Content-Type: multipart/mixed; boundary=SocialCalcSpreadsheetControlSave" + ].join("\n"); + var sep2 = [ + "--SocialCalcSpreadsheetControlSave", + "Content-type: text/plain; charset=UTF-8" + ].join("\n") + "\n"; + var meta = [ + "# SocialCalc Spreadsheet Control Save", + "part:sheet" + ].join("\n"); + var end = "--SocialCalcSpreadsheetControlSave--"; + function sheet_to_eth_data(ws) { + if (!ws || !ws["!ref"]) return ""; + var o9 = [], oo = [], cell, coord = ""; + var r8 = decode_range(ws["!ref"]); + var dense = ws["!data"] != null; + for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + coord = encode_cell({ r: R3, c: C3 }); + cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord]; + if (!cell || cell.v == null || cell.t === "z") continue; + oo = ["cell", coord, "t"]; + switch (cell.t) { + case "s": + oo.push(encode2(cell.v)); + break; + case "b": + oo[2] = "vt" + (cell.f ? "f" : "c"); + oo[3] = "nl"; + oo[4] = cell.v ? "1" : "0"; + oo[5] = encode2(cell.f || (cell.v ? "TRUE" : "FALSE")); + break; + case "d": + var t6 = datenum(parseDate(cell.v)); + oo[2] = "vtc"; + oo[3] = "nd"; + oo[4] = "" + t6; + oo[5] = cell.w || SSF_format(cell.z || table_fmt[14], t6); + break; + case "n": + if (isFinite(cell.v)) { + if (!cell.f) { + oo[2] = "v"; + oo[3] = cell.v; + } else { + oo[2] = "vtf"; + oo[3] = "n"; + oo[4] = cell.v; + oo[5] = encode2(cell.f); + } + } else { + oo[2] = "vt" + (cell.f ? "f" : "c"); + oo[3] = "e" + BErr[isNaN(cell.v) ? 36 : 7]; + oo[4] = "0"; + oo[5] = cell.f || oo[3].slice(1); + oo[6] = "e"; + oo[7] = oo[3].slice(1); + } + break; + case "e": + continue; + } + o9.push(oo.join(":")); + } + } + o9.push("sheet:c:" + (r8.e.c - r8.s.c + 1) + ":r:" + (r8.e.r - r8.s.r + 1) + ":tvf:1"); + o9.push("valueformat:1:text-wiki"); + return o9.join("\n"); + } + function sheet_to_eth(ws) { + return [header, sep2, meta, sep2, sheet_to_eth_data(ws), end].join("\n"); + } + return { + to_workbook: eth_to_workbook, + to_sheet: eth_to_sheet, + from_sheet: sheet_to_eth + }; + })(); + PRN = /* @__PURE__ */ (function() { + function set_text_arr(data, arr, R3, C3, o9) { + if (o9.raw) arr[R3][C3] = data; + else if (data === "") { + } else if (data === "TRUE") arr[R3][C3] = true; + else if (data === "FALSE") arr[R3][C3] = false; + else if (!isNaN(fuzzynum(data))) arr[R3][C3] = fuzzynum(data); + else if (!isNaN(fuzzydate(data).getDate())) arr[R3][C3] = parseDate(data); + else if (data.charCodeAt(0) == 35 && RBErr[data] != null) arr[R3][C3] = { t: "e", v: RBErr[data], w: data }; + else arr[R3][C3] = data; + } + function prn_to_aoa_str(f4, opts) { + var o9 = opts || {}; + var arr = []; + if (!f4 || f4.length === 0) return arr; + var lines = f4.split(/[\r\n]/); + var L3 = lines.length - 1; + while (L3 >= 0 && lines[L3].length === 0) --L3; + var start = 10, idx = 0; + var R3 = 0; + for (; R3 <= L3; ++R3) { + idx = lines[R3].indexOf(" "); + if (idx == -1) idx = lines[R3].length; + else idx++; + start = Math.max(start, idx); + } + for (R3 = 0; R3 <= L3; ++R3) { + arr[R3] = []; + var C3 = 0; + set_text_arr(lines[R3].slice(0, start).trim(), arr, R3, C3, o9); + for (C3 = 1; C3 <= (lines[R3].length - start) / 10 + 1; ++C3) + set_text_arr(lines[R3].slice(start + (C3 - 1) * 10, start + C3 * 10).trim(), arr, R3, C3, o9); + } + if (o9.sheetRows) arr = arr.slice(0, o9.sheetRows); + return arr; + } + var guess_seps = { + 44: ",", + 9: " ", + 59: ";", + 124: "|" + }; + var guess_sep_weights = { + 44: 3, + 9: 2, + 59: 1, + 124: 0 + }; + function guess_sep(str2) { + var cnt = {}, instr = false, end = 0, cc = 0; + for (; end < str2.length; ++end) { + if ((cc = str2.charCodeAt(end)) == 34) instr = !instr; + else if (!instr && cc in guess_seps) cnt[cc] = (cnt[cc] || 0) + 1; + } + cc = []; + for (end in cnt) if (Object.prototype.hasOwnProperty.call(cnt, end)) { + cc.push([cnt[end], end]); + } + if (!cc.length) { + cnt = guess_sep_weights; + for (end in cnt) if (Object.prototype.hasOwnProperty.call(cnt, end)) { + cc.push([cnt[end], end]); + } + } + cc.sort(function(a3, b4) { + return a3[0] - b4[0] || guess_sep_weights[a3[1]] - guess_sep_weights[b4[1]]; + }); + return guess_seps[cc.pop()[1]] || 44; + } + function dsv_to_sheet_str(str2, opts) { + var o9 = opts || {}; + var sep2 = ""; + if (DENSE != null && o9.dense == null) o9.dense = DENSE; + var ws = {}; + if (o9.dense) ws["!data"] = []; + var range2 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } }; + if (str2.slice(0, 4) == "sep=") { + if (str2.charCodeAt(5) == 13 && str2.charCodeAt(6) == 10) { + sep2 = str2.charAt(4); + str2 = str2.slice(7); + } else if (str2.charCodeAt(5) == 13 || str2.charCodeAt(5) == 10) { + sep2 = str2.charAt(4); + str2 = str2.slice(6); + } else sep2 = guess_sep(str2.slice(0, 1024)); + } else if (o9 && o9.FS) sep2 = o9.FS; + else sep2 = guess_sep(str2.slice(0, 1024)); + var R3 = 0, C3 = 0, v4 = 0; + var start = 0, end = 0, sepcc = sep2.charCodeAt(0), instr = false, cc = 0, startcc = str2.charCodeAt(0); + var _re = o9.dateNF != null ? dateNF_regex(o9.dateNF) : null; + function finish_cell() { + var s6 = str2.slice(start, end); + if (s6.slice(-1) == "\r") s6 = s6.slice(0, -1); + var cell = {}; + if (s6.charAt(0) == '"' && s6.charAt(s6.length - 1) == '"') s6 = s6.slice(1, -1).replace(/""/g, '"'); + if (o9.cellText !== false) cell.w = s6; + if (s6.length === 0) cell.t = "z"; + else if (o9.raw) { + cell.t = "s"; + cell.v = s6; + } else if (s6.trim().length === 0) { + cell.t = "s"; + cell.v = s6; + } else if (s6.charCodeAt(0) == 61) { + if (s6.charCodeAt(1) == 34 && s6.charCodeAt(s6.length - 1) == 34) { + cell.t = "s"; + cell.v = s6.slice(2, -1).replace(/""/g, '"'); + } else if (fuzzyfmla(s6)) { + cell.t = "s"; + cell.f = s6.slice(1); + cell.v = s6; + } else { + cell.t = "s"; + cell.v = s6; + } + } else if (s6 == "TRUE") { + cell.t = "b"; + cell.v = true; + } else if (s6 == "FALSE") { + cell.t = "b"; + cell.v = false; + } else if (!isNaN(v4 = fuzzynum(s6))) { + cell.t = "n"; + cell.v = v4; + } else if (!isNaN((v4 = fuzzydate(s6)).getDate()) || _re && s6.match(_re)) { + cell.z = o9.dateNF || table_fmt[14]; + if (_re && s6.match(_re)) { + var news = dateNF_fix(s6, o9.dateNF, s6.match(_re) || []); + v4 = parseDate(news); + if (o9 && o9.UTC === false) v4 = utc_to_local(v4); + } else if (o9 && o9.UTC === false) v4 = utc_to_local(v4); + else if (o9.cellText !== false && o9.dateNF) cell.w = SSF_format(cell.z, v4); + if (o9.cellDates) { + cell.t = "d"; + cell.v = v4; + } else { + cell.t = "n"; + cell.v = datenum(v4); + } + if (!o9.cellNF) delete cell.z; + } else if (s6.charCodeAt(0) == 35 && RBErr[s6] != null) { + cell.t = "e"; + cell.w = s6; + cell.v = RBErr[s6]; + } else { + cell.t = "s"; + cell.v = s6; + } + if (cell.t == "z") { + } else if (o9.dense) { + if (!ws["!data"][R3]) ws["!data"][R3] = []; + ws["!data"][R3][C3] = cell; + } else ws[encode_cell({ c: C3, r: R3 })] = cell; + start = end + 1; + startcc = str2.charCodeAt(start); + if (range2.e.c < C3) range2.e.c = C3; + if (range2.e.r < R3) range2.e.r = R3; + if (cc == sepcc) ++C3; + else { + C3 = 0; + ++R3; + if (o9.sheetRows && o9.sheetRows <= R3) return true; + } + } + outer: for (; end < str2.length; ++end) switch (cc = str2.charCodeAt(end)) { + case 34: + if (startcc === 34) instr = !instr; + break; + case 13: + if (instr) break; + if (str2.charCodeAt(end + 1) == 10) ++end; + /* falls through */ + case sepcc: + case 10: + if (!instr && finish_cell()) break outer; + break; + default: + break; + } + if (end - start > 0) finish_cell(); + ws["!ref"] = encode_range(range2); + return ws; + } + function prn_to_sheet_str(str2, opts) { + if (!(opts && opts.PRN)) return dsv_to_sheet_str(str2, opts); + if (opts.FS) return dsv_to_sheet_str(str2, opts); + if (str2.slice(0, 4) == "sep=") return dsv_to_sheet_str(str2, opts); + if (str2.indexOf(" ") >= 0 || str2.indexOf(",") >= 0 || str2.indexOf(";") >= 0) return dsv_to_sheet_str(str2, opts); + return aoa_to_sheet(prn_to_aoa_str(str2, opts), opts); + } + function prn_to_sheet(d4, opts) { + var str2 = "", bytes = opts.type == "string" ? [0, 0, 0, 0] : firstbyte(d4, opts); + switch (opts.type) { + case "base64": + str2 = Base64_decode(d4); + break; + case "binary": + str2 = d4; + break; + case "buffer": + if (opts.codepage == 65001) str2 = d4.toString("utf8"); + else if (opts.codepage && typeof $cptable !== "undefined") str2 = $cptable.utils.decode(opts.codepage, d4); + else str2 = has_buf && Buffer.isBuffer(d4) ? d4.toString("binary") : a2s(d4); + break; + case "array": + str2 = cc2str(d4); + break; + case "string": + str2 = d4; + break; + default: + throw new Error("Unrecognized type " + opts.type); + } + if (bytes[0] == 239 && bytes[1] == 187 && bytes[2] == 191) str2 = utf8read(str2.slice(3)); + else if (opts.type != "string" && opts.type != "buffer" && opts.codepage == 65001) str2 = utf8read(str2); + else if (opts.type == "binary" && typeof $cptable !== "undefined" && opts.codepage) str2 = $cptable.utils.decode(opts.codepage, $cptable.utils.encode(28591, str2)); + if (str2.slice(0, 19) == "socialcalc:version:") return ETH.to_sheet(opts.type == "string" ? str2 : utf8read(str2), opts); + return prn_to_sheet_str(str2, opts); + } + function prn_to_workbook(d4, opts) { + return sheet_to_workbook(prn_to_sheet(d4, opts), opts); + } + function sheet_to_prn(ws) { + var o9 = []; + if (!ws["!ref"]) return ""; + var r8 = safe_decode_range(ws["!ref"]), cell; + var dense = ws["!data"] != null; + for (var R3 = r8.s.r; R3 <= r8.e.r; ++R3) { + var oo = []; + for (var C3 = r8.s.c; C3 <= r8.e.c; ++C3) { + var coord = encode_cell({ r: R3, c: C3 }); + cell = dense ? (ws["!data"][R3] || [])[C3] : ws[coord]; + if (!cell || cell.v == null) { + oo.push(" "); + continue; + } + var w3 = (cell.w || (format_cell(cell), cell.w) || "").slice(0, 10); + while (w3.length < 10) w3 += " "; + oo.push(w3 + (C3 === 0 ? " " : "")); + } + o9.push(oo.join("")); + } + return o9.join("\n"); + } + return { + to_workbook: prn_to_workbook, + to_sheet: prn_to_sheet, + from_sheet: sheet_to_prn + }; + })(); + WK_ = /* @__PURE__ */ (function() { + function lotushopper(data, cb, opts) { + if (!data) return; + prep_blob(data, data.l || 0); + var Enum3 = opts.Enum || WK1Enum; + while (data.l < data.length) { + var RT = data.read_shift(2); + var R3 = Enum3[RT] || Enum3[65535]; + var length = data.read_shift(2); + var tgt = data.l + length; + var d4 = R3.f && R3.f(data, length, opts); + data.l = tgt; + if (cb(d4, R3, RT)) return; + } + } + function lotus_to_workbook(d4, opts) { + switch (opts.type) { + case "base64": + return lotus_to_workbook_buf(s2a(Base64_decode(d4)), opts); + case "binary": + return lotus_to_workbook_buf(s2a(d4), opts); + case "buffer": + case "array": + return lotus_to_workbook_buf(d4, opts); + } + throw "Unsupported type " + opts.type; + } + var LOTUS_DATE_FMTS = [ + "mmmm", + "dd-mmm-yyyy", + "dd-mmm", + "mmm-yyyy", + "@", + // "text"? + "mm/dd", + "hh:mm:ss AM/PM", + // 7 + "hh:mm AM/PM", + "mm/dd/yyyy", + "mm/dd", + "hh:mm:ss", + "hh:mm" + // 12 + ]; + function lotus_to_workbook_buf(d4, opts) { + if (!d4) return d4; + var o9 = opts || {}; + if (DENSE != null && o9.dense == null) o9.dense = DENSE; + var s6 = {}, n7 = "Sheet1", next_n = "", sidx = 0; + var sheets = {}, snames = [], realnames = [], sdata = []; + if (o9.dense) sdata = s6["!data"] = []; + var refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + var sheetRows = o9.sheetRows || 0; + var lastcell = {}; + if (d4[4] == 81 && d4[5] == 80 && d4[6] == 87) return qpw_to_workbook_buf(d4, opts); + if (d4[2] == 0) { + if (d4[3] == 8 || d4[3] == 9) { + if (d4.length >= 16 && d4[14] == 5 && d4[15] === 108) throw new Error("Unsupported Works 3 for Mac file"); + } + } + if (d4[2] == 2) { + o9.Enum = WK1Enum; + lotushopper(d4, function(val2, R3, RT) { + switch (RT) { + case 0: + o9.vers = val2; + if (val2 >= 4096) o9.qpro = true; + break; + case 255: + o9.vers = val2; + o9.works = true; + break; + case 6: + refguess = val2; + break; + /* RANGE */ + case 204: + if (val2) next_n = val2; + break; + /* SHEETNAMECS */ + case 222: + next_n = val2; + break; + /* SHEETNAMELP */ + case 15: + /* LABEL */ + case 51: + if ((!o9.qpro && !o9.works || RT == 51) && val2[1].v.charCodeAt(0) < 48) val2[1].v = val2[1].v.slice(1); + if (o9.works || o9.works2) val2[1].v = val2[1].v.replace(/\r\n/g, "\n"); + /* falls through */ + case 13: + /* INTEGER */ + case 14: + /* NUMBER */ + case 16: + if ((val2[2] & 112) == 112 && (val2[2] & 15) > 1 && (val2[2] & 15) < 15) { + val2[1].z = o9.dateNF || LOTUS_DATE_FMTS[(val2[2] & 15) - 1] || table_fmt[14]; + if (o9.cellDates) { + val2[1].v = numdate(val2[1].v); + val2[1].t = typeof val2[1].v == "number" ? "n" : "d"; + } + } + if (o9.qpro) { + if (val2[3] > sidx) { + s6["!ref"] = encode_range(refguess); + sheets[n7] = s6; + snames.push(n7); + s6 = {}; + if (o9.dense) sdata = s6["!data"] = []; + refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + sidx = val2[3]; + n7 = next_n || "Sheet" + (sidx + 1); + next_n = ""; + } + } + var tmpcell = o9.dense ? (sdata[val2[0].r] || [])[val2[0].c] : s6[encode_cell(val2[0])]; + if (tmpcell) { + tmpcell.t = val2[1].t; + tmpcell.v = val2[1].v; + if (val2[1].z != null) tmpcell.z = val2[1].z; + if (val2[1].f != null) tmpcell.f = val2[1].f; + lastcell = tmpcell; + break; + } + if (o9.dense) { + if (!sdata[val2[0].r]) sdata[val2[0].r] = []; + sdata[val2[0].r][val2[0].c] = val2[1]; + } else s6[encode_cell(val2[0])] = val2[1]; + lastcell = val2[1]; + break; + case 21509: + o9.works2 = true; + break; + case 21506: + { + if (val2 == 5281) { + lastcell.z = "hh:mm:ss"; + if (o9.cellDates && lastcell.t == "n") { + lastcell.v = numdate(lastcell.v); + lastcell.t = typeof lastcell.v == "number" ? "n" : "d"; + } + } + } + break; + } + }, o9); + } else if (d4[2] == 26 || d4[2] == 14) { + o9.Enum = WK3Enum; + if (d4[2] == 14) { + o9.qpro = true; + d4.l = 0; + } + lotushopper(d4, function(val2, R3, RT) { + switch (RT) { + case 204: + n7 = val2; + break; + /* SHEETNAMECS */ + case 22: + if (val2[1].v.charCodeAt(0) < 48) val2[1].v = val2[1].v.slice(1); + val2[1].v = val2[1].v.replace(/\x0F./g, function($$) { + return String.fromCharCode($$.charCodeAt(1) - 32); + }).replace(/\r\n/g, "\n"); + /* falls through */ + case 23: + /* NUMBER17 */ + case 24: + /* NUMBER18 */ + case 25: + /* FORMULA19 */ + case 37: + /* NUMBER25 */ + case 39: + /* NUMBER27 */ + case 40: + if (val2[3] > sidx) { + s6["!ref"] = encode_range(refguess); + sheets[n7] = s6; + snames.push(n7); + s6 = {}; + if (o9.dense) sdata = s6["!data"] = []; + refguess = { s: { r: 0, c: 0 }, e: { r: 0, c: 0 } }; + sidx = val2[3]; + n7 = "Sheet" + (sidx + 1); + } + if (sheetRows > 0 && val2[0].r >= sheetRows) break; + if (o9.dense) { + if (!sdata[val2[0].r]) sdata[val2[0].r] = []; + sdata[val2[0].r][val2[0].c] = val2[1]; + } else s6[encode_cell(val2[0])] = val2[1]; + if (refguess.e.c < val2[0].c) refguess.e.c = val2[0].c; + if (refguess.e.r < val2[0].r) refguess.e.r = val2[0].r; + break; + case 27: + if (val2[14e3]) realnames[val2[14e3][0]] = val2[14e3][1]; + break; + case 1537: + realnames[val2[0]] = val2[1]; + if (val2[0] == sidx) n7 = val2[1]; + break; + default: + break; + } + }, o9); + } else throw new Error("Unrecognized LOTUS BOF " + d4[2]); + s6["!ref"] = encode_range(refguess); + sheets[next_n || n7] = s6; + snames.push(next_n || n7); + if (!realnames.length) return { SheetNames: snames, Sheets: sheets }; + var osheets = {}, rnames = []; + for (var i7 = 0; i7 < realnames.length; ++i7) if (sheets[snames[i7]]) { + rnames.push(realnames[i7] || snames[i7]); + osheets[realnames[i7]] = sheets[realnames[i7]] || sheets[snames[i7]]; + } else { + rnames.push(realnames[i7]); + osheets[realnames[i7]] = { "!ref": "A1" }; + } + return { SheetNames: rnames, Sheets: osheets }; + } + function sheet_to_wk1(ws, opts) { + var o9 = opts || {}; + if (+o9.codepage >= 0) set_cp(+o9.codepage); + if (o9.type == "string") throw new Error("Cannot write WK1 to JS string"); + var ba = buf_array(); + if (!ws["!ref"]) throw new Error("Cannot export empty sheet to WK1"); + var range2 = safe_decode_range(ws["!ref"]); + var dense = ws["!data"] != null; + var cols = []; + write_biff_rec(ba, 0, write_BOF_WK1(1030)); + write_biff_rec(ba, 6, write_RANGE(range2)); + var max_R = Math.min(range2.e.r, 8191); + for (var C3 = range2.s.c; C3 <= range2.e.c; ++C3) cols[C3] = encode_col(C3); + for (var R3 = range2.s.r; R3 <= max_R; ++R3) { + var rr = encode_row(R3); + for (C3 = range2.s.c; C3 <= range2.e.c; ++C3) { + var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[cols[C3] + rr]; + if (!cell || cell.t == "z") continue; + switch (cell.t) { + case "n": + if ((cell.v | 0) == cell.v && cell.v >= -32768 && cell.v <= 32767) write_biff_rec(ba, 13, write_INTEGER(R3, C3, cell)); + else write_biff_rec(ba, 14, write_NUMBER(R3, C3, cell)); + break; + case "d": + var dc = datenum(cell.v); + if ((dc | 0) == dc && dc >= -32768 && dc <= 32767) write_biff_rec(ba, 13, write_INTEGER(R3, C3, { t: "n", v: dc, z: cell.z || table_fmt[14] })); + else write_biff_rec(ba, 14, write_NUMBER(R3, C3, { t: "n", v: dc, z: cell.z || table_fmt[14] })); + break; + default: + var str2 = format_cell(cell); + write_biff_rec(ba, 15, write_LABEL(R3, C3, str2.slice(0, 239))); + } + } + } + write_biff_rec(ba, 1); + return ba.end(); + } + function book_to_wk3(wb, opts) { + var o9 = opts || {}; + if (+o9.codepage >= 0) set_cp(+o9.codepage); + if (o9.type == "string") throw new Error("Cannot write WK3 to JS string"); + var ba = buf_array(); + write_biff_rec(ba, 0, write_BOF_WK3(wb)); + for (var i7 = 0, cnt = 0; i7 < wb.SheetNames.length; ++i7) if ((wb.Sheets[wb.SheetNames[i7]] || {})["!ref"]) write_biff_rec(ba, 27, write_XFORMAT_SHEETNAME(wb.SheetNames[i7], cnt++)); + var wsidx = 0; + for (i7 = 0; i7 < wb.SheetNames.length; ++i7) { + var ws = wb.Sheets[wb.SheetNames[i7]]; + if (!ws || !ws["!ref"]) continue; + var range2 = safe_decode_range(ws["!ref"]); + var dense = ws["!data"] != null; + var cols = []; + var max_R = Math.min(range2.e.r, 8191); + for (var R3 = range2.s.r; R3 <= max_R; ++R3) { + var rr = encode_row(R3); + for (var C3 = range2.s.c; C3 <= range2.e.c; ++C3) { + if (R3 === range2.s.r) cols[C3] = encode_col(C3); + var ref = cols[C3] + rr; + var cell = dense ? (ws["!data"][R3] || [])[C3] : ws[ref]; + if (!cell || cell.t == "z") continue; + if (cell.t == "n") { + write_biff_rec(ba, 23, write_NUMBER_17(R3, C3, wsidx, cell.v)); + } else { + var str2 = format_cell(cell); + write_biff_rec(ba, 22, write_LABEL_16(R3, C3, wsidx, str2.slice(0, 239))); + } + } + } + ++wsidx; + } + write_biff_rec(ba, 1); + return ba.end(); + } + function write_BOF_WK1(v4) { + var out = new_buf(2); + out.write_shift(2, v4); + return out; + } + function write_BOF_WK3(wb) { + var out = new_buf(26); + out.write_shift(2, 4096); + out.write_shift(2, 4); + out.write_shift(4, 0); + var rows = 0, cols = 0, wscnt = 0; + for (var i7 = 0; i7 < wb.SheetNames.length; ++i7) { + var name = wb.SheetNames[i7]; + var ws = wb.Sheets[name]; + if (!ws || !ws["!ref"]) continue; + ++wscnt; + var range2 = decode_range(ws["!ref"]); + if (rows < range2.e.r) rows = range2.e.r; + if (cols < range2.e.c) cols = range2.e.c; + } + if (rows > 8191) rows = 8191; + out.write_shift(2, rows); + out.write_shift(1, wscnt); + out.write_shift(1, cols); + out.write_shift(2, 0); + out.write_shift(2, 0); + out.write_shift(1, 1); + out.write_shift(1, 2); + out.write_shift(4, 0); + out.write_shift(4, 0); + return out; + } + function parse_RANGE(blob, length, opts) { + var o9 = { s: { c: 0, r: 0 }, e: { c: 0, r: 0 } }; + if (length == 8 && opts.qpro) { + o9.s.c = blob.read_shift(1); + blob.l++; + o9.s.r = blob.read_shift(2); + o9.e.c = blob.read_shift(1); + blob.l++; + o9.e.r = blob.read_shift(2); + return o9; + } + o9.s.c = blob.read_shift(2); + o9.s.r = blob.read_shift(2); + if (length == 12 && opts.qpro) blob.l += 2; + o9.e.c = blob.read_shift(2); + o9.e.r = blob.read_shift(2); + if (length == 12 && opts.qpro) blob.l += 2; + if (o9.s.c == 65535) o9.s.c = o9.e.c = o9.s.r = o9.e.r = 0; + return o9; + } + function write_RANGE(range2) { + var out = new_buf(8); + out.write_shift(2, range2.s.c); + out.write_shift(2, range2.s.r); + out.write_shift(2, range2.e.c); + out.write_shift(2, range2.e.r); + return out; + } + function parse_cell(blob, length, opts) { + var o9 = [{ c: 0, r: 0 }, { t: "n", v: 0 }, 0, 0]; + if (opts.qpro && opts.vers != 20768) { + o9[0].c = blob.read_shift(1); + o9[3] = blob.read_shift(1); + o9[0].r = blob.read_shift(2); + blob.l += 2; + } else if (opts.works) { + o9[0].c = blob.read_shift(2); + o9[0].r = blob.read_shift(2); + o9[2] = blob.read_shift(2); + } else { + o9[2] = blob.read_shift(1); + o9[0].c = blob.read_shift(2); + o9[0].r = blob.read_shift(2); + } + return o9; + } + function get_wk1_fmt(cell) { + if (cell.z && fmt_is_date(cell.z)) { + return 240 | (LOTUS_DATE_FMTS.indexOf(cell.z) + 1 || 2); + } + return 255; + } + function parse_LABEL(blob, length, opts) { + var tgt = blob.l + length; + var o9 = parse_cell(blob, length, opts); + o9[1].t = "s"; + if ((opts.vers & 65534) == 20768) { + blob.l++; + var len = blob.read_shift(1); + o9[1].v = blob.read_shift(len, "utf8"); + return o9; + } + if (opts.qpro) blob.l++; + o9[1].v = blob.read_shift(tgt - blob.l, "cstr"); + return o9; + } + function write_LABEL(R3, C3, s6) { + var o9 = new_buf(7 + s6.length); + o9.write_shift(1, 255); + o9.write_shift(2, C3); + o9.write_shift(2, R3); + o9.write_shift(1, 39); + for (var i7 = 0; i7 < o9.length; ++i7) { + var cc = s6.charCodeAt(i7); + o9.write_shift(1, cc >= 128 ? 95 : cc); + } + o9.write_shift(1, 0); + return o9; + } + function parse_STRING(blob, length, opts) { + var tgt = blob.l + length; + var o9 = parse_cell(blob, length, opts); + o9[1].t = "s"; + if (opts.vers == 20768) { + var len = blob.read_shift(1); + o9[1].v = blob.read_shift(len, "utf8"); + return o9; + } + o9[1].v = blob.read_shift(tgt - blob.l, "cstr"); + return o9; + } + function parse_INTEGER(blob, length, opts) { + var o9 = parse_cell(blob, length, opts); + o9[1].v = blob.read_shift(2, "i"); + return o9; + } + function write_INTEGER(R3, C3, cell) { + var o9 = new_buf(7); + o9.write_shift(1, get_wk1_fmt(cell)); + o9.write_shift(2, C3); + o9.write_shift(2, R3); + o9.write_shift(2, cell.v, "i"); + return o9; + } + function parse_NUMBER(blob, length, opts) { + var o9 = parse_cell(blob, length, opts); + o9[1].v = blob.read_shift(8, "f"); + return o9; + } + function write_NUMBER(R3, C3, cell) { + var o9 = new_buf(13); + o9.write_shift(1, get_wk1_fmt(cell)); + o9.write_shift(2, C3); + o9.write_shift(2, R3); + o9.write_shift(8, cell.v, "f"); + return o9; + } + function parse_FORMULA(blob, length, opts) { + var tgt = blob.l + length; + var o9 = parse_cell(blob, length, opts); + o9[1].v = blob.read_shift(8, "f"); + if (opts.qpro) blob.l = tgt; + else { + var flen = blob.read_shift(2); + wk1_fmla_to_csf(blob.slice(blob.l, blob.l + flen), o9); + blob.l += flen; + } + return o9; + } + function wk1_parse_rc(B3, V3, col) { + var rel2 = V3 & 32768; + V3 &= ~32768; + V3 = (rel2 ? B3 : 0) + (V3 >= 8192 ? V3 - 16384 : V3); + return (rel2 ? "" : "$") + (col ? encode_col(V3) : encode_row(V3)); + } + var FuncTab = { + 31: ["NA", 0], + // 0x20: ["ERR", 0], + 33: ["ABS", 1], + 34: ["TRUNC", 1], + 35: ["SQRT", 1], + 36: ["LOG", 1], + 37: ["LN", 1], + 38: ["PI", 0], + 39: ["SIN", 1], + 40: ["COS", 1], + 41: ["TAN", 1], + 42: ["ATAN2", 2], + 43: ["ATAN", 1], + 44: ["ASIN", 1], + 45: ["ACOS", 1], + 46: ["EXP", 1], + 47: ["MOD", 2], + // 0x30 + 49: ["ISNA", 1], + 50: ["ISERR", 1], + 51: ["FALSE", 0], + 52: ["TRUE", 0], + 53: ["RAND", 0], + 54: ["DATE", 3], + // 0x37 NOW + // 0x38 PMT + // 0x39 PV + // 0x3A FV + // 0x3B IF + // 0x3C DAY + // 0x3D MONTH + // 0x3E YEAR + 63: ["ROUND", 2], + 64: ["TIME", 3], + // 0x41 HOUR + // 0x42 MINUTE + // 0x43 SECOND + 68: ["ISNUMBER", 1], + 69: ["ISTEXT", 1], + 70: ["LEN", 1], + 71: ["VALUE", 1], + // 0x48: ["FIXED", ?? 1], + 73: ["MID", 3], + 74: ["CHAR", 1], + // 0x4B + // 0x4C FIND + // 0x4D DATEVALUE + // 0x4E TIMEVALUE + // 0x4F CELL + 80: ["SUM", 69], + 81: ["AVERAGEA", 69], + 82: ["COUNTA", 69], + 83: ["MINA", 69], + 84: ["MAXA", 69], + // 0x55 VLOOKUP + // 0x56 NPV + // 0x57 VAR + // 0x58 STD + // 0x59 IRR + // 0x5A HLOOKUP + // 0x5B DSUM + // 0x5C DAVERAGE + // 0x5D DCOUNTA + // 0x5E DMIN + // 0x5F DMAX + // 0x60 DVARP + // 0x61 DSTDEVP + // 0x62 INDEX + // 0x63 COLS + // 0x64 ROWS + // 0x65 REPEAT + 102: ["UPPER", 1], + 103: ["LOWER", 1], + // 0x68 LEFT + // 0x69 RIGHT + // 0x6A REPLACE + 107: ["PROPER", 1], + // 0x6C CELL + 109: ["TRIM", 1], + // 0x6E CLEAN + 111: ["T", 1] + // 0x70 V + }; + var BinOpTab = [ + "", + "", + "", + "", + "", + "", + "", + "", + // eslint-disable-line no-mixed-spaces-and-tabs + "", + "+", + "-", + "*", + "/", + "^", + "=", + "<>", + // eslint-disable-line no-mixed-spaces-and-tabs + "<=", + ">=", + "<", + ">", + "", + "", + "", + "", + // eslint-disable-line no-mixed-spaces-and-tabs + "&", + "", + "", + "", + "", + "", + "", + "" + // eslint-disable-line no-mixed-spaces-and-tabs + ]; + function wk1_fmla_to_csf(blob, o9) { + prep_blob(blob, 0); + var out = [], argc = 0, R3 = "", C3 = "", argL = "", argR = ""; + while (blob.l < blob.length) { + var cc = blob[blob.l++]; + switch (cc) { + case 0: + out.push(blob.read_shift(8, "f")); + break; + case 1: + { + C3 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true); + R3 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false); + out.push(C3 + R3); + } + break; + case 2: + { + var c6 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true); + var r8 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false); + C3 = wk1_parse_rc(o9[0].c, blob.read_shift(2), true); + R3 = wk1_parse_rc(o9[0].r, blob.read_shift(2), false); + out.push(c6 + r8 + ":" + C3 + R3); + } + break; + case 3: + if (blob.l < blob.length) { + console.error("WK1 premature formula end"); + return; + } + break; + case 4: + out.push("(" + out.pop() + ")"); + break; + case 5: + out.push(blob.read_shift(2)); + break; + case 6: + { + var Z2 = ""; + while (cc = blob[blob.l++]) Z2 += String.fromCharCode(cc); + out.push('"' + Z2.replace(/"/g, '""') + '"'); + } + break; + case 8: + out.push("-" + out.pop()); + break; + case 23: + out.push("+" + out.pop()); + break; + case 22: + out.push("NOT(" + out.pop() + ")"); + break; + case 20: + case 21: + { + argR = out.pop(); + argL = out.pop(); + out.push(["AND", "OR"][cc - 20] + "(" + argL + "," + argR + ")"); + } + break; + default: + if (cc < 32 && BinOpTab[cc]) { + argR = out.pop(); + argL = out.pop(); + out.push(argL + BinOpTab[cc] + argR); + } else if (FuncTab[cc]) { + argc = FuncTab[cc][1]; + if (argc == 69) argc = blob[blob.l++]; + if (argc > out.length) { + console.error("WK1 bad formula parse 0x" + cc.toString(16) + ":|" + out.join("|") + "|"); + return; + } + var args = out.slice(-argc); + out.length -= argc; + out.push(FuncTab[cc][0] + "(" + args.join(",") + ")"); + } else if (cc <= 7) return console.error("WK1 invalid opcode " + cc.toString(16)); + else if (cc <= 24) return console.error("WK1 unsupported op " + cc.toString(16)); + else if (cc <= 30) return console.error("WK1 invalid opcode " + cc.toString(16)); + else if (cc <= 115) return console.error("WK1 unsupported function opcode " + cc.toString(16)); + else return console.error("WK1 unrecognized opcode " + cc.toString(16)); + } + } + if (out.length == 1) o9[1].f = "" + out[0]; + else console.error("WK1 bad formula parse |" + out.join("|") + "|"); + } + function parse_cell_3(blob) { + var o9 = [{ c: 0, r: 0 }, { t: "n", v: 0 }, 0]; + o9[0].r = blob.read_shift(2); + o9[3] = blob[blob.l++]; + o9[0].c = blob[blob.l++]; + return o9; + } + function parse_LABEL_16(blob, length) { + var o9 = parse_cell_3(blob, length); + o9[1].t = "s"; + o9[1].v = blob.read_shift(length - 4, "cstr"); + return o9; + } + function write_LABEL_16(R3, C3, wsidx, s6) { + var o9 = new_buf(6 + s6.length); + o9.write_shift(2, R3); + o9.write_shift(1, wsidx); + o9.write_shift(1, C3); + o9.write_shift(1, 39); + for (var i7 = 0; i7 < s6.length; ++i7) { + var cc = s6.charCodeAt(i7); + o9.write_shift(1, cc >= 128 ? 95 : cc); + } + o9.write_shift(1, 0); + return o9; + } + function parse_NUMBER_18(blob, length) { + var o9 = parse_cell_3(blob, length); + o9[1].v = blob.read_shift(2); + var v4 = o9[1].v >> 1; + if (o9[1].v & 1) { + switch (v4 & 7) { + case 0: + v4 = (v4 >> 3) * 5e3; + break; + case 1: + v4 = (v4 >> 3) * 500; + break; + case 2: + v4 = (v4 >> 3) / 20; + break; + case 3: + v4 = (v4 >> 3) / 200; + break; + case 4: + v4 = (v4 >> 3) / 2e3; + break; + case 5: + v4 = (v4 >> 3) / 2e4; + break; + case 6: + v4 = (v4 >> 3) / 16; + break; + case 7: + v4 = (v4 >> 3) / 64; + break; + } + } + o9[1].v = v4; + return o9; + } + function parse_NUMBER_17(blob, length) { + var o9 = parse_cell_3(blob, length); + var v1 = blob.read_shift(4); + var v22 = blob.read_shift(4); + var e9 = blob.read_shift(2); + if (e9 == 65535) { + if (v1 === 0 && v22 === 3221225472) { + o9[1].t = "e"; + o9[1].v = 15; + } else if (v1 === 0 && v22 === 3489660928) { + o9[1].t = "e"; + o9[1].v = 42; + } else o9[1].v = 0; + return o9; + } + var s6 = e9 & 32768; + e9 = (e9 & 32767) - 16446; + o9[1].v = (1 - s6 * 2) * (v22 * Math.pow(2, e9 + 32) + v1 * Math.pow(2, e9)); + return o9; + } + function write_NUMBER_17(R3, C3, wsidx, v4) { + var o9 = new_buf(14); + o9.write_shift(2, R3); + o9.write_shift(1, wsidx); + o9.write_shift(1, C3); + if (v4 == 0) { + o9.write_shift(4, 0); + o9.write_shift(4, 0); + o9.write_shift(2, 65535); + return o9; + } + var s6 = 0, e9 = 0, v1 = 0, v22 = 0; + if (v4 < 0) { + s6 = 1; + v4 = -v4; + } + e9 = Math.log2(v4) | 0; + v4 /= Math.pow(2, e9 - 31); + v22 = v4 >>> 0; + if ((v22 & 2147483648) == 0) { + v4 /= 2; + ++e9; + v22 = v4 >>> 0; + } + v4 -= v22; + v22 |= 2147483648; + v22 >>>= 0; + v4 *= Math.pow(2, 32); + v1 = v4 >>> 0; + o9.write_shift(4, v1); + o9.write_shift(4, v22); + e9 += 16383 + (s6 ? 32768 : 0); + o9.write_shift(2, e9); + return o9; + } + function parse_FORMULA_19(blob, length) { + var o9 = parse_NUMBER_17(blob, 14); + blob.l += length - 14; + return o9; + } + function parse_NUMBER_25(blob, length) { + var o9 = parse_cell_3(blob, length); + var v1 = blob.read_shift(4); + o9[1].v = v1 >> 6; + return o9; + } + function parse_NUMBER_27(blob, length) { + var o9 = parse_cell_3(blob, length); + var v1 = blob.read_shift(8, "f"); + o9[1].v = v1; + return o9; + } + function parse_FORMULA_28(blob, length) { + var o9 = parse_NUMBER_27(blob, 12); + blob.l += length - 12; + return o9; + } + function parse_SHEETNAMECS(blob, length) { + return blob[blob.l + length - 1] == 0 ? blob.read_shift(length, "cstr") : ""; + } + function parse_SHEETNAMELP(blob, length) { + var len = blob[blob.l++]; + if (len > length - 1) len = length - 1; + var o9 = ""; + while (o9.length < len) o9 += String.fromCharCode(blob[blob.l++]); + return o9; + } + function parse_SHEETINFOQP(blob, length, opts) { + if (!opts.qpro || length < 21) return; + var id = blob.read_shift(1); + blob.l += 17; + blob.l += 1; + blob.l += 2; + var nm = blob.read_shift(length - 21, "cstr"); + return [id, nm]; + } + function parse_XFORMAT(blob, length) { + var o9 = {}, tgt = blob.l + length; + while (blob.l < tgt) { + var dt = blob.read_shift(2); + if (dt == 14e3) { + o9[dt] = [0, ""]; + o9[dt][0] = blob.read_shift(2); + while (blob[blob.l]) { + o9[dt][1] += String.fromCharCode(blob[blob.l]); + blob.l++; + } + blob.l++; + } + } + return o9; + } + function write_XFORMAT_SHEETNAME(name, wsidx) { + var out = new_buf(5 + name.length); + out.write_shift(2, 14e3); + out.write_shift(2, wsidx); + for (var i7 = 0; i7 < name.length; ++i7) { + var cc = name.charCodeAt(i7); + out[out.l++] = cc > 127 ? 95 : cc; + } + out[out.l++] = 0; + return out; + } + var WK1Enum = { + 0: { n: "BOF", f: parseuint16 }, + 1: { n: "EOF" }, + 2: { n: "CALCMODE" }, + 3: { n: "CALCORDER" }, + 4: { n: "SPLIT" }, + 5: { n: "SYNC" }, + 6: { n: "RANGE", f: parse_RANGE }, + 7: { n: "WINDOW1" }, + 8: { n: "COLW1" }, + 9: { n: "WINTWO" }, + 10: { n: "COLW2" }, + 11: { n: "NAME" }, + 12: { n: "BLANK" }, + 13: { n: "INTEGER", f: parse_INTEGER }, + 14: { n: "NUMBER", f: parse_NUMBER }, + 15: { n: "LABEL", f: parse_LABEL }, + 16: { n: "FORMULA", f: parse_FORMULA }, + 24: { n: "TABLE" }, + 25: { n: "ORANGE" }, + 26: { n: "PRANGE" }, + 27: { n: "SRANGE" }, + 28: { n: "FRANGE" }, + 29: { n: "KRANGE1" }, + 32: { n: "HRANGE" }, + 35: { n: "KRANGE2" }, + 36: { n: "PROTEC" }, + 37: { n: "FOOTER" }, + 38: { n: "HEADER" }, + 39: { n: "SETUP" }, + 40: { n: "MARGINS" }, + 41: { n: "LABELFMT" }, + 42: { n: "TITLES" }, + 43: { n: "SHEETJS" }, + 45: { n: "GRAPH" }, + 46: { n: "NGRAPH" }, + 47: { n: "CALCCOUNT" }, + 48: { n: "UNFORMATTED" }, + 49: { n: "CURSORW12" }, + 50: { n: "WINDOW" }, + 51: { n: "STRING", f: parse_STRING }, + 55: { n: "PASSWORD" }, + 56: { n: "LOCKED" }, + 60: { n: "QUERY" }, + 61: { n: "QUERYNAME" }, + 62: { n: "PRINT" }, + 63: { n: "PRINTNAME" }, + 64: { n: "GRAPH2" }, + 65: { n: "GRAPHNAME" }, + 66: { n: "ZOOM" }, + 67: { n: "SYMSPLIT" }, + 68: { n: "NSROWS" }, + 69: { n: "NSCOLS" }, + 70: { n: "RULER" }, + 71: { n: "NNAME" }, + 72: { n: "ACOMM" }, + 73: { n: "AMACRO" }, + 74: { n: "PARSE" }, + // 0x0064 + 102: { n: "PRANGES??" }, + 103: { n: "RRANGES??" }, + 104: { n: "FNAME??" }, + 105: { n: "MRANGES??" }, + // 0x0096 + // 0x0099 + // 0x009A + // 0x009B + // 0x009C + // 0x00C0 + // 0x00C7 + // 0x00C9 + 204: { n: "SHEETNAMECS", f: parse_SHEETNAMECS }, + // 0x00CD + 222: { n: "SHEETNAMELP", f: parse_SHEETNAMELP }, + 255: { n: "BOF", f: parseuint16 }, + 21506: { n: "WKSNF", f: parseuint16 }, + 65535: { n: "" } + }; + var WK3Enum = { + 0: { n: "BOF" }, + 1: { n: "EOF" }, + 2: { n: "PASSWORD" }, + 3: { n: "CALCSET" }, + 4: { n: "WINDOWSET" }, + 5: { n: "SHEETCELLPTR" }, + 6: { n: "SHEETLAYOUT" }, + 7: { n: "COLUMNWIDTH" }, + 8: { n: "HIDDENCOLUMN" }, + 9: { n: "USERRANGE" }, + 10: { n: "SYSTEMRANGE" }, + 11: { n: "ZEROFORCE" }, + 12: { n: "SORTKEYDIR" }, + 13: { n: "FILESEAL" }, + 14: { n: "DATAFILLNUMS" }, + 15: { n: "PRINTMAIN" }, + 16: { n: "PRINTSTRING" }, + 17: { n: "GRAPHMAIN" }, + 18: { n: "GRAPHSTRING" }, + 19: { n: "??" }, + 20: { n: "ERRCELL" }, + 21: { n: "NACELL" }, + 22: { n: "LABEL16", f: parse_LABEL_16 }, + 23: { n: "NUMBER17", f: parse_NUMBER_17 }, + 24: { n: "NUMBER18", f: parse_NUMBER_18 }, + 25: { n: "FORMULA19", f: parse_FORMULA_19 }, + 26: { n: "FORMULA1A" }, + 27: { n: "XFORMAT", f: parse_XFORMAT }, + 28: { n: "DTLABELMISC" }, + 29: { n: "DTLABELCELL" }, + 30: { n: "GRAPHWINDOW" }, + 31: { n: "CPA" }, + 32: { n: "LPLAUTO" }, + 33: { n: "QUERY" }, + 34: { n: "HIDDENSHEET" }, + 35: { n: "??" }, + 37: { n: "NUMBER25", f: parse_NUMBER_25 }, + 38: { n: "??" }, + 39: { n: "NUMBER27", f: parse_NUMBER_27 }, + 40: { n: "FORMULA28", f: parse_FORMULA_28 }, + 142: { n: "??" }, + 147: { n: "??" }, + 150: { n: "??" }, + 151: { n: "??" }, + 152: { n: "??" }, + 153: { n: "??" }, + 154: { n: "??" }, + 155: { n: "??" }, + 156: { n: "??" }, + 163: { n: "??" }, + 174: { n: "??" }, + 175: { n: "??" }, + 176: { n: "??" }, + 177: { n: "??" }, + 184: { n: "??" }, + 185: { n: "??" }, + 186: { n: "??" }, + 187: { n: "??" }, + 188: { n: "??" }, + 195: { n: "??" }, + 201: { n: "??" }, + 204: { n: "SHEETNAMECS", f: parse_SHEETNAMECS }, + 205: { n: "??" }, + 206: { n: "??" }, + 207: { n: "??" }, + 208: { n: "??" }, + 256: { n: "??" }, + 259: { n: "??" }, + 260: { n: "??" }, + 261: { n: "??" }, + 262: { n: "??" }, + 263: { n: "??" }, + 265: { n: "??" }, + 266: { n: "??" }, + 267: { n: "??" }, + 268: { n: "??" }, + 270: { n: "??" }, + 271: { n: "??" }, + 384: { n: "??" }, + 389: { n: "??" }, + 390: { n: "??" }, + 393: { n: "??" }, + 396: { n: "??" }, + 512: { n: "??" }, + 514: { n: "??" }, + 513: { n: "??" }, + 516: { n: "??" }, + 517: { n: "??" }, + 640: { n: "??" }, + 641: { n: "??" }, + 642: { n: "??" }, + 643: { n: "??" }, + 644: { n: "??" }, + 645: { n: "??" }, + 646: { n: "??" }, + 647: { n: "??" }, + 648: { n: "??" }, + 658: { n: "??" }, + 659: { n: "??" }, + 660: { n: "??" }, + 661: { n: "??" }, + 662: { n: "??" }, + 665: { n: "??" }, + 666: { n: "??" }, + 768: { n: "??" }, + 772: { n: "??" }, + 1537: { n: "SHEETINFOQP", f: parse_SHEETINFOQP }, + 1600: { n: "??" }, + 1602: { n: "??" }, + 1793: { n: "??" }, + 1794: { n: "??" }, + 1795: { n: "??" }, + 1796: { n: "??" }, + 1920: { n: "??" }, + 2048: { n: "??" }, + 2049: { n: "??" }, + 2052: { n: "??" }, + 2688: { n: "??" }, + 10998: { n: "??" }, + 12849: { n: "??" }, + 28233: { n: "??" }, + 28484: { n: "??" }, + 65535: { n: "" } + }; + var QPWNFTable = { + 5: "dd-mmm-yy", + 6: "dd-mmm", + 7: "mmm-yy", + 8: "mm/dd/yy", + // Long Date Intl + 10: "hh:mm:ss AM/PM", + 11: "hh:mm AM/PM", + 14: "dd-mmm-yyyy", + 15: "mmm-yyyy", + /* It is suspected that the the low nybble specifies decimal places */ + 34: "0.00", + 50: "0.00;[Red]0.00", + 66: "0.00;(0.00)", + 82: "0.00;[Red](0.00)", + 162: '"$"#,##0.00;\\("$"#,##0.00\\)', + 288: "0%", + 304: "0E+00", + 320: "# ?/?" + }; + function parse_qpw_str(p4) { + var cch = p4.read_shift(2); + var flags = p4.read_shift(1); + if (flags != 0) throw "unsupported QPW string type " + flags.toString(16); + return p4.read_shift(cch, "sbcs-cont"); + } + function qpw_to_workbook_buf(d4, opts) { + prep_blob(d4, 0); + var o9 = opts || {}; + if (DENSE != null && o9.dense == null) o9.dense = DENSE; + var s6 = {}; + if (o9.dense) s6["!data"] = []; + var SST = [], sname = "", formulae = []; + var range2 = { s: { r: -1, c: -1 }, e: { r: -1, c: -1 } }; + var cnt = 0, type = 0, C3 = 0, R3 = 0; + var wb = { SheetNames: [], Sheets: {} }; + var FMTS = []; + outer: while (d4.l < d4.length) { + var RT = d4.read_shift(2), length = d4.read_shift(2); + var p4 = d4.slice(d4.l, d4.l + length); + prep_blob(p4, 0); + switch (RT) { + case 1: + if (p4.read_shift(4) != 962023505) throw "Bad QPW9 BOF!"; + break; + case 2: + break outer; + case 8: + break; + // TODO: this is tied to custom number formats + case 10: + { + var fcnt = p4.read_shift(4); + var step = (p4.length - p4.l) / fcnt | 0; + for (var ifmt = 0; ifmt < fcnt; ++ifmt) { + var end = p4.l + step; + var fmt = {}; + p4.l += 2; + fmt.numFmtId = p4.read_shift(2); + if (QPWNFTable[fmt.numFmtId]) fmt.z = QPWNFTable[fmt.numFmtId]; + p4.l = end; + FMTS.push(fmt); + } + } + break; + /* TODO: The behavior here should be consistent with Numbers: QP Notebook ~ .TN.SheetArchive, QP Sheet ~ .TST.TableModelArchive */ + case 1025: + break; + case 1026: + break; + case 1031: + { + p4.l += 12; + while (p4.l < p4.length) { + cnt = p4.read_shift(2); + type = p4.read_shift(1); + SST.push(p4.read_shift(cnt, "cstr")); + } + } + break; + case 1032: + { + } + break; + case 1537: + { + var sidx = p4.read_shift(2); + s6 = {}; + if (o9.dense) s6["!data"] = []; + range2.s.c = p4.read_shift(2); + range2.e.c = p4.read_shift(2); + range2.s.r = p4.read_shift(4); + range2.e.r = p4.read_shift(4); + p4.l += 4; + if (p4.l + 2 < p4.length) { + cnt = p4.read_shift(2); + type = p4.read_shift(1); + sname = cnt == 0 ? "" : p4.read_shift(cnt, "cstr"); + } + if (!sname) sname = encode_col(sidx); + } + break; + case 1538: + { + if (range2.s.c > 255 || range2.s.r > 999999) break; + if (range2.e.c < range2.s.c) range2.e.c = range2.s.c; + if (range2.e.r < range2.s.r) range2.e.r = range2.s.r; + s6["!ref"] = encode_range(range2); + book_append_sheet(wb, s6, sname); + } + break; + case 2561: + { + C3 = p4.read_shift(2); + if (range2.e.c < C3) range2.e.c = C3; + if (range2.s.c > C3) range2.s.c = C3; + R3 = p4.read_shift(4); + if (range2.s.r > R3) range2.s.r = R3; + R3 = p4.read_shift(4); + if (range2.e.r < R3) range2.e.r = R3; + } + break; + case 3073: + { + R3 = p4.read_shift(4), cnt = p4.read_shift(4); + if (range2.s.r > R3) range2.s.r = R3; + if (range2.e.r < R3 + cnt - 1) range2.e.r = R3 + cnt - 1; + var CC = encode_col(C3); + while (p4.l < p4.length) { + var cell = { t: "z" }; + var flags = p4.read_shift(1), fmtidx = -1; + if (flags & 128) fmtidx = p4.read_shift(2); + var mul = flags & 64 ? p4.read_shift(2) - 1 : 0; + switch (flags & 31) { + case 0: + break; + case 1: + break; + case 2: + cell = { t: "n", v: p4.read_shift(2) }; + break; + case 3: + cell = { t: "n", v: p4.read_shift(2, "i") }; + break; + case 4: + cell = { t: "n", v: parse_RkNumber(p4) }; + break; + case 5: + cell = { t: "n", v: p4.read_shift(8, "f") }; + break; + case 7: + cell = { t: "s", v: SST[type = p4.read_shift(4) - 1] }; + break; + case 8: + cell = { t: "n", v: p4.read_shift(8, "f") }; + p4.l += 2; + p4.l += 4; + if (isNaN(cell.v)) cell = { t: "e", v: 15 }; + break; + default: + throw "Unrecognized QPW cell type " + (flags & 31); + } + if (fmtidx != -1 && (FMTS[fmtidx - 1] || {}).z) cell.z = FMTS[fmtidx - 1].z; + var delta = 0; + if (flags & 32) switch (flags & 31) { + case 2: + delta = p4.read_shift(2); + break; + case 3: + delta = p4.read_shift(2, "i"); + break; + case 7: + delta = p4.read_shift(2); + break; + default: + throw "Unsupported delta for QPW cell type " + (flags & 31); + } + if (!(!o9.sheetStubs && cell.t == "z")) { + var newcell = dup(cell); + if (cell.t == "n" && cell.z && fmt_is_date(cell.z) && o9.cellDates) { + newcell.v = numdate(cell.v); + newcell.t = typeof newcell.v == "number" ? "n" : "d"; + } + if (s6["!data"] != null) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + s6["!data"][R3][C3] = newcell; + } else s6[CC + encode_row(R3)] = newcell; + } + ++R3; + --cnt; + while (mul-- > 0 && cnt >= 0) { + if (flags & 32) switch (flags & 31) { + case 2: + cell = { t: "n", v: cell.v + delta & 65535 }; + break; + case 3: + cell = { t: "n", v: cell.v + delta & 65535 }; + if (cell.v > 32767) cell.v -= 65536; + break; + case 7: + cell = { t: "s", v: SST[type = type + delta >>> 0] }; + break; + default: + throw "Cannot apply delta for QPW cell type " + (flags & 31); + } + else switch (flags & 31) { + case 1: + cell = { t: "z" }; + break; + case 2: + cell = { t: "n", v: p4.read_shift(2) }; + break; + case 7: + cell = { t: "s", v: SST[type = p4.read_shift(4) - 1] }; + break; + default: + throw "Cannot apply repeat for QPW cell type " + (flags & 31); + } + if (fmtidx != -1) ; + if (!(!o9.sheetStubs && cell.t == "z")) { + if (s6["!data"] != null) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + s6["!data"][R3][C3] = cell; + } else s6[CC + encode_row(R3)] = cell; + } + ++R3; + --cnt; + } + } + } + break; + case 3074: + { + C3 = p4.read_shift(2); + R3 = p4.read_shift(4); + var str2 = parse_qpw_str(p4); + if (s6["!data"] != null) { + if (!s6["!data"][R3]) s6["!data"][R3] = []; + s6["!data"][R3][C3] = { t: "s", v: str2 }; + } else s6[encode_col(C3) + encode_row(R3)] = { t: "s", v: str2 }; + } + break; + default: + break; + } + d4.l += length; + } + return wb; + } + return { + sheet_to_wk1, + book_to_wk3, + to_workbook: lotus_to_workbook + }; + })(); + parse_rs = /* @__PURE__ */ (function() { + function parse_r(r8) { + var t6 = str_match_xml_ns(r8, "t"); + if (!t6) return { t: "s", v: "" }; + var o9 = { t: "s", v: unescapexml(t6[1]) }; + var rpr = str_match_xml_ns(r8, "rPr"); + if (rpr) o9.s = parse_rpr(rpr[1]); + return o9; + } + var rregex = /<(?:\w+:)?r>/g, rend = /<\/(?:\w+:)?r>/; + return function parse_rs2(rs) { + return rs.replace(rregex, "").split(rend).map(parse_r).filter(function(r8) { + return r8.v; + }); + }; + })(); + rs_to_html = /* @__PURE__ */ (function parse_rs_factory() { + var nlregex = /(\r\n|\n)/g; + function parse_rpr2(font, intro, outro) { + var style = []; + if (font.u) style.push("text-decoration: underline;"); + if (font.uval) style.push("text-underline-style:" + font.uval + ";"); + if (font.sz) style.push("font-size:" + font.sz + "pt;"); + if (font.outline) style.push("text-effect: outline;"); + if (font.shadow) style.push("text-shadow: auto;"); + intro.push(''); + if (font.b) { + intro.push(""); + outro.push(""); + } + if (font.i) { + intro.push(""); + outro.push(""); + } + if (font.strike) { + intro.push(""); + outro.push(""); + } + var align = font.valign || ""; + if (align == "superscript" || align == "super") align = "sup"; + else if (align == "subscript") align = "sub"; + if (align != "") { + intro.push("<" + align + ">"); + outro.push(""); + } + outro.push(""); + return font; + } + function r_to_html(r8) { + var terms = [[], r8.v, []]; + if (!r8.v) return ""; + if (r8.s) parse_rpr2(r8.s, terms[0], terms[2]); + return terms[0].join("") + terms[1].replace(nlregex, "
") + terms[2].join(""); + } + return function parse_rs2(rs) { + return rs.map(r_to_html).join(""); + }; + })(); + sitregex = /<(?:\w+:)?t\b[^<>]*>([^<]*)<\/(?:\w+:)?t>/g; + sirregex = /<(?:\w+:)?r\b[^<>]*>/; + sstr1 = /<(?:\w+:)?(?:si|sstItem)>/g; + sstr2 = /<\/(?:\w+:)?(?:si|sstItem)>/; + crypto_CreateXorArray_Method1 = /* @__PURE__ */ (function() { + var PadArray = [187, 255, 255, 186, 255, 255, 185, 128, 0, 190, 15, 0, 191, 15, 0]; + var InitialCode = [57840, 7439, 52380, 33984, 4364, 3600, 61902, 12606, 6258, 57657, 54287, 34041, 10252, 43370, 20163]; + var XorMatrix = [44796, 19929, 39858, 10053, 20106, 40212, 10761, 31585, 63170, 64933, 60267, 50935, 40399, 11199, 17763, 35526, 1453, 2906, 5812, 11624, 23248, 885, 1770, 3540, 7080, 14160, 28320, 56640, 55369, 41139, 20807, 41614, 21821, 43642, 17621, 28485, 56970, 44341, 19019, 38038, 14605, 29210, 60195, 50791, 40175, 10751, 21502, 43004, 24537, 18387, 36774, 3949, 7898, 15796, 31592, 63184, 47201, 24803, 49606, 37805, 14203, 28406, 56812, 17824, 35648, 1697, 3394, 6788, 13576, 27152, 43601, 17539, 35078, 557, 1114, 2228, 4456, 30388, 60776, 51953, 34243, 7079, 14158, 28316, 14128, 28256, 56512, 43425, 17251, 34502, 7597, 13105, 26210, 52420, 35241, 883, 1766, 3532, 4129, 8258, 16516, 33032, 4657, 9314, 18628]; + var Ror = function(Byte) { + return (Byte / 2 | Byte * 128) & 255; + }; + var XorRor = function(byte1, byte2) { + return Ror(byte1 ^ byte2); + }; + var CreateXorKey_Method1 = function(Password) { + var XorKey = InitialCode[Password.length - 1]; + var CurrentElement = 104; + for (var i7 = Password.length - 1; i7 >= 0; --i7) { + var Char = Password[i7]; + for (var j3 = 0; j3 != 7; ++j3) { + if (Char & 64) XorKey ^= XorMatrix[CurrentElement]; + Char *= 2; + --CurrentElement; + } + } + return XorKey; + }; + return function(password) { + var Password = _JS2ANSI(password); + var XorKey = CreateXorKey_Method1(Password); + var Index3 = Password.length; + var ObfuscationArray = new_raw_buf(16); + for (var i7 = 0; i7 != 16; ++i7) ObfuscationArray[i7] = 0; + var Temp, PasswordLastChar, PadIndex; + if ((Index3 & 1) === 1) { + Temp = XorKey >> 8; + ObfuscationArray[Index3] = XorRor(PadArray[0], Temp); + --Index3; + Temp = XorKey & 255; + PasswordLastChar = Password[Password.length - 1]; + ObfuscationArray[Index3] = XorRor(PasswordLastChar, Temp); + } + while (Index3 > 0) { + --Index3; + Temp = XorKey >> 8; + ObfuscationArray[Index3] = XorRor(Password[Index3], Temp); + --Index3; + Temp = XorKey & 255; + ObfuscationArray[Index3] = XorRor(Password[Index3], Temp); + } + Index3 = 15; + PadIndex = 15 - Password.length; + while (PadIndex > 0) { + Temp = XorKey >> 8; + ObfuscationArray[Index3] = XorRor(PadArray[PadIndex], Temp); + --Index3; + --PadIndex; + Temp = XorKey & 255; + ObfuscationArray[Index3] = XorRor(Password[Index3], Temp); + --Index3; + --PadIndex; + } + return ObfuscationArray; + }; + })(); + crypto_DecryptData_Method1 = function(password, Data, XorArrayIndex, XorArray, O2) { + if (!O2) O2 = Data; + if (!XorArray) XorArray = crypto_CreateXorArray_Method1(password); + var Index3, Value; + for (Index3 = 0; Index3 != Data.length; ++Index3) { + Value = Data[Index3]; + Value ^= XorArray[XorArrayIndex]; + Value = (Value >> 5 | Value << 3) & 255; + O2[Index3] = Value; + ++XorArrayIndex; + } + return [O2, XorArrayIndex, XorArray]; + }; + crypto_MakeXorDecryptor = function(password) { + var XorArrayIndex = 0, XorArray = crypto_CreateXorArray_Method1(password); + return function(Data) { + var O2 = crypto_DecryptData_Method1("", Data, XorArrayIndex, XorArray); + XorArrayIndex = O2[1]; + return O2[0]; + }; + }; + DEF_MDW = 6; + MAX_MDW = 15; + MIN_MDW = 1; + MDW = DEF_MDW; + DEF_PPI = 96; + PPI = DEF_PPI; + XLMLPatternTypeMap = { + "None": "none", + "Solid": "solid", + "Gray50": "mediumGray", + "Gray75": "darkGray", + "Gray25": "lightGray", + "HorzStripe": "darkHorizontal", + "VertStripe": "darkVertical", + "ReverseDiagStripe": "darkDown", + "DiagStripe": "darkUp", + "DiagCross": "darkGrid", + "ThickDiagCross": "darkTrellis", + "ThinHorzStripe": "lightHorizontal", + "ThinVertStripe": "lightVertical", + "ThinReverseDiagStripe": "lightDown", + "ThinHorzCross": "lightGrid" + }; + cellXF_uint = ["numFmtId", "fillId", "fontId", "borderId", "xfId"]; + cellXF_bool = ["applyAlignment", "applyBorder", "applyFill", "applyFont", "applyNumberFormat", "applyProtection", "pivotButton", "quotePrefix"]; + parse_sty_xml = /* @__PURE__ */ (function make_pstyx() { + return function parse_sty_xml2(data, themes, opts) { + var styles2 = {}; + if (!data) return styles2; + data = remove_doctype(str_remove_ng(data, "")); + var t6; + if (t6 = str_match_xml_ns(data, "numFmts")) parse_numFmts(t6[0], styles2, opts); + if (t6 = str_match_xml_ns(data, "fonts")) parse_fonts(t6[0], styles2, themes, opts); + if (t6 = str_match_xml_ns(data, "fills")) parse_fills(t6[0], styles2, themes, opts); + if (t6 = str_match_xml_ns(data, "borders")) parse_borders(t6[0], styles2, themes, opts); + if (t6 = str_match_xml_ns(data, "cellXfs")) parse_cellXfs(t6[0], styles2, opts); + return styles2; + }; + })(); + parse_BrtFill = parsenoop; + parse_BrtBorder = parsenoop; + XLSXThemeClrScheme = [ + "
", + "
", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ]; + parse_BrtCommentAuthor = parse_XLWideString; + CT_VBA = "application/vnd.ms-office.vbaProject"; + rc_to_a1 = /* @__PURE__ */ (function() { + var rcregex = /(^|[^A-Za-z_])R(\[?-?\d+\]|[1-9]\d*|)C(\[?-?\d+\]|[1-9]\d*|)(?![A-Za-z0-9_])/g; + var rcbase = { r: 0, c: 0 }; + function rcfunc($$, $1, $22, $32) { + var cRel = false, rRel = false; + if ($22.length == 0) rRel = true; + else if ($22.charAt(0) == "[") { + rRel = true; + $22 = $22.slice(1, -1); + } + if ($32.length == 0) cRel = true; + else if ($32.charAt(0) == "[") { + cRel = true; + $32 = $32.slice(1, -1); + } + var R3 = $22.length > 0 ? parseInt($22, 10) | 0 : 0, C3 = $32.length > 0 ? parseInt($32, 10) | 0 : 0; + if (cRel) C3 += rcbase.c; + else --C3; + if (rRel) R3 += rcbase.r; + else --R3; + return $1 + (cRel ? "" : "$") + encode_col(C3) + (rRel ? "" : "$") + encode_row(R3); + } + return function rc_to_a12(fstr, base) { + rcbase = base; + return fstr.replace(rcregex, rcfunc); + }; + })(); + crefregex = /(^|[^._A-Z0-9])(\$?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])(\$?)(\d{1,7})(?![_.\(A-Za-z0-9])/g; + try { + crefregex = /(^|[^._A-Z0-9])([$]?)([A-Z]{1,2}|[A-W][A-Z]{2}|X[A-E][A-Z]|XF[A-D])([$]?)(10[0-3]\d{4}|104[0-7]\d{3}|1048[0-4]\d{2}|10485[0-6]\d|104857[0-6]|[1-9]\d{0,5})(?![_.\(A-Za-z0-9])/g; + } catch (e9) { + } + a1_to_rc = /* @__PURE__ */ (function() { + return function a1_to_rc2(fstr, base) { + return fstr.replace(crefregex, function($0, $1, $22, $32, $4, $5) { + var c6 = decode_col($32) - ($22 ? 0 : base.c); + var r8 = decode_row($5) - ($4 ? 0 : base.r); + var R3 = $4 == "$" ? r8 + 1 : r8 == 0 ? "" : "[" + r8 + "]"; + var C3 = $22 == "$" ? c6 + 1 : c6 == 0 ? "" : "[" + c6 + "]"; + return $1 + "R" + R3 + "C" + C3; + }); + }; + })(); + parse_PtgMemErr = parsenoop; + parse_PtgMemNoMem = parsenoop; + parse_PtgTbl = parsenoop; + parse_PtgElfCol = parse_PtgElfLoc; + parse_PtgElfColS = parse_PtgElfNoop; + parse_PtgElfColSV = parse_PtgElfNoop; + parse_PtgElfColV = parse_PtgElfLoc; + parse_PtgElfRadical = parse_PtgElfLoc; + parse_PtgElfRadicalLel = parse_PtgElfLel; + parse_PtgElfRadicalS = parse_PtgElfNoop; + parse_PtgElfRw = parse_PtgElfLoc; + parse_PtgElfRwV = parse_PtgElfLoc; + PtgListRT = [ + "Data", + "All", + "Headers", + "??", + "?Data2", + "??", + "?DataHeaders", + "??", + "Totals", + "??", + "??", + "??", + "?DataTotals", + "??", + "??", + "??", + "?Current" + ]; + PtgTypes = { + 1: { n: "PtgExp", f: parse_PtgExp }, + 2: { n: "PtgTbl", f: parse_PtgTbl }, + 3: { n: "PtgAdd", f: parseread1 }, + 4: { n: "PtgSub", f: parseread1 }, + 5: { n: "PtgMul", f: parseread1 }, + 6: { n: "PtgDiv", f: parseread1 }, + 7: { n: "PtgPower", f: parseread1 }, + 8: { n: "PtgConcat", f: parseread1 }, + 9: { n: "PtgLt", f: parseread1 }, + 10: { n: "PtgLe", f: parseread1 }, + 11: { n: "PtgEq", f: parseread1 }, + 12: { n: "PtgGe", f: parseread1 }, + 13: { n: "PtgGt", f: parseread1 }, + 14: { n: "PtgNe", f: parseread1 }, + 15: { n: "PtgIsect", f: parseread1 }, + 16: { n: "PtgUnion", f: parseread1 }, + 17: { n: "PtgRange", f: parseread1 }, + 18: { n: "PtgUplus", f: parseread1 }, + 19: { n: "PtgUminus", f: parseread1 }, + 20: { n: "PtgPercent", f: parseread1 }, + 21: { n: "PtgParen", f: parseread1 }, + 22: { n: "PtgMissArg", f: parseread1 }, + 23: { n: "PtgStr", f: parse_PtgStr }, + 26: { n: "PtgSheet", f: parse_PtgSheet }, + 27: { n: "PtgEndSheet", f: parse_PtgEndSheet }, + 28: { n: "PtgErr", f: parse_PtgErr }, + 29: { n: "PtgBool", f: parse_PtgBool }, + 30: { n: "PtgInt", f: parse_PtgInt }, + 31: { n: "PtgNum", f: parse_PtgNum }, + 32: { n: "PtgArray", f: parse_PtgArray }, + 33: { n: "PtgFunc", f: parse_PtgFunc }, + 34: { n: "PtgFuncVar", f: parse_PtgFuncVar }, + 35: { n: "PtgName", f: parse_PtgName }, + 36: { n: "PtgRef", f: parse_PtgRef }, + 37: { n: "PtgArea", f: parse_PtgArea }, + 38: { n: "PtgMemArea", f: parse_PtgMemArea }, + 39: { n: "PtgMemErr", f: parse_PtgMemErr }, + 40: { n: "PtgMemNoMem", f: parse_PtgMemNoMem }, + 41: { n: "PtgMemFunc", f: parse_PtgMemFunc }, + 42: { n: "PtgRefErr", f: parse_PtgRefErr }, + 43: { n: "PtgAreaErr", f: parse_PtgAreaErr }, + 44: { n: "PtgRefN", f: parse_PtgRefN }, + 45: { n: "PtgAreaN", f: parse_PtgAreaN }, + 46: { n: "PtgMemAreaN", f: parse_PtgMemAreaN }, + 47: { n: "PtgMemNoMemN", f: parse_PtgMemNoMemN }, + 57: { n: "PtgNameX", f: parse_PtgNameX }, + 58: { n: "PtgRef3d", f: parse_PtgRef3d }, + 59: { n: "PtgArea3d", f: parse_PtgArea3d }, + 60: { n: "PtgRefErr3d", f: parse_PtgRefErr3d }, + 61: { n: "PtgAreaErr3d", f: parse_PtgAreaErr3d }, + 255: {} + }; + PtgDupes = { + 64: 32, + 96: 32, + 65: 33, + 97: 33, + 66: 34, + 98: 34, + 67: 35, + 99: 35, + 68: 36, + 100: 36, + 69: 37, + 101: 37, + 70: 38, + 102: 38, + 71: 39, + 103: 39, + 72: 40, + 104: 40, + 73: 41, + 105: 41, + 74: 42, + 106: 42, + 75: 43, + 107: 43, + 76: 44, + 108: 44, + 77: 45, + 109: 45, + 78: 46, + 110: 46, + 79: 47, + 111: 47, + 88: 34, + 120: 34, + 89: 57, + 121: 57, + 90: 58, + 122: 58, + 91: 59, + 123: 59, + 92: 60, + 124: 60, + 93: 61, + 125: 61 + }; + Ptg18 = { + 1: { n: "PtgElfLel", f: parse_PtgElfLel }, + 2: { n: "PtgElfRw", f: parse_PtgElfRw }, + 3: { n: "PtgElfCol", f: parse_PtgElfCol }, + 6: { n: "PtgElfRwV", f: parse_PtgElfRwV }, + 7: { n: "PtgElfColV", f: parse_PtgElfColV }, + 10: { n: "PtgElfRadical", f: parse_PtgElfRadical }, + 11: { n: "PtgElfRadicalS", f: parse_PtgElfRadicalS }, + 13: { n: "PtgElfColS", f: parse_PtgElfColS }, + 15: { n: "PtgElfColSV", f: parse_PtgElfColSV }, + 16: { n: "PtgElfRadicalLel", f: parse_PtgElfRadicalLel }, + 25: { n: "PtgList", f: parse_PtgList }, + 29: { n: "PtgSxName", f: parse_PtgSxName }, + 255: {} + }; + Ptg19 = { + 0: { n: "PtgAttrNoop", f: parse_PtgAttrNoop }, + 1: { n: "PtgAttrSemi", f: parse_PtgAttrSemi }, + 2: { n: "PtgAttrIf", f: parse_PtgAttrIf }, + 4: { n: "PtgAttrChoose", f: parse_PtgAttrChoose }, + 8: { n: "PtgAttrGoto", f: parse_PtgAttrGoto }, + 16: { n: "PtgAttrSum", f: parse_PtgAttrSum }, + 32: { n: "PtgAttrBaxcel", f: parse_PtgAttrBaxcel }, + 33: { n: "PtgAttrBaxcel", f: parse_PtgAttrBaxcel }, + 64: { n: "PtgAttrSpace", f: parse_PtgAttrSpace }, + 65: { n: "PtgAttrSpaceSemi", f: parse_PtgAttrSpaceSemi }, + 128: { n: "PtgAttrIfError", f: parse_PtgAttrIfError }, + 255: {} + }; + PtgBinOp = { + PtgAdd: "+", + PtgConcat: "&", + PtgDiv: "/", + PtgEq: "=", + PtgGe: ">=", + PtgGt: ">", + PtgLe: "<=", + PtgLt: "<", + PtgMul: "*", + PtgNe: "<>", + PtgPower: "^", + PtgSub: "-" + }; + parse_XLSBArrayParsedFormula = parse_XLSBParsedFormula; + parse_XLSBCellParsedFormula = parse_XLSBParsedFormula; + parse_XLSBNameParsedFormula = parse_XLSBParsedFormula; + parse_XLSBSharedParsedFormula = parse_XLSBParsedFormula; + Cetab = { + 0: "BEEP", + 1: "OPEN", + 2: "OPEN.LINKS", + 3: "CLOSE.ALL", + 4: "SAVE", + 5: "SAVE.AS", + 6: "FILE.DELETE", + 7: "PAGE.SETUP", + 8: "PRINT", + 9: "PRINTER.SETUP", + 10: "QUIT", + 11: "NEW.WINDOW", + 12: "ARRANGE.ALL", + 13: "WINDOW.SIZE", + 14: "WINDOW.MOVE", + 15: "FULL", + 16: "CLOSE", + 17: "RUN", + 22: "SET.PRINT.AREA", + 23: "SET.PRINT.TITLES", + 24: "SET.PAGE.BREAK", + 25: "REMOVE.PAGE.BREAK", + 26: "FONT", + 27: "DISPLAY", + 28: "PROTECT.DOCUMENT", + 29: "PRECISION", + 30: "A1.R1C1", + 31: "CALCULATE.NOW", + 32: "CALCULATION", + 34: "DATA.FIND", + 35: "EXTRACT", + 36: "DATA.DELETE", + 37: "SET.DATABASE", + 38: "SET.CRITERIA", + 39: "SORT", + 40: "DATA.SERIES", + 41: "TABLE", + 42: "FORMAT.NUMBER", + 43: "ALIGNMENT", + 44: "STYLE", + 45: "BORDER", + 46: "CELL.PROTECTION", + 47: "COLUMN.WIDTH", + 48: "UNDO", + 49: "CUT", + 50: "COPY", + 51: "PASTE", + 52: "CLEAR", + 53: "PASTE.SPECIAL", + 54: "EDIT.DELETE", + 55: "INSERT", + 56: "FILL.RIGHT", + 57: "FILL.DOWN", + 61: "DEFINE.NAME", + 62: "CREATE.NAMES", + 63: "FORMULA.GOTO", + 64: "FORMULA.FIND", + 65: "SELECT.LAST.CELL", + 66: "SHOW.ACTIVE.CELL", + 67: "GALLERY.AREA", + 68: "GALLERY.BAR", + 69: "GALLERY.COLUMN", + 70: "GALLERY.LINE", + 71: "GALLERY.PIE", + 72: "GALLERY.SCATTER", + 73: "COMBINATION", + 74: "PREFERRED", + 75: "ADD.OVERLAY", + 76: "GRIDLINES", + 77: "SET.PREFERRED", + 78: "AXES", + 79: "LEGEND", + 80: "ATTACH.TEXT", + 81: "ADD.ARROW", + 82: "SELECT.CHART", + 83: "SELECT.PLOT.AREA", + 84: "PATTERNS", + 85: "MAIN.CHART", + 86: "OVERLAY", + 87: "SCALE", + 88: "FORMAT.LEGEND", + 89: "FORMAT.TEXT", + 90: "EDIT.REPEAT", + 91: "PARSE", + 92: "JUSTIFY", + 93: "HIDE", + 94: "UNHIDE", + 95: "WORKSPACE", + 96: "FORMULA", + 97: "FORMULA.FILL", + 98: "FORMULA.ARRAY", + 99: "DATA.FIND.NEXT", + 100: "DATA.FIND.PREV", + 101: "FORMULA.FIND.NEXT", + 102: "FORMULA.FIND.PREV", + 103: "ACTIVATE", + 104: "ACTIVATE.NEXT", + 105: "ACTIVATE.PREV", + 106: "UNLOCKED.NEXT", + 107: "UNLOCKED.PREV", + 108: "COPY.PICTURE", + 109: "SELECT", + 110: "DELETE.NAME", + 111: "DELETE.FORMAT", + 112: "VLINE", + 113: "HLINE", + 114: "VPAGE", + 115: "HPAGE", + 116: "VSCROLL", + 117: "HSCROLL", + 118: "ALERT", + 119: "NEW", + 120: "CANCEL.COPY", + 121: "SHOW.CLIPBOARD", + 122: "MESSAGE", + 124: "PASTE.LINK", + 125: "APP.ACTIVATE", + 126: "DELETE.ARROW", + 127: "ROW.HEIGHT", + 128: "FORMAT.MOVE", + 129: "FORMAT.SIZE", + 130: "FORMULA.REPLACE", + 131: "SEND.KEYS", + 132: "SELECT.SPECIAL", + 133: "APPLY.NAMES", + 134: "REPLACE.FONT", + 135: "FREEZE.PANES", + 136: "SHOW.INFO", + 137: "SPLIT", + 138: "ON.WINDOW", + 139: "ON.DATA", + 140: "DISABLE.INPUT", + 142: "OUTLINE", + 143: "LIST.NAMES", + 144: "FILE.CLOSE", + 145: "SAVE.WORKBOOK", + 146: "DATA.FORM", + 147: "COPY.CHART", + 148: "ON.TIME", + 149: "WAIT", + 150: "FORMAT.FONT", + 151: "FILL.UP", + 152: "FILL.LEFT", + 153: "DELETE.OVERLAY", + 155: "SHORT.MENUS", + 159: "SET.UPDATE.STATUS", + 161: "COLOR.PALETTE", + 162: "DELETE.STYLE", + 163: "WINDOW.RESTORE", + 164: "WINDOW.MAXIMIZE", + 166: "CHANGE.LINK", + 167: "CALCULATE.DOCUMENT", + 168: "ON.KEY", + 169: "APP.RESTORE", + 170: "APP.MOVE", + 171: "APP.SIZE", + 172: "APP.MINIMIZE", + 173: "APP.MAXIMIZE", + 174: "BRING.TO.FRONT", + 175: "SEND.TO.BACK", + 185: "MAIN.CHART.TYPE", + 186: "OVERLAY.CHART.TYPE", + 187: "SELECT.END", + 188: "OPEN.MAIL", + 189: "SEND.MAIL", + 190: "STANDARD.FONT", + 191: "CONSOLIDATE", + 192: "SORT.SPECIAL", + 193: "GALLERY.3D.AREA", + 194: "GALLERY.3D.COLUMN", + 195: "GALLERY.3D.LINE", + 196: "GALLERY.3D.PIE", + 197: "VIEW.3D", + 198: "GOAL.SEEK", + 199: "WORKGROUP", + 200: "FILL.GROUP", + 201: "UPDATE.LINK", + 202: "PROMOTE", + 203: "DEMOTE", + 204: "SHOW.DETAIL", + 206: "UNGROUP", + 207: "OBJECT.PROPERTIES", + 208: "SAVE.NEW.OBJECT", + 209: "SHARE", + 210: "SHARE.NAME", + 211: "DUPLICATE", + 212: "APPLY.STYLE", + 213: "ASSIGN.TO.OBJECT", + 214: "OBJECT.PROTECTION", + 215: "HIDE.OBJECT", + 216: "SET.EXTRACT", + 217: "CREATE.PUBLISHER", + 218: "SUBSCRIBE.TO", + 219: "ATTRIBUTES", + 220: "SHOW.TOOLBAR", + 222: "PRINT.PREVIEW", + 223: "EDIT.COLOR", + 224: "SHOW.LEVELS", + 225: "FORMAT.MAIN", + 226: "FORMAT.OVERLAY", + 227: "ON.RECALC", + 228: "EDIT.SERIES", + 229: "DEFINE.STYLE", + 240: "LINE.PRINT", + 243: "ENTER.DATA", + 249: "GALLERY.RADAR", + 250: "MERGE.STYLES", + 251: "EDITION.OPTIONS", + 252: "PASTE.PICTURE", + 253: "PASTE.PICTURE.LINK", + 254: "SPELLING", + 256: "ZOOM", + 259: "INSERT.OBJECT", + 260: "WINDOW.MINIMIZE", + 265: "SOUND.NOTE", + 266: "SOUND.PLAY", + 267: "FORMAT.SHAPE", + 268: "EXTEND.POLYGON", + 269: "FORMAT.AUTO", + 272: "GALLERY.3D.BAR", + 273: "GALLERY.3D.SURFACE", + 274: "FILL.AUTO", + 276: "CUSTOMIZE.TOOLBAR", + 277: "ADD.TOOL", + 278: "EDIT.OBJECT", + 279: "ON.DOUBLECLICK", + 280: "ON.ENTRY", + 281: "WORKBOOK.ADD", + 282: "WORKBOOK.MOVE", + 283: "WORKBOOK.COPY", + 284: "WORKBOOK.OPTIONS", + 285: "SAVE.WORKSPACE", + 288: "CHART.WIZARD", + 289: "DELETE.TOOL", + 290: "MOVE.TOOL", + 291: "WORKBOOK.SELECT", + 292: "WORKBOOK.ACTIVATE", + 293: "ASSIGN.TO.TOOL", + 295: "COPY.TOOL", + 296: "RESET.TOOL", + 297: "CONSTRAIN.NUMERIC", + 298: "PASTE.TOOL", + 302: "WORKBOOK.NEW", + 305: "SCENARIO.CELLS", + 306: "SCENARIO.DELETE", + 307: "SCENARIO.ADD", + 308: "SCENARIO.EDIT", + 309: "SCENARIO.SHOW", + 310: "SCENARIO.SHOW.NEXT", + 311: "SCENARIO.SUMMARY", + 312: "PIVOT.TABLE.WIZARD", + 313: "PIVOT.FIELD.PROPERTIES", + 314: "PIVOT.FIELD", + 315: "PIVOT.ITEM", + 316: "PIVOT.ADD.FIELDS", + 318: "OPTIONS.CALCULATION", + 319: "OPTIONS.EDIT", + 320: "OPTIONS.VIEW", + 321: "ADDIN.MANAGER", + 322: "MENU.EDITOR", + 323: "ATTACH.TOOLBARS", + 324: "VBAActivate", + 325: "OPTIONS.CHART", + 328: "VBA.INSERT.FILE", + 330: "VBA.PROCEDURE.DEFINITION", + 336: "ROUTING.SLIP", + 338: "ROUTE.DOCUMENT", + 339: "MAIL.LOGON", + 342: "INSERT.PICTURE", + 343: "EDIT.TOOL", + 344: "GALLERY.DOUGHNUT", + 350: "CHART.TREND", + 352: "PIVOT.ITEM.PROPERTIES", + 354: "WORKBOOK.INSERT", + 355: "OPTIONS.TRANSITION", + 356: "OPTIONS.GENERAL", + 370: "FILTER.ADVANCED", + 373: "MAIL.ADD.MAILER", + 374: "MAIL.DELETE.MAILER", + 375: "MAIL.REPLY", + 376: "MAIL.REPLY.ALL", + 377: "MAIL.FORWARD", + 378: "MAIL.NEXT.LETTER", + 379: "DATA.LABEL", + 380: "INSERT.TITLE", + 381: "FONT.PROPERTIES", + 382: "MACRO.OPTIONS", + 383: "WORKBOOK.HIDE", + 384: "WORKBOOK.UNHIDE", + 385: "WORKBOOK.DELETE", + 386: "WORKBOOK.NAME", + 388: "GALLERY.CUSTOM", + 390: "ADD.CHART.AUTOFORMAT", + 391: "DELETE.CHART.AUTOFORMAT", + 392: "CHART.ADD.DATA", + 393: "AUTO.OUTLINE", + 394: "TAB.ORDER", + 395: "SHOW.DIALOG", + 396: "SELECT.ALL", + 397: "UNGROUP.SHEETS", + 398: "SUBTOTAL.CREATE", + 399: "SUBTOTAL.REMOVE", + 400: "RENAME.OBJECT", + 412: "WORKBOOK.SCROLL", + 413: "WORKBOOK.NEXT", + 414: "WORKBOOK.PREV", + 415: "WORKBOOK.TAB.SPLIT", + 416: "FULL.SCREEN", + 417: "WORKBOOK.PROTECT", + 420: "SCROLLBAR.PROPERTIES", + 421: "PIVOT.SHOW.PAGES", + 422: "TEXT.TO.COLUMNS", + 423: "FORMAT.CHARTTYPE", + 424: "LINK.FORMAT", + 425: "TRACER.DISPLAY", + 430: "TRACER.NAVIGATE", + 431: "TRACER.CLEAR", + 432: "TRACER.ERROR", + 433: "PIVOT.FIELD.GROUP", + 434: "PIVOT.FIELD.UNGROUP", + 435: "CHECKBOX.PROPERTIES", + 436: "LABEL.PROPERTIES", + 437: "LISTBOX.PROPERTIES", + 438: "EDITBOX.PROPERTIES", + 439: "PIVOT.REFRESH", + 440: "LINK.COMBO", + 441: "OPEN.TEXT", + 442: "HIDE.DIALOG", + 443: "SET.DIALOG.FOCUS", + 444: "ENABLE.OBJECT", + 445: "PUSHBUTTON.PROPERTIES", + 446: "SET.DIALOG.DEFAULT", + 447: "FILTER", + 448: "FILTER.SHOW.ALL", + 449: "CLEAR.OUTLINE", + 450: "FUNCTION.WIZARD", + 451: "ADD.LIST.ITEM", + 452: "SET.LIST.ITEM", + 453: "REMOVE.LIST.ITEM", + 454: "SELECT.LIST.ITEM", + 455: "SET.CONTROL.VALUE", + 456: "SAVE.COPY.AS", + 458: "OPTIONS.LISTS.ADD", + 459: "OPTIONS.LISTS.DELETE", + 460: "SERIES.AXES", + 461: "SERIES.X", + 462: "SERIES.Y", + 463: "ERRORBAR.X", + 464: "ERRORBAR.Y", + 465: "FORMAT.CHART", + 466: "SERIES.ORDER", + 467: "MAIL.LOGOFF", + 468: "CLEAR.ROUTING.SLIP", + 469: "APP.ACTIVATE.MICROSOFT", + 470: "MAIL.EDIT.MAILER", + 471: "ON.SHEET", + 472: "STANDARD.WIDTH", + 473: "SCENARIO.MERGE", + 474: "SUMMARY.INFO", + 475: "FIND.FILE", + 476: "ACTIVE.CELL.FONT", + 477: "ENABLE.TIPWIZARD", + 478: "VBA.MAKE.ADDIN", + 480: "INSERTDATATABLE", + 481: "WORKGROUP.OPTIONS", + 482: "MAIL.SEND.MAILER", + 485: "AUTOCORRECT", + 489: "POST.DOCUMENT", + 491: "PICKLIST", + 493: "VIEW.SHOW", + 494: "VIEW.DEFINE", + 495: "VIEW.DELETE", + 509: "SHEET.BACKGROUND", + 510: "INSERT.MAP.OBJECT", + 511: "OPTIONS.MENONO", + 517: "MSOCHECKS", + 518: "NORMAL", + 519: "LAYOUT", + 520: "RM.PRINT.AREA", + 521: "CLEAR.PRINT.AREA", + 522: "ADD.PRINT.AREA", + 523: "MOVE.BRK", + 545: "HIDECURR.NOTE", + 546: "HIDEALL.NOTES", + 547: "DELETE.NOTE", + 548: "TRAVERSE.NOTES", + 549: "ACTIVATE.NOTES", + 620: "PROTECT.REVISIONS", + 621: "UNPROTECT.REVISIONS", + 647: "OPTIONS.ME", + 653: "WEB.PUBLISH", + 667: "NEWWEBQUERY", + 673: "PIVOT.TABLE.CHART", + 753: "OPTIONS.SAVE", + 755: "OPTIONS.SPELL", + 808: "HIDEALL.INKANNOTS" + }; + Ftab = { + 0: "COUNT", + 1: "IF", + 2: "ISNA", + 3: "ISERROR", + 4: "SUM", + 5: "AVERAGE", + 6: "MIN", + 7: "MAX", + 8: "ROW", + 9: "COLUMN", + 10: "NA", + 11: "NPV", + 12: "STDEV", + 13: "DOLLAR", + 14: "FIXED", + 15: "SIN", + 16: "COS", + 17: "TAN", + 18: "ATAN", + 19: "PI", + 20: "SQRT", + 21: "EXP", + 22: "LN", + 23: "LOG10", + 24: "ABS", + 25: "INT", + 26: "SIGN", + 27: "ROUND", + 28: "LOOKUP", + 29: "INDEX", + 30: "REPT", + 31: "MID", + 32: "LEN", + 33: "VALUE", + 34: "TRUE", + 35: "FALSE", + 36: "AND", + 37: "OR", + 38: "NOT", + 39: "MOD", + 40: "DCOUNT", + 41: "DSUM", + 42: "DAVERAGE", + 43: "DMIN", + 44: "DMAX", + 45: "DSTDEV", + 46: "VAR", + 47: "DVAR", + 48: "TEXT", + 49: "LINEST", + 50: "TREND", + 51: "LOGEST", + 52: "GROWTH", + 53: "GOTO", + 54: "HALT", + 55: "RETURN", + 56: "PV", + 57: "FV", + 58: "NPER", + 59: "PMT", + 60: "RATE", + 61: "MIRR", + 62: "IRR", + 63: "RAND", + 64: "MATCH", + 65: "DATE", + 66: "TIME", + 67: "DAY", + 68: "MONTH", + 69: "YEAR", + 70: "WEEKDAY", + 71: "HOUR", + 72: "MINUTE", + 73: "SECOND", + 74: "NOW", + 75: "AREAS", + 76: "ROWS", + 77: "COLUMNS", + 78: "OFFSET", + 79: "ABSREF", + 80: "RELREF", + 81: "ARGUMENT", + 82: "SEARCH", + 83: "TRANSPOSE", + 84: "ERROR", + 85: "STEP", + 86: "TYPE", + 87: "ECHO", + 88: "SET.NAME", + 89: "CALLER", + 90: "DEREF", + 91: "WINDOWS", + 92: "SERIES", + 93: "DOCUMENTS", + 94: "ACTIVE.CELL", + 95: "SELECTION", + 96: "RESULT", + 97: "ATAN2", + 98: "ASIN", + 99: "ACOS", + 100: "CHOOSE", + 101: "HLOOKUP", + 102: "VLOOKUP", + 103: "LINKS", + 104: "INPUT", + 105: "ISREF", + 106: "GET.FORMULA", + 107: "GET.NAME", + 108: "SET.VALUE", + 109: "LOG", + 110: "EXEC", + 111: "CHAR", + 112: "LOWER", + 113: "UPPER", + 114: "PROPER", + 115: "LEFT", + 116: "RIGHT", + 117: "EXACT", + 118: "TRIM", + 119: "REPLACE", + 120: "SUBSTITUTE", + 121: "CODE", + 122: "NAMES", + 123: "DIRECTORY", + 124: "FIND", + 125: "CELL", + 126: "ISERR", + 127: "ISTEXT", + 128: "ISNUMBER", + 129: "ISBLANK", + 130: "T", + 131: "N", + 132: "FOPEN", + 133: "FCLOSE", + 134: "FSIZE", + 135: "FREADLN", + 136: "FREAD", + 137: "FWRITELN", + 138: "FWRITE", + 139: "FPOS", + 140: "DATEVALUE", + 141: "TIMEVALUE", + 142: "SLN", + 143: "SYD", + 144: "DDB", + 145: "GET.DEF", + 146: "REFTEXT", + 147: "TEXTREF", + 148: "INDIRECT", + 149: "REGISTER", + 150: "CALL", + 151: "ADD.BAR", + 152: "ADD.MENU", + 153: "ADD.COMMAND", + 154: "ENABLE.COMMAND", + 155: "CHECK.COMMAND", + 156: "RENAME.COMMAND", + 157: "SHOW.BAR", + 158: "DELETE.MENU", + 159: "DELETE.COMMAND", + 160: "GET.CHART.ITEM", + 161: "DIALOG.BOX", + 162: "CLEAN", + 163: "MDETERM", + 164: "MINVERSE", + 165: "MMULT", + 166: "FILES", + 167: "IPMT", + 168: "PPMT", + 169: "COUNTA", + 170: "CANCEL.KEY", + 171: "FOR", + 172: "WHILE", + 173: "BREAK", + 174: "NEXT", + 175: "INITIATE", + 176: "REQUEST", + 177: "POKE", + 178: "EXECUTE", + 179: "TERMINATE", + 180: "RESTART", + 181: "HELP", + 182: "GET.BAR", + 183: "PRODUCT", + 184: "FACT", + 185: "GET.CELL", + 186: "GET.WORKSPACE", + 187: "GET.WINDOW", + 188: "GET.DOCUMENT", + 189: "DPRODUCT", + 190: "ISNONTEXT", + 191: "GET.NOTE", + 192: "NOTE", + 193: "STDEVP", + 194: "VARP", + 195: "DSTDEVP", + 196: "DVARP", + 197: "TRUNC", + 198: "ISLOGICAL", + 199: "DCOUNTA", + 200: "DELETE.BAR", + 201: "UNREGISTER", + 204: "USDOLLAR", + 205: "FINDB", + 206: "SEARCHB", + 207: "REPLACEB", + 208: "LEFTB", + 209: "RIGHTB", + 210: "MIDB", + 211: "LENB", + 212: "ROUNDUP", + 213: "ROUNDDOWN", + 214: "ASC", + 215: "DBCS", + 216: "RANK", + 219: "ADDRESS", + 220: "DAYS360", + 221: "TODAY", + 222: "VDB", + 223: "ELSE", + 224: "ELSE.IF", + 225: "END.IF", + 226: "FOR.CELL", + 227: "MEDIAN", + 228: "SUMPRODUCT", + 229: "SINH", + 230: "COSH", + 231: "TANH", + 232: "ASINH", + 233: "ACOSH", + 234: "ATANH", + 235: "DGET", + 236: "CREATE.OBJECT", + 237: "VOLATILE", + 238: "LAST.ERROR", + 239: "CUSTOM.UNDO", + 240: "CUSTOM.REPEAT", + 241: "FORMULA.CONVERT", + 242: "GET.LINK.INFO", + 243: "TEXT.BOX", + 244: "INFO", + 245: "GROUP", + 246: "GET.OBJECT", + 247: "DB", + 248: "PAUSE", + 251: "RESUME", + 252: "FREQUENCY", + 253: "ADD.TOOLBAR", + 254: "DELETE.TOOLBAR", + 255: "User", + 256: "RESET.TOOLBAR", + 257: "EVALUATE", + 258: "GET.TOOLBAR", + 259: "GET.TOOL", + 260: "SPELLING.CHECK", + 261: "ERROR.TYPE", + 262: "APP.TITLE", + 263: "WINDOW.TITLE", + 264: "SAVE.TOOLBAR", + 265: "ENABLE.TOOL", + 266: "PRESS.TOOL", + 267: "REGISTER.ID", + 268: "GET.WORKBOOK", + 269: "AVEDEV", + 270: "BETADIST", + 271: "GAMMALN", + 272: "BETAINV", + 273: "BINOMDIST", + 274: "CHIDIST", + 275: "CHIINV", + 276: "COMBIN", + 277: "CONFIDENCE", + 278: "CRITBINOM", + 279: "EVEN", + 280: "EXPONDIST", + 281: "FDIST", + 282: "FINV", + 283: "FISHER", + 284: "FISHERINV", + 285: "FLOOR", + 286: "GAMMADIST", + 287: "GAMMAINV", + 288: "CEILING", + 289: "HYPGEOMDIST", + 290: "LOGNORMDIST", + 291: "LOGINV", + 292: "NEGBINOMDIST", + 293: "NORMDIST", + 294: "NORMSDIST", + 295: "NORMINV", + 296: "NORMSINV", + 297: "STANDARDIZE", + 298: "ODD", + 299: "PERMUT", + 300: "POISSON", + 301: "TDIST", + 302: "WEIBULL", + 303: "SUMXMY2", + 304: "SUMX2MY2", + 305: "SUMX2PY2", + 306: "CHITEST", + 307: "CORREL", + 308: "COVAR", + 309: "FORECAST", + 310: "FTEST", + 311: "INTERCEPT", + 312: "PEARSON", + 313: "RSQ", + 314: "STEYX", + 315: "SLOPE", + 316: "TTEST", + 317: "PROB", + 318: "DEVSQ", + 319: "GEOMEAN", + 320: "HARMEAN", + 321: "SUMSQ", + 322: "KURT", + 323: "SKEW", + 324: "ZTEST", + 325: "LARGE", + 326: "SMALL", + 327: "QUARTILE", + 328: "PERCENTILE", + 329: "PERCENTRANK", + 330: "MODE", + 331: "TRIMMEAN", + 332: "TINV", + 334: "MOVIE.COMMAND", + 335: "GET.MOVIE", + 336: "CONCATENATE", + 337: "POWER", + 338: "PIVOT.ADD.DATA", + 339: "GET.PIVOT.TABLE", + 340: "GET.PIVOT.FIELD", + 341: "GET.PIVOT.ITEM", + 342: "RADIANS", + 343: "DEGREES", + 344: "SUBTOTAL", + 345: "SUMIF", + 346: "COUNTIF", + 347: "COUNTBLANK", + 348: "SCENARIO.GET", + 349: "OPTIONS.LISTS.GET", + 350: "ISPMT", + 351: "DATEDIF", + 352: "DATESTRING", + 353: "NUMBERSTRING", + 354: "ROMAN", + 355: "OPEN.DIALOG", + 356: "SAVE.DIALOG", + 357: "VIEW.GET", + 358: "GETPIVOTDATA", + 359: "HYPERLINK", + 360: "PHONETIC", + 361: "AVERAGEA", + 362: "MAXA", + 363: "MINA", + 364: "STDEVPA", + 365: "VARPA", + 366: "STDEVA", + 367: "VARA", + 368: "BAHTTEXT", + 369: "THAIDAYOFWEEK", + 370: "THAIDIGIT", + 371: "THAIMONTHOFYEAR", + 372: "THAINUMSOUND", + 373: "THAINUMSTRING", + 374: "THAISTRINGLENGTH", + 375: "ISTHAIDIGIT", + 376: "ROUNDBAHTDOWN", + 377: "ROUNDBAHTUP", + 378: "THAIYEAR", + 379: "RTD", + 380: "CUBEVALUE", + 381: "CUBEMEMBER", + 382: "CUBEMEMBERPROPERTY", + 383: "CUBERANKEDMEMBER", + 384: "HEX2BIN", + 385: "HEX2DEC", + 386: "HEX2OCT", + 387: "DEC2BIN", + 388: "DEC2HEX", + 389: "DEC2OCT", + 390: "OCT2BIN", + 391: "OCT2HEX", + 392: "OCT2DEC", + 393: "BIN2DEC", + 394: "BIN2OCT", + 395: "BIN2HEX", + 396: "IMSUB", + 397: "IMDIV", + 398: "IMPOWER", + 399: "IMABS", + 400: "IMSQRT", + 401: "IMLN", + 402: "IMLOG2", + 403: "IMLOG10", + 404: "IMSIN", + 405: "IMCOS", + 406: "IMEXP", + 407: "IMARGUMENT", + 408: "IMCONJUGATE", + 409: "IMAGINARY", + 410: "IMREAL", + 411: "COMPLEX", + 412: "IMSUM", + 413: "IMPRODUCT", + 414: "SERIESSUM", + 415: "FACTDOUBLE", + 416: "SQRTPI", + 417: "QUOTIENT", + 418: "DELTA", + 419: "GESTEP", + 420: "ISEVEN", + 421: "ISODD", + 422: "MROUND", + 423: "ERF", + 424: "ERFC", + 425: "BESSELJ", + 426: "BESSELK", + 427: "BESSELY", + 428: "BESSELI", + 429: "XIRR", + 430: "XNPV", + 431: "PRICEMAT", + 432: "YIELDMAT", + 433: "INTRATE", + 434: "RECEIVED", + 435: "DISC", + 436: "PRICEDISC", + 437: "YIELDDISC", + 438: "TBILLEQ", + 439: "TBILLPRICE", + 440: "TBILLYIELD", + 441: "PRICE", + 442: "YIELD", + 443: "DOLLARDE", + 444: "DOLLARFR", + 445: "NOMINAL", + 446: "EFFECT", + 447: "CUMPRINC", + 448: "CUMIPMT", + 449: "EDATE", + 450: "EOMONTH", + 451: "YEARFRAC", + 452: "COUPDAYBS", + 453: "COUPDAYS", + 454: "COUPDAYSNC", + 455: "COUPNCD", + 456: "COUPNUM", + 457: "COUPPCD", + 458: "DURATION", + 459: "MDURATION", + 460: "ODDLPRICE", + 461: "ODDLYIELD", + 462: "ODDFPRICE", + 463: "ODDFYIELD", + 464: "RANDBETWEEN", + 465: "WEEKNUM", + 466: "AMORDEGRC", + 467: "AMORLINC", + 468: "CONVERT", + 724: "SHEETJS", + 469: "ACCRINT", + 470: "ACCRINTM", + 471: "WORKDAY", + 472: "NETWORKDAYS", + 473: "GCD", + 474: "MULTINOMIAL", + 475: "LCM", + 476: "FVSCHEDULE", + 477: "CUBEKPIMEMBER", + 478: "CUBESET", + 479: "CUBESETCOUNT", + 480: "IFERROR", + 481: "COUNTIFS", + 482: "SUMIFS", + 483: "AVERAGEIF", + 484: "AVERAGEIFS" + }; + FtabArgc = { + 2: 1, + 3: 1, + 10: 0, + 15: 1, + 16: 1, + 17: 1, + 18: 1, + 19: 0, + 20: 1, + 21: 1, + 22: 1, + 23: 1, + 24: 1, + 25: 1, + 26: 1, + 27: 2, + 30: 2, + 31: 3, + 32: 1, + 33: 1, + 34: 0, + 35: 0, + 38: 1, + 39: 2, + 40: 3, + 41: 3, + 42: 3, + 43: 3, + 44: 3, + 45: 3, + 47: 3, + 48: 2, + 53: 1, + 61: 3, + 63: 0, + 65: 3, + 66: 3, + 67: 1, + 68: 1, + 69: 1, + 70: 1, + 71: 1, + 72: 1, + 73: 1, + 74: 0, + 75: 1, + 76: 1, + 77: 1, + 79: 2, + 80: 2, + 83: 1, + 85: 0, + 86: 1, + 89: 0, + 90: 1, + 94: 0, + 95: 0, + 97: 2, + 98: 1, + 99: 1, + 101: 3, + 102: 3, + 105: 1, + 106: 1, + 108: 2, + 111: 1, + 112: 1, + 113: 1, + 114: 1, + 117: 2, + 118: 1, + 119: 4, + 121: 1, + 126: 1, + 127: 1, + 128: 1, + 129: 1, + 130: 1, + 131: 1, + 133: 1, + 134: 1, + 135: 1, + 136: 2, + 137: 2, + 138: 2, + 140: 1, + 141: 1, + 142: 3, + 143: 4, + 144: 4, + 161: 1, + 162: 1, + 163: 1, + 164: 1, + 165: 2, + 172: 1, + 175: 2, + 176: 2, + 177: 3, + 178: 2, + 179: 1, + 184: 1, + 186: 1, + 189: 3, + 190: 1, + 195: 3, + 196: 3, + 197: 1, + 198: 1, + 199: 3, + 201: 1, + 207: 4, + 210: 3, + 211: 1, + 212: 2, + 213: 2, + 214: 1, + 215: 1, + 225: 0, + 229: 1, + 230: 1, + 231: 1, + 232: 1, + 233: 1, + 234: 1, + 235: 3, + 244: 1, + 247: 4, + 252: 2, + 257: 1, + 261: 1, + 271: 1, + 273: 4, + 274: 2, + 275: 2, + 276: 2, + 277: 3, + 278: 3, + 279: 1, + 280: 3, + 281: 3, + 282: 3, + 283: 1, + 284: 1, + 285: 2, + 286: 4, + 287: 3, + 288: 2, + 289: 4, + 290: 3, + 291: 3, + 292: 3, + 293: 4, + 294: 1, + 295: 3, + 296: 1, + 297: 3, + 298: 1, + 299: 2, + 300: 3, + 301: 3, + 302: 4, + 303: 2, + 304: 2, + 305: 2, + 306: 2, + 307: 2, + 308: 2, + 309: 3, + 310: 2, + 311: 2, + 312: 2, + 313: 2, + 314: 2, + 315: 2, + 316: 4, + 325: 2, + 326: 2, + 327: 2, + 328: 2, + 331: 2, + 332: 2, + 337: 2, + 342: 1, + 343: 1, + 346: 2, + 347: 1, + 350: 4, + 351: 3, + 352: 1, + 353: 2, + 360: 1, + 368: 1, + 369: 1, + 370: 1, + 371: 1, + 372: 1, + 373: 1, + 374: 1, + 375: 1, + 376: 1, + 377: 1, + 378: 1, + 382: 3, + 385: 1, + 392: 1, + 393: 1, + 396: 2, + 397: 2, + 398: 2, + 399: 1, + 400: 1, + 401: 1, + 402: 1, + 403: 1, + 404: 1, + 405: 1, + 406: 1, + 407: 1, + 408: 1, + 409: 1, + 410: 1, + 414: 4, + 415: 1, + 416: 1, + 417: 2, + 420: 1, + 421: 1, + 422: 2, + 424: 1, + 425: 2, + 426: 2, + 427: 2, + 428: 2, + 430: 3, + 438: 3, + 439: 3, + 440: 3, + 443: 2, + 444: 2, + 445: 2, + 446: 2, + 447: 6, + 448: 6, + 449: 2, + 450: 2, + 464: 2, + 468: 3, + 476: 2, + 479: 1, + 480: 2, + 65535: 0 + }; + strs = {}; + _ssfopts = {}; + mergecregex = /<(?:\w+:)?mergeCell ref=["'][A-Z0-9:]+['"]\s*[\/]?>/g; + hlinkregex = /<(?:\w+:)?hyperlink [^<>]*>/mg; + dimregex = /"(\w*:\w*)"/; + colregex = /<(?:\w+:)?col\b[^<>]*[\/]?>/g; + afregex = /<(?:\w+:)?autoFilter[^>]*/g; + marginregex = /<(?:\w+:)?pageMargins[^<>]*\/>/g; + sheetprregex = /<(?:\w+:)?sheetPr\b[^<>]*?\/>/; + sviewregex = /<(?:\w:)?sheetView(?:[^<>a-z][^<>]*)?\/?>/g; + parse_ws_xml_data = /* @__PURE__ */ (function() { + var cellregex = /<(?:\w+:)?c[ \/>]/, rowregex = /<\/(?:\w+:)?row>/; + var rregex = /r=["']([^"']*)["']/; + var refregex = /ref=["']([^"']*)["']/; + return function parse_ws_xml_data2(sdata, s6, opts, guess, themes, styles2, wb) { + var ri = 0, x2 = "", cells = [], cref = [], idx = 0, i7 = 0, cc = 0, d4 = "", p4; + var tag, tagr = 0, tagc = 0; + var sstr, ftag; + var fmtid = 0, fillid = 0; + var do_format = Array.isArray(styles2.CellXf), cf; + var arrayf = []; + var sharedf = []; + var dense = s6["!data"] != null; + var rows = [], rowobj = {}, rowrite = false; + var sheetStubs = !!opts.sheetStubs; + var date1904 = !!((wb || {}).WBProps || {}).date1904; + for (var marr = sdata.split(rowregex), mt = 0, marrlen = marr.length; mt != marrlen; ++mt) { + x2 = marr[mt].trim(); + var xlen = x2.length; + if (xlen === 0) continue; + var rstarti = 0; + outa: for (ri = 0; ri < xlen; ++ri) switch ( + /*x.charCodeAt(ri)*/ + x2[ri] + ) { + case ">": + if ( + /*x.charCodeAt(ri-1) != 47*/ + x2[ri - 1] != "/" + ) { + ++ri; + break outa; + } + if (opts && opts.cellStyles) { + tag = parsexmltag(x2.slice(rstarti, ri), true); + tagr = tag.r != null ? parseInt(tag.r, 10) : tagr + 1; + tagc = -1; + if (opts.sheetRows && opts.sheetRows < tagr) continue; + rowobj = {}; + rowrite = false; + if (tag.ht) { + rowrite = true; + rowobj.hpt = parseFloat(tag.ht); + rowobj.hpx = pt2px(rowobj.hpt); + } + if (tag.hidden && parsexmlbool(tag.hidden)) { + rowrite = true; + rowobj.hidden = true; + } + if (tag.outlineLevel != null) { + rowrite = true; + rowobj.level = +tag.outlineLevel; + } + if (rowrite) rows[tagr - 1] = rowobj; + } + break; + case "<": + rstarti = ri; + break; + } + if (rstarti >= ri) break; + tag = parsexmltag(x2.slice(rstarti, ri), true); + tagr = tag.r != null ? parseInt(tag.r, 10) : tagr + 1; + tagc = -1; + if (opts.sheetRows && opts.sheetRows < tagr) continue; + if (!opts.nodim) { + if (guess.s.r > tagr - 1) guess.s.r = tagr - 1; + if (guess.e.r < tagr - 1) guess.e.r = tagr - 1; + } + if (opts && opts.cellStyles) { + rowobj = {}; + rowrite = false; + if (tag.ht) { + rowrite = true; + rowobj.hpt = parseFloat(tag.ht); + rowobj.hpx = pt2px(rowobj.hpt); + } + if (tag.hidden && parsexmlbool(tag.hidden)) { + rowrite = true; + rowobj.hidden = true; + } + if (tag.outlineLevel != null) { + rowrite = true; + rowobj.level = +tag.outlineLevel; + } + if (rowrite) rows[tagr - 1] = rowobj; + } + cells = x2.slice(ri).split(cellregex); + for (var rslice = 0; rslice != cells.length; ++rslice) if (cells[rslice].trim().charAt(0) != "<") break; + cells = cells.slice(rslice); + for (ri = 0; ri != cells.length; ++ri) { + x2 = cells[ri].trim(); + if (x2.length === 0) continue; + cref = x2.match(rregex); + idx = ri; + i7 = 0; + cc = 0; + x2 = "" : "") + x2; + if (cref != null && cref.length === 2) { + idx = 0; + d4 = cref[1]; + for (i7 = 0; i7 != d4.length; ++i7) { + if ((cc = d4.charCodeAt(i7) - 64) < 1 || cc > 26) break; + idx = 26 * idx + cc; + } + --idx; + tagc = idx; + } else ++tagc; + for (i7 = 0; i7 != x2.length; ++i7) if (x2.charCodeAt(i7) === 62) break; + ++i7; + tag = parsexmltag(x2.slice(0, i7), true); + if (!tag.r) tag.r = encode_cell({ r: tagr - 1, c: tagc }); + d4 = x2.slice(i7); + p4 = { t: "" }; + if ((cref = str_match_xml_ns(d4, "v")) != null && /*::cref != null && */ + cref[1] !== "") p4.v = unescapexml(cref[1]); + if (opts.cellFormula) { + if ((cref = str_match_xml_ns(d4, "f")) != null) { + if (cref[1] == "") { + if ( + /*::cref != null && cref[0] != null && */ + cref[0].indexOf('t="shared"') > -1 + ) { + ftag = parsexmltag(cref[0]); + if (sharedf[ftag.si]) p4.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2], tag.r); + } + } else { + p4.f = unescapexml(utf8read(cref[1]), true); + if (!opts.xlfn) p4.f = _xlfn(p4.f); + if ( + /*::cref != null && cref[0] != null && */ + cref[0].indexOf('t="array"') > -1 + ) { + p4.F = (d4.match(refregex) || [])[1]; + if (p4.F.indexOf(":") > -1) arrayf.push([safe_decode_range(p4.F), p4.F]); + } else if ( + /*::cref != null && cref[0] != null && */ + cref[0].indexOf('t="shared"') > -1 + ) { + ftag = parsexmltag(cref[0]); + var ___f = unescapexml(utf8read(cref[1])); + if (!opts.xlfn) ___f = _xlfn(___f); + sharedf[parseInt(ftag.si, 10)] = [ftag, ___f, tag.r]; + } + } + } else if (cref = d4.match(/]*\/>/)) { + ftag = parsexmltag(cref[0]); + if (sharedf[ftag.si]) p4.f = shift_formula_xlsx(sharedf[ftag.si][1], sharedf[ftag.si][2], tag.r); + } + var _tag = decode_cell(tag.r); + for (i7 = 0; i7 < arrayf.length; ++i7) + if (_tag.r >= arrayf[i7][0].s.r && _tag.r <= arrayf[i7][0].e.r) { + if (_tag.c >= arrayf[i7][0].s.c && _tag.c <= arrayf[i7][0].e.c) + p4.F = arrayf[i7][1]; + } + } + if (tag.t == null && p4.v === void 0) { + if (p4.f || p4.F) { + p4.v = 0; + p4.t = "n"; + } else if (!sheetStubs) continue; + else p4.t = "z"; + } else p4.t = tag.t || "n"; + if (guess.s.c > tagc) guess.s.c = tagc; + if (guess.e.c < tagc) guess.e.c = tagc; + switch (p4.t) { + case "n": + if (p4.v == "" || p4.v == null) { + if (!sheetStubs) continue; + p4.t = "z"; + } else p4.v = parseFloat(p4.v); + break; + case "s": + if (typeof p4.v == "undefined") { + if (!sheetStubs) continue; + p4.t = "z"; + } else { + sstr = strs[parseInt(p4.v, 10)]; + p4.v = sstr.t; + p4.r = sstr.r; + if (opts.cellHTML) p4.h = sstr.h; + } + break; + case "str": + p4.t = "s"; + p4.v = p4.v != null ? unescapexml(utf8read(p4.v), true) : ""; + if (opts.cellHTML) p4.h = escapehtml(p4.v); + break; + case "inlineStr": + cref = str_match_xml_ns(d4, "is"); + p4.t = "s"; + if (cref != null && (sstr = parse_si(cref[1]))) { + p4.v = sstr.t; + if (opts.cellHTML) p4.h = sstr.h; + } else p4.v = ""; + break; + case "b": + p4.v = parsexmlbool(p4.v); + break; + case "d": + if (opts.cellDates) p4.v = parseDate(p4.v, date1904); + else { + p4.v = datenum(parseDate(p4.v, date1904), date1904); + p4.t = "n"; + } + break; + /* error string in .w, number in .v */ + case "e": + if (!opts || opts.cellText !== false) p4.w = p4.v; + p4.v = RBErr[p4.v]; + break; + } + fmtid = fillid = 0; + cf = null; + if (do_format && tag.s !== void 0) { + cf = styles2.CellXf[tag.s]; + if (cf != null) { + if (cf.numFmtId != null) fmtid = cf.numFmtId; + if (opts.cellStyles) { + if (cf.fillId != null) fillid = cf.fillId; + } + } + } + safe_format(p4, fmtid, fillid, opts, themes, styles2, date1904); + if (opts.cellDates && do_format && p4.t == "n" && fmt_is_date(table_fmt[fmtid])) { + p4.v = numdate(p4.v + (date1904 ? 1462 : 0)); + p4.t = typeof p4.v == "number" ? "n" : "d"; + } + if (tag.cm && opts.xlmeta) { + var cm = (opts.xlmeta.Cell || [])[+tag.cm - 1]; + if (cm && cm.type == "XLDAPR") p4.D = true; + } + var _r; + if (opts.nodim) { + _r = decode_cell(tag.r); + if (guess.s.r > _r.r) guess.s.r = _r.r; + if (guess.e.r < _r.r) guess.e.r = _r.r; + } + if (dense) { + _r = decode_cell(tag.r); + if (!s6["!data"][_r.r]) s6["!data"][_r.r] = []; + s6["!data"][_r.r][_r.c] = p4; + } else s6[tag.r] = p4; + } + } + if (rows.length > 0) s6["!rows"] = rows; + }; + })(); + parse_BrtWsDim = parse_UncheckedRfX; + parse_BrtMergeCell = parse_UncheckedRfX; + BrtMarginKeys = ["left", "right", "top", "bottom", "header", "footer"]; + WBPropsDef = [ + ["allowRefreshQuery", false, "bool"], + ["autoCompressPictures", true, "bool"], + ["backupFile", false, "bool"], + ["checkCompatibility", false, "bool"], + ["CodeName", ""], + ["date1904", false, "bool"], + ["defaultThemeVersion", 0, "int"], + ["filterPrivacy", false, "bool"], + ["hidePivotFieldList", false, "bool"], + ["promptedSolutions", false, "bool"], + ["publishItems", false, "bool"], + ["refreshAllConnections", false, "bool"], + ["saveExternalLinkValues", true, "bool"], + ["showBorderUnselectedTables", true, "bool"], + ["showInkAnnotation", true, "bool"], + ["showObjects", "all"], + ["showPivotChartFilter", false, "bool"], + ["updateLinks", "userSet"] + ]; + WBViewDef = [ + ["activeTab", 0, "int"], + ["autoFilterDateGrouping", true, "bool"], + ["firstSheet", 0, "int"], + ["minimized", false, "bool"], + ["showHorizontalScroll", true, "bool"], + ["showSheetTabs", true, "bool"], + ["showVerticalScroll", true, "bool"], + ["tabRatio", 600, "int"], + ["visibility", "visible"] + //window{Height,Width}, {x,y}Window + ]; + SheetDef = [ + //['state', 'visible'] + ]; + CalcPrDef = [ + ["calcCompleted", "true"], + ["calcMode", "auto"], + ["calcOnSave", "true"], + ["concurrentCalc", "true"], + ["fullCalcOnLoad", "false"], + ["fullPrecision", "true"], + ["iterate", "false"], + ["iterateCount", "100"], + ["iterateDelta", "0.001"], + ["refMode", "A1"] + ]; + badchars = /* @__PURE__ */ ":][*?/\\".split(""); + wbnsregex = /<\w+:workbook/; + attregexg2 = /\b((?:\w+:)?[\w]+)=((?:")([^"]*)(?:")|(?:')([^']*)(?:'))/g; + attregex2 = /\b((?:\w+:)?[\w]+)=((?:")(?:[^"]*)(?:")|(?:')(?:[^']*)(?:'))/; + CONTINUE_RT = [60, 1084, 2066, 2165, 2175]; + PSCLSID = { + SI: "e0859ff2f94f6810ab9108002b27b3d9", + DSI: "02d5cdd59c2e1b10939708002b2cf9ae", + UDI: "05d5cdd59c2e1b10939708002b2cf9ae" + }; + XLSBRecordEnum = { + 0: { + /* n:"BrtRowHdr", */ + f: parse_BrtRowHdr + }, + 1: { + /* n:"BrtCellBlank", */ + f: parse_BrtCellBlank + }, + 2: { + /* n:"BrtCellRk", */ + f: parse_BrtCellRk + }, + 3: { + /* n:"BrtCellError", */ + f: parse_BrtCellError + }, + 4: { + /* n:"BrtCellBool", */ + f: parse_BrtCellBool + }, + 5: { + /* n:"BrtCellReal", */ + f: parse_BrtCellReal + }, + 6: { + /* n:"BrtCellSt", */ + f: parse_BrtCellSt + }, + 7: { + /* n:"BrtCellIsst", */ + f: parse_BrtCellIsst + }, + 8: { + /* n:"BrtFmlaString", */ + f: parse_BrtFmlaString + }, + 9: { + /* n:"BrtFmlaNum", */ + f: parse_BrtFmlaNum + }, + 10: { + /* n:"BrtFmlaBool", */ + f: parse_BrtFmlaBool + }, + 11: { + /* n:"BrtFmlaError", */ + f: parse_BrtFmlaError + }, + 12: { + /* n:"BrtShortBlank", */ + f: parse_BrtShortBlank + }, + 13: { + /* n:"BrtShortRk", */ + f: parse_BrtShortRk + }, + 14: { + /* n:"BrtShortError", */ + f: parse_BrtShortError + }, + 15: { + /* n:"BrtShortBool", */ + f: parse_BrtShortBool + }, + 16: { + /* n:"BrtShortReal", */ + f: parse_BrtShortReal + }, + 17: { + /* n:"BrtShortSt", */ + f: parse_BrtShortSt + }, + 18: { + /* n:"BrtShortIsst", */ + f: parse_BrtShortIsst + }, + 19: { + /* n:"BrtSSTItem", */ + f: parse_RichStr + }, + 20: { + /* n:"BrtPCDIMissing" */ + }, + 21: { + /* n:"BrtPCDINumber" */ + }, + 22: { + /* n:"BrtPCDIBoolean" */ + }, + 23: { + /* n:"BrtPCDIError" */ + }, + 24: { + /* n:"BrtPCDIString" */ + }, + 25: { + /* n:"BrtPCDIDatetime" */ + }, + 26: { + /* n:"BrtPCDIIndex" */ + }, + 27: { + /* n:"BrtPCDIAMissing" */ + }, + 28: { + /* n:"BrtPCDIANumber" */ + }, + 29: { + /* n:"BrtPCDIABoolean" */ + }, + 30: { + /* n:"BrtPCDIAError" */ + }, + 31: { + /* n:"BrtPCDIAString" */ + }, + 32: { + /* n:"BrtPCDIADatetime" */ + }, + 33: { + /* n:"BrtPCRRecord" */ + }, + 34: { + /* n:"BrtPCRRecordDt" */ + }, + 35: { + /* n:"BrtFRTBegin", */ + T: 1 + }, + 36: { + /* n:"BrtFRTEnd", */ + T: -1 + }, + 37: { + /* n:"BrtACBegin", */ + T: 1 + }, + 38: { + /* n:"BrtACEnd", */ + T: -1 + }, + 39: { + /* n:"BrtName", */ + f: parse_BrtName + }, + 40: { + /* n:"BrtIndexRowBlock" */ + }, + 42: { + /* n:"BrtIndexBlock" */ + }, + 43: { + /* n:"BrtFont", */ + f: parse_BrtFont + }, + 44: { + /* n:"BrtFmt", */ + f: parse_BrtFmt + }, + 45: { + /* n:"BrtFill", */ + f: parse_BrtFill + }, + 46: { + /* n:"BrtBorder", */ + f: parse_BrtBorder + }, + 47: { + /* n:"BrtXF", */ + f: parse_BrtXF + }, + 48: { + /* n:"BrtStyle" */ + }, + 49: { + /* n:"BrtCellMeta", */ + f: parse_Int32LE + }, + 50: { + /* n:"BrtValueMeta" */ + }, + 51: { + /* n:"BrtMdb" */ + f: parse_BrtMdb + }, + 52: { + /* n:"BrtBeginFmd", */ + T: 1 + }, + 53: { + /* n:"BrtEndFmd", */ + T: -1 + }, + 54: { + /* n:"BrtBeginMdx", */ + T: 1 + }, + 55: { + /* n:"BrtEndMdx", */ + T: -1 + }, + 56: { + /* n:"BrtBeginMdxTuple", */ + T: 1 + }, + 57: { + /* n:"BrtEndMdxTuple", */ + T: -1 + }, + 58: { + /* n:"BrtMdxMbrIstr" */ + }, + 59: { + /* n:"BrtStr" */ + }, + 60: { + /* n:"BrtColInfo", */ + f: parse_ColInfo + }, + 62: { + /* n:"BrtCellRString", */ + f: parse_BrtCellRString + }, + 63: { + /* n:"BrtCalcChainItem$", */ + f: parse_BrtCalcChainItem$ + }, + 64: { + /* n:"BrtDVal", */ + f: parse_BrtDVal + }, + 65: { + /* n:"BrtSxvcellNum" */ + }, + 66: { + /* n:"BrtSxvcellStr" */ + }, + 67: { + /* n:"BrtSxvcellBool" */ + }, + 68: { + /* n:"BrtSxvcellErr" */ + }, + 69: { + /* n:"BrtSxvcellDate" */ + }, + 70: { + /* n:"BrtSxvcellNil" */ + }, + 128: { + /* n:"BrtFileVersion" */ + }, + 129: { + /* n:"BrtBeginSheet", */ + T: 1 + }, + 130: { + /* n:"BrtEndSheet", */ + T: -1 + }, + 131: { + /* n:"BrtBeginBook", */ + T: 1, + f: parsenoop, + p: 0 + }, + 132: { + /* n:"BrtEndBook", */ + T: -1 + }, + 133: { + /* n:"BrtBeginWsViews", */ + T: 1 + }, + 134: { + /* n:"BrtEndWsViews", */ + T: -1 + }, + 135: { + /* n:"BrtBeginBookViews", */ + T: 1 + }, + 136: { + /* n:"BrtEndBookViews", */ + T: -1 + }, + 137: { + /* n:"BrtBeginWsView", */ + T: 1, + f: parse_BrtBeginWsView + }, + 138: { + /* n:"BrtEndWsView", */ + T: -1 + }, + 139: { + /* n:"BrtBeginCsViews", */ + T: 1 + }, + 140: { + /* n:"BrtEndCsViews", */ + T: -1 + }, + 141: { + /* n:"BrtBeginCsView", */ + T: 1 + }, + 142: { + /* n:"BrtEndCsView", */ + T: -1 + }, + 143: { + /* n:"BrtBeginBundleShs", */ + T: 1 + }, + 144: { + /* n:"BrtEndBundleShs", */ + T: -1 + }, + 145: { + /* n:"BrtBeginSheetData", */ + T: 1 + }, + 146: { + /* n:"BrtEndSheetData", */ + T: -1 + }, + 147: { + /* n:"BrtWsProp", */ + f: parse_BrtWsProp + }, + 148: { + /* n:"BrtWsDim", */ + f: parse_BrtWsDim, + p: 16 + }, + 151: { + /* n:"BrtPane", */ + f: parse_BrtPane + }, + 152: { + /* n:"BrtSel" */ + }, + 153: { + /* n:"BrtWbProp", */ + f: parse_BrtWbProp + }, + 154: { + /* n:"BrtWbFactoid" */ + }, + 155: { + /* n:"BrtFileRecover" */ + }, + 156: { + /* n:"BrtBundleSh", */ + f: parse_BrtBundleSh + }, + 157: { + /* n:"BrtCalcProp" */ + }, + 158: { + /* n:"BrtBookView" */ + }, + 159: { + /* n:"BrtBeginSst", */ + T: 1, + f: parse_BrtBeginSst + }, + 160: { + /* n:"BrtEndSst", */ + T: -1 + }, + 161: { + /* n:"BrtBeginAFilter", */ + T: 1, + f: parse_UncheckedRfX + }, + 162: { + /* n:"BrtEndAFilter", */ + T: -1 + }, + 163: { + /* n:"BrtBeginFilterColumn", */ + T: 1 + }, + 164: { + /* n:"BrtEndFilterColumn", */ + T: -1 + }, + 165: { + /* n:"BrtBeginFilters", */ + T: 1 + }, + 166: { + /* n:"BrtEndFilters", */ + T: -1 + }, + 167: { + /* n:"BrtFilter" */ + }, + 168: { + /* n:"BrtColorFilter" */ + }, + 169: { + /* n:"BrtIconFilter" */ + }, + 170: { + /* n:"BrtTop10Filter" */ + }, + 171: { + /* n:"BrtDynamicFilter" */ + }, + 172: { + /* n:"BrtBeginCustomFilters", */ + T: 1 + }, + 173: { + /* n:"BrtEndCustomFilters", */ + T: -1 + }, + 174: { + /* n:"BrtCustomFilter" */ + }, + 175: { + /* n:"BrtAFilterDateGroupItem" */ + }, + 176: { + /* n:"BrtMergeCell", */ + f: parse_BrtMergeCell + }, + 177: { + /* n:"BrtBeginMergeCells", */ + T: 1 + }, + 178: { + /* n:"BrtEndMergeCells", */ + T: -1 + }, + 179: { + /* n:"BrtBeginPivotCacheDef", */ + T: 1 + }, + 180: { + /* n:"BrtEndPivotCacheDef", */ + T: -1 + }, + 181: { + /* n:"BrtBeginPCDFields", */ + T: 1 + }, + 182: { + /* n:"BrtEndPCDFields", */ + T: -1 + }, + 183: { + /* n:"BrtBeginPCDField", */ + T: 1 + }, + 184: { + /* n:"BrtEndPCDField", */ + T: -1 + }, + 185: { + /* n:"BrtBeginPCDSource", */ + T: 1 + }, + 186: { + /* n:"BrtEndPCDSource", */ + T: -1 + }, + 187: { + /* n:"BrtBeginPCDSRange", */ + T: 1 + }, + 188: { + /* n:"BrtEndPCDSRange", */ + T: -1 + }, + 189: { + /* n:"BrtBeginPCDFAtbl", */ + T: 1 + }, + 190: { + /* n:"BrtEndPCDFAtbl", */ + T: -1 + }, + 191: { + /* n:"BrtBeginPCDIRun", */ + T: 1 + }, + 192: { + /* n:"BrtEndPCDIRun", */ + T: -1 + }, + 193: { + /* n:"BrtBeginPivotCacheRecords", */ + T: 1 + }, + 194: { + /* n:"BrtEndPivotCacheRecords", */ + T: -1 + }, + 195: { + /* n:"BrtBeginPCDHierarchies", */ + T: 1 + }, + 196: { + /* n:"BrtEndPCDHierarchies", */ + T: -1 + }, + 197: { + /* n:"BrtBeginPCDHierarchy", */ + T: 1 + }, + 198: { + /* n:"BrtEndPCDHierarchy", */ + T: -1 + }, + 199: { + /* n:"BrtBeginPCDHFieldsUsage", */ + T: 1 + }, + 200: { + /* n:"BrtEndPCDHFieldsUsage", */ + T: -1 + }, + 201: { + /* n:"BrtBeginExtConnection", */ + T: 1 + }, + 202: { + /* n:"BrtEndExtConnection", */ + T: -1 + }, + 203: { + /* n:"BrtBeginECDbProps", */ + T: 1 + }, + 204: { + /* n:"BrtEndECDbProps", */ + T: -1 + }, + 205: { + /* n:"BrtBeginECOlapProps", */ + T: 1 + }, + 206: { + /* n:"BrtEndECOlapProps", */ + T: -1 + }, + 207: { + /* n:"BrtBeginPCDSConsol", */ + T: 1 + }, + 208: { + /* n:"BrtEndPCDSConsol", */ + T: -1 + }, + 209: { + /* n:"BrtBeginPCDSCPages", */ + T: 1 + }, + 210: { + /* n:"BrtEndPCDSCPages", */ + T: -1 + }, + 211: { + /* n:"BrtBeginPCDSCPage", */ + T: 1 + }, + 212: { + /* n:"BrtEndPCDSCPage", */ + T: -1 + }, + 213: { + /* n:"BrtBeginPCDSCPItem", */ + T: 1 + }, + 214: { + /* n:"BrtEndPCDSCPItem", */ + T: -1 + }, + 215: { + /* n:"BrtBeginPCDSCSets", */ + T: 1 + }, + 216: { + /* n:"BrtEndPCDSCSets", */ + T: -1 + }, + 217: { + /* n:"BrtBeginPCDSCSet", */ + T: 1 + }, + 218: { + /* n:"BrtEndPCDSCSet", */ + T: -1 + }, + 219: { + /* n:"BrtBeginPCDFGroup", */ + T: 1 + }, + 220: { + /* n:"BrtEndPCDFGroup", */ + T: -1 + }, + 221: { + /* n:"BrtBeginPCDFGItems", */ + T: 1 + }, + 222: { + /* n:"BrtEndPCDFGItems", */ + T: -1 + }, + 223: { + /* n:"BrtBeginPCDFGRange", */ + T: 1 + }, + 224: { + /* n:"BrtEndPCDFGRange", */ + T: -1 + }, + 225: { + /* n:"BrtBeginPCDFGDiscrete", */ + T: 1 + }, + 226: { + /* n:"BrtEndPCDFGDiscrete", */ + T: -1 + }, + 227: { + /* n:"BrtBeginPCDSDTupleCache", */ + T: 1 + }, + 228: { + /* n:"BrtEndPCDSDTupleCache", */ + T: -1 + }, + 229: { + /* n:"BrtBeginPCDSDTCEntries", */ + T: 1 + }, + 230: { + /* n:"BrtEndPCDSDTCEntries", */ + T: -1 + }, + 231: { + /* n:"BrtBeginPCDSDTCEMembers", */ + T: 1 + }, + 232: { + /* n:"BrtEndPCDSDTCEMembers", */ + T: -1 + }, + 233: { + /* n:"BrtBeginPCDSDTCEMember", */ + T: 1 + }, + 234: { + /* n:"BrtEndPCDSDTCEMember", */ + T: -1 + }, + 235: { + /* n:"BrtBeginPCDSDTCQueries", */ + T: 1 + }, + 236: { + /* n:"BrtEndPCDSDTCQueries", */ + T: -1 + }, + 237: { + /* n:"BrtBeginPCDSDTCQuery", */ + T: 1 + }, + 238: { + /* n:"BrtEndPCDSDTCQuery", */ + T: -1 + }, + 239: { + /* n:"BrtBeginPCDSDTCSets", */ + T: 1 + }, + 240: { + /* n:"BrtEndPCDSDTCSets", */ + T: -1 + }, + 241: { + /* n:"BrtBeginPCDSDTCSet", */ + T: 1 + }, + 242: { + /* n:"BrtEndPCDSDTCSet", */ + T: -1 + }, + 243: { + /* n:"BrtBeginPCDCalcItems", */ + T: 1 + }, + 244: { + /* n:"BrtEndPCDCalcItems", */ + T: -1 + }, + 245: { + /* n:"BrtBeginPCDCalcItem", */ + T: 1 + }, + 246: { + /* n:"BrtEndPCDCalcItem", */ + T: -1 + }, + 247: { + /* n:"BrtBeginPRule", */ + T: 1 + }, + 248: { + /* n:"BrtEndPRule", */ + T: -1 + }, + 249: { + /* n:"BrtBeginPRFilters", */ + T: 1 + }, + 250: { + /* n:"BrtEndPRFilters", */ + T: -1 + }, + 251: { + /* n:"BrtBeginPRFilter", */ + T: 1 + }, + 252: { + /* n:"BrtEndPRFilter", */ + T: -1 + }, + 253: { + /* n:"BrtBeginPNames", */ + T: 1 + }, + 254: { + /* n:"BrtEndPNames", */ + T: -1 + }, + 255: { + /* n:"BrtBeginPName", */ + T: 1 + }, + 256: { + /* n:"BrtEndPName", */ + T: -1 + }, + 257: { + /* n:"BrtBeginPNPairs", */ + T: 1 + }, + 258: { + /* n:"BrtEndPNPairs", */ + T: -1 + }, + 259: { + /* n:"BrtBeginPNPair", */ + T: 1 + }, + 260: { + /* n:"BrtEndPNPair", */ + T: -1 + }, + 261: { + /* n:"BrtBeginECWebProps", */ + T: 1 + }, + 262: { + /* n:"BrtEndECWebProps", */ + T: -1 + }, + 263: { + /* n:"BrtBeginEcWpTables", */ + T: 1 + }, + 264: { + /* n:"BrtEndECWPTables", */ + T: -1 + }, + 265: { + /* n:"BrtBeginECParams", */ + T: 1 + }, + 266: { + /* n:"BrtEndECParams", */ + T: -1 + }, + 267: { + /* n:"BrtBeginECParam", */ + T: 1 + }, + 268: { + /* n:"BrtEndECParam", */ + T: -1 + }, + 269: { + /* n:"BrtBeginPCDKPIs", */ + T: 1 + }, + 270: { + /* n:"BrtEndPCDKPIs", */ + T: -1 + }, + 271: { + /* n:"BrtBeginPCDKPI", */ + T: 1 + }, + 272: { + /* n:"BrtEndPCDKPI", */ + T: -1 + }, + 273: { + /* n:"BrtBeginDims", */ + T: 1 + }, + 274: { + /* n:"BrtEndDims", */ + T: -1 + }, + 275: { + /* n:"BrtBeginDim", */ + T: 1 + }, + 276: { + /* n:"BrtEndDim", */ + T: -1 + }, + 277: { + /* n:"BrtIndexPartEnd" */ + }, + 278: { + /* n:"BrtBeginStyleSheet", */ + T: 1 + }, + 279: { + /* n:"BrtEndStyleSheet", */ + T: -1 + }, + 280: { + /* n:"BrtBeginSXView", */ + T: 1 + }, + 281: { + /* n:"BrtEndSXVI", */ + T: -1 + }, + 282: { + /* n:"BrtBeginSXVI", */ + T: 1 + }, + 283: { + /* n:"BrtBeginSXVIs", */ + T: 1 + }, + 284: { + /* n:"BrtEndSXVIs", */ + T: -1 + }, + 285: { + /* n:"BrtBeginSXVD", */ + T: 1 + }, + 286: { + /* n:"BrtEndSXVD", */ + T: -1 + }, + 287: { + /* n:"BrtBeginSXVDs", */ + T: 1 + }, + 288: { + /* n:"BrtEndSXVDs", */ + T: -1 + }, + 289: { + /* n:"BrtBeginSXPI", */ + T: 1 + }, + 290: { + /* n:"BrtEndSXPI", */ + T: -1 + }, + 291: { + /* n:"BrtBeginSXPIs", */ + T: 1 + }, + 292: { + /* n:"BrtEndSXPIs", */ + T: -1 + }, + 293: { + /* n:"BrtBeginSXDI", */ + T: 1 + }, + 294: { + /* n:"BrtEndSXDI", */ + T: -1 + }, + 295: { + /* n:"BrtBeginSXDIs", */ + T: 1 + }, + 296: { + /* n:"BrtEndSXDIs", */ + T: -1 + }, + 297: { + /* n:"BrtBeginSXLI", */ + T: 1 + }, + 298: { + /* n:"BrtEndSXLI", */ + T: -1 + }, + 299: { + /* n:"BrtBeginSXLIRws", */ + T: 1 + }, + 300: { + /* n:"BrtEndSXLIRws", */ + T: -1 + }, + 301: { + /* n:"BrtBeginSXLICols", */ + T: 1 + }, + 302: { + /* n:"BrtEndSXLICols", */ + T: -1 + }, + 303: { + /* n:"BrtBeginSXFormat", */ + T: 1 + }, + 304: { + /* n:"BrtEndSXFormat", */ + T: -1 + }, + 305: { + /* n:"BrtBeginSXFormats", */ + T: 1 + }, + 306: { + /* n:"BrtEndSxFormats", */ + T: -1 + }, + 307: { + /* n:"BrtBeginSxSelect", */ + T: 1 + }, + 308: { + /* n:"BrtEndSxSelect", */ + T: -1 + }, + 309: { + /* n:"BrtBeginISXVDRws", */ + T: 1 + }, + 310: { + /* n:"BrtEndISXVDRws", */ + T: -1 + }, + 311: { + /* n:"BrtBeginISXVDCols", */ + T: 1 + }, + 312: { + /* n:"BrtEndISXVDCols", */ + T: -1 + }, + 313: { + /* n:"BrtEndSXLocation", */ + T: -1 + }, + 314: { + /* n:"BrtBeginSXLocation", */ + T: 1 + }, + 315: { + /* n:"BrtEndSXView", */ + T: -1 + }, + 316: { + /* n:"BrtBeginSXTHs", */ + T: 1 + }, + 317: { + /* n:"BrtEndSXTHs", */ + T: -1 + }, + 318: { + /* n:"BrtBeginSXTH", */ + T: 1 + }, + 319: { + /* n:"BrtEndSXTH", */ + T: -1 + }, + 320: { + /* n:"BrtBeginISXTHRws", */ + T: 1 + }, + 321: { + /* n:"BrtEndISXTHRws", */ + T: -1 + }, + 322: { + /* n:"BrtBeginISXTHCols", */ + T: 1 + }, + 323: { + /* n:"BrtEndISXTHCols", */ + T: -1 + }, + 324: { + /* n:"BrtBeginSXTDMPS", */ + T: 1 + }, + 325: { + /* n:"BrtEndSXTDMPs", */ + T: -1 + }, + 326: { + /* n:"BrtBeginSXTDMP", */ + T: 1 + }, + 327: { + /* n:"BrtEndSXTDMP", */ + T: -1 + }, + 328: { + /* n:"BrtBeginSXTHItems", */ + T: 1 + }, + 329: { + /* n:"BrtEndSXTHItems", */ + T: -1 + }, + 330: { + /* n:"BrtBeginSXTHItem", */ + T: 1 + }, + 331: { + /* n:"BrtEndSXTHItem", */ + T: -1 + }, + 332: { + /* n:"BrtBeginMetadata", */ + T: 1 + }, + 333: { + /* n:"BrtEndMetadata", */ + T: -1 + }, + 334: { + /* n:"BrtBeginEsmdtinfo", */ + T: 1 + }, + 335: { + /* n:"BrtMdtinfo", */ + f: parse_BrtMdtinfo + }, + 336: { + /* n:"BrtEndEsmdtinfo", */ + T: -1 + }, + 337: { + /* n:"BrtBeginEsmdb", */ + f: parse_BrtBeginEsmdb, + T: 1 + }, + 338: { + /* n:"BrtEndEsmdb", */ + T: -1 + }, + 339: { + /* n:"BrtBeginEsfmd", */ + T: 1 + }, + 340: { + /* n:"BrtEndEsfmd", */ + T: -1 + }, + 341: { + /* n:"BrtBeginSingleCells", */ + T: 1 + }, + 342: { + /* n:"BrtEndSingleCells", */ + T: -1 + }, + 343: { + /* n:"BrtBeginList", */ + T: 1 + }, + 344: { + /* n:"BrtEndList", */ + T: -1 + }, + 345: { + /* n:"BrtBeginListCols", */ + T: 1 + }, + 346: { + /* n:"BrtEndListCols", */ + T: -1 + }, + 347: { + /* n:"BrtBeginListCol", */ + T: 1 + }, + 348: { + /* n:"BrtEndListCol", */ + T: -1 + }, + 349: { + /* n:"BrtBeginListXmlCPr", */ + T: 1 + }, + 350: { + /* n:"BrtEndListXmlCPr", */ + T: -1 + }, + 351: { + /* n:"BrtListCCFmla" */ + }, + 352: { + /* n:"BrtListTrFmla" */ + }, + 353: { + /* n:"BrtBeginExternals", */ + T: 1 + }, + 354: { + /* n:"BrtEndExternals", */ + T: -1 + }, + 355: { + /* n:"BrtSupBookSrc", */ + f: parse_RelID + }, + 357: { + /* n:"BrtSupSelf" */ + }, + 358: { + /* n:"BrtSupSame" */ + }, + 359: { + /* n:"BrtSupTabs" */ + }, + 360: { + /* n:"BrtBeginSupBook", */ + T: 1 + }, + 361: { + /* n:"BrtPlaceholderName" */ + }, + 362: { + /* n:"BrtExternSheet", */ + f: parse_ExternSheet + }, + 363: { + /* n:"BrtExternTableStart" */ + }, + 364: { + /* n:"BrtExternTableEnd" */ + }, + 366: { + /* n:"BrtExternRowHdr" */ + }, + 367: { + /* n:"BrtExternCellBlank" */ + }, + 368: { + /* n:"BrtExternCellReal" */ + }, + 369: { + /* n:"BrtExternCellBool" */ + }, + 370: { + /* n:"BrtExternCellError" */ + }, + 371: { + /* n:"BrtExternCellString" */ + }, + 372: { + /* n:"BrtBeginEsmdx", */ + T: 1 + }, + 373: { + /* n:"BrtEndEsmdx", */ + T: -1 + }, + 374: { + /* n:"BrtBeginMdxSet", */ + T: 1 + }, + 375: { + /* n:"BrtEndMdxSet", */ + T: -1 + }, + 376: { + /* n:"BrtBeginMdxMbrProp", */ + T: 1 + }, + 377: { + /* n:"BrtEndMdxMbrProp", */ + T: -1 + }, + 378: { + /* n:"BrtBeginMdxKPI", */ + T: 1 + }, + 379: { + /* n:"BrtEndMdxKPI", */ + T: -1 + }, + 380: { + /* n:"BrtBeginEsstr", */ + T: 1 + }, + 381: { + /* n:"BrtEndEsstr", */ + T: -1 + }, + 382: { + /* n:"BrtBeginPRFItem", */ + T: 1 + }, + 383: { + /* n:"BrtEndPRFItem", */ + T: -1 + }, + 384: { + /* n:"BrtBeginPivotCacheIDs", */ + T: 1 + }, + 385: { + /* n:"BrtEndPivotCacheIDs", */ + T: -1 + }, + 386: { + /* n:"BrtBeginPivotCacheID", */ + T: 1 + }, + 387: { + /* n:"BrtEndPivotCacheID", */ + T: -1 + }, + 388: { + /* n:"BrtBeginISXVIs", */ + T: 1 + }, + 389: { + /* n:"BrtEndISXVIs", */ + T: -1 + }, + 390: { + /* n:"BrtBeginColInfos", */ + T: 1 + }, + 391: { + /* n:"BrtEndColInfos", */ + T: -1 + }, + 392: { + /* n:"BrtBeginRwBrk", */ + T: 1 + }, + 393: { + /* n:"BrtEndRwBrk", */ + T: -1 + }, + 394: { + /* n:"BrtBeginColBrk", */ + T: 1 + }, + 395: { + /* n:"BrtEndColBrk", */ + T: -1 + }, + 396: { + /* n:"BrtBrk" */ + }, + 397: { + /* n:"BrtUserBookView" */ + }, + 398: { + /* n:"BrtInfo" */ + }, + 399: { + /* n:"BrtCUsr" */ + }, + 400: { + /* n:"BrtUsr" */ + }, + 401: { + /* n:"BrtBeginUsers", */ + T: 1 + }, + 403: { + /* n:"BrtEOF" */ + }, + 404: { + /* n:"BrtUCR" */ + }, + 405: { + /* n:"BrtRRInsDel" */ + }, + 406: { + /* n:"BrtRREndInsDel" */ + }, + 407: { + /* n:"BrtRRMove" */ + }, + 408: { + /* n:"BrtRREndMove" */ + }, + 409: { + /* n:"BrtRRChgCell" */ + }, + 410: { + /* n:"BrtRREndChgCell" */ + }, + 411: { + /* n:"BrtRRHeader" */ + }, + 412: { + /* n:"BrtRRUserView" */ + }, + 413: { + /* n:"BrtRRRenSheet" */ + }, + 414: { + /* n:"BrtRRInsertSh" */ + }, + 415: { + /* n:"BrtRRDefName" */ + }, + 416: { + /* n:"BrtRRNote" */ + }, + 417: { + /* n:"BrtRRConflict" */ + }, + 418: { + /* n:"BrtRRTQSIF" */ + }, + 419: { + /* n:"BrtRRFormat" */ + }, + 420: { + /* n:"BrtRREndFormat" */ + }, + 421: { + /* n:"BrtRRAutoFmt" */ + }, + 422: { + /* n:"BrtBeginUserShViews", */ + T: 1 + }, + 423: { + /* n:"BrtBeginUserShView", */ + T: 1 + }, + 424: { + /* n:"BrtEndUserShView", */ + T: -1 + }, + 425: { + /* n:"BrtEndUserShViews", */ + T: -1 + }, + 426: { + /* n:"BrtArrFmla", */ + f: parse_BrtArrFmla + }, + 427: { + /* n:"BrtShrFmla", */ + f: parse_BrtShrFmla + }, + 428: { + /* n:"BrtTable" */ + }, + 429: { + /* n:"BrtBeginExtConnections", */ + T: 1 + }, + 430: { + /* n:"BrtEndExtConnections", */ + T: -1 + }, + 431: { + /* n:"BrtBeginPCDCalcMems", */ + T: 1 + }, + 432: { + /* n:"BrtEndPCDCalcMems", */ + T: -1 + }, + 433: { + /* n:"BrtBeginPCDCalcMem", */ + T: 1 + }, + 434: { + /* n:"BrtEndPCDCalcMem", */ + T: -1 + }, + 435: { + /* n:"BrtBeginPCDHGLevels", */ + T: 1 + }, + 436: { + /* n:"BrtEndPCDHGLevels", */ + T: -1 + }, + 437: { + /* n:"BrtBeginPCDHGLevel", */ + T: 1 + }, + 438: { + /* n:"BrtEndPCDHGLevel", */ + T: -1 + }, + 439: { + /* n:"BrtBeginPCDHGLGroups", */ + T: 1 + }, + 440: { + /* n:"BrtEndPCDHGLGroups", */ + T: -1 + }, + 441: { + /* n:"BrtBeginPCDHGLGroup", */ + T: 1 + }, + 442: { + /* n:"BrtEndPCDHGLGroup", */ + T: -1 + }, + 443: { + /* n:"BrtBeginPCDHGLGMembers", */ + T: 1 + }, + 444: { + /* n:"BrtEndPCDHGLGMembers", */ + T: -1 + }, + 445: { + /* n:"BrtBeginPCDHGLGMember", */ + T: 1 + }, + 446: { + /* n:"BrtEndPCDHGLGMember", */ + T: -1 + }, + 447: { + /* n:"BrtBeginQSI", */ + T: 1 + }, + 448: { + /* n:"BrtEndQSI", */ + T: -1 + }, + 449: { + /* n:"BrtBeginQSIR", */ + T: 1 + }, + 450: { + /* n:"BrtEndQSIR", */ + T: -1 + }, + 451: { + /* n:"BrtBeginDeletedNames", */ + T: 1 + }, + 452: { + /* n:"BrtEndDeletedNames", */ + T: -1 + }, + 453: { + /* n:"BrtBeginDeletedName", */ + T: 1 + }, + 454: { + /* n:"BrtEndDeletedName", */ + T: -1 + }, + 455: { + /* n:"BrtBeginQSIFs", */ + T: 1 + }, + 456: { + /* n:"BrtEndQSIFs", */ + T: -1 + }, + 457: { + /* n:"BrtBeginQSIF", */ + T: 1 + }, + 458: { + /* n:"BrtEndQSIF", */ + T: -1 + }, + 459: { + /* n:"BrtBeginAutoSortScope", */ + T: 1 + }, + 460: { + /* n:"BrtEndAutoSortScope", */ + T: -1 + }, + 461: { + /* n:"BrtBeginConditionalFormatting", */ + T: 1 + }, + 462: { + /* n:"BrtEndConditionalFormatting", */ + T: -1 + }, + 463: { + /* n:"BrtBeginCFRule", */ + T: 1 + }, + 464: { + /* n:"BrtEndCFRule", */ + T: -1 + }, + 465: { + /* n:"BrtBeginIconSet", */ + T: 1 + }, + 466: { + /* n:"BrtEndIconSet", */ + T: -1 + }, + 467: { + /* n:"BrtBeginDatabar", */ + T: 1 + }, + 468: { + /* n:"BrtEndDatabar", */ + T: -1 + }, + 469: { + /* n:"BrtBeginColorScale", */ + T: 1 + }, + 470: { + /* n:"BrtEndColorScale", */ + T: -1 + }, + 471: { + /* n:"BrtCFVO" */ + }, + 472: { + /* n:"BrtExternValueMeta" */ + }, + 473: { + /* n:"BrtBeginColorPalette", */ + T: 1 + }, + 474: { + /* n:"BrtEndColorPalette", */ + T: -1 + }, + 475: { + /* n:"BrtIndexedColor" */ + }, + 476: { + /* n:"BrtMargins", */ + f: parse_BrtMargins + }, + 477: { + /* n:"BrtPrintOptions" */ + }, + 478: { + /* n:"BrtPageSetup" */ + }, + 479: { + /* n:"BrtBeginHeaderFooter", */ + T: 1 + }, + 480: { + /* n:"BrtEndHeaderFooter", */ + T: -1 + }, + 481: { + /* n:"BrtBeginSXCrtFormat", */ + T: 1 + }, + 482: { + /* n:"BrtEndSXCrtFormat", */ + T: -1 + }, + 483: { + /* n:"BrtBeginSXCrtFormats", */ + T: 1 + }, + 484: { + /* n:"BrtEndSXCrtFormats", */ + T: -1 + }, + 485: { + /* n:"BrtWsFmtInfo", */ + f: parse_BrtWsFmtInfo + }, + 486: { + /* n:"BrtBeginMgs", */ + T: 1 + }, + 487: { + /* n:"BrtEndMGs", */ + T: -1 + }, + 488: { + /* n:"BrtBeginMGMaps", */ + T: 1 + }, + 489: { + /* n:"BrtEndMGMaps", */ + T: -1 + }, + 490: { + /* n:"BrtBeginMG", */ + T: 1 + }, + 491: { + /* n:"BrtEndMG", */ + T: -1 + }, + 492: { + /* n:"BrtBeginMap", */ + T: 1 + }, + 493: { + /* n:"BrtEndMap", */ + T: -1 + }, + 494: { + /* n:"BrtHLink", */ + f: parse_BrtHLink + }, + 495: { + /* n:"BrtBeginDCon", */ + T: 1 + }, + 496: { + /* n:"BrtEndDCon", */ + T: -1 + }, + 497: { + /* n:"BrtBeginDRefs", */ + T: 1 + }, + 498: { + /* n:"BrtEndDRefs", */ + T: -1 + }, + 499: { + /* n:"BrtDRef" */ + }, + 500: { + /* n:"BrtBeginScenMan", */ + T: 1 + }, + 501: { + /* n:"BrtEndScenMan", */ + T: -1 + }, + 502: { + /* n:"BrtBeginSct", */ + T: 1 + }, + 503: { + /* n:"BrtEndSct", */ + T: -1 + }, + 504: { + /* n:"BrtSlc" */ + }, + 505: { + /* n:"BrtBeginDXFs", */ + T: 1 + }, + 506: { + /* n:"BrtEndDXFs", */ + T: -1 + }, + 507: { + /* n:"BrtDXF" */ + }, + 508: { + /* n:"BrtBeginTableStyles", */ + T: 1 + }, + 509: { + /* n:"BrtEndTableStyles", */ + T: -1 + }, + 510: { + /* n:"BrtBeginTableStyle", */ + T: 1 + }, + 511: { + /* n:"BrtEndTableStyle", */ + T: -1 + }, + 512: { + /* n:"BrtTableStyleElement" */ + }, + 513: { + /* n:"BrtTableStyleClient" */ + }, + 514: { + /* n:"BrtBeginVolDeps", */ + T: 1 + }, + 515: { + /* n:"BrtEndVolDeps", */ + T: -1 + }, + 516: { + /* n:"BrtBeginVolType", */ + T: 1 + }, + 517: { + /* n:"BrtEndVolType", */ + T: -1 + }, + 518: { + /* n:"BrtBeginVolMain", */ + T: 1 + }, + 519: { + /* n:"BrtEndVolMain", */ + T: -1 + }, + 520: { + /* n:"BrtBeginVolTopic", */ + T: 1 + }, + 521: { + /* n:"BrtEndVolTopic", */ + T: -1 + }, + 522: { + /* n:"BrtVolSubtopic" */ + }, + 523: { + /* n:"BrtVolRef" */ + }, + 524: { + /* n:"BrtVolNum" */ + }, + 525: { + /* n:"BrtVolErr" */ + }, + 526: { + /* n:"BrtVolStr" */ + }, + 527: { + /* n:"BrtVolBool" */ + }, + 528: { + /* n:"BrtBeginCalcChain$", */ + T: 1 + }, + 529: { + /* n:"BrtEndCalcChain$", */ + T: -1 + }, + 530: { + /* n:"BrtBeginSortState", */ + T: 1 + }, + 531: { + /* n:"BrtEndSortState", */ + T: -1 + }, + 532: { + /* n:"BrtBeginSortCond", */ + T: 1 + }, + 533: { + /* n:"BrtEndSortCond", */ + T: -1 + }, + 534: { + /* n:"BrtBookProtection" */ + }, + 535: { + /* n:"BrtSheetProtection" */ + }, + 536: { + /* n:"BrtRangeProtection" */ + }, + 537: { + /* n:"BrtPhoneticInfo" */ + }, + 538: { + /* n:"BrtBeginECTxtWiz", */ + T: 1 + }, + 539: { + /* n:"BrtEndECTxtWiz", */ + T: -1 + }, + 540: { + /* n:"BrtBeginECTWFldInfoLst", */ + T: 1 + }, + 541: { + /* n:"BrtEndECTWFldInfoLst", */ + T: -1 + }, + 542: { + /* n:"BrtBeginECTwFldInfo", */ + T: 1 + }, + 548: { + /* n:"BrtFileSharing" */ + }, + 549: { + /* n:"BrtOleSize" */ + }, + 550: { + /* n:"BrtDrawing", */ + f: parse_RelID + }, + 551: { + /* n:"BrtLegacyDrawing", */ + f: parse_XLNullableWideString + }, + 552: { + /* n:"BrtLegacyDrawingHF" */ + }, + 553: { + /* n:"BrtWebOpt" */ + }, + 554: { + /* n:"BrtBeginWebPubItems", */ + T: 1 + }, + 555: { + /* n:"BrtEndWebPubItems", */ + T: -1 + }, + 556: { + /* n:"BrtBeginWebPubItem", */ + T: 1 + }, + 557: { + /* n:"BrtEndWebPubItem", */ + T: -1 + }, + 558: { + /* n:"BrtBeginSXCondFmt", */ + T: 1 + }, + 559: { + /* n:"BrtEndSXCondFmt", */ + T: -1 + }, + 560: { + /* n:"BrtBeginSXCondFmts", */ + T: 1 + }, + 561: { + /* n:"BrtEndSXCondFmts", */ + T: -1 + }, + 562: { + /* n:"BrtBkHim" */ + }, + 564: { + /* n:"BrtColor" */ + }, + 565: { + /* n:"BrtBeginIndexedColors", */ + T: 1 + }, + 566: { + /* n:"BrtEndIndexedColors", */ + T: -1 + }, + 569: { + /* n:"BrtBeginMRUColors", */ + T: 1 + }, + 570: { + /* n:"BrtEndMRUColors", */ + T: -1 + }, + 572: { + /* n:"BrtMRUColor" */ + }, + 573: { + /* n:"BrtBeginDVals", */ + T: 1 + }, + 574: { + /* n:"BrtEndDVals", */ + T: -1 + }, + 577: { + /* n:"BrtSupNameStart" */ + }, + 578: { + /* n:"BrtSupNameValueStart" */ + }, + 579: { + /* n:"BrtSupNameValueEnd" */ + }, + 580: { + /* n:"BrtSupNameNum" */ + }, + 581: { + /* n:"BrtSupNameErr" */ + }, + 582: { + /* n:"BrtSupNameSt" */ + }, + 583: { + /* n:"BrtSupNameNil" */ + }, + 584: { + /* n:"BrtSupNameBool" */ + }, + 585: { + /* n:"BrtSupNameFmla" */ + }, + 586: { + /* n:"BrtSupNameBits" */ + }, + 587: { + /* n:"BrtSupNameEnd" */ + }, + 588: { + /* n:"BrtEndSupBook", */ + T: -1 + }, + 589: { + /* n:"BrtCellSmartTagProperty" */ + }, + 590: { + /* n:"BrtBeginCellSmartTag", */ + T: 1 + }, + 591: { + /* n:"BrtEndCellSmartTag", */ + T: -1 + }, + 592: { + /* n:"BrtBeginCellSmartTags", */ + T: 1 + }, + 593: { + /* n:"BrtEndCellSmartTags", */ + T: -1 + }, + 594: { + /* n:"BrtBeginSmartTags", */ + T: 1 + }, + 595: { + /* n:"BrtEndSmartTags", */ + T: -1 + }, + 596: { + /* n:"BrtSmartTagType" */ + }, + 597: { + /* n:"BrtBeginSmartTagTypes", */ + T: 1 + }, + 598: { + /* n:"BrtEndSmartTagTypes", */ + T: -1 + }, + 599: { + /* n:"BrtBeginSXFilters", */ + T: 1 + }, + 600: { + /* n:"BrtEndSXFilters", */ + T: -1 + }, + 601: { + /* n:"BrtBeginSXFILTER", */ + T: 1 + }, + 602: { + /* n:"BrtEndSXFilter", */ + T: -1 + }, + 603: { + /* n:"BrtBeginFills", */ + T: 1 + }, + 604: { + /* n:"BrtEndFills", */ + T: -1 + }, + 605: { + /* n:"BrtBeginCellWatches", */ + T: 1 + }, + 606: { + /* n:"BrtEndCellWatches", */ + T: -1 + }, + 607: { + /* n:"BrtCellWatch" */ + }, + 608: { + /* n:"BrtBeginCRErrs", */ + T: 1 + }, + 609: { + /* n:"BrtEndCRErrs", */ + T: -1 + }, + 610: { + /* n:"BrtCrashRecErr" */ + }, + 611: { + /* n:"BrtBeginFonts", */ + T: 1 + }, + 612: { + /* n:"BrtEndFonts", */ + T: -1 + }, + 613: { + /* n:"BrtBeginBorders", */ + T: 1 + }, + 614: { + /* n:"BrtEndBorders", */ + T: -1 + }, + 615: { + /* n:"BrtBeginFmts", */ + T: 1 + }, + 616: { + /* n:"BrtEndFmts", */ + T: -1 + }, + 617: { + /* n:"BrtBeginCellXFs", */ + T: 1 + }, + 618: { + /* n:"BrtEndCellXFs", */ + T: -1 + }, + 619: { + /* n:"BrtBeginStyles", */ + T: 1 + }, + 620: { + /* n:"BrtEndStyles", */ + T: -1 + }, + 625: { + /* n:"BrtBigName" */ + }, + 626: { + /* n:"BrtBeginCellStyleXFs", */ + T: 1 + }, + 627: { + /* n:"BrtEndCellStyleXFs", */ + T: -1 + }, + 628: { + /* n:"BrtBeginComments", */ + T: 1 + }, + 629: { + /* n:"BrtEndComments", */ + T: -1 + }, + 630: { + /* n:"BrtBeginCommentAuthors", */ + T: 1 + }, + 631: { + /* n:"BrtEndCommentAuthors", */ + T: -1 + }, + 632: { + /* n:"BrtCommentAuthor", */ + f: parse_BrtCommentAuthor + }, + 633: { + /* n:"BrtBeginCommentList", */ + T: 1 + }, + 634: { + /* n:"BrtEndCommentList", */ + T: -1 + }, + 635: { + /* n:"BrtBeginComment", */ + T: 1, + f: parse_BrtBeginComment + }, + 636: { + /* n:"BrtEndComment", */ + T: -1 + }, + 637: { + /* n:"BrtCommentText", */ + f: parse_BrtCommentText + }, + 638: { + /* n:"BrtBeginOleObjects", */ + T: 1 + }, + 639: { + /* n:"BrtOleObject" */ + }, + 640: { + /* n:"BrtEndOleObjects", */ + T: -1 + }, + 641: { + /* n:"BrtBeginSxrules", */ + T: 1 + }, + 642: { + /* n:"BrtEndSxRules", */ + T: -1 + }, + 643: { + /* n:"BrtBeginActiveXControls", */ + T: 1 + }, + 644: { + /* n:"BrtActiveX" */ + }, + 645: { + /* n:"BrtEndActiveXControls", */ + T: -1 + }, + 646: { + /* n:"BrtBeginPCDSDTCEMembersSortBy", */ + T: 1 + }, + 648: { + /* n:"BrtBeginCellIgnoreECs", */ + T: 1 + }, + 649: { + /* n:"BrtCellIgnoreEC" */ + }, + 650: { + /* n:"BrtEndCellIgnoreECs", */ + T: -1 + }, + 651: { + /* n:"BrtCsProp", */ + f: parse_BrtCsProp + }, + 652: { + /* n:"BrtCsPageSetup" */ + }, + 653: { + /* n:"BrtBeginUserCsViews", */ + T: 1 + }, + 654: { + /* n:"BrtEndUserCsViews", */ + T: -1 + }, + 655: { + /* n:"BrtBeginUserCsView", */ + T: 1 + }, + 656: { + /* n:"BrtEndUserCsView", */ + T: -1 + }, + 657: { + /* n:"BrtBeginPcdSFCIEntries", */ + T: 1 + }, + 658: { + /* n:"BrtEndPCDSFCIEntries", */ + T: -1 + }, + 659: { + /* n:"BrtPCDSFCIEntry" */ + }, + 660: { + /* n:"BrtBeginListParts", */ + T: 1 + }, + 661: { + /* n:"BrtListPart" */ + }, + 662: { + /* n:"BrtEndListParts", */ + T: -1 + }, + 663: { + /* n:"BrtSheetCalcProp" */ + }, + 664: { + /* n:"BrtBeginFnGroup", */ + T: 1 + }, + 665: { + /* n:"BrtFnGroup" */ + }, + 666: { + /* n:"BrtEndFnGroup", */ + T: -1 + }, + 667: { + /* n:"BrtSupAddin" */ + }, + 668: { + /* n:"BrtSXTDMPOrder" */ + }, + 669: { + /* n:"BrtCsProtection" */ + }, + 671: { + /* n:"BrtBeginWsSortMap", */ + T: 1 + }, + 672: { + /* n:"BrtEndWsSortMap", */ + T: -1 + }, + 673: { + /* n:"BrtBeginRRSort", */ + T: 1 + }, + 674: { + /* n:"BrtEndRRSort", */ + T: -1 + }, + 675: { + /* n:"BrtRRSortItem" */ + }, + 676: { + /* n:"BrtFileSharingIso" */ + }, + 677: { + /* n:"BrtBookProtectionIso" */ + }, + 678: { + /* n:"BrtSheetProtectionIso" */ + }, + 679: { + /* n:"BrtCsProtectionIso" */ + }, + 680: { + /* n:"BrtRangeProtectionIso" */ + }, + 681: { + /* n:"BrtDValList" */ + }, + 1024: { + /* n:"BrtRwDescent" */ + }, + 1025: { + /* n:"BrtKnownFonts" */ + }, + 1026: { + /* n:"BrtBeginSXTupleSet", */ + T: 1 + }, + 1027: { + /* n:"BrtEndSXTupleSet", */ + T: -1 + }, + 1028: { + /* n:"BrtBeginSXTupleSetHeader", */ + T: 1 + }, + 1029: { + /* n:"BrtEndSXTupleSetHeader", */ + T: -1 + }, + 1030: { + /* n:"BrtSXTupleSetHeaderItem" */ + }, + 1031: { + /* n:"BrtBeginSXTupleSetData", */ + T: 1 + }, + 1032: { + /* n:"BrtEndSXTupleSetData", */ + T: -1 + }, + 1033: { + /* n:"BrtBeginSXTupleSetRow", */ + T: 1 + }, + 1034: { + /* n:"BrtEndSXTupleSetRow", */ + T: -1 + }, + 1035: { + /* n:"BrtSXTupleSetRowItem" */ + }, + 1036: { + /* n:"BrtNameExt" */ + }, + 1037: { + /* n:"BrtPCDH14" */ + }, + 1038: { + /* n:"BrtBeginPCDCalcMem14", */ + T: 1 + }, + 1039: { + /* n:"BrtEndPCDCalcMem14", */ + T: -1 + }, + 1040: { + /* n:"BrtSXTH14" */ + }, + 1041: { + /* n:"BrtBeginSparklineGroup", */ + T: 1 + }, + 1042: { + /* n:"BrtEndSparklineGroup", */ + T: -1 + }, + 1043: { + /* n:"BrtSparkline" */ + }, + 1044: { + /* n:"BrtSXDI14" */ + }, + 1045: { + /* n:"BrtWsFmtInfoEx14" */ + }, + 1046: { + /* n:"BrtBeginConditionalFormatting14", */ + T: 1 + }, + 1047: { + /* n:"BrtEndConditionalFormatting14", */ + T: -1 + }, + 1048: { + /* n:"BrtBeginCFRule14", */ + T: 1 + }, + 1049: { + /* n:"BrtEndCFRule14", */ + T: -1 + }, + 1050: { + /* n:"BrtCFVO14" */ + }, + 1051: { + /* n:"BrtBeginDatabar14", */ + T: 1 + }, + 1052: { + /* n:"BrtBeginIconSet14", */ + T: 1 + }, + 1053: { + /* n:"BrtDVal14", */ + f: parse_BrtDVal14 + }, + 1054: { + /* n:"BrtBeginDVals14", */ + T: 1 + }, + 1055: { + /* n:"BrtColor14" */ + }, + 1056: { + /* n:"BrtBeginSparklines", */ + T: 1 + }, + 1057: { + /* n:"BrtEndSparklines", */ + T: -1 + }, + 1058: { + /* n:"BrtBeginSparklineGroups", */ + T: 1 + }, + 1059: { + /* n:"BrtEndSparklineGroups", */ + T: -1 + }, + 1061: { + /* n:"BrtSXVD14" */ + }, + 1062: { + /* n:"BrtBeginSXView14", */ + T: 1 + }, + 1063: { + /* n:"BrtEndSXView14", */ + T: -1 + }, + 1064: { + /* n:"BrtBeginSXView16", */ + T: 1 + }, + 1065: { + /* n:"BrtEndSXView16", */ + T: -1 + }, + 1066: { + /* n:"BrtBeginPCD14", */ + T: 1 + }, + 1067: { + /* n:"BrtEndPCD14", */ + T: -1 + }, + 1068: { + /* n:"BrtBeginExtConn14", */ + T: 1 + }, + 1069: { + /* n:"BrtEndExtConn14", */ + T: -1 + }, + 1070: { + /* n:"BrtBeginSlicerCacheIDs", */ + T: 1 + }, + 1071: { + /* n:"BrtEndSlicerCacheIDs", */ + T: -1 + }, + 1072: { + /* n:"BrtBeginSlicerCacheID", */ + T: 1 + }, + 1073: { + /* n:"BrtEndSlicerCacheID", */ + T: -1 + }, + 1075: { + /* n:"BrtBeginSlicerCache", */ + T: 1 + }, + 1076: { + /* n:"BrtEndSlicerCache", */ + T: -1 + }, + 1077: { + /* n:"BrtBeginSlicerCacheDef", */ + T: 1 + }, + 1078: { + /* n:"BrtEndSlicerCacheDef", */ + T: -1 + }, + 1079: { + /* n:"BrtBeginSlicersEx", */ + T: 1 + }, + 1080: { + /* n:"BrtEndSlicersEx", */ + T: -1 + }, + 1081: { + /* n:"BrtBeginSlicerEx", */ + T: 1 + }, + 1082: { + /* n:"BrtEndSlicerEx", */ + T: -1 + }, + 1083: { + /* n:"BrtBeginSlicer", */ + T: 1 + }, + 1084: { + /* n:"BrtEndSlicer", */ + T: -1 + }, + 1085: { + /* n:"BrtSlicerCachePivotTables" */ + }, + 1086: { + /* n:"BrtBeginSlicerCacheOlapImpl", */ + T: 1 + }, + 1087: { + /* n:"BrtEndSlicerCacheOlapImpl", */ + T: -1 + }, + 1088: { + /* n:"BrtBeginSlicerCacheLevelsData", */ + T: 1 + }, + 1089: { + /* n:"BrtEndSlicerCacheLevelsData", */ + T: -1 + }, + 1090: { + /* n:"BrtBeginSlicerCacheLevelData", */ + T: 1 + }, + 1091: { + /* n:"BrtEndSlicerCacheLevelData", */ + T: -1 + }, + 1092: { + /* n:"BrtBeginSlicerCacheSiRanges", */ + T: 1 + }, + 1093: { + /* n:"BrtEndSlicerCacheSiRanges", */ + T: -1 + }, + 1094: { + /* n:"BrtBeginSlicerCacheSiRange", */ + T: 1 + }, + 1095: { + /* n:"BrtEndSlicerCacheSiRange", */ + T: -1 + }, + 1096: { + /* n:"BrtSlicerCacheOlapItem" */ + }, + 1097: { + /* n:"BrtBeginSlicerCacheSelections", */ + T: 1 + }, + 1098: { + /* n:"BrtSlicerCacheSelection" */ + }, + 1099: { + /* n:"BrtEndSlicerCacheSelections", */ + T: -1 + }, + 1100: { + /* n:"BrtBeginSlicerCacheNative", */ + T: 1 + }, + 1101: { + /* n:"BrtEndSlicerCacheNative", */ + T: -1 + }, + 1102: { + /* n:"BrtSlicerCacheNativeItem" */ + }, + 1103: { + /* n:"BrtRangeProtection14" */ + }, + 1104: { + /* n:"BrtRangeProtectionIso14" */ + }, + 1105: { + /* n:"BrtCellIgnoreEC14" */ + }, + 1111: { + /* n:"BrtList14" */ + }, + 1112: { + /* n:"BrtCFIcon" */ + }, + 1113: { + /* n:"BrtBeginSlicerCachesPivotCacheIDs", */ + T: 1 + }, + 1114: { + /* n:"BrtEndSlicerCachesPivotCacheIDs", */ + T: -1 + }, + 1115: { + /* n:"BrtBeginSlicers", */ + T: 1 + }, + 1116: { + /* n:"BrtEndSlicers", */ + T: -1 + }, + 1117: { + /* n:"BrtWbProp14" */ + }, + 1118: { + /* n:"BrtBeginSXEdit", */ + T: 1 + }, + 1119: { + /* n:"BrtEndSXEdit", */ + T: -1 + }, + 1120: { + /* n:"BrtBeginSXEdits", */ + T: 1 + }, + 1121: { + /* n:"BrtEndSXEdits", */ + T: -1 + }, + 1122: { + /* n:"BrtBeginSXChange", */ + T: 1 + }, + 1123: { + /* n:"BrtEndSXChange", */ + T: -1 + }, + 1124: { + /* n:"BrtBeginSXChanges", */ + T: 1 + }, + 1125: { + /* n:"BrtEndSXChanges", */ + T: -1 + }, + 1126: { + /* n:"BrtSXTupleItems" */ + }, + 1128: { + /* n:"BrtBeginSlicerStyle", */ + T: 1 + }, + 1129: { + /* n:"BrtEndSlicerStyle", */ + T: -1 + }, + 1130: { + /* n:"BrtSlicerStyleElement" */ + }, + 1131: { + /* n:"BrtBeginStyleSheetExt14", */ + T: 1 + }, + 1132: { + /* n:"BrtEndStyleSheetExt14", */ + T: -1 + }, + 1133: { + /* n:"BrtBeginSlicerCachesPivotCacheID", */ + T: 1 + }, + 1134: { + /* n:"BrtEndSlicerCachesPivotCacheID", */ + T: -1 + }, + 1135: { + /* n:"BrtBeginConditionalFormattings", */ + T: 1 + }, + 1136: { + /* n:"BrtEndConditionalFormattings", */ + T: -1 + }, + 1137: { + /* n:"BrtBeginPCDCalcMemExt", */ + T: 1 + }, + 1138: { + /* n:"BrtEndPCDCalcMemExt", */ + T: -1 + }, + 1139: { + /* n:"BrtBeginPCDCalcMemsExt", */ + T: 1 + }, + 1140: { + /* n:"BrtEndPCDCalcMemsExt", */ + T: -1 + }, + 1141: { + /* n:"BrtPCDField14" */ + }, + 1142: { + /* n:"BrtBeginSlicerStyles", */ + T: 1 + }, + 1143: { + /* n:"BrtEndSlicerStyles", */ + T: -1 + }, + 1144: { + /* n:"BrtBeginSlicerStyleElements", */ + T: 1 + }, + 1145: { + /* n:"BrtEndSlicerStyleElements", */ + T: -1 + }, + 1146: { + /* n:"BrtCFRuleExt" */ + }, + 1147: { + /* n:"BrtBeginSXCondFmt14", */ + T: 1 + }, + 1148: { + /* n:"BrtEndSXCondFmt14", */ + T: -1 + }, + 1149: { + /* n:"BrtBeginSXCondFmts14", */ + T: 1 + }, + 1150: { + /* n:"BrtEndSXCondFmts14", */ + T: -1 + }, + 1152: { + /* n:"BrtBeginSortCond14", */ + T: 1 + }, + 1153: { + /* n:"BrtEndSortCond14", */ + T: -1 + }, + 1154: { + /* n:"BrtEndDVals14", */ + T: -1 + }, + 1155: { + /* n:"BrtEndIconSet14", */ + T: -1 + }, + 1156: { + /* n:"BrtEndDatabar14", */ + T: -1 + }, + 1157: { + /* n:"BrtBeginColorScale14", */ + T: 1 + }, + 1158: { + /* n:"BrtEndColorScale14", */ + T: -1 + }, + 1159: { + /* n:"BrtBeginSxrules14", */ + T: 1 + }, + 1160: { + /* n:"BrtEndSxrules14", */ + T: -1 + }, + 1161: { + /* n:"BrtBeginPRule14", */ + T: 1 + }, + 1162: { + /* n:"BrtEndPRule14", */ + T: -1 + }, + 1163: { + /* n:"BrtBeginPRFilters14", */ + T: 1 + }, + 1164: { + /* n:"BrtEndPRFilters14", */ + T: -1 + }, + 1165: { + /* n:"BrtBeginPRFilter14", */ + T: 1 + }, + 1166: { + /* n:"BrtEndPRFilter14", */ + T: -1 + }, + 1167: { + /* n:"BrtBeginPRFItem14", */ + T: 1 + }, + 1168: { + /* n:"BrtEndPRFItem14", */ + T: -1 + }, + 1169: { + /* n:"BrtBeginCellIgnoreECs14", */ + T: 1 + }, + 1170: { + /* n:"BrtEndCellIgnoreECs14", */ + T: -1 + }, + 1171: { + /* n:"BrtDxf14" */ + }, + 1172: { + /* n:"BrtBeginDxF14s", */ + T: 1 + }, + 1173: { + /* n:"BrtEndDxf14s", */ + T: -1 + }, + 1177: { + /* n:"BrtFilter14" */ + }, + 1178: { + /* n:"BrtBeginCustomFilters14", */ + T: 1 + }, + 1180: { + /* n:"BrtCustomFilter14" */ + }, + 1181: { + /* n:"BrtIconFilter14" */ + }, + 1182: { + /* n:"BrtPivotCacheConnectionName" */ + }, + 2048: { + /* n:"BrtBeginDecoupledPivotCacheIDs", */ + T: 1 + }, + 2049: { + /* n:"BrtEndDecoupledPivotCacheIDs", */ + T: -1 + }, + 2050: { + /* n:"BrtDecoupledPivotCacheID" */ + }, + 2051: { + /* n:"BrtBeginPivotTableRefs", */ + T: 1 + }, + 2052: { + /* n:"BrtEndPivotTableRefs", */ + T: -1 + }, + 2053: { + /* n:"BrtPivotTableRef" */ + }, + 2054: { + /* n:"BrtSlicerCacheBookPivotTables" */ + }, + 2055: { + /* n:"BrtBeginSxvcells", */ + T: 1 + }, + 2056: { + /* n:"BrtEndSxvcells", */ + T: -1 + }, + 2057: { + /* n:"BrtBeginSxRow", */ + T: 1 + }, + 2058: { + /* n:"BrtEndSxRow", */ + T: -1 + }, + 2060: { + /* n:"BrtPcdCalcMem15" */ + }, + 2067: { + /* n:"BrtQsi15" */ + }, + 2068: { + /* n:"BrtBeginWebExtensions", */ + T: 1 + }, + 2069: { + /* n:"BrtEndWebExtensions", */ + T: -1 + }, + 2070: { + /* n:"BrtWebExtension" */ + }, + 2071: { + /* n:"BrtAbsPath15" */ + }, + 2072: { + /* n:"BrtBeginPivotTableUISettings", */ + T: 1 + }, + 2073: { + /* n:"BrtEndPivotTableUISettings", */ + T: -1 + }, + 2075: { + /* n:"BrtTableSlicerCacheIDs" */ + }, + 2076: { + /* n:"BrtTableSlicerCacheID" */ + }, + 2077: { + /* n:"BrtBeginTableSlicerCache", */ + T: 1 + }, + 2078: { + /* n:"BrtEndTableSlicerCache", */ + T: -1 + }, + 2079: { + /* n:"BrtSxFilter15" */ + }, + 2080: { + /* n:"BrtBeginTimelineCachePivotCacheIDs", */ + T: 1 + }, + 2081: { + /* n:"BrtEndTimelineCachePivotCacheIDs", */ + T: -1 + }, + 2082: { + /* n:"BrtTimelineCachePivotCacheID" */ + }, + 2083: { + /* n:"BrtBeginTimelineCacheIDs", */ + T: 1 + }, + 2084: { + /* n:"BrtEndTimelineCacheIDs", */ + T: -1 + }, + 2085: { + /* n:"BrtBeginTimelineCacheID", */ + T: 1 + }, + 2086: { + /* n:"BrtEndTimelineCacheID", */ + T: -1 + }, + 2087: { + /* n:"BrtBeginTimelinesEx", */ + T: 1 + }, + 2088: { + /* n:"BrtEndTimelinesEx", */ + T: -1 + }, + 2089: { + /* n:"BrtBeginTimelineEx", */ + T: 1 + }, + 2090: { + /* n:"BrtEndTimelineEx", */ + T: -1 + }, + 2091: { + /* n:"BrtWorkBookPr15" */ + }, + 2092: { + /* n:"BrtPCDH15" */ + }, + 2093: { + /* n:"BrtBeginTimelineStyle", */ + T: 1 + }, + 2094: { + /* n:"BrtEndTimelineStyle", */ + T: -1 + }, + 2095: { + /* n:"BrtTimelineStyleElement" */ + }, + 2096: { + /* n:"BrtBeginTimelineStylesheetExt15", */ + T: 1 + }, + 2097: { + /* n:"BrtEndTimelineStylesheetExt15", */ + T: -1 + }, + 2098: { + /* n:"BrtBeginTimelineStyles", */ + T: 1 + }, + 2099: { + /* n:"BrtEndTimelineStyles", */ + T: -1 + }, + 2100: { + /* n:"BrtBeginTimelineStyleElements", */ + T: 1 + }, + 2101: { + /* n:"BrtEndTimelineStyleElements", */ + T: -1 + }, + 2102: { + /* n:"BrtDxf15" */ + }, + 2103: { + /* n:"BrtBeginDxfs15", */ + T: 1 + }, + 2104: { + /* n:"BrtEndDxfs15", */ + T: -1 + }, + 2105: { + /* n:"BrtSlicerCacheHideItemsWithNoData" */ + }, + 2106: { + /* n:"BrtBeginItemUniqueNames", */ + T: 1 + }, + 2107: { + /* n:"BrtEndItemUniqueNames", */ + T: -1 + }, + 2108: { + /* n:"BrtItemUniqueName" */ + }, + 2109: { + /* n:"BrtBeginExtConn15", */ + T: 1 + }, + 2110: { + /* n:"BrtEndExtConn15", */ + T: -1 + }, + 2111: { + /* n:"BrtBeginOledbPr15", */ + T: 1 + }, + 2112: { + /* n:"BrtEndOledbPr15", */ + T: -1 + }, + 2113: { + /* n:"BrtBeginDataFeedPr15", */ + T: 1 + }, + 2114: { + /* n:"BrtEndDataFeedPr15", */ + T: -1 + }, + 2115: { + /* n:"BrtTextPr15" */ + }, + 2116: { + /* n:"BrtRangePr15" */ + }, + 2117: { + /* n:"BrtDbCommand15" */ + }, + 2118: { + /* n:"BrtBeginDbTables15", */ + T: 1 + }, + 2119: { + /* n:"BrtEndDbTables15", */ + T: -1 + }, + 2120: { + /* n:"BrtDbTable15" */ + }, + 2121: { + /* n:"BrtBeginDataModel", */ + T: 1 + }, + 2122: { + /* n:"BrtEndDataModel", */ + T: -1 + }, + 2123: { + /* n:"BrtBeginModelTables", */ + T: 1 + }, + 2124: { + /* n:"BrtEndModelTables", */ + T: -1 + }, + 2125: { + /* n:"BrtModelTable" */ + }, + 2126: { + /* n:"BrtBeginModelRelationships", */ + T: 1 + }, + 2127: { + /* n:"BrtEndModelRelationships", */ + T: -1 + }, + 2128: { + /* n:"BrtModelRelationship" */ + }, + 2129: { + /* n:"BrtBeginECTxtWiz15", */ + T: 1 + }, + 2130: { + /* n:"BrtEndECTxtWiz15", */ + T: -1 + }, + 2131: { + /* n:"BrtBeginECTWFldInfoLst15", */ + T: 1 + }, + 2132: { + /* n:"BrtEndECTWFldInfoLst15", */ + T: -1 + }, + 2133: { + /* n:"BrtBeginECTWFldInfo15", */ + T: 1 + }, + 2134: { + /* n:"BrtFieldListActiveItem" */ + }, + 2135: { + /* n:"BrtPivotCacheIdVersion" */ + }, + 2136: { + /* n:"BrtSXDI15" */ + }, + 2137: { + /* n:"BrtBeginModelTimeGroupings", */ + T: 1 + }, + 2138: { + /* n:"BrtEndModelTimeGroupings", */ + T: -1 + }, + 2139: { + /* n:"BrtBeginModelTimeGrouping", */ + T: 1 + }, + 2140: { + /* n:"BrtEndModelTimeGrouping", */ + T: -1 + }, + 2141: { + /* n:"BrtModelTimeGroupingCalcCol" */ + }, + 3072: { + /* n:"BrtUid" */ + }, + 3073: { + /* n:"BrtRevisionPtr" */ + }, + 4096: { + /* n:"BrtBeginDynamicArrayPr", */ + T: 1 + }, + 4097: { + /* n:"BrtEndDynamicArrayPr", */ + T: -1 + }, + 5002: { + /* n:"BrtBeginRichValueBlock", */ + T: 1 + }, + 5003: { + /* n:"BrtEndRichValueBlock", */ + T: -1 + }, + 5081: { + /* n:"BrtBeginRichFilters", */ + T: 1 + }, + 5082: { + /* n:"BrtEndRichFilters", */ + T: -1 + }, + 5083: { + /* n:"BrtRichFilter" */ + }, + 5084: { + /* n:"BrtBeginRichFilterColumn", */ + T: 1 + }, + 5085: { + /* n:"BrtEndRichFilterColumn", */ + T: -1 + }, + 5086: { + /* n:"BrtBeginCustomRichFilters", */ + T: 1 + }, + 5087: { + /* n:"BrtEndCustomRichFilters", */ + T: -1 + }, + 5088: { + /* n:"BrtCustomRichFilter" */ + }, + 5089: { + /* n:"BrtTop10RichFilter" */ + }, + 5090: { + /* n:"BrtDynamicRichFilter" */ + }, + 5092: { + /* n:"BrtBeginRichSortCondition", */ + T: 1 + }, + 5093: { + /* n:"BrtEndRichSortCondition", */ + T: -1 + }, + 5094: { + /* n:"BrtRichFilterDateGroupItem" */ + }, + 5095: { + /* n:"BrtBeginCalcFeatures", */ + T: 1 + }, + 5096: { + /* n:"BrtEndCalcFeatures", */ + T: -1 + }, + 5097: { + /* n:"BrtCalcFeature" */ + }, + 5099: { + /* n:"BrtExternalLinksPr" */ + }, + 65535: { n: "" } + }; + XLSRecordEnum = { + /* [MS-XLS] 2.3 Record Enumeration 2021-08-17 */ + 6: { + /* n:"Formula", */ + f: parse_Formula + }, + 10: { + /* n:"EOF", */ + f: parsenoop2 + }, + 12: { + /* n:"CalcCount", */ + f: parseuint16 + }, + // + 13: { + /* n:"CalcMode", */ + f: parseuint16 + }, + // + 14: { + /* n:"CalcPrecision", */ + f: parsebool + }, + // + 15: { + /* n:"CalcRefMode", */ + f: parsebool + }, + // + 16: { + /* n:"CalcDelta", */ + f: parse_Xnum + }, + // + 17: { + /* n:"CalcIter", */ + f: parsebool + }, + // + 18: { + /* n:"Protect", */ + f: parsebool + }, + 19: { + /* n:"Password", */ + f: parseuint16 + }, + 20: { + /* n:"Header", */ + f: parse_XLHeaderFooter + }, + 21: { + /* n:"Footer", */ + f: parse_XLHeaderFooter + }, + 23: { + /* n:"ExternSheet", */ + f: parse_ExternSheet + }, + 24: { + /* n:"Lbl", */ + f: parse_Lbl + }, + 25: { + /* n:"WinProtect", */ + f: parsebool + }, + 26: { + /* n:"VerticalPageBreaks", */ + }, + 27: { + /* n:"HorizontalPageBreaks", */ + }, + 28: { + /* n:"Note", */ + f: parse_Note + }, + 29: { + /* n:"Selection", */ + }, + 34: { + /* n:"Date1904", */ + f: parsebool + }, + 35: { + /* n:"ExternName", */ + f: parse_ExternName + }, + 38: { + /* n:"LeftMargin", */ + f: parse_Xnum + }, + // * + 39: { + /* n:"RightMargin", */ + f: parse_Xnum + }, + // * + 40: { + /* n:"TopMargin", */ + f: parse_Xnum + }, + // * + 41: { + /* n:"BottomMargin", */ + f: parse_Xnum + }, + // * + 42: { + /* n:"PrintRowCol", */ + f: parsebool + }, + 43: { + /* n:"PrintGrid", */ + f: parsebool + }, + 47: { + /* n:"FilePass", */ + f: parse_FilePass + }, + 49: { + /* n:"Font", */ + f: parse_Font + }, + 51: { + /* n:"PrintSize", */ + f: parseuint16 + }, + 60: { + /* n:"Continue", */ + }, + 61: { + /* n:"Window1", */ + f: parse_Window1 + }, + 64: { + /* n:"Backup", */ + f: parsebool + }, + 65: { + /* n:"Pane", */ + f: parse_Pane + }, + 66: { + /* n:"CodePage", */ + f: parseuint16 + }, + 77: { + /* n:"Pls", */ + }, + 80: { + /* n:"DCon", */ + }, + 81: { + /* n:"DConRef", */ + }, + 82: { + /* n:"DConName", */ + }, + 85: { + /* n:"DefColWidth", */ + f: parseuint16 + }, + 89: { + /* n:"XCT", */ + }, + 90: { + /* n:"CRN", */ + }, + 91: { + /* n:"FileSharing", */ + }, + 92: { + /* n:"WriteAccess", */ + f: parse_WriteAccess + }, + 93: { + /* n:"Obj", */ + f: parse_Obj + }, + 94: { + /* n:"Uncalced", */ + }, + 95: { + /* n:"CalcSaveRecalc", */ + f: parsebool + }, + // + 96: { + /* n:"Template", */ + }, + 97: { + /* n:"Intl", */ + }, + 99: { + /* n:"ObjProtect", */ + f: parsebool + }, + 125: { + /* n:"ColInfo", */ + f: parse_ColInfo + }, + 128: { + /* n:"Guts", */ + f: parse_Guts + }, + 129: { + /* n:"WsBool", */ + f: parse_WsBool + }, + 130: { + /* n:"GridSet", */ + f: parseuint16 + }, + 131: { + /* n:"HCenter", */ + f: parsebool + }, + 132: { + /* n:"VCenter", */ + f: parsebool + }, + 133: { + /* n:"BoundSheet8", */ + f: parse_BoundSheet8 + }, + 134: { + /* n:"WriteProtect", */ + }, + 140: { + /* n:"Country", */ + f: parse_Country + }, + 141: { + /* n:"HideObj", */ + f: parseuint16 + }, + 144: { + /* n:"Sort", */ + }, + 146: { + /* n:"Palette", */ + f: parse_Palette + }, + 151: { + /* n:"Sync", */ + }, + 152: { + /* n:"LPr", */ + }, + 153: { + /* n:"DxGCol", */ + }, + 154: { + /* n:"FnGroupName", */ + }, + 155: { + /* n:"FilterMode", */ + }, + 156: { + /* n:"BuiltInFnGroupCount", */ + f: parseuint16 + }, + 157: { + /* n:"AutoFilterInfo", */ + }, + 158: { + /* n:"AutoFilter", */ + }, + 160: { + /* n:"Scl", */ + f: parse_Scl + }, + 161: { + /* n:"Setup", */ + f: parse_Setup + }, + 174: { + /* n:"ScenMan", */ + }, + 175: { + /* n:"SCENARIO", */ + }, + 176: { + /* n:"SxView", */ + }, + 177: { + /* n:"Sxvd", */ + }, + 178: { + /* n:"SXVI", */ + }, + 180: { + /* n:"SxIvd", */ + }, + 181: { + /* n:"SXLI", */ + }, + 182: { + /* n:"SXPI", */ + }, + 184: { + /* n:"DocRoute", */ + }, + 185: { + /* n:"RecipName", */ + }, + 189: { + /* n:"MulRk", */ + f: parse_MulRk + }, + 190: { + /* n:"MulBlank", */ + f: parse_MulBlank + }, + 193: { + /* n:"Mms", */ + f: parsenoop2 + }, + 197: { + /* n:"SXDI", */ + }, + 198: { + /* n:"SXDB", */ + }, + 199: { + /* n:"SXFDB", */ + }, + 200: { + /* n:"SXDBB", */ + }, + 201: { + /* n:"SXNum", */ + }, + 202: { + /* n:"SxBool", */ + f: parsebool + }, + 203: { + /* n:"SxErr", */ + }, + 204: { + /* n:"SXInt", */ + }, + 205: { + /* n:"SXString", */ + }, + 206: { + /* n:"SXDtr", */ + }, + 207: { + /* n:"SxNil", */ + }, + 208: { + /* n:"SXTbl", */ + }, + 209: { + /* n:"SXTBRGIITM", */ + }, + 210: { + /* n:"SxTbpg", */ + }, + 211: { + /* n:"ObProj", */ + }, + 213: { + /* n:"SXStreamID", */ + }, + 215: { + /* n:"DBCell", */ + }, + 216: { + /* n:"SXRng", */ + }, + 217: { + /* n:"SxIsxoper", */ + }, + 218: { + /* n:"BookBool", */ + f: parseuint16 + }, + 220: { + /* n:"DbOrParamQry", */ + }, + 221: { + /* n:"ScenarioProtect", */ + f: parsebool + }, + 222: { + /* n:"OleObjectSize", */ + }, + 224: { + /* n:"XF", */ + f: parse_XF + }, + 225: { + /* n:"InterfaceHdr", */ + f: parse_InterfaceHdr + }, + 226: { + /* n:"InterfaceEnd", */ + f: parsenoop2 + }, + 227: { + /* n:"SXVS", */ + }, + 229: { + /* n:"MergeCells", */ + f: parse_MergeCells + }, + 233: { + /* n:"BkHim", */ + }, + 235: { + /* n:"MsoDrawingGroup", */ + }, + 236: { + /* n:"MsoDrawing", */ + }, + 237: { + /* n:"MsoDrawingSelection", */ + }, + 239: { + /* n:"PhoneticInfo", */ + }, + 240: { + /* n:"SxRule", */ + }, + 241: { + /* n:"SXEx", */ + }, + 242: { + /* n:"SxFilt", */ + }, + 244: { + /* n:"SxDXF", */ + }, + 245: { + /* n:"SxItm", */ + }, + 246: { + /* n:"SxName", */ + }, + 247: { + /* n:"SxSelect", */ + }, + 248: { + /* n:"SXPair", */ + }, + 249: { + /* n:"SxFmla", */ + }, + 251: { + /* n:"SxFormat", */ + }, + 252: { + /* n:"SST", */ + f: parse_SST + }, + 253: { + /* n:"LabelSst", */ + f: parse_LabelSst + }, + 255: { + /* n:"ExtSST", */ + f: parse_ExtSST + }, + 256: { + /* n:"SXVDEx", */ + }, + 259: { + /* n:"SXFormula", */ + }, + 290: { + /* n:"SXDBEx", */ + }, + 311: { + /* n:"RRDInsDel", */ + }, + 312: { + /* n:"RRDHead", */ + }, + 315: { + /* n:"RRDChgCell", */ + }, + 317: { + /* n:"RRTabId", */ + f: parseuint16a + }, + 318: { + /* n:"RRDRenSheet", */ + }, + 319: { + /* n:"RRSort", */ + }, + 320: { + /* n:"RRDMove", */ + }, + 330: { + /* n:"RRFormat", */ + }, + 331: { + /* n:"RRAutoFmt", */ + }, + 333: { + /* n:"RRInsertSh", */ + }, + 334: { + /* n:"RRDMoveBegin", */ + }, + 335: { + /* n:"RRDMoveEnd", */ + }, + 336: { + /* n:"RRDInsDelBegin", */ + }, + 337: { + /* n:"RRDInsDelEnd", */ + }, + 338: { + /* n:"RRDConflict", */ + }, + 339: { + /* n:"RRDDefName", */ + }, + 340: { + /* n:"RRDRstEtxp", */ + }, + 351: { + /* n:"LRng", */ + }, + 352: { + /* n:"UsesELFs", */ + f: parsebool + }, + 353: { + /* n:"DSF", */ + f: parsenoop2 + }, + 401: { + /* n:"CUsr", */ + }, + 402: { + /* n:"CbUsr", */ + }, + 403: { + /* n:"UsrInfo", */ + }, + 404: { + /* n:"UsrExcl", */ + }, + 405: { + /* n:"FileLock", */ + }, + 406: { + /* n:"RRDInfo", */ + }, + 407: { + /* n:"BCUsrs", */ + }, + 408: { + /* n:"UsrChk", */ + }, + 425: { + /* n:"UserBView", */ + }, + 426: { + /* n:"UserSViewBegin", */ + }, + 427: { + /* n:"UserSViewEnd", */ + }, + 428: { + /* n:"RRDUserView", */ + }, + 429: { + /* n:"Qsi", */ + }, + 430: { + /* n:"SupBook", */ + f: parse_SupBook + }, + 431: { + /* n:"Prot4Rev", */ + f: parsebool + }, + 432: { + /* n:"CondFmt", */ + }, + 433: { + /* n:"CF", */ + }, + 434: { + /* n:"DVal", */ + }, + 437: { + /* n:"DConBin", */ + }, + 438: { + /* n:"TxO", */ + f: parse_TxO + }, + 439: { + /* n:"RefreshAll", */ + f: parsebool + }, + // + 440: { + /* n:"HLink", */ + f: parse_HLink + }, + 441: { + /* n:"Lel", */ + }, + 442: { + /* n:"CodeName", */ + f: parse_XLUnicodeString + }, + 443: { + /* n:"SXFDBType", */ + }, + 444: { + /* n:"Prot4RevPass", */ + f: parseuint16 + }, + 445: { + /* n:"ObNoMacros", */ + }, + 446: { + /* n:"Dv", */ + }, + 448: { + /* n:"Excel9File", */ + f: parsenoop2 + }, + 449: { + /* n:"RecalcId", */ + f: parse_RecalcId, + r: 2 + }, + 450: { + /* n:"EntExU2", */ + f: parsenoop2 + }, + 512: { + /* n:"Dimensions", */ + f: parse_Dimensions + }, + 513: { + /* n:"Blank", */ + f: parse_Blank + }, + 515: { + /* n:"Number", */ + f: parse_Number + }, + 516: { + /* n:"Label", */ + f: parse_Label + }, + 517: { + /* n:"BoolErr", */ + f: parse_BoolErr + }, + 519: { + /* n:"String", */ + f: parse_String + }, + 520: { + /* n:"Row", */ + f: parse_Row + }, + 523: { + /* n:"Index", */ + }, + 545: { + /* n:"Array", */ + f: parse_Array + }, + 549: { + /* n:"DefaultRowHeight", */ + f: parse_DefaultRowHeight + }, + 566: { + /* n:"Table", */ + }, + 574: { + /* n:"Window2", */ + f: parse_Window2 + }, + 638: { + /* n:"RK", */ + f: parse_RK + }, + 659: { + /* n:"Style", */ + }, + 1048: { + /* n:"BigName", */ + }, + 1054: { + /* n:"Format", */ + f: parse_Format + }, + 1084: { + /* n:"ContinueBigName", */ + }, + 1212: { + /* n:"ShrFmla", */ + f: parse_ShrFmla + }, + 2048: { + /* n:"HLinkTooltip", */ + f: parse_HLinkTooltip + }, + 2049: { + /* n:"WebPub", */ + }, + 2050: { + /* n:"QsiSXTag", */ + }, + 2051: { + /* n:"DBQueryExt", */ + }, + 2052: { + /* n:"ExtString", */ + }, + 2053: { + /* n:"TxtQry", */ + }, + 2054: { + /* n:"Qsir", */ + }, + 2055: { + /* n:"Qsif", */ + }, + 2056: { + /* n:"RRDTQSIF", */ + }, + 2057: { + /* n:"BOF", */ + f: parse_BOF + }, + 2058: { + /* n:"OleDbConn", */ + }, + 2059: { + /* n:"WOpt", */ + }, + 2060: { + /* n:"SXViewEx", */ + }, + 2061: { + /* n:"SXTH", */ + }, + 2062: { + /* n:"SXPIEx", */ + }, + 2063: { + /* n:"SXVDTEx", */ + }, + 2064: { + /* n:"SXViewEx9", */ + }, + 2066: { + /* n:"ContinueFrt", */ + }, + 2067: { + /* n:"RealTimeData", */ + }, + 2128: { + /* n:"ChartFrtInfo", */ + }, + 2129: { + /* n:"FrtWrapper", */ + }, + 2130: { + /* n:"StartBlock", */ + }, + 2131: { + /* n:"EndBlock", */ + }, + 2132: { + /* n:"StartObject", */ + }, + 2133: { + /* n:"EndObject", */ + }, + 2134: { + /* n:"CatLab", */ + }, + 2135: { + /* n:"YMult", */ + }, + 2136: { + /* n:"SXViewLink", */ + }, + 2137: { + /* n:"PivotChartBits", */ + }, + 2138: { + /* n:"FrtFontList", */ + }, + 2146: { + /* n:"SheetExt", */ + }, + 2147: { + /* n:"BookExt", */ + r: 12 + }, + 2148: { + /* n:"SXAddl", */ + }, + 2149: { + /* n:"CrErr", */ + }, + 2150: { + /* n:"HFPicture", */ + }, + 2151: { + /* n:"FeatHdr", */ + f: parsenoop2 + }, + 2152: { + /* n:"Feat", */ + }, + 2154: { + /* n:"DataLabExt", */ + }, + 2155: { + /* n:"DataLabExtContents", */ + }, + 2156: { + /* n:"CellWatch", */ + }, + 2161: { + /* n:"FeatHdr11", */ + }, + 2162: { + /* n:"Feature11", */ + }, + 2164: { + /* n:"DropDownObjIds", */ + }, + 2165: { + /* n:"ContinueFrt11", */ + }, + 2166: { + /* n:"DConn", */ + }, + 2167: { + /* n:"List12", */ + }, + 2168: { + /* n:"Feature12", */ + }, + 2169: { + /* n:"CondFmt12", */ + }, + 2170: { + /* n:"CF12", */ + }, + 2171: { + /* n:"CFEx", */ + }, + 2172: { + /* n:"XFCRC", */ + f: parse_XFCRC, + r: 12 + }, + 2173: { + /* n:"XFExt", */ + f: parse_XFExt, + r: 12 + }, + 2174: { + /* n:"AutoFilter12", */ + }, + 2175: { + /* n:"ContinueFrt12", */ + }, + 2180: { + /* n:"MDTInfo", */ + }, + 2181: { + /* n:"MDXStr", */ + }, + 2182: { + /* n:"MDXTuple", */ + }, + 2183: { + /* n:"MDXSet", */ + }, + 2184: { + /* n:"MDXProp", */ + }, + 2185: { + /* n:"MDXKPI", */ + }, + 2186: { + /* n:"MDB", */ + }, + 2187: { + /* n:"PLV", */ + }, + 2188: { + /* n:"Compat12", */ + f: parsebool, + r: 12 + }, + 2189: { + /* n:"DXF", */ + }, + 2190: { + /* n:"TableStyles", */ + r: 12 + }, + 2191: { + /* n:"TableStyle", */ + }, + 2192: { + /* n:"TableStyleElement", */ + }, + 2194: { + /* n:"StyleExt", */ + }, + 2195: { + /* n:"NamePublish", */ + }, + 2196: { + /* n:"NameCmt", */ + f: parse_NameCmt, + r: 12 + }, + 2197: { + /* n:"SortData", */ + }, + 2198: { + /* n:"Theme", */ + f: parse_Theme, + r: 12 + }, + 2199: { + /* n:"GUIDTypeLib", */ + }, + 2200: { + /* n:"FnGrp12", */ + }, + 2201: { + /* n:"NameFnGrp12", */ + }, + 2202: { + /* n:"MTRSettings", */ + f: parse_MTRSettings, + r: 12 + }, + 2203: { + /* n:"CompressPictures", */ + f: parsenoop2 + }, + 2204: { + /* n:"HeaderFooter", */ + }, + 2205: { + /* n:"CrtLayout12", */ + }, + 2206: { + /* n:"CrtMlFrt", */ + }, + 2207: { + /* n:"CrtMlFrtContinue", */ + }, + 2211: { + /* n:"ForceFullCalculation", */ + f: parse_ForceFullCalculation + }, + 2212: { + /* n:"ShapePropsStream", */ + }, + 2213: { + /* n:"TextPropsStream", */ + }, + 2214: { + /* n:"RichTextStream", */ + }, + 2215: { + /* n:"CrtLayout12A", */ + }, + 4097: { + /* n:"Units", */ + }, + 4098: { + /* n:"Chart", */ + }, + 4099: { + /* n:"Series", */ + }, + 4102: { + /* n:"DataFormat", */ + }, + 4103: { + /* n:"LineFormat", */ + }, + 4105: { + /* n:"MarkerFormat", */ + }, + 4106: { + /* n:"AreaFormat", */ + }, + 4107: { + /* n:"PieFormat", */ + }, + 4108: { + /* n:"AttachedLabel", */ + }, + 4109: { + /* n:"SeriesText", */ + }, + 4116: { + /* n:"ChartFormat", */ + }, + 4117: { + /* n:"Legend", */ + }, + 4118: { + /* n:"SeriesList", */ + }, + 4119: { + /* n:"Bar", */ + }, + 4120: { + /* n:"Line", */ + }, + 4121: { + /* n:"Pie", */ + }, + 4122: { + /* n:"Area", */ + }, + 4123: { + /* n:"Scatter", */ + }, + 4124: { + /* n:"CrtLine", */ + }, + 4125: { + /* n:"Axis", */ + }, + 4126: { + /* n:"Tick", */ + }, + 4127: { + /* n:"ValueRange", */ + }, + 4128: { + /* n:"CatSerRange", */ + }, + 4129: { + /* n:"AxisLine", */ + }, + 4130: { + /* n:"CrtLink", */ + }, + 4132: { + /* n:"DefaultText", */ + }, + 4133: { + /* n:"Text", */ + }, + 4134: { + /* n:"FontX", */ + f: parseuint16 + }, + 4135: { + /* n:"ObjectLink", */ + }, + 4146: { + /* n:"Frame", */ + }, + 4147: { + /* n:"Begin", */ + }, + 4148: { + /* n:"End", */ + }, + 4149: { + /* n:"PlotArea", */ + }, + 4154: { + /* n:"Chart3d", */ + }, + 4156: { + /* n:"PicF", */ + }, + 4157: { + /* n:"DropBar", */ + }, + 4158: { + /* n:"Radar", */ + }, + 4159: { + /* n:"Surf", */ + }, + 4160: { + /* n:"RadarArea", */ + }, + 4161: { + /* n:"AxisParent", */ + }, + 4163: { + /* n:"LegendException", */ + }, + 4164: { + /* n:"ShtProps", */ + f: parse_ShtProps + }, + 4165: { + /* n:"SerToCrt", */ + }, + 4166: { + /* n:"AxesUsed", */ + }, + 4168: { + /* n:"SBaseRef", */ + }, + 4170: { + /* n:"SerParent", */ + }, + 4171: { + /* n:"SerAuxTrend", */ + }, + 4174: { + /* n:"IFmtRecord", */ + }, + 4175: { + /* n:"Pos", */ + }, + 4176: { + /* n:"AlRuns", */ + }, + 4177: { + /* n:"BRAI", */ + }, + 4187: { + /* n:"SerAuxErrBar", */ + }, + 4188: { + /* n:"ClrtClient", */ + f: parse_ClrtClient + }, + 4189: { + /* n:"SerFmt", */ + }, + 4191: { + /* n:"Chart3DBarShape", */ + }, + 4192: { + /* n:"Fbi", */ + }, + 4193: { + /* n:"BopPop", */ + }, + 4194: { + /* n:"AxcExt", */ + }, + 4195: { + /* n:"Dat", */ + }, + 4196: { + /* n:"PlotGrowth", */ + }, + 4197: { + /* n:"SIIndex", */ + }, + 4198: { + /* n:"GelFrame", */ + }, + 4199: { + /* n:"BopPopCustom", */ + }, + 4200: { + /* n:"Fbi2", */ + }, + 0: { + /* n:"Dimensions", */ + f: parse_Dimensions + }, + 1: { + /* n:"BIFF2BLANK", */ + }, + 2: { + /* n:"BIFF2INT", */ + f: parse_BIFF2INT + }, + 3: { + /* n:"BIFF2NUM", */ + f: parse_BIFF2NUM + }, + 4: { + /* n:"BIFF2STR", */ + f: parse_BIFF2STR + }, + 5: { + /* n:"BIFF2BOOLERR", */ + f: parse_BIFF2BOOLERR + }, + 7: { + /* n:"String", */ + f: parse_BIFF2STRING + }, + 8: { + /* n:"BIFF2ROW", */ + }, + 9: { + /* n:"BOF", */ + f: parse_BOF + }, + 11: { + /* n:"Index", */ + }, + 22: { + /* n:"ExternCount", */ + f: parseuint16 + }, + 30: { + /* n:"BIFF2FORMAT", */ + f: parse_BIFF2Format + }, + 31: { + /* n:"BIFF2FMTCNT", */ + }, + /* 16-bit cnt of BIFF2FORMAT records */ + 32: { + /* n:"BIFF2COLINFO", */ + }, + 33: { + /* n:"Array", */ + f: parse_Array + }, + 36: { + /* n:"COLWIDTH", */ + }, + 37: { + /* n:"DefaultRowHeight", */ + f: parse_DefaultRowHeight + }, + // 0x002c ?? + // 0x002d ?? + // 0x002e ?? + // 0x0030 FONTCOUNT: number of fonts + 50: { + /* n:"BIFF2FONTXTRA", */ + f: parse_BIFF2FONTXTRA + }, + // 0x0035: INFOOPTS + // 0x0036: TABLE (BIFF2 only) + // 0x0037: TABLE2 (BIFF2 only) + // 0x0038: WNDESK + // 0x0039 ?? + // 0x003a: BEGINPREF + // 0x003b: ENDPREF + 62: { + /* n:"BIFF2WINDOW2", */ + }, + // 0x003f ?? + // 0x0046: SHOWSCROLL + // 0x0047: SHOWFORMULA + // 0x0048: STATUSBAR + // 0x0049: SHORTMENUS + // 0x004A: + // 0x004B: + // 0x004C: + // 0x004E: + // 0x004F: + // 0x0058: TOOLBAR (BIFF3) + /* - - - */ + 52: { + /* n:"DDEObjName", */ + }, + 67: { + /* n:"BIFF2XF", */ + f: parse_BIFF2XF + }, + 68: { + /* n:"BIFF2XFINDEX", */ + f: parseuint16 + }, + 69: { + /* n:"BIFF2FONTCLR", */ + }, + 86: { + /* n:"BIFF4FMTCNT", */ + }, + /* 16-bit cnt, similar to BIFF2 */ + 126: { + /* n:"RK", */ + }, + /* Not necessarily same as 0x027e */ + 127: { + /* n:"ImData", */ + f: parse_ImData + }, + 135: { + /* n:"Addin", */ + }, + 136: { + /* n:"Edg", */ + }, + 137: { + /* n:"Pub", */ + }, + // 0x8A + // 0x8B LH: alternate menu key flag (BIFF3/4) + // 0x8E + 143: { + /* n:"BIFF4SheetInfo", */ + f: parse_BIFF4SheetInfo + }, + 145: { + /* n:"Sub", */ + }, + // 0x93 STYLE + 148: { + /* n:"LHRecord", */ + }, + 149: { + /* n:"LHNGraph", */ + }, + 150: { + /* n:"Sound", */ + }, + // 0xA2 FNPROTO: function prototypes (BIFF4) + // 0xA3 + // 0xA8 + 169: { + /* n:"CoordList", */ + }, + 171: { + /* n:"GCW", */ + }, + 188: { + /* n:"ShrFmla", */ + }, + /* Not necessarily same as 0x04bc */ + 191: { + /* n:"ToolbarHdr", */ + }, + 192: { + /* n:"ToolbarEnd", */ + }, + 194: { + /* n:"AddMenu", */ + }, + 195: { + /* n:"DelMenu", */ + }, + 214: { + /* n:"RString", */ + f: parse_RString + }, + 223: { + /* n:"UDDesc", */ + }, + 234: { + /* n:"TabIdConf", */ + }, + 354: { + /* n:"XL5Modify", */ + }, + 421: { + /* n:"FileSharing2", */ + }, + 518: { + /* n:"Formula", */ + f: parse_Formula + }, + 521: { + /* n:"BOF", */ + f: parse_BOF + }, + 536: { + /* n:"Lbl", */ + f: parse_Lbl + }, + 547: { + /* n:"ExternName", */ + f: parse_ExternName + }, + 561: { + /* n:"Font", */ + }, + 579: { + /* n:"BIFF3XF", */ + f: parse_BIFF3XF + }, + 1030: { + /* n:"Formula", */ + f: parse_Formula + }, + 1033: { + /* n:"BOF", */ + f: parse_BOF + }, + 1091: { + /* n:"BIFF4XF", */ + f: parse_BIFF4XF + }, + 2157: { + /* n:"FeatInfo", */ + }, + 2163: { + /* n:"FeatInfo11", */ + }, + 2177: { + /* n:"SXAddl12", */ + }, + 2240: { + /* n:"AutoWebPub", */ + }, + 2241: { + /* n:"ListObj", */ + }, + 2242: { + /* n:"ListField", */ + }, + 2243: { + /* n:"ListDV", */ + }, + 2244: { + /* n:"ListCondFmt", */ + }, + 2245: { + /* n:"ListCF", */ + }, + 2246: { + /* n:"FMQry", */ + }, + 2247: { + /* n:"FMSQry", */ + }, + 2248: { + /* n:"PLV", */ + }, + 2249: { + /* n:"LnExt", */ + }, + 2250: { + /* n:"MkrExt", */ + }, + 2251: { + /* n:"CrtCoopt", */ + }, + 2262: { + /* n:"FRTArchId$", */ + r: 12 + }, + /* --- multiplan 4 records --- */ + 101: { + /* n:"", */ + }, + // one per window + 102: { + /* n:"", */ + }, + // calc settings + 105: { + /* n:"", */ + }, + // print header + 106: { + /* n:"", */ + }, + // print footer + 107: { + /* n:"", */ + }, + // print settings + 109: { + /* n:"", */ + }, + // one per window + 112: { + /* n:"", */ + }, + // includes default col width + 114: { + /* n:"", */ + }, + // includes selected cell + 29282: {} + }; + HTML_BEGIN = 'SheetJS Table Export'; + HTML_END = ""; + subarray = (function() { + try { + if (typeof Uint8Array == "undefined") + return "slice"; + if (typeof Uint8Array.prototype.subarray == "undefined") + return "slice"; + if (typeof Buffer !== "undefined") { + if (typeof Buffer.prototype.subarray == "undefined") + return "slice"; + if ((typeof Buffer.from == "function" ? Buffer.from([72, 62]) : new Buffer([72, 62])) instanceof Uint8Array) + return "subarray"; + return "slice"; + } + return "subarray"; + } catch (e9) { + return "slice"; + } + })(); + numbers_lut_new = function() { + return { sst: [], rsst: [], ofmt: [], nfmt: [], fmla: [], ferr: [], cmnt: [] }; + }; + qreg = /"/g; + utils = { + encode_col, + encode_row, + encode_cell, + encode_range, + decode_col, + decode_row, + split_cell, + decode_cell, + decode_range, + format_cell, + sheet_new, + sheet_add_aoa, + sheet_add_json, + sheet_add_dom, + aoa_to_sheet, + json_to_sheet, + table_to_sheet: parse_dom_table, + table_to_book, + sheet_to_csv, + sheet_to_txt, + sheet_to_json, + sheet_to_html, + sheet_to_formulae, + sheet_to_row_object_array: sheet_to_json, + sheet_get_cell: ws_get_cell_stub, + book_new, + book_append_sheet, + book_set_sheet_visibility, + cell_set_number_format, + cell_set_hyperlink, + cell_set_internal_link, + cell_add_comment, + sheet_set_array_formula, + consts: { + SHEET_VISIBLE: 0, + SHEET_HIDDEN: 1, + SHEET_VERY_HIDDEN: 2 + } + }; + version3 = XLSX.version; + } +}); + +// ../pi-mono/packages/web-ui/dist/utils/attachment-utils.js +async function loadAttachment(source, fileName) { + let arrayBuffer; + let detectedFileName = fileName || "unnamed"; + let mimeType = "application/octet-stream"; + let size = 0; + if (typeof source === "string") { + const response = await fetch(source); + if (!response.ok) { + throw new Error(i18n("Failed to fetch file")); + } + arrayBuffer = await response.arrayBuffer(); + size = arrayBuffer.byteLength; + mimeType = response.headers.get("content-type") || mimeType; + if (!fileName) { + const urlParts = source.split("/"); + detectedFileName = urlParts[urlParts.length - 1] || "document"; + } + } else if (source instanceof File) { + arrayBuffer = await source.arrayBuffer(); + size = source.size; + mimeType = source.type || mimeType; + detectedFileName = fileName || source.name; + } else if (source instanceof Blob) { + arrayBuffer = await source.arrayBuffer(); + size = source.size; + mimeType = source.type || mimeType; + } else if (source instanceof ArrayBuffer) { + arrayBuffer = source; + size = source.byteLength; + } else { + throw new Error(i18n("Invalid source type")); + } + const uint8Array = new Uint8Array(arrayBuffer); + let binary = ""; + const chunkSize = 32768; + for (let i7 = 0; i7 < uint8Array.length; i7 += chunkSize) { + const chunk = uint8Array.slice(i7, i7 + chunkSize); + binary += String.fromCharCode(...chunk); + } + const base64Content = btoa(binary); + const id = `${detectedFileName}_${Date.now()}_${Math.random()}`; + if (mimeType === "application/pdf" || detectedFileName.toLowerCase().endsWith(".pdf")) { + const { extractedText, preview } = await processPdf(arrayBuffer, detectedFileName); + return { + id, + type: "document", + fileName: detectedFileName, + mimeType: "application/pdf", + size, + content: base64Content, + extractedText, + preview + }; + } + if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || detectedFileName.toLowerCase().endsWith(".docx")) { + const { extractedText } = await processDocx(arrayBuffer, detectedFileName); + return { + id, + type: "document", + fileName: detectedFileName, + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + size, + content: base64Content, + extractedText + }; + } + if (mimeType === "application/vnd.openxmlformats-officedocument.presentationml.presentation" || detectedFileName.toLowerCase().endsWith(".pptx")) { + const { extractedText } = await processPptx(arrayBuffer, detectedFileName); + return { + id, + type: "document", + fileName: detectedFileName, + mimeType: "application/vnd.openxmlformats-officedocument.presentationml.presentation", + size, + content: base64Content, + extractedText + }; + } + const excelMimeTypes = [ + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.ms-excel" + ]; + if (excelMimeTypes.includes(mimeType) || detectedFileName.toLowerCase().endsWith(".xlsx") || detectedFileName.toLowerCase().endsWith(".xls")) { + const { extractedText } = await processExcel(arrayBuffer, detectedFileName); + return { + id, + type: "document", + fileName: detectedFileName, + mimeType: mimeType.startsWith("application/vnd") ? mimeType : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + size, + content: base64Content, + extractedText + }; + } + if (mimeType.startsWith("image/")) { + return { + id, + type: "image", + fileName: detectedFileName, + mimeType, + size, + content: base64Content, + preview: base64Content + // For images, preview is the same as content + }; + } + const textExtensions = [ + ".txt", + ".md", + ".json", + ".xml", + ".html", + ".css", + ".js", + ".ts", + ".jsx", + ".tsx", + ".yml", + ".yaml" + ]; + const isTextFile = mimeType.startsWith("text/") || textExtensions.some((ext2) => detectedFileName.toLowerCase().endsWith(ext2)); + if (isTextFile) { + const decoder = new TextDecoder(); + const text3 = decoder.decode(arrayBuffer); + return { + id, + type: "document", + fileName: detectedFileName, + mimeType: mimeType.startsWith("text/") ? mimeType : "text/plain", + size, + content: base64Content, + extractedText: text3 + }; + } + throw new Error(`Unsupported file type: ${mimeType}`); +} +async function processPdf(arrayBuffer, fileName) { + let pdf = null; + try { + pdf = await getDocument({ data: arrayBuffer }).promise; + let extractedText = ``; + for (let i7 = 1; i7 <= pdf.numPages; i7++) { + const page = await pdf.getPage(i7); + const textContent = await page.getTextContent(); + const pageText = textContent.items.map((item) => item.str).filter((str2) => str2.trim()).join(" "); + extractedText += ` + +${pageText} +`; + } + extractedText += "\n"; + const preview = await generatePdfPreview(pdf); + return { extractedText, preview }; + } catch (error) { + console.error("Error processing PDF:", error); + throw new Error(`Failed to process PDF: ${String(error)}`); + } finally { + if (pdf) { + pdf.destroy(); + } + } +} +async function generatePdfPreview(pdf) { + try { + const page = await pdf.getPage(1); + const viewport = page.getViewport({ scale: 1 }); + const scale = Math.min(160 / viewport.width, 160 / viewport.height); + const scaledViewport = page.getViewport({ scale }); + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + if (!context) { + return void 0; + } + canvas.height = scaledViewport.height; + canvas.width = scaledViewport.width; + const renderContext = { + canvasContext: context, + viewport: scaledViewport, + canvas + }; + await page.render(renderContext).promise; + return canvas.toDataURL("image/png").split(",")[1]; + } catch (error) { + console.error("Error generating PDF preview:", error); + return void 0; + } +} +async function processDocx(arrayBuffer, fileName) { + try { + const wordDoc = await parseAsync(arrayBuffer); + let extractedText = ` + +`; + const body = wordDoc.documentPart?.body; + if (body?.children) { + const texts = []; + for (const element of body.children) { + const text3 = extractTextFromElement(element); + if (text3) { + texts.push(text3); + } + } + extractedText += texts.join("\n"); + } + extractedText += ` + +`; + return { extractedText }; + } catch (error) { + console.error("Error processing DOCX:", error); + throw new Error(`Failed to process DOCX: ${String(error)}`); + } +} +function extractTextFromElement(element) { + let text3 = ""; + const elementType = element.type?.toLowerCase() || ""; + if (elementType === "paragraph" && element.children) { + for (const child of element.children) { + const childType = child.type?.toLowerCase() || ""; + if (childType === "run" && child.children) { + for (const textChild of child.children) { + const textType = textChild.type?.toLowerCase() || ""; + if (textType === "text") { + text3 += textChild.text || ""; + } + } + } else if (childType === "text") { + text3 += child.text || ""; + } + } + } else if (elementType === "table") { + if (element.children) { + const tableTexts = []; + for (const row of element.children) { + const rowType = row.type?.toLowerCase() || ""; + if (rowType === "tablerow" && row.children) { + const rowTexts = []; + for (const cell of row.children) { + const cellType = cell.type?.toLowerCase() || ""; + if (cellType === "tablecell" && cell.children) { + const cellTexts = []; + for (const cellElement of cell.children) { + const cellText = extractTextFromElement(cellElement); + if (cellText) + cellTexts.push(cellText); + } + if (cellTexts.length > 0) + rowTexts.push(cellTexts.join(" ")); + } + } + if (rowTexts.length > 0) + tableTexts.push(rowTexts.join(" | ")); + } + } + if (tableTexts.length > 0) { + text3 = ` +[Table] +${tableTexts.join("\n")} +[/Table] +`; + } + } + } else if (element.children && Array.isArray(element.children)) { + const childTexts = []; + for (const child of element.children) { + const childText = extractTextFromElement(child); + if (childText) + childTexts.push(childText); + } + text3 = childTexts.join(" "); + } + return text3.trim(); +} +async function processPptx(arrayBuffer, fileName) { + try { + const zip = await import_jszip2.default.loadAsync(arrayBuffer); + let extractedText = ``; + const slideFiles = Object.keys(zip.files).filter((name) => name.match(/ppt\/slides\/slide\d+\.xml$/)).sort((a3, b4) => { + const numA = Number.parseInt(a3.match(/slide(\d+)\.xml$/)?.[1] || "0", 10); + const numB = Number.parseInt(b4.match(/slide(\d+)\.xml$/)?.[1] || "0", 10); + return numA - numB; + }); + for (let i7 = 0; i7 < slideFiles.length; i7++) { + const slideFile = zip.file(slideFiles[i7]); + if (slideFile) { + const slideXml = await slideFile.async("text"); + const textMatches = slideXml.match(/]*>([^<]+)<\/a:t>/g); + if (textMatches) { + extractedText += ` +`; + const slideTexts = textMatches.map((match2) => { + const textMatch = match2.match(/]*>([^<]+)<\/a:t>/); + return textMatch ? textMatch[1] : ""; + }).filter((t6) => t6.trim()); + if (slideTexts.length > 0) { + extractedText += ` +${slideTexts.join("\n")}`; + } + extractedText += "\n"; + } + } + } + const notesFiles = Object.keys(zip.files).filter((name) => name.match(/ppt\/notesSlides\/notesSlide\d+\.xml$/)).sort((a3, b4) => { + const numA = Number.parseInt(a3.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10); + const numB = Number.parseInt(b4.match(/notesSlide(\d+)\.xml$/)?.[1] || "0", 10); + return numA - numB; + }); + if (notesFiles.length > 0) { + extractedText += "\n"; + for (const noteFile of notesFiles) { + const file = zip.file(noteFile); + if (file) { + const noteXml = await file.async("text"); + const textMatches = noteXml.match(/]*>([^<]+)<\/a:t>/g); + if (textMatches) { + const noteTexts = textMatches.map((match2) => { + const textMatch = match2.match(/]*>([^<]+)<\/a:t>/); + return textMatch ? textMatch[1] : ""; + }).filter((t6) => t6.trim()); + if (noteTexts.length > 0) { + const slideNum = noteFile.match(/notesSlide(\d+)\.xml$/)?.[1]; + extractedText += ` +[Slide ${slideNum} notes]: ${noteTexts.join(" ")}`; + } + } + } + } + extractedText += "\n"; + } + extractedText += "\n"; + return { extractedText }; + } catch (error) { + console.error("Error processing PPTX:", error); + throw new Error(`Failed to process PPTX: ${String(error)}`); + } +} +async function processExcel(arrayBuffer, fileName) { + try { + const workbook = readSync(arrayBuffer, { type: "array" }); + let extractedText = ``; + for (const [index2, sheetName] of workbook.SheetNames.entries()) { + const worksheet = workbook.Sheets[sheetName]; + const csvText = utils.sheet_to_csv(worksheet); + extractedText += ` + +${csvText} +`; + } + extractedText += "\n"; + return { extractedText }; + } catch (error) { + console.error("Error processing Excel:", error); + throw new Error(`Failed to process Excel: ${String(error)}`); + } +} +var import_jszip2; +var init_attachment_utils = __esm({ + "../pi-mono/packages/web-ui/dist/utils/attachment-utils.js"() { + "use strict"; + init_process_shim(); + init_docx_preview(); + import_jszip2 = __toESM(require_jszip_min(), 1); + init_pdf(); + init_xlsx(); + init_i18n2(); + GlobalWorkerOptions.workerSrc = new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url).toString(); + } +}); + +// node_modules/lit/html.js +var init_html = __esm({ + "node_modules/lit/html.js"() { + init_process_shim(); + init_lit_html(); + } +}); + +// ../mini-lit/dist/ModeToggle.js +var __decorate3, ModeToggle; +var init_ModeToggle = __esm({ + "../mini-lit/dist/ModeToggle.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_decorators(); + init_i18n(); + __decorate3 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + ModeToggle = class ModeToggle2 extends i4 { + constructor() { + super(...arguments); + this.modes = [i18n("Mode 1"), i18n("Mode 2")]; + this.selectedIndex = 0; + } + createRenderRoot() { + return this; + } + setMode(index2) { + if (this.selectedIndex !== index2 && index2 >= 0 && index2 < this.modes.length) { + this.selectedIndex = index2; + this.dispatchEvent(new CustomEvent("mode-change", { + detail: { index: index2, mode: this.modes[index2] }, + bubbles: true + })); + } + } + render() { + if (this.modes.length < 2) + return b2``; + return b2` +
+ ${this.modes.map((mode, index2) => b2` + + `)} +
+ `; + } + }; + __decorate3([ + n6({ type: Array }) + ], ModeToggle.prototype, "modes", void 0); + __decorate3([ + n6({ type: Number }) + ], ModeToggle.prototype, "selectedIndex", void 0); + ModeToggle = __decorate3([ + t5("mode-toggle") + ], ModeToggle); + } +}); + +// ../pi-mono/packages/web-ui/dist/dialogs/AttachmentOverlay.js +var __decorate4, AttachmentOverlay; +var init_AttachmentOverlay = __esm({ + "../pi-mono/packages/web-ui/dist/dialogs/AttachmentOverlay.js"() { + "use strict"; + init_process_shim(); + init_ModeToggle(); + init_dist(); + init_Button(); + init_docx_preview(); + init_lit(); + init_decorators(); + init_lucide2(); + init_pdf(); + init_xlsx(); + init_i18n2(); + __decorate4 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + AttachmentOverlay = class _AttachmentOverlay extends i4 { + constructor() { + super(...arguments); + this.showExtractedText = false; + this.error = null; + this.currentLoadingTask = null; + this.handleBackdropClick = () => { + this.close(); + }; + this.handleDownload = () => { + if (!this.attachment) + return; + const byteCharacters = atob(this.attachment.content); + const byteNumbers = new Array(byteCharacters.length); + for (let i7 = 0; i7 < byteCharacters.length; i7++) { + byteNumbers[i7] = byteCharacters.charCodeAt(i7); + } + const byteArray = new Uint8Array(byteNumbers); + const blob = new Blob([byteArray], { type: this.attachment.mimeType }); + const url = URL.createObjectURL(blob); + const a3 = document.createElement("a"); + a3.href = url; + a3.download = this.attachment.fileName; + document.body.appendChild(a3); + a3.click(); + document.body.removeChild(a3); + URL.revokeObjectURL(url); + }; + } + createRenderRoot() { + return this; + } + static open(attachment, onClose) { + const overlay = new _AttachmentOverlay(); + overlay.attachment = attachment; + overlay.onCloseCallback = onClose; + document.body.appendChild(overlay); + overlay.setupEventListeners(); + } + setupEventListeners() { + this.boundHandleKeyDown = (e9) => { + if (e9.key === "Escape") { + this.close(); + } + }; + window.addEventListener("keydown", this.boundHandleKeyDown); + } + close() { + this.cleanup(); + if (this.boundHandleKeyDown) { + window.removeEventListener("keydown", this.boundHandleKeyDown); + } + this.onCloseCallback?.(); + this.remove(); + } + getFileType() { + if (!this.attachment) + return "text"; + if (this.attachment.type === "image") + return "image"; + if (this.attachment.mimeType === "application/pdf") + return "pdf"; + if (this.attachment.mimeType?.includes("wordprocessingml")) + return "docx"; + if (this.attachment.mimeType?.includes("presentationml") || this.attachment.fileName.toLowerCase().endsWith(".pptx")) + return "pptx"; + if (this.attachment.mimeType?.includes("spreadsheetml") || this.attachment.mimeType?.includes("ms-excel") || this.attachment.fileName.toLowerCase().endsWith(".xlsx") || this.attachment.fileName.toLowerCase().endsWith(".xls")) + return "excel"; + return "text"; + } + getFileTypeLabel() { + const type = this.getFileType(); + switch (type) { + case "pdf": + return i18n("PDF"); + case "docx": + return i18n("Document"); + case "pptx": + return i18n("Presentation"); + case "excel": + return i18n("Spreadsheet"); + default: + return ""; + } + } + cleanup() { + this.showExtractedText = false; + this.error = null; + if (this.currentLoadingTask) { + this.currentLoadingTask.destroy(); + this.currentLoadingTask = null; + } + } + render() { + if (!this.attachment) + return b2``; + return b2` + +
+ +
e9.stopPropagation()}> +
+
+ ${this.attachment.fileName} +
+
+ ${this.renderToggle()} + ${Button({ + variant: "ghost", + size: "icon", + onClick: this.handleDownload, + children: icon(Download2, "sm"), + className: "h-8 w-8" + })} + ${Button({ + variant: "ghost", + size: "icon", + onClick: () => this.close(), + children: icon(X, "sm"), + className: "h-8 w-8" + })} +
+
+
+ + +
e9.stopPropagation()}> + ${this.renderContent()} +
+
+ `; + } + renderToggle() { + if (!this.attachment) + return b2``; + const fileType = this.getFileType(); + const hasExtractedText = !!this.attachment.extractedText; + const showToggle = fileType !== "image" && fileType !== "text" && fileType !== "pptx" && hasExtractedText; + if (!showToggle) + return b2``; + const fileTypeLabel = this.getFileTypeLabel(); + return b2` + { + e9.stopPropagation(); + this.showExtractedText = e9.detail.index === 1; + this.error = null; + }} + > + `; + } + renderContent() { + if (!this.attachment) + return b2``; + if (this.error) { + return b2` +
+
${i18n("Error loading file")}
+
${this.error}
+
+ `; + } + return this.renderFileContent(); + } + renderFileContent() { + if (!this.attachment) + return b2``; + const fileType = this.getFileType(); + if (this.showExtractedText && fileType !== "image") { + return b2` +
+
${this.attachment.extractedText || i18n("No text content available")}
+
+ `; + } + switch (fileType) { + case "image": { + const imageUrl = `data:${this.attachment.mimeType};base64,${this.attachment.content}`; + return b2` + ${this.attachment.fileName} + `; + } + case "pdf": + return b2` +
+ `; + case "docx": + return b2` +
+ `; + case "excel": + return b2`
`; + case "pptx": + return b2` +
+ `; + default: + return b2` +
+
${this.attachment.extractedText || i18n("No content available")}
+
+ `; + } + } + async updated(changedProperties) { + super.updated(changedProperties); + if ((changedProperties.has("attachment") || changedProperties.has("showExtractedText")) && this.attachment && !this.showExtractedText && !this.error) { + const fileType = this.getFileType(); + switch (fileType) { + case "pdf": + await this.renderPdf(); + break; + case "docx": + await this.renderDocx(); + break; + case "excel": + await this.renderExcel(); + break; + case "pptx": + await this.renderExtractedText(); + break; + } + } + } + async renderPdf() { + const container = this.querySelector("#pdf-container"); + if (!container || !this.attachment) + return; + let pdf = null; + try { + const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content); + if (this.currentLoadingTask) { + this.currentLoadingTask.destroy(); + } + this.currentLoadingTask = getDocument({ data: arrayBuffer }); + pdf = await this.currentLoadingTask.promise; + this.currentLoadingTask = null; + container.innerHTML = ""; + const wrapper = document.createElement("div"); + wrapper.className = ""; + container.appendChild(wrapper); + for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) { + const page = await pdf.getPage(pageNum); + const pageContainer = document.createElement("div"); + pageContainer.className = "mb-4 last:mb-0"; + const canvas = document.createElement("canvas"); + const context = canvas.getContext("2d"); + const viewport = page.getViewport({ scale: 1.5 }); + canvas.height = viewport.height; + canvas.width = viewport.width; + canvas.className = "w-full max-w-full h-auto block mx-auto bg-white rounded shadow-sm border border-border"; + if (context) { + context.fillStyle = "white"; + context.fillRect(0, 0, canvas.width, canvas.height); + } + await page.render({ + canvasContext: context, + viewport, + canvas + }).promise; + pageContainer.appendChild(canvas); + if (pageNum < pdf.numPages) { + const separator = document.createElement("div"); + separator.className = "h-px bg-border my-4"; + pageContainer.appendChild(separator); + } + wrapper.appendChild(pageContainer); + } + } catch (error) { + console.error("Error rendering PDF:", error); + this.error = error?.message || i18n("Failed to load PDF"); + } finally { + if (pdf) { + pdf.destroy(); + } + } + } + async renderDocx() { + const container = this.querySelector("#docx-container"); + if (!container || !this.attachment) + return; + try { + const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content); + container.innerHTML = ""; + const wrapper = document.createElement("div"); + wrapper.className = "docx-wrapper-custom"; + container.appendChild(wrapper); + await renderAsync(arrayBuffer, wrapper, void 0, { + className: "docx", + inWrapper: true, + ignoreWidth: true, + // Let it be responsive + ignoreHeight: false, + ignoreFonts: false, + breakPages: true, + ignoreLastRenderedPageBreak: true, + experimental: false, + trimXmlDeclaration: true, + useBase64URL: false, + renderHeaders: true, + renderFooters: true, + renderFootnotes: true, + renderEndnotes: true + }); + const style = document.createElement("style"); + style.textContent = ` + #docx-container { + padding: 0; + } + + #docx-container .docx-wrapper-custom { + max-width: 100%; + overflow-x: auto; + } + + #docx-container .docx-wrapper { + max-width: 100% !important; + margin: 0 !important; + background: transparent !important; + padding: 0em !important; + } + + #docx-container .docx-wrapper > section.docx { + box-shadow: none !important; + border: none !important; + border-radius: 0 !important; + margin: 0 !important; + padding: 2em !important; + background: white !important; + color: black !important; + max-width: 100% !important; + width: 100% !important; + min-width: 0 !important; + overflow-x: auto !important; + } + + /* Fix tables and wide content */ + #docx-container table { + max-width: 100% !important; + width: auto !important; + overflow-x: auto !important; + display: block !important; + } + + #docx-container img { + max-width: 100% !important; + height: auto !important; + } + + /* Fix paragraphs and text */ + #docx-container p, + #docx-container span, + #docx-container div { + max-width: 100% !important; + word-wrap: break-word !important; + overflow-wrap: break-word !important; + } + + /* Hide page breaks in web view */ + #docx-container .docx-page-break { + display: none !important; + } + `; + container.appendChild(style); + } catch (error) { + console.error("Error rendering DOCX:", error); + this.error = error?.message || i18n("Failed to load document"); + } + } + async renderExcel() { + const container = this.querySelector("#excel-container"); + if (!container || !this.attachment) + return; + try { + const arrayBuffer = this.base64ToArrayBuffer(this.attachment.content); + const workbook = readSync(arrayBuffer, { type: "array" }); + container.innerHTML = ""; + const wrapper = document.createElement("div"); + wrapper.className = "overflow-auto h-full flex flex-col"; + container.appendChild(wrapper); + if (workbook.SheetNames.length > 1) { + const tabContainer = document.createElement("div"); + tabContainer.className = "flex gap-2 mb-4 border-b border-border sticky top-0 bg-card z-10"; + const sheetContents = []; + workbook.SheetNames.forEach((sheetName, index2) => { + const tab = document.createElement("button"); + tab.textContent = sheetName; + tab.className = index2 === 0 ? "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary" : "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors"; + const sheetDiv = document.createElement("div"); + sheetDiv.style.display = index2 === 0 ? "flex" : "none"; + sheetDiv.className = "flex-1 overflow-auto"; + sheetDiv.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName)); + sheetContents.push(sheetDiv); + tab.onclick = () => { + tabContainer.querySelectorAll("button").forEach((btn, btnIndex) => { + if (btnIndex === index2) { + btn.className = "px-4 py-2 text-sm font-medium border-b-2 border-primary text-primary"; + } else { + btn.className = "px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:border-b-2 hover:border-border transition-colors"; + } + }); + sheetContents.forEach((content, contentIndex) => { + content.style.display = contentIndex === index2 ? "flex" : "none"; + }); + }; + tabContainer.appendChild(tab); + }); + wrapper.appendChild(tabContainer); + sheetContents.forEach((content) => { + wrapper.appendChild(content); + }); + } else { + const sheetName = workbook.SheetNames[0]; + wrapper.appendChild(this.renderExcelSheet(workbook.Sheets[sheetName], sheetName)); + } + } catch (error) { + console.error("Error rendering Excel:", error); + this.error = error?.message || i18n("Failed to load spreadsheet"); + } + } + renderExcelSheet(worksheet, sheetName) { + const sheetDiv = document.createElement("div"); + const htmlTable = utils.sheet_to_html(worksheet, { id: `sheet-${sheetName}` }); + const tempDiv = document.createElement("div"); + tempDiv.innerHTML = htmlTable; + const table = tempDiv.querySelector("table"); + if (table) { + table.className = "w-full border-collapse text-foreground"; + table.querySelectorAll("td, th").forEach((cell) => { + const cellEl = cell; + cellEl.className = "border border-border px-3 py-2 text-sm text-left"; + }); + const headerCells = table.querySelectorAll("thead th, tr:first-child td"); + if (headerCells.length > 0) { + headerCells.forEach((th) => { + const thEl = th; + thEl.className = "border border-border px-3 py-2 text-sm font-semibold bg-muted text-foreground sticky top-0"; + }); + } + table.querySelectorAll("tbody tr:nth-child(even)").forEach((row) => { + const rowEl = row; + rowEl.className = "bg-muted/30"; + }); + sheetDiv.appendChild(table); + } + return sheetDiv; + } + base64ToArrayBuffer(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i7 = 0; i7 < binaryString.length; i7++) { + bytes[i7] = binaryString.charCodeAt(i7); + } + return bytes.buffer; + } + async renderExtractedText() { + const container = this.querySelector("#pptx-container"); + if (!container || !this.attachment) + return; + try { + container.innerHTML = ""; + const wrapper = document.createElement("div"); + wrapper.className = "p-6 overflow-auto"; + const pre = document.createElement("pre"); + pre.className = "whitespace-pre-wrap text-sm text-foreground font-mono"; + pre.textContent = this.attachment.extractedText || i18n("No text content available"); + wrapper.appendChild(pre); + container.appendChild(wrapper); + } catch (error) { + console.error("Error rendering extracted text:", error); + this.error = error?.message || i18n("Failed to display text content"); + } + } + }; + __decorate4([ + r7() + ], AttachmentOverlay.prototype, "attachment", void 0); + __decorate4([ + r7() + ], AttachmentOverlay.prototype, "showExtractedText", void 0); + __decorate4([ + r7() + ], AttachmentOverlay.prototype, "error", void 0); + if (!customElements.get("attachment-overlay")) { + customElements.define("attachment-overlay", AttachmentOverlay); + } + } +}); + +// ../pi-mono/packages/web-ui/dist/components/AttachmentTile.js +var __decorate5, AttachmentTile; +var init_AttachmentTile = __esm({ + "../pi-mono/packages/web-ui/dist/components/AttachmentTile.js"() { + "use strict"; + init_process_shim(); + init_icons(); + init_lit(); + init_decorators(); + init_html(); + init_lucide2(); + init_AttachmentOverlay(); + init_i18n2(); + __decorate5 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + AttachmentTile = class AttachmentTile2 extends i4 { + constructor() { + super(...arguments); + this.showDelete = false; + this.handleClick = () => { + AttachmentOverlay.open(this.attachment); + }; + } + createRenderRoot() { + return this; + } + connectedCallback() { + super.connectedCallback(); + this.style.display = "block"; + this.classList.add("max-h-16"); + } + render() { + const hasPreview = !!this.attachment.preview; + const isImage = this.attachment.type === "image"; + const isPdf = this.attachment.mimeType === "application/pdf"; + const isExcel = this.attachment.mimeType?.includes("spreadsheetml") || this.attachment.fileName.toLowerCase().endsWith(".xlsx") || this.attachment.fileName.toLowerCase().endsWith(".xls"); + const getDocumentIcon = () => { + if (isExcel) + return icon(FileSpreadsheet, "md"); + return icon(FileText, "md"); + }; + return b2` +
+ ${hasPreview ? b2` +
+ ${this.attachment.fileName} + ${isPdf ? b2` + +
+
${i18n("PDF")}
+
+ ` : ""} +
+ ` : b2` + +
+ ${getDocumentIcon()} +
+ ${this.attachment.fileName.length > 10 ? `${this.attachment.fileName.substring(0, 8)}...` : this.attachment.fileName} +
+
+ `} + ${this.showDelete ? b2` + + ` : ""} +
+ `; + } + }; + __decorate5([ + n6({ type: Object }) + ], AttachmentTile.prototype, "attachment", void 0); + __decorate5([ + n6({ type: Boolean }) + ], AttachmentTile.prototype, "showDelete", void 0); + __decorate5([ + n6() + ], AttachmentTile.prototype, "onDelete", void 0); + AttachmentTile = __decorate5([ + t5("attachment-tile") + ], AttachmentTile); + } +}); + +// ../pi-mono/packages/web-ui/dist/components/MessageEditor.js +var __decorate6, MessageEditor; +var init_MessageEditor = __esm({ + "../pi-mono/packages/web-ui/dist/components/MessageEditor.js"() { + "use strict"; + init_process_shim(); + init_dist(); + init_Button(); + init_Select(); + init_lit(); + init_decorators(); + init_ref2(); + init_lucide2(); + init_attachment_utils(); + init_i18n2(); + init_AttachmentTile(); + __decorate6 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + MessageEditor = class MessageEditor2 extends i4 { + constructor() { + super(...arguments); + this._value = ""; + this.textareaRef = e5(); + this.isStreaming = false; + this.thinkingLevel = "off"; + this.showAttachmentButton = true; + this.showModelSelector = true; + this.showThinkingSelector = true; + this.attachments = []; + this.maxFiles = 10; + this.maxFileSize = 20 * 1024 * 1024; + this.acceptedTypes = "image/*,application/pdf,.docx,.pptx,.xlsx,.xls,.txt,.md,.json,.xml,.html,.css,.js,.ts,.jsx,.tsx,.yml,.yaml"; + this.processingFiles = false; + this.isDragging = false; + this.fileInputRef = e5(); + this.handleTextareaInput = (e9) => { + const textarea = e9.target; + this.value = textarea.value; + this.onInput?.(this.value); + }; + this.handleKeyDown = (e9) => { + if (e9.key === "Enter" && !e9.shiftKey) { + e9.preventDefault(); + if (!this.isStreaming && !this.processingFiles && (this.value.trim() || this.attachments.length > 0)) { + this.handleSend(); + } + } else if (e9.key === "Escape" && this.isStreaming) { + e9.preventDefault(); + this.onAbort?.(); + } + }; + this.handlePaste = async (e9) => { + const items = e9.clipboardData?.items; + if (!items) + return; + const imageFiles = []; + for (let i7 = 0; i7 < items.length; i7++) { + const item = items[i7]; + if (item.type.startsWith("image/")) { + const file = item.getAsFile(); + if (file) { + imageFiles.push(file); + } + } + } + if (imageFiles.length > 0) { + e9.preventDefault(); + if (imageFiles.length + this.attachments.length > this.maxFiles) { + alert(`Maximum ${this.maxFiles} files allowed`); + return; + } + this.processingFiles = true; + const newAttachments = []; + for (const file of imageFiles) { + try { + if (file.size > this.maxFileSize) { + alert(`Image exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`); + continue; + } + const attachment = await loadAttachment(file); + newAttachments.push(attachment); + } catch (error) { + console.error("Error processing pasted image:", error); + alert(`Failed to process pasted image: ${String(error)}`); + } + } + this.attachments = [...this.attachments, ...newAttachments]; + this.onFilesChange?.(this.attachments); + this.processingFiles = false; + } + }; + this.handleSend = () => { + this.onSend?.(this.value, this.attachments); + }; + this.handleAttachmentClick = () => { + this.fileInputRef.value?.click(); + }; + this.handleDragOver = (e9) => { + e9.preventDefault(); + e9.stopPropagation(); + if (!this.isDragging) { + this.isDragging = true; + } + }; + this.handleDragLeave = (e9) => { + e9.preventDefault(); + e9.stopPropagation(); + const rect = e9.currentTarget.getBoundingClientRect(); + const x2 = e9.clientX; + const y4 = e9.clientY; + if (x2 <= rect.left || x2 >= rect.right || y4 <= rect.top || y4 >= rect.bottom) { + this.isDragging = false; + } + }; + this.handleDrop = async (e9) => { + e9.preventDefault(); + e9.stopPropagation(); + this.isDragging = false; + const files = Array.from(e9.dataTransfer?.files || []); + if (files.length === 0) + return; + if (files.length + this.attachments.length > this.maxFiles) { + alert(`Maximum ${this.maxFiles} files allowed`); + return; + } + this.processingFiles = true; + const newAttachments = []; + for (const file of files) { + try { + if (file.size > this.maxFileSize) { + alert(`${file.name} exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`); + continue; + } + const attachment = await loadAttachment(file); + newAttachments.push(attachment); + } catch (error) { + console.error(`Error processing ${file.name}:`, error); + alert(`Failed to process ${file.name}: ${String(error)}`); + } + } + this.attachments = [...this.attachments, ...newAttachments]; + this.onFilesChange?.(this.attachments); + this.processingFiles = false; + }; + } + get value() { + return this._value; + } + set value(val2) { + const oldValue = this._value; + this._value = val2; + this.requestUpdate("value", oldValue); + } + createRenderRoot() { + return this; + } + async handleFilesSelected(e9) { + const input = e9.target; + const files = Array.from(input.files || []); + if (files.length === 0) + return; + if (files.length + this.attachments.length > this.maxFiles) { + alert(`Maximum ${this.maxFiles} files allowed`); + input.value = ""; + return; + } + this.processingFiles = true; + const newAttachments = []; + for (const file of files) { + try { + if (file.size > this.maxFileSize) { + alert(`${file.name} exceeds maximum size of ${Math.round(this.maxFileSize / 1024 / 1024)}MB`); + continue; + } + const attachment = await loadAttachment(file); + newAttachments.push(attachment); + } catch (error) { + console.error(`Error processing ${file.name}:`, error); + alert(`Failed to process ${file.name}: ${String(error)}`); + } + } + this.attachments = [...this.attachments, ...newAttachments]; + this.onFilesChange?.(this.attachments); + this.processingFiles = false; + input.value = ""; + } + removeFile(fileId) { + this.attachments = this.attachments.filter((f4) => f4.id !== fileId); + this.onFilesChange?.(this.attachments); + } + firstUpdated() { + const textarea = this.textareaRef.value; + if (textarea) { + textarea.focus(); + } + } + render() { + const model = this.currentModel; + const supportsThinking = model?.reasoning === true; + return b2` +
+ + ${this.isDragging ? b2` +
+
${i18n("Drop files here")}
+
+ ` : ""} + + + ${this.attachments.length > 0 ? b2` +
+ ${this.attachments.map((attachment) => b2` + this.removeFile(attachment.id)} + > + `)} +
+ ` : ""} + + + + + + + +
+ +
+ ${this.showAttachmentButton ? this.processingFiles ? b2` +
+ ${icon(LoaderCircle, "sm", "animate-spin text-muted-foreground")} +
+ ` : b2` + ${Button({ + variant: "ghost", + size: "icon", + className: "h-8 w-8", + onClick: this.handleAttachmentClick, + children: icon(Paperclip, "sm") + })} + ` : ""} + ${supportsThinking && this.showThinkingSelector ? b2` + ${Select({ + value: this.thinkingLevel, + placeholder: i18n("Off"), + options: [ + { value: "off", label: i18n("Off"), icon: icon(Brain, "sm") }, + { value: "minimal", label: i18n("Minimal"), icon: icon(Brain, "sm") }, + { value: "low", label: i18n("Low"), icon: icon(Brain, "sm") }, + { value: "medium", label: i18n("Medium"), icon: icon(Brain, "sm") }, + { value: "high", label: i18n("High"), icon: icon(Brain, "sm") } + ], + onChange: (value) => { + this.onThinkingChange?.(value); + }, + width: "80px", + size: "sm", + variant: "ghost", + fitContent: true + })} + ` : ""} +
+ + +
+ ${this.showModelSelector && this.currentModel ? b2` + ${Button({ + variant: "ghost", + size: "sm", + onClick: () => { + this.textareaRef.value?.focus(); + requestAnimationFrame(() => { + this.onModelSelect?.(); + }); + }, + children: b2` + ${icon(Sparkles, "sm")} + ${this.currentModel.id} + `, + className: "h-8 text-xs truncate" + })} + ` : ""} + ${this.isStreaming ? b2` + ${Button({ + variant: "ghost", + size: "icon", + onClick: this.onAbort, + children: icon(Square, "sm"), + className: "h-8 w-8" + })} + ` : b2` + ${Button({ + variant: "ghost", + size: "icon", + onClick: this.handleSend, + disabled: !this.value.trim() && this.attachments.length === 0 || this.processingFiles, + children: b2`
${icon(Send, "sm")}
`, + className: "h-8 w-8" + })} + `} +
+
+
+ `; + } + }; + __decorate6([ + n6() + ], MessageEditor.prototype, "value", null); + __decorate6([ + n6() + ], MessageEditor.prototype, "isStreaming", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "currentModel", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "thinkingLevel", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "showAttachmentButton", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "showModelSelector", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "showThinkingSelector", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "onInput", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "onSend", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "onAbort", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "onModelSelect", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "onThinkingChange", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "onFilesChange", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "attachments", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "maxFiles", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "maxFileSize", void 0); + __decorate6([ + n6() + ], MessageEditor.prototype, "acceptedTypes", void 0); + __decorate6([ + r7() + ], MessageEditor.prototype, "processingFiles", void 0); + __decorate6([ + r7() + ], MessageEditor.prototype, "isDragging", void 0); + MessageEditor = __decorate6([ + t5("message-editor") + ], MessageEditor); + } +}); + +// node_modules/lit-html/directives/repeat.js +var u4, c5; +var init_repeat = __esm({ + "node_modules/lit-html/directives/repeat.js"() { + init_process_shim(); + init_lit_html(); + init_directive(); + init_directive_helpers(); + u4 = (e9, s6, t6) => { + const r8 = /* @__PURE__ */ new Map(); + for (let l5 = s6; l5 <= t6; l5++) r8.set(e9[l5], l5); + return r8; + }; + c5 = e4(class extends i6 { + constructor(e9) { + if (super(e9), e9.type !== t4.CHILD) throw Error("repeat() can only be used in text expressions"); + } + dt(e9, s6, t6) { + let r8; + void 0 === t6 ? t6 = s6 : void 0 !== s6 && (r8 = s6); + const l5 = [], o9 = []; + let i7 = 0; + for (const s7 of e9) l5[i7] = r8 ? r8(s7, i7) : i7, o9[i7] = t6(s7, i7), i7++; + return { values: o9, keys: l5 }; + } + render(e9, s6, t6) { + return this.dt(e9, s6, t6).values; + } + update(s6, [t6, r8, c6]) { + const d4 = M2(s6), { values: p4, keys: a3 } = this.dt(t6, r8, c6); + if (!Array.isArray(d4)) return this.ut = a3, p4; + const h7 = this.ut ??= [], v4 = []; + let m4, y4, x2 = 0, j3 = d4.length - 1, k2 = 0, w3 = p4.length - 1; + for (; x2 <= j3 && k2 <= w3; ) if (null === d4[x2]) x2++; + else if (null === d4[j3]) j3--; + else if (h7[x2] === a3[k2]) v4[k2] = u3(d4[x2], p4[k2]), x2++, k2++; + else if (h7[j3] === a3[w3]) v4[w3] = u3(d4[j3], p4[w3]), j3--, w3--; + else if (h7[x2] === a3[w3]) v4[w3] = u3(d4[x2], p4[w3]), v2(s6, v4[w3 + 1], d4[x2]), x2++, w3--; + else if (h7[j3] === a3[k2]) v4[k2] = u3(d4[j3], p4[k2]), v2(s6, d4[x2], d4[j3]), j3--, k2++; + else if (void 0 === m4 && (m4 = u4(a3, k2, w3), y4 = u4(h7, x2, j3)), m4.has(h7[x2])) if (m4.has(h7[j3])) { + const e9 = y4.get(a3[k2]), t7 = void 0 !== e9 ? d4[e9] : null; + if (null === t7) { + const e10 = v2(s6, d4[x2]); + u3(e10, p4[k2]), v4[k2] = e10; + } else v4[k2] = u3(t7, p4[k2]), v2(s6, d4[x2], t7), d4[e9] = null; + k2++; + } else h3(d4[j3]), j3--; + else h3(d4[x2]), x2++; + for (; k2 <= w3; ) { + const e9 = v2(s6, v4[w3 + 1]); + u3(e9, p4[k2]), v4[k2++] = e9; + } + for (; x2 <= j3; ) { + const e9 = d4[x2++]; + null !== e9 && h3(e9); + } + return this.ut = a3, p3(s6, v4), E; + } + }); + } +}); + +// node_modules/lit/directives/repeat.js +var init_repeat2 = __esm({ + "node_modules/lit/directives/repeat.js"() { + init_process_shim(); + init_repeat(); + } +}); + +// ../pi-mono/packages/web-ui/dist/components/message-renderer-registry.js +function registerMessageRenderer(role, renderer) { + messageRenderers.set(role, renderer); +} +function renderMessage(message) { + return messageRenderers.get(message.role)?.render(message); +} +var messageRenderers; +var init_message_renderer_registry = __esm({ + "../pi-mono/packages/web-ui/dist/components/message-renderer-registry.js"() { + "use strict"; + init_process_shim(); + messageRenderers = /* @__PURE__ */ new Map(); + } +}); + +// ../pi-mono/packages/web-ui/dist/components/MessageList.js +var __decorate7, MessageList; +var init_MessageList = __esm({ + "../pi-mono/packages/web-ui/dist/components/MessageList.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_decorators(); + init_repeat2(); + init_message_renderer_registry(); + __decorate7 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + MessageList = class extends i4 { + constructor() { + super(...arguments); + this.messages = []; + this.tools = []; + this.isStreaming = false; + } + createRenderRoot() { + return this; + } + connectedCallback() { + super.connectedCallback(); + this.style.display = "block"; + } + buildRenderItems() { + const resultByCallId = /* @__PURE__ */ new Map(); + for (const message of this.messages) { + if (message.role === "toolResult") { + resultByCallId.set(message.toolCallId, message); + } + } + const items = []; + let index2 = 0; + for (const msg of this.messages) { + if (msg.role === "artifact") { + continue; + } + const customTemplate = renderMessage(msg); + if (customTemplate) { + items.push({ key: `msg:${index2}`, template: customTemplate }); + index2++; + continue; + } + if (msg.role === "user" || msg.role === "user-with-attachments") { + items.push({ + key: `msg:${index2}`, + template: b2`` + }); + index2++; + } else if (msg.role === "assistant") { + const amsg = msg; + items.push({ + key: `msg:${index2}`, + template: b2`` + }); + index2++; + } else { + } + } + return items; + } + render() { + const items = this.buildRenderItems(); + return b2`
+ ${c5(items, (it) => it.key, (it) => it.template)} +
`; + } + }; + __decorate7([ + n6({ type: Array }) + ], MessageList.prototype, "messages", void 0); + __decorate7([ + n6({ type: Array }) + ], MessageList.prototype, "tools", void 0); + __decorate7([ + n6({ type: Object }) + ], MessageList.prototype, "pendingToolCalls", void 0); + __decorate7([ + n6({ type: Boolean }) + ], MessageList.prototype, "isStreaming", void 0); + __decorate7([ + n6({ attribute: false }) + ], MessageList.prototype, "onCostClick", void 0); + if (!customElements.get("message-list")) { + customElements.define("message-list", MessageList); + } + } +}); + +// ../pi-mono/packages/web-ui/dist/components/sandbox/ConsoleRuntimeProvider.js +var ConsoleRuntimeProvider; +var init_ConsoleRuntimeProvider = __esm({ + "../pi-mono/packages/web-ui/dist/components/sandbox/ConsoleRuntimeProvider.js"() { + "use strict"; + init_process_shim(); + ConsoleRuntimeProvider = class { + constructor() { + this.logs = []; + this.completionError = null; + this.completed = false; + } + getData() { + return {}; + } + getDescription() { + return ""; + } + getRuntime() { + return (_sandboxId) => { + if (!window.__originalConsole) { + window.__originalConsole = { + log: console.log.bind(console), + error: console.error.bind(console), + warn: console.warn.bind(console), + info: console.info.bind(console) + }; + } + const originalConsole = window.__originalConsole; + const pendingSends = []; + ["log", "error", "warn", "info"].forEach((method) => { + console[method] = (...args) => { + const text3 = args.map((arg) => { + try { + return typeof arg === "object" ? JSON.stringify(arg) : String(arg); + } catch { + return String(arg); + } + }).join(" "); + originalConsole[method].apply(console, args); + if (window.sendRuntimeMessage) { + const sendPromise = window.sendRuntimeMessage({ + type: "console", + method, + text: text3, + args + }).catch(() => { + }); + pendingSends.push(sendPromise); + } + }; + }); + if (window.onCompleted) { + window.onCompleted(async (_success) => { + if (pendingSends.length > 0) { + await Promise.all(pendingSends); + } + }); + } + let lastError = null; + window.addEventListener("error", (e9) => { + const text3 = `${e9.error?.stack || e9.message || String(e9)} at line ${e9.lineno || "?"}:${e9.colno || "?"}`; + lastError = { + message: e9.error?.message || e9.message || String(e9), + stack: e9.error?.stack || text3 + }; + }); + window.addEventListener("unhandledrejection", (e9) => { + const text3 = `Unhandled promise rejection: ${e9.reason?.message || e9.reason || "Unknown error"}`; + lastError = { + message: e9.reason?.message || String(e9.reason) || "Unhandled promise rejection", + stack: e9.reason?.stack || text3 + }; + }); + let completionSent = false; + window.complete = async (error, returnValue) => { + if (completionSent) + return; + completionSent = true; + const finalError = error || lastError; + if (window.sendRuntimeMessage) { + if (finalError) { + await window.sendRuntimeMessage({ + type: "execution-error", + error: finalError + }); + } else { + await window.sendRuntimeMessage({ + type: "execution-complete", + returnValue + }); + } + } + }; + }; + } + async handleMessage(message, respond) { + if (message.type === "console") { + this.logs.push({ + type: message.method === "error" ? "error" : message.method === "warn" ? "warn" : message.method === "info" ? "info" : "log", + text: message.text, + args: message.args + }); + respond({ success: true }); + } + } + /** + * Get collected console logs + */ + getLogs() { + return this.logs; + } + /** + * Get completion status + */ + isCompleted() { + return this.completed; + } + /** + * Get completion error if any + */ + getCompletionError() { + return this.completionError; + } + /** + * Reset state for reuse + */ + reset() { + this.logs = []; + this.completionError = null; + this.completed = false; + } + }; + } +}); + +// ../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageBridge.js +var RuntimeMessageBridge; +var init_RuntimeMessageBridge = __esm({ + "../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageBridge.js"() { + "use strict"; + init_process_shim(); + RuntimeMessageBridge = class _RuntimeMessageBridge { + /** + * Generate sendRuntimeMessage() function as injectable string. + * Returns the function source code to be injected into target context. + */ + static generateBridgeCode(options) { + if (options.context === "sandbox-iframe") { + return _RuntimeMessageBridge.generateSandboxBridge(options.sandboxId); + } else { + return _RuntimeMessageBridge.generateUserScriptBridge(options.sandboxId); + } + } + static generateSandboxBridge(sandboxId) { + return ` +window.__completionCallbacks = []; +window.sendRuntimeMessage = async (message) => { + const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9); + + return new Promise((resolve, reject) => { + const handler = (e) => { + if (e.data.type === 'runtime-response' && e.data.messageId === messageId) { + window.removeEventListener('message', handler); + if (e.data.success) { + resolve(e.data); + } else { + reject(new Error(e.data.error || 'Operation failed')); + } + } + }; + + window.addEventListener('message', handler); + + window.parent.postMessage({ + ...message, + sandboxId: ${JSON.stringify(sandboxId)}, + messageId: messageId + }, '*'); + + // Timeout after 30s + setTimeout(() => { + window.removeEventListener('message', handler); + reject(new Error('Runtime message timeout')); + }, 30000); + }); +}; +window.onCompleted = (callback) => { + window.__completionCallbacks.push(callback); +}; +`.trim(); + } + static generateUserScriptBridge(sandboxId) { + return ` +window.__completionCallbacks = []; +window.sendRuntimeMessage = async (message) => { + return await chrome.runtime.sendMessage({ + ...message, + sandboxId: ${JSON.stringify(sandboxId)} + }); +}; +window.onCompleted = (callback) => { + window.__completionCallbacks.push(callback); +}; +`.trim(); + } + }; + } +}); + +// ../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageRouter.js +var RuntimeMessageRouter, RUNTIME_MESSAGE_ROUTER; +var init_RuntimeMessageRouter = __esm({ + "../pi-mono/packages/web-ui/dist/components/sandbox/RuntimeMessageRouter.js"() { + "use strict"; + init_process_shim(); + RuntimeMessageRouter = class { + constructor() { + this.sandboxes = /* @__PURE__ */ new Map(); + this.messageListener = null; + this.userScriptMessageListener = null; + } + /** + * Register a new sandbox with its runtime providers. + * Call this BEFORE creating the iframe (for sandbox contexts) or executing user script. + */ + registerSandbox(sandboxId, providers, consumers) { + this.sandboxes.set(sandboxId, { + sandboxId, + iframe: null, + // Will be set via setSandboxIframe() for sandbox contexts + providers, + consumers: new Set(consumers) + }); + this.setupListener(); + } + /** + * Update the iframe reference for a sandbox. + * Call this AFTER creating the iframe. + * This is needed so providers can send responses back to the sandbox. + */ + setSandboxIframe(sandboxId, iframe) { + const context = this.sandboxes.get(sandboxId); + if (context) { + context.iframe = iframe; + } + } + /** + * Unregister a sandbox and remove all its consumers. + * Call this when the sandbox is destroyed. + */ + unregisterSandbox(sandboxId) { + this.sandboxes.delete(sandboxId); + if (this.sandboxes.size === 0) { + if (this.messageListener) { + window.removeEventListener("message", this.messageListener); + this.messageListener = null; + } + if (this.userScriptMessageListener && typeof chrome !== "undefined" && chrome.runtime?.onUserScriptMessage) { + chrome.runtime.onUserScriptMessage.removeListener(this.userScriptMessageListener); + this.userScriptMessageListener = null; + } + } + } + /** + * Add a message consumer for a sandbox. + * Consumers receive broadcast messages (console, execution-complete, etc.) + */ + addConsumer(sandboxId, consumer) { + const context = this.sandboxes.get(sandboxId); + if (context) { + context.consumers.add(consumer); + } + } + /** + * Remove a message consumer from a sandbox. + */ + removeConsumer(sandboxId, consumer) { + const context = this.sandboxes.get(sandboxId); + if (context) { + context.consumers.delete(consumer); + } + } + /** + * Setup the global message listeners (called automatically) + */ + setupListener() { + if (!this.messageListener) { + this.messageListener = async (e9) => { + const { sandboxId, messageId } = e9.data; + if (!sandboxId) + return; + const context = this.sandboxes.get(sandboxId); + if (!context) { + return; + } + const respond = (response) => { + context.iframe?.contentWindow?.postMessage({ + type: "runtime-response", + messageId, + sandboxId, + ...response + }, "*"); + }; + for (const provider of context.providers) { + if (provider.handleMessage) { + await provider.handleMessage(e9.data, respond); + } + } + for (const consumer of context.consumers) { + await consumer.handleMessage(e9.data); + } + }; + window.addEventListener("message", this.messageListener); + } + if (!this.userScriptMessageListener) { + if (typeof chrome === "undefined" || !chrome.runtime?.onUserScriptMessage) { + return; + } + this.userScriptMessageListener = (message, _sender, sendResponse) => { + const { sandboxId } = message; + if (!sandboxId) + return false; + const context = this.sandboxes.get(sandboxId); + if (!context) + return false; + const respond = (response) => { + sendResponse({ + ...response, + sandboxId + }); + }; + (async () => { + for (const provider of context.providers) { + if (provider.handleMessage) { + await provider.handleMessage(message, respond); + } + } + for (const consumer of context.consumers) { + await consumer.handleMessage(message); + } + })(); + return true; + }; + chrome.runtime.onUserScriptMessage.addListener(this.userScriptMessageListener); + } + } + }; + RUNTIME_MESSAGE_ROUTER = new RuntimeMessageRouter(); + } +}); + +// ../pi-mono/packages/web-ui/dist/components/SandboxedIframe.js +function escapeScriptContent(code) { + return code.replace(/<\/script/gi, "<\\/script"); +} +var __decorate8, SandboxIframe; +var init_SandboxedIframe = __esm({ + "../pi-mono/packages/web-ui/dist/components/SandboxedIframe.js"() { + "use strict"; + init_process_shim(); + init_lit(); + init_decorators(); + init_ConsoleRuntimeProvider(); + init_RuntimeMessageBridge(); + init_RuntimeMessageRouter(); + __decorate8 = function(decorators, target, key, desc) { + var c6 = arguments.length, r8 = c6 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d4; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r8 = Reflect.decorate(decorators, target, key, desc); + else for (var i7 = decorators.length - 1; i7 >= 0; i7--) if (d4 = decorators[i7]) r8 = (c6 < 3 ? d4(r8) : c6 > 3 ? d4(target, key, r8) : d4(target, key)) || r8; + return c6 > 3 && r8 && Object.defineProperty(target, key, r8), r8; + }; + SandboxIframe = class SandboxIframe2 extends i4 { + createRenderRoot() { + return this; + } + connectedCallback() { + super.connectedCallback(); + } + disconnectedCallback() { + super.disconnectedCallback(); + this.iframe?.remove(); + } + /** + * Load HTML content into sandbox and keep it displayed (for HTML artifacts) + * @param sandboxId Unique ID + * @param htmlContent Full HTML content + * @param providers Runtime providers to inject + * @param consumers Message consumers to register (optional) + */ + loadContent(sandboxId, htmlContent, providers = [], consumers = []) { + try { + RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId); + } catch { + } + providers = [new ConsoleRuntimeProvider(), ...providers]; + RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers); + const completeHtml = this.prepareHtmlDocument(sandboxId, htmlContent, providers, { + isHtmlArtifact: true, + isStandalone: false + }); + const validationError = this.validateHtml(completeHtml); + if (validationError) { + console.error("HTML validation failed:", validationError); + this.iframe?.remove(); + this.iframe = document.createElement("iframe"); + this.iframe.style.cssText = "width: 100%; height: 100%; border: none;"; + this.iframe.srcdoc = ` + + +

HTML Validation Error

+
${validationError}
+ + + `; + this.appendChild(this.iframe); + return; + } + this.iframe?.remove(); + if (this.sandboxUrlProvider) { + this.loadViaSandboxUrl(sandboxId, completeHtml); + } else { + this.loadViaSrcdoc(sandboxId, completeHtml); + } + } + loadViaSandboxUrl(sandboxId, completeHtml) { + this.iframe = document.createElement("iframe"); + this.iframe.sandbox.add("allow-scripts"); + this.iframe.sandbox.add("allow-modals"); + this.iframe.style.width = "100%"; + this.iframe.style.height = "100%"; + this.iframe.style.border = "none"; + this.iframe.src = this.sandboxUrlProvider(); + RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe); + const externalUrlHandler = (e9) => { + if (e9.data.type === "open-external-url" && e9.source === this.iframe?.contentWindow) { + const chromeAPI = globalThis.chrome; + if (chromeAPI?.tabs) { + chromeAPI.tabs.create({ url: e9.data.url }); + } else { + window.open(e9.data.url, "_blank"); + } + } + }; + window.addEventListener("message", externalUrlHandler); + const readyHandler = (e9) => { + if (e9.data.type === "sandbox-ready" && e9.source === this.iframe?.contentWindow) { + window.removeEventListener("message", readyHandler); + window.removeEventListener("message", errorHandler); + this.iframe?.contentWindow?.postMessage({ + type: "sandbox-load", + sandboxId, + code: completeHtml + }, "*"); + } + }; + const errorHandler = (e9) => { + if (e9.data.type === "sandbox-error" && e9.source === this.iframe?.contentWindow) { + window.removeEventListener("message", readyHandler); + window.removeEventListener("message", errorHandler); + window.postMessage({ + sandboxId, + type: "execution-error", + error: { message: e9.data.error, stack: e9.data.stack } + }, "*"); + } + }; + window.addEventListener("message", readyHandler); + window.addEventListener("message", errorHandler); + this.appendChild(this.iframe); + } + loadViaSrcdoc(sandboxId, completeHtml) { + this.iframe = document.createElement("iframe"); + this.iframe.sandbox.add("allow-scripts"); + this.iframe.sandbox.add("allow-modals"); + this.iframe.style.width = "100%"; + this.iframe.style.height = "100%"; + this.iframe.style.border = "none"; + this.iframe.srcdoc = completeHtml; + RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe); + const externalUrlHandler = (e9) => { + if (e9.data.type === "open-external-url" && e9.source === this.iframe?.contentWindow) { + window.open(e9.data.url, "_blank"); + } + }; + window.addEventListener("message", externalUrlHandler); + this.appendChild(this.iframe); + } + /** + * Execute code in sandbox + * @param sandboxId Unique ID for this execution + * @param code User code (plain JS for REPL, or full HTML for artifacts) + * @param providers Runtime providers to inject + * @param consumers Additional message consumers (optional, execute has its own internal consumer) + * @param signal Abort signal + * @returns Promise resolving to execution result + */ + async execute(sandboxId, code, providers = [], consumers = [], signal, isHtmlArtifact = false) { + if (signal?.aborted) { + throw new Error("Execution aborted"); + } + const consoleProvider = new ConsoleRuntimeProvider(); + providers = [consoleProvider, ...providers]; + RUNTIME_MESSAGE_ROUTER.registerSandbox(sandboxId, providers, consumers); + for (const provider of providers) { + provider.onExecutionStart?.(sandboxId, signal); + } + const files = []; + let completed = false; + return new Promise((resolve2, reject) => { + const executionConsumer = { + async handleMessage(message) { + if (message.type === "file-returned") { + files.push({ + fileName: message.fileName, + content: message.content, + mimeType: message.mimeType + }); + } else if (message.type === "execution-complete") { + completed = true; + cleanup(); + resolve2({ + success: true, + console: consoleProvider.getLogs(), + files, + returnValue: message.returnValue + }); + } else if (message.type === "execution-error") { + completed = true; + cleanup(); + resolve2({ success: false, console: consoleProvider.getLogs(), error: message.error, files }); + } + } + }; + RUNTIME_MESSAGE_ROUTER.addConsumer(sandboxId, executionConsumer); + const cleanup = () => { + for (const provider of providers) { + provider.onExecutionEnd?.(sandboxId); + } + RUNTIME_MESSAGE_ROUTER.unregisterSandbox(sandboxId); + signal?.removeEventListener("abort", abortHandler); + clearTimeout(timeoutId); + this.iframe?.remove(); + this.iframe = void 0; + }; + const abortHandler = () => { + if (!completed) { + completed = true; + cleanup(); + reject(new Error("Execution aborted")); + } + }; + if (signal) { + signal.addEventListener("abort", abortHandler); + } + const timeoutId = setTimeout(() => { + if (!completed) { + completed = true; + cleanup(); + resolve2({ + success: false, + console: consoleProvider.getLogs(), + error: { message: "Execution timeout (120s)", stack: "" }, + files + }); + } + }, 12e4); + const completeHtml = this.prepareHtmlDocument(sandboxId, code, providers, { + isHtmlArtifact, + isStandalone: false + }); + const validationError = this.validateHtml(completeHtml); + if (validationError) { + reject(new Error(`HTML validation failed: ${validationError}`)); + return; + } + if (this.sandboxUrlProvider) { + this.iframe = document.createElement("iframe"); + this.iframe.sandbox.add("allow-scripts", "allow-modals"); + this.iframe.style.cssText = "width: 100%; height: 100%; border: none;"; + this.iframe.src = this.sandboxUrlProvider(); + RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe); + const readyHandler = (e9) => { + if (e9.data.type === "sandbox-ready" && e9.source === this.iframe?.contentWindow) { + window.removeEventListener("message", readyHandler); + window.removeEventListener("message", errorHandler); + this.iframe?.contentWindow?.postMessage({ + type: "sandbox-load", + sandboxId, + code: completeHtml + }, "*"); + } + }; + const errorHandler = (e9) => { + if (e9.data.type === "sandbox-error" && e9.source === this.iframe?.contentWindow) { + window.removeEventListener("message", readyHandler); + window.removeEventListener("message", errorHandler); + window.postMessage({ + sandboxId, + type: "execution-error", + error: { message: e9.data.error, stack: e9.data.stack } + }, "*"); + } + }; + window.addEventListener("message", readyHandler); + window.addEventListener("message", errorHandler); + this.appendChild(this.iframe); + } else { + this.iframe = document.createElement("iframe"); + this.iframe.sandbox.add("allow-scripts", "allow-modals"); + this.iframe.style.cssText = "width: 100%; height: 100%; border: none; display: none;"; + this.iframe.srcdoc = completeHtml; + RUNTIME_MESSAGE_ROUTER.setSandboxIframe(sandboxId, this.iframe); + this.appendChild(this.iframe); + } + }); + } + /** + * Validate HTML using DOMParser - returns error message if invalid, null if valid + * Note: JavaScript syntax validation is done in sandbox.js to avoid CSP restrictions + */ + validateHtml(html) { + try { + const parser = new DOMParser(); + const doc = parser.parseFromString(html, "text/html"); + const parserError = doc.querySelector("parsererror"); + if (parserError) { + return parserError.textContent || "Unknown parse error"; + } + return null; + } catch (error) { + return error.message || "Unknown validation error"; + } + } + /** + * Prepare complete HTML document with runtime + user code + * PUBLIC so HtmlArtifact can use it for download button + */ + prepareHtmlDocument(sandboxId, userCode, providers = [], options) { + const opts = { + isHtmlArtifact: false, + isStandalone: false, + ...options + }; + const runtime = this.getRuntimeScript(sandboxId, providers, opts.isStandalone || false); + if (opts.isHtmlArtifact) { + const headMatch = userCode.match(/]*>/i); + if (headMatch) { + const index2 = headMatch.index + headMatch[0].length; + return userCode.slice(0, index2) + runtime + userCode.slice(index2); + } + const htmlMatch = userCode.match(/]*>/i); + if (htmlMatch) { + const index2 = htmlMatch.index + htmlMatch[0].length; + return userCode.slice(0, index2) + runtime + userCode.slice(index2); + } + return runtime + userCode; + } else { + const escapedUserCode = escapeScriptContent(userCode); + return ` + + + ${runtime} + + + + + diff --git a/theme-loader.js b/theme-loader.js new file mode 100644 index 0000000..1cd8a3e --- /dev/null +++ b/theme-loader.js @@ -0,0 +1,8 @@ +// Apply theme immediately to prevent white flash +// This runs before any other scripts or CSS +(function() { + const theme = localStorage.getItem('theme') || 'system'; + if (theme === 'dark' || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)) { + document.documentElement.classList.add('dark'); + } +})();